I am writing a program to add all the multiples of a number less than 100, but I can't seem to figure it out. Can someone give me some guidance as to why it's not working? The value for multipleSum keeps returning as 0.
#include <iostream>
#include <iomanip>
usingnamespace st;
int multipleNum;
intmultipleSum = Sum;
/*
* prompts user for info
*/
int prompt()
{
cout << "What multiples are we adding? ";
cin >> multipleNum;
}
int check()
{
int Sum;
int multipleSum;
int multiple;
for (int mult = 1; multiple >= 100; mult += 1)
multiple = mult * multipleNum;
multipleSum = multipleSum + multiple;
return Sum;
}
int display()
{
cout << "The sum of multiples of " << multipleNum << " less than 100 are: " << multipleSum;
}
int main()
{
prompt();
check();
display();
}
Just looking at your program in the function "check" line 18 defines the variable "Sum" which has an unknown or garbage value. On my computer this number is usually "-858993460". So for line 22 "multiple", which also has a garbage value will have the result of 1 * -858993460. This will take a little time for "mult" to reach 100.
Line 24 returns "Sum", which still has a garbage value since it never changed, to main where it is never used.
Also the variables "multipleSum" and "multiple" are lost when the function ends. This tends to make the function useless.
The "display" function uses the two variables from the "check" function which were lost when the function went out of scope.
In the "prompt" function you are using a variable that was never defined in the function or passed to the function.
There are quite a few errors I can spot:
1) It should be usingnamespace std; not st
2) You are missing a space in intmultipleSum
3) You are initializing multipleSum to Sum even though Sum doesn't exist.
4) You haven't initialized the variables before using them in check() so they have random values.
5) You are missing braces after for
6) You're returning Sum in check() but never use it.
As it appears, all these are something which the compiler would have warned you about, or you should have known yourself.
No offense, but in programming it's imperative to use your brain .