C++/For Loop

Advertisement


Question
Hi
Using C, I was asked to use For Loop to calculate the answer for the sum of 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10.  Although I know how to display these numbers in sequence using a For Loop, but I could not use For Loop to calculate the sum of these numbers.  Any suggestions?  

Answer
Katrina,
Fortunately the answer to your question is pretty easy. Since you know how to write the loop to print out the numbers, you have already done the hard part. I'm going to assume your loop looks something like this (without dealing with the + sign):

for (int i = 1; i <= 10; i++) {
cout << i << endl;
}

All you need to do is have some sort of temporary variable that you keep adding 'i' to every time the loop is run. So the loop would look like this:

int sum = 0;
for (int i = 0; i <= 10; i++) {
cout << i << endl;
sum = sum + i;
}
cout << "The sum is: " << sum << endl;

Every time the loop is run, the value of 'i', be it 1, 2, 3, 4, etc. is added to the variable 'sum', which keeps track of the sum of 1 + 2 + 3...+ 10. I hope this answers your question. If you have any more, or need a better explanation, please let me know.

Best Of Luck,
Alan

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Alan F.

Expertise

Having problems with any basic or intermediate parts of C++? I can answer those questions for you using simple English. I have been taking C++ in school for a couple years, so I still remember what it was like to be a beginner (especially with C++, which is a difficult language)!

Experience

I have a C++ web page that discuses the basics of C++. The address is: http://www.afweb.net/complang/

©2016 About.com. All rights reserved.