10 11 12 13 14 15 16 17 18 19 20
100
99
98
97
96
95
94
93
92
91
90
Enter number 1: 10
Enter number 2: 20
Enter number 3: -5
Enter number 4: 7
Enter number 5: 23
The sum is 55.
This is the samle output that I am supposed to reproduce with codes. I got.
#include %26lt;iostream.h%26gt;
int main () {
int counter, num, sum, numValues;
cout %26lt;%26lt; "Loop Examples 2" %26lt;%26lt; endl %26lt;%26lt; endl;
counter = 10;
do {
cout %26lt;%26lt; counter %26lt;%26lt; " ";
counter++;
} while (counter %26lt;= 20);
cout %26lt;%26lt; endl %26lt;%26lt; endl;
counter = 101;
do {
counter--;
cout %26lt;%26lt; counter %26lt;%26lt; endl;
} while (counter %26gt; 90);
cout %26lt;%26lt; endl;
numValues = 1;
do {
cout %26lt;%26lt; "Enter number" %26lt;%26lt; numValues %26lt;%26lt; ": " ;
cin %26gt;%26gt; num;
numValues++;
sum+= num;
} while (numValues %26gt; 0 %26amp;%26amp; numValues %26lt; 6);
cout %26lt;%26lt; endl;
cout %26lt;%26lt; "The Sum is: " %26lt;%26lt; sum %26lt;%26lt; endl;
return 0;
}
My problem is when i compile and run this program, the Sum does NOT come out right.
Slight problem with my c++ program?
You're problem is right here:
sum += num;
sum isn't initialized to 0. It's garbage when it starts out. That's why your output is wrong.
When you declare sum do this:
int sum = 0;
Reply:Where do you assign an initial value to sum? When you declare a value in C++, its initial value is whatever happens to be at that spot of memory at that time. You need to make sure to set sum=0; before the loop that uses it.
A side note:
Using for loops will make your program simpler and easier to read. Here is the code with the sum variable initialized to 0 and using for loops:
#include %26lt;iostream.h%26gt;
int main () {
int num, sum, numValues;
cout %26lt;%26lt; "Loop Examples 2" %26lt;%26lt; endl %26lt;%26lt; endl;
for (int counter = 10; counter %26lt;=20; counter++)
{
cout %26lt;%26lt; counter %26lt;%26lt; " ";
}
cout %26lt;%26lt; endl %26lt;%26lt; endl;
for (counter = 100; counter %26gt;= 90; counter--)
{
cout %26lt;%26lt; counter %26lt;%26lt; endl;
}
cout %26lt;%26lt; endl;
sum = 0;
for (numValues = 1; numValues %26lt; 6; numValues++)
{
cout %26lt;%26lt; "Enter number" %26lt;%26lt; numValues %26lt;%26lt; ": " ;
cin %26gt;%26gt; num;
sum+=num;
}
cout %26lt;%26lt; endl;
cout %26lt;%26lt; "The Sum is: " %26lt;%26lt; sum %26lt;%26lt; endl;
return 0;
}
Reply:use sum += num; to correct your problem.
Dornessa
http://onlinedownlinebuilders.com
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment