No syntax error but not printing result - c++

I can't get the sum to print out
I did not get any warnings or such.
Trying to do this question here:http://projecteuler.net/problem=1
the program runs and then just stalls forever.
// Adding multiples of this and following equations
#include "std_lib_cmpt125.h"
void SumMultiple(int Max,int Base)
{
int i=0;
int sum=0;
for(i;i<Max;i+Base)
{
sum=i+sum;
};
cout<<"The sum"<<sum;
}
int main()
{
int base=0;
int max=0;
int sum=0;
cout<<"Please enter the sum's multiple: (ex. 3: 3,6,9,12...)\n";
cin>>base;
cout<<"Please enter the sum's maximum: (ex. 10000)\n";
cin>>max;
SumMultiple(max,base);
return 0;
}
}

You missed to increment the i,
for(i;i<Max;i=i+Base)
{
..
}
Or
for(i;i<Max;i+=Base)
{
..
}

Change:
int i=0;
int sum=0;
for(i;i<Max;i+Base)
{
sum=i+sum;
};
To:
int sum = 0;
for (int i = 0; i < Max; i += Base)
{
sum += i;
}
Note that the first statement in the original for loop does nothing, that the value of i must be incremented (which is accomplished most simply with the += operator), and that the semicolon after the closing brace is unnecessary.
It's customary in C++ to declare a loop variable in the loop itself, to limit its scope and emphasize its purpose as a counter.

You have an extra Brace } at the end and you are not incrementing i

Change the
for(i;i<Max;i+Base)
{
sum=i+sum;
};
cout<<"The sum"<<sum;
into
for(i;i<Max;i=i+Base)
{
sum=i+sum;
};
cout<<"The sum"<<sum;
or
for(i;i<Max;i+=Base)
{
sum=i+sum;
};
cout<<"The sum"<<sum;
The above code will increment the counter i and display the necessary result

Also you aren't going to get the answer with that function. problem 1 is looking for the sum of all multiples of 3 or 5 from [1..999]
try this
for ( int i = 1; i < Max ; i++ )
sum += ((i % 3 && i % 5) ? 0 : i ;
return sum

Related

Finding the smallest positive number

Question: Smallest Positive missing number
What is wrong with this code?
class Solution
{
public:
//Function to find the smallest positive number missing from the array.
int missingNumber(int arr[], int n)
{
// Your code here
sort(arr,arr+n);
int index=1;
int a;
for(int i=0;i<n;i++){
if(arr[i]>0){
if(arr[i]!=index){
a=index;
break;
}
else{
index++;
}
}
}
return index;
}
};
In every iteration your i is increasing, so this condition which you have written in your for loop:
arr[i]!=index
Here, let's say if the input array has duplicate elements, then for 2 consecutive values of i you will get the same value in arr[i]. In the first comparison, this condition will hold false, so you go to the else part and increment the index value. In the next iteration, your condition arr[i]!=index is always going to be true, as arr[i] is still the same but the index is increased. Thus your program will break from the for loop and the index value is getting returned. That is where it's failing.
So, it will always fail whenever you have duplicate positive elements in your input array. Except for the case when the largest item in the array is the only duplicate in input.
Here's one hint:
for(int i=0;i<n;i++){
if(arr[i]>0){
if(arr[i]!=index){
a=index;
break;
}
else{
index++;
}
}
}
imagine your sorted array is [-10, -5, 0, 1, 2, 3, 4, 5]
When i==3. arr[3] is equal 1, which is the first number you want to evaluate against index. But index will be equal to 3, not 1 as you might have intended.
And as others have pointed out - duplicate numbers in the array are not handled either.
Second hint:
What if I told you... that there was a way to solve this problem without having to sort the input array at all? What if you had an allocated an array of bools of length N to work with....
You should only increase index if arr[i] == index or else you'll get the wrong result for arrays with duplicates, like {1,2,3,4,5,5,6,7}.
int missingNumber(int arr[], int n) {
std::sort(arr,arr + n);
int index=1;
int a;
for(int i=0; i < n; i++) {
if(arr[i] > 0) {
if(arr[i] == index) { // equal, step
++index;
} else if(arr[i] > index) { // greater, we found the missing one
a=index;
break;
} // else, arr[i] == index - 1, don't step
}
}
return index;
}
You are missing a great opportunity to use the sorted array though. Since you're only interested in positive numbers, you can use std::upper_bound to find the first positive number. This search is done very efficiently and it also means that you don't have to check if(arr[i] > 0) in every iteration of your loop.
Example:
int missingNumber(int arr[], int n) {
int* end = arr + n;
std::sort(arr, end);
int* it = std::upper_bound(arr, end, 0); // find the first number greater than 0
int expected = 1;
while(it != end && *it <= expected) {
if(*it == expected) ++expected;
++it;
}
return expected;
}
Alternatively, std::partition the array to put the positve numbers first in the array even before you sort it. That means that you'll not waste time sorting non-positive numbers.
int missingNumber(int arr[], int n) {
int* end = arr + n;
end = std::partition(arr, end, [](int x){ return x > 0; });
std::sort(arr, end);
int expected = 1;
for(int* it = arr; it != end && *it <= expected; ++it) {
if(*it == expected) ++expected;
}
return expected;
}
You can try using a counting array and then walk the array until you come to an empty space.
int main() {
int N;
cin >> N;
int num; // set to zero b/c zero is out lowest possible number
vector<int> numbers;
while (cin >> num) {
numbers.push_back(num);
}
//create a counting array to add a 1 to all the positions that exist
int * cA = new int[10000] {0};
for (int i = 0; i < N; i++) {
if (numbers[i] >= 0) {
cA[numbers[i]]++;
}
}
for (int i = 1; i < 10000; i++) {
if (cA[i] == 0) {
num = i;
break;
}
}
cout << num;
delete []cA;
return 0;
}
How Code Works : first get element count and add all items into Vector by Loop,with second loop going to 1000 i check from 1 to 1000 if any of 1,2,3,4,... is not in the vector i print missing,i do this with bool variable res,if any of loop counter starting from 1 to 1000 is in the vector res variable is set to True otherwise False.be careful in each run of For Loop from 1 to 1000 you should set res=False
#include <iostream>
#include <vector>
using namespace std;
//Programmer : Salar Ashgi
int main()
{
vector<int> v;
int k=0;
cout<<"Enter array count ?\n";
cin>>k;
int n;
for(int i=0;i<k;i++)
{
cout<<"Enter num "<<i+1<<" : ";
cin>>n;
v.push_back(n);
}
bool res=false;
for(int i=1;i<=1000;i++)
{
res=false;
for(int j=0;j<k;j++)
{
if(v[j]==i)
{
res=true;
break;
}
}
if(!res)
{
cout<<i<<" is missing !";
break;
}
}
}

Why is it not printing the coding of the void functions?

Can some help me and explain where i got it wrong?
I just don't know where I'm wrong;C
void largest(int);
void smallest(int);
void average(double);
int main()
{
int n=0,i=1,num,max=0,min=0,sum=0;
double avg=0;
cout<<"Please enter total number of integers: ";
cin>>n;
cout<<"\n";
while (n>0)
{
cout<<"Enter integer "<<i<<": ";
cin>>num;
if (num>max)
max=num;
if (num<min)
min=num;
sum=sum+num;
n--;
i++;
}
avg=sum/n;
largest(max);
smallest(min);
average(avg);
return 0;
}
void largest(int max)
{
cout<<"The largest integer is: "<<max;
}
void smallest(int min)
{
cout<<"The smallest integer is: "<<min;
}
void average(double avg)
{
cout<<"The average is: "<<avg;
}
From my understanding im not so sure if this is correct but i need to use void to print out a message and im a bit confuse as to when i should use void and what does the difference between double& and double when i use it?
Process exited ... with return value 3221225620
3221225620 is the numeric code for a STATUS_INTEGER_DIVIDE_BY_ZERO (0xC0000094) exception, which means your code is crashing before it has a chance to print out its messages.
On this line:
avg=sum/n;
n is 0 at this point, because the while loop above it had decremented n on each iteration until n reached 0.
To avoid that, change the while loop to not modify n anymore:
while (i <= n)
{
...
i++;
}
Or, use a for loop instead:
for (int i = 1; i <= n; ++i)
{
...
}
you're dividing by 0, since you're modifying n until it reaches 0 and then use it to divide, it's better if you iterate with another variable instead of reducing the value of n. so the problem isn't that it's not printing, it's that the program dies before reaching that

(C++) Generate first p*n perfect square numbers in an array (p and n inputted from the keyboard)

I input p and n (int type) numbers from my keyboard, I want to generate the first p*n square numbers into the array pp[99]. Here's my code:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int i, j, n, p, pp[19];
cout<<"n="; cin>>n;
cout<<"p="; cin>>p;
i=n*p;
j=-1;
while(i!=0)
{
if(sqrt(i)==(float)sqrt(i))
{
j++;
pp[j]=i;
}
i--;
}
for(i=0; i<n*p; i++)
cout<<pp[i]<<" ";
return 0;
}
But I am encountering the following problem: If I for example I enter p=3 and n=3, it will only show me the first 3 square numbers instead of 9, the rest 6 being zeros. Now I know why this happens, just not sure how to fix it (it's checking the first n * p natural numbers and seeing which are squares, not the first n*p squares).
If I take the i-- and add it in the if{ } statement then the algorithm will never end, once it reaches a non-square number (which will be instant unless the first one it checks is a perfect square) the algorithm will stop succeeding in iteration and will be blocked checking the same number an infinite amount of times.
Any way to fix this?
Instead of searching for them, generate them.
int square(int x)
{
return x * x;
}
int main()
{
int n = 0;
int p = 0;
std::cin >> n >> p;
int limit = n * p;
int squares[99] = {};
for (int i = 0; i < limit; i++)
{
squares[i] = square(i+1);
}
for (int i = 0; i < limit; i++)
{
std::cout << squares[i] << ' ';
}
}

why there is unexpected value 6295648 come with answer 11110001 in output?here input is 241 and 2

void base(int n,int b)
{
int x[20],k=0;
while(n!=0)
{
x[k]=n%b;
n=n/b;
k=k+1;
}
for(int i=0;i<=k;i++)
{
cout<<x[k-i];
}
return ;
}
int main()
{
int number,baise;
cin>>number;
cin>>baise;
base(number,baise);
return 0;
}
It is program of base expansion. I wrote a function for that and in main() I call it with 2 parameters (that I want to convert into another base) and baise (that is a base value into which a number is converted). The program runs and it also gives output but with the input it gives some undesirable values, which is 6295648 in this case.
Input:
241
2
Output
629564811110001
But the output should be 11110001 only. I don't understand why the value 6295648 comes.
for(int i=0;i<=k;i++)
{
cout<<x[k-i];
}
At the first iteration of the loop, the executed statement is:
cout << x[k];
where x[k] is never assigned, which is an UB.
Changing the loop initialization statement to x = 1 solves this problem. Or more clearly,
for(int i = k-1; i >= 0; i--)
{
cout << x[i];
}
The issue with your code is that k gets incremented post the assignment in the x[] array i.e. In the last iteration k gets incremented to 8. Then in case of k-i when the value of i is 0 .. x[k-i] goes out of bounds.
#include <iostream>
using namespace std;
void base(int n,int b)
{
int x[20],k=-1;
while(n!=0)
{
x[++k]=n%b; //pre increment
n=n/b;
}
for(int i=0;i<=k; i++)//now k contains the index of the last element
{
cout<<x[k-i];
}
return ;
}
int main()
{
int number,baise;
cin>>number;
cin>>baise;
base(number,baise);
return 0;
}

Strange output produced by program

I think that my code works. However, it outputs 01111E5, or 17B879DD, or something like that.
Can someone please tell me why.
I am aware that I set the limit of P instead of 10,001. My code is like that because I start with 3, skipping the prime number 2.
#include <iostream>
bool prime (int i)
{
bool result = true;
int isitprime = i;
for(int j = 2; j < isitprime; j++) ///prime number tester
{
if(isitprime%j == 0) result = false;
}
return result;
}
int main (void)
{
using namespace std;
int PrimeNumbers = 1;
int x = 0;
for (int i = 3 ; PrimeNumbers <=10000; i++)
{
if(prime(i))
{
int prime = i;
PrimeNumbers +=1;
}
}
cout<<prime<<endl;
system ("pause");
return 0;
}
cout<<prime<<endl;
prints the address of the function bool prime (int i), not the variable you declared. Just rename the function or the variable (note that you'll also have to change its scope, or move the cout inside the loop - that's if you want to print them all):
for (int i = 3 ; PrimeNumbers <=10000; i++)
{
if(prime(i))
{
cout << i << endl;
PrimeNumbers++;
}
}
Also:
for(int j = 2; j < isitprime; j++) ///prime number tester
{
if(isitprime%j == 0) result = false;
}
could be optimized, since (1) you don't need to check all numbers till isitprime, but at most to sqrt(isitprimt) and (2) you only need to check until result is false, at which point you can break out of the loop.
The output isn't strange at all.
cout<<prime<<endl;
You're printing the function pointer of prime here.
You were probably intending to print the variable you create here:
int prime = i;
But this is in the loop scope. In fact, if you compile with warnings enabled, your compiler should tell you that this variable is never used. Also, it's bad practice to give variables in C or C++ the same name as functions (or any other variable in a higher level scope).
Your loop in the main program does not stop correctly because the test variable, PrimeNumbers may not change.
Try:
for (int i = 3; i < 10000; i++)
{
//...
}
Also, because you declared the variable prime inside an if statement, it disappears after the if statement is executed:
if (prime(i))
{
int prime = i; // <-- Declare the variable before the for loop.
//...
The code for finding prime number from nth to 2(1 is neither prime nor composite) is written below, i havent used math.h header file , did something different and surpizingly it works pretty cool....
Code is:
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class prime
{
int a;
int i;
public:
void display();
};
void prime::display()
{
cout<<"Enter the number to see primes less than it till 2";
cin>>a;
int count=0;
for(int j=a;j>=1;j--)
{
for(int i=1;i<=j;i++)
{
if(j%i==0)
{
count++;
}
}
if(count==2)
{
cout<<"\t"<<j;
}
count=0;
}
}
void main()
{
clrscr();
prime k;
k.display();
getch();
}
if you want to find the prime number from 1 to n,hope this will help u.
#include <iostream>
#include <vector>
static bool _isprime (int number)
{
if(number==1)
{
return false;
}
bool flag=true;
if(number==2||number%2!=0)
{
for(int i=2;i<number;i++)
{
if(number%i==0)
{
flag=false;
}
}
}
else flag=false;
return flag;
}
int main (void)
{
using namespace std;
vector<int> primenumber;
cout<<"prime number between 1 and ?"<<endl;
int x=0;
cin>>x;
for(int i=0;i<=x;i++)
{
if(_isprime(i)==true)
{
//cout<<x<<" is a prime number"<<endl;
primenumber.push_back(i);
}
//else cout<<x<<" is not a prime number"<<endl;
}
for(int i=0;i<primenumber.size();i++)
{
cout<<primenumber[i]<<endl;
}
cout<<"the number of prime number is "<<primenumber.size()<<endl;
system("pause");
return 0;
}