while loop problem in c++

Using while loop write a program that prompts the user for two integers.
Print each number in the range specified by those two integers.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;
int main(){
int a,b;
cin >> a >> b ;
int i=a;
while (i <= b){
cout << i << endl;
i++;
}}

1
2
3
4
5
//output (if enter a=2 and b=5)
2
3
4
5
Last edited on
Thanks byOmer for replay soon. I have another problem.
How it look if i allow user to choose two number (2nd number is greater than first) and add all ranging from first to second number? Example : suppose I want to choose 5 and 22 and add all the number from 5 to 22 using while loop. Here 5 and 22 are user choice can be chosen bt "std::cin"
do you want to sum ? example 5+6+7+8+9+10+....+22 is it true ?
yes thats right i want to sum 5+6+7+....+22.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
int main()
{
    int a,b;
    cin>>a>>b;
    int i = a;
    int sum = 0; // you need to set it to 0 so that it starts from that number, otherwise it'll give you a huge random number. 

    while (i <= b)
    {
        cout << i << endl;
        sum = sum + i; //everytime the loop runs, it will add counter value to the sum value.
        i++;
    }
    cout<<"Sum of the numbers between "<<a<<" and "<<b<<" is "<<sum<<endl;
}
Last edited on
thaanks a lot Peril
Topic archived. No new replies allowed.