I need some help resolving a few exercises for the while statement. Below is the original code:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
int main()
{
int sum = 0, val = 1;
while (val <= 10) {
sum += val;
++val;
}
std::cout << "Sum of 1 to 10 inclusive is "
<< sum << std::endl;
return 0;
}
Output:
Sum of 1 to 10 inclusive is 55
Now, I have to do these exercises:
Exercise 1.9: Write a program that uses a while to sum the numbers from
50 to 100.
Exercise 1.10: In addition to the ++ operator that adds 1 to its operand,
there is a decrement operator (--) that subtracts 1. Use the decrement
operator to write a while that prints the numbers from ten down to zero.
Exercise 1.11: Write a program that prompts the user for two integers.
Print each number in the range specified by those two integers.
Can somebody help me resolve them all? I know that the while statement keeps a repeating something until it's false. I also have no idea how the program outputs 55.
Help is really appreciated!
Thank you for your fast response my friend, can you write everything in code? I started C++ yesterday, and the while statement is just so hard for me to understand, I have no idea why.
int start=0; // the low end of the range
int end=10; // high end of the range
while (start<end) {
// do whatever operation: adding, outputting, calling functions, etc
start++ /*increment the control variable. without this, the loop will
run forever.*/
}
So: 1.9 will require that start will equal 50, and end will equal 100. Or instead of using a variable (as in while (start<end)), you can just use the actual number (start<100). Inside this loop just add start to sum and increment start.
1.10 is very similar, except instead while (start<someNumber), start already is greater than the termination value, so you use while (start>someNumber) and instead of adding numbers inside the loop, just cout<<start, so each number start get assigned to will be output.
1.11 is slightly more complicated so here goes:
1 2 3 4 5 6 7 8
int num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
while (num1<=num2) {
cout << num1 << endl;
num1++;
}