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!
A for loop has this structure: for (initialization list;while-like condition;increment list)
All for loops can be converted to while loops:
{
initialization list;
while (while-like condition){
//...
increment list;
}
}
Variables declared in the initialization list have scope only inside the loop:
1 2 3 4 5 6
for (int a=0;a<10;a++){
//OK. a exists here
std::cout <<a<<std::endl;
}
//Wrong! a went out of scope when the for loop ended.
std::cout <<a<<std::endl;
It's possible to declare more than one variable: for (int a=0,b=10;a<10;a++,b--){
Despite what I called them, practically anything can go in the initialization and increment lists, even function calls:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void init(int &a){
a=0;
}
void inc(int &a){
a++;
}
//...
/*
Note that you can either declare variables, or do other stuff, but not both.
This is not valid:
for (int a,init(a);//...
*/
int a;
for (init(a);a<10;inc(a)){//...