English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Here's my code:

#include
using namespace std;

int main()
{
int i = 0, max = 0, sum = 0;
char indicator = 'y';
cout<<"Please enter number 5: "; cin>>max;
cout< for(i=1; i<=max; i++)
sum+=i;
cout< <<"The Sum is = "< cout<<"Do you wish to display the odd sum?"< cout<<"Enter y for yes, (n to end)"; cin>>indicator;
if(indicator=='y')
{
for(i=1; max<=max; i=1+2)
sum=sum+i;
cout< <<"The odd sum is = "< }
cout<<"Okay Bye"< return 0;
}

The answer for the 1st sum is correct 15
But the Odd sum answer should be 9 and it's aint displaying and wrong answer.

2007-01-25 19:17:40 · 5 answers · asked by capphire 2 in Computers & Internet Programming & Design

5 answers

You forgot to re-initialize sum. It's adding 9 to 15 and giving you 24, right? And yeah, I missed it, but you also need to have i = i + 2, not i = 1 + 2.

if(indicator=='y')
{
sum = 0;
for(i=1; max<=max; i=i+2)
sum=sum+i;
cout< <<"The odd sum is = "< }

2007-01-25 19:30:28 · answer #1 · answered by Anonymous · 0 0

Two problems:

You need to add a line that zeros your sum for the second accumulation:

if(indicator=='y')
{
sum=0; // NEW LINE TO RESET SUM
for(i=1; max<=max; i=1+2)


And the line :

for(i=1; max<=max; i=1+2)

Needs to be re-written:

for(i=1;i<=max;i+=2) // NOT max<=max and NOT i=1+2

2007-01-26 03:32:37 · answer #2 · answered by jbtascam 5 · 0 0

I never got to C++, but do you want i=3 or do you want i=i+2?
Your line is:
for(i=1; max<=max; i=1+2)
, which would always make i=3.

2007-01-26 03:33:50 · answer #3 · answered by Big Bruce 6 · 0 0

Yeah, i have to agree with some of the other answers.

sum needs to be reinitialized to 0 before the second for loop.

the second for loop looks funky to me. Especially the condition max<=max and i=1+2.

2007-01-26 03:39:32 · answer #4 · answered by SlyMcFly 4 · 0 0

for(i=1; max<=max; i=1+2)

That is very wrong there, check your study material what is not right.

2007-01-26 04:24:21 · answer #5 · answered by Andy T 7 · 0 0

fedest.com, questions and answers