For/while loops

I need to write program that asks a user for two numbers and then computes and outputs the sum of all of the consecutive numbers between the two numbers. Like if the user were to enter numbers 45 and 51, the program would compute (45 + 46 + 47 + 48 + 49 + 50 + 51) then output the result to the screen. Assume that the first number will always be less than the second number.

The program can contain either a for or a while. Loop but it is basically personal preference as to which one to use.

I am having trouble writing this program, I know that it is simple. But any help setting it up would be greatly appreciated!

Something like this should work:
1
2
3
4
int i[2], s=0;
for (cin >> i[0] >> i[1]; i[0]<=i[1]; i[0]++)
      s+=i[0];
cout << '\n' << s;
Last edited on
Bazzy, please don't just post code for people, we need to help them learn, not do it for them.
Bazzy,
I don't understand the cin within the for loop. Since you are reading in two values, how does the for loop know where to start?
@ jpeg
I think people could learn from examples and that code needs to be improved

@ grcunning
the for(a; b; c) {block} works as follow:
'a' is executed
while 'b' is true, performs the block and then 'c'.
My example is as writing
1
2
3
4
5
6
7
8
int i[2], s=0;
cin >> i[0] >> i[1];
while ( i[0]<=i[1])
{
      s+=i[0];
      i[0]++;
}
cout << '\n' << s;
@ Bazzy
I don't disagree with you, but many, many, MANY students will just copy and paste your code and never learn it for themselves.
Topic archived. No new replies allowed.