Tuesday, July 28, 2009

C++ Using - for -?

My teacher wants me to write the code out using "for"





Question from my teacher:


Enter: 5


1 to 5 = 15 //Example (1+2+3+4+5 = 15)


1 to 5 = 9 //Odd Number (1+3+5 = 9)





I've successful write the code of 1 to 5 = 15


But 1 to 5 = 9 %26lt;%26lt; Odd number I dont know





#include %26lt;iostream%26gt;


using namespace std;





int main()


{


int i=0, max=0;





cout%26lt;%26lt;endl


%26lt;%26lt;"Please enter number 5: ";


cin%26gt;%26gt;max;


cout%26lt;%26lt;endl;





for(i = 1; i %26lt;=max; i++)


sum+=1;





cout%26lt;%26lt;endl


%26lt;%26lt;Total Sum: "%26lt;%26lt;sum


%26lt;%26lt;endl;


return 0;


}





Can someone help me coding out the question that teacher ask me?

C++ Using - for -?
sum = 0;


for (i=1;i%26lt;5;i+=2)


{


sum+=i;


}





the for statement is broken into 3 sections... initialization, comparison, and increment/decrement.





you could have a for loop that looks like





bool done = FALSE;


for (i=0; (i%26lt;10 || done);i=i*2)


{








}
Reply:#include %26lt;iostream%26gt;


using namespace std;





int main()


{


int i=0, max=0;


int sum=0, myvariable=1;


cout%26lt;%26lt;endl


%26lt;%26lt;"Please enter number 3: ";


cin%26gt;%26gt;max;


cout%26lt;%26lt;endl;





for(i = 1; i %26lt;=max; i++){


sum+=myvariable;


myvariable=myvariable+2;


}


cout%26lt;%26lt;endl


%26lt;%26lt;Total Sum: "%26lt;%26lt;sum


%26lt;%26lt;endl;


return 0;


}





here notice that i have added curly brackets to "for" statement. cos it is more than one line now.





anything you wanna ask about the code, just send your question to my mail, man. efefef20@yahoo.com. i hope this program works for you. it is working as expected in my computer. i think your teacher will like it also. take it easy.


No comments:

Post a Comment