Loops

Can anyone point me in the right direction to help me figure this out more/understand it. I am trying to figure out to do this (the answer is given so I am not asking for homework help or anything).

1
2
3
4
5
6
7
8
9
10
11
12
13
14


int sum=0, i=1;
bool flag=true;
while (i<=5 && flag)
{  
    sum = sum + i*i;   
    i++;     
  if(sum>10)     
        flag=false;  
    }
cout << i <<sum;
Answer:414
closed account (SECMoG1T)
Wrong! Answer:414 look at what you used to display your answer
cout << i <<sum;
the answer is 14 while i is 4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main(){
	int sum = 0, i = 1;
	bool flag = true;
	
	
	while (i <= 5 && flag)  //This is saying that while i <= 5 and flag is still true do the following things inside the brackets
	{
		sum = sum + i*i;    // sum is now equal to sum + i^2
		i++;				//Add one to your 'i' counter

		if (sum > 10)			//Now check if the sum is greater than 10
			flag = false;		//if it is, set the flag to false.
	}
	std::cout << "i is equal to: " << i << "\n";
	std::cout << "sum is equal to: " << sum << "\n";
}


The answer is not 414, it's 4 and 14.
Ok, so that was from my C++ instructor on my mid term review. :-/
So it's sum= 0 + 2*2
2 being i=1++ ??? ya? na? wheres the 14?

u guys r way 2 good at this!!!
closed account (SECMoG1T)

0+(0*0)=0
0+(1*1)=1
1+(2*2)=5
5+(3*3)=14

if(14>10)     
        flag=false;///this flag is turned off
Last edited on
I think I got this one down. Thanks a lot!
Topic archived. No new replies allowed.