need help with while loop!

#include <iostream>
using namespace std;

int main() {
int n1, n2;
int i=n1;
cout << "Enter 2 numbers "<< endl;
cin >> n1, n2;
while (i<=n2){
cout << i << endl;
i = i+1;
}
return 0;
}
I can't get this to print the numbers between n1 and n2
there are two error , write it like this :

#include <iostream>
using namespace std;
int main()
{
int n1, n2, i ;
cout << "Enter 2 numbers "<< endl;
cin >> n1 >> n2;
i=n1;
while (i<=n2)
{
cout << i << endl;
i = i+1;
}
return 0;
}
Last edited on
Both of you, use [code][/code] to highlight the code!

Now the errors.
Firstly, the position of i = n1 is wrong, it will come after you take the value of n1.

Move it after the cin Line. Then set the value of i. Right now it is setting some garbage value to i since n1 has no value assigned to it.

Also when you want to take in more than one input with cin, you do it just as you output something with cout. By using >> for every variable whose value you want...

One question for you regardin your problem:
What if I input n1 as 10 and n2 as 3?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace std;

int main()
{
   int n1, n2, floor, ceil;
   cout << "Enter 2 numbers: " << endl;
   cin >> n1 >> n2;

   if(n1 <= n2)
   {
      floor = n1;
      ceil   = n2;
   }
   else
   {
      floor = n2;
      ceil   = n1;
   }

   while(floor <= ceil)
   {
      cout << floor << endl;
      floor++;
   }

   return 0;
}
@mcrist:
I had intended it to be for the OP so that he may try to find out the solution!!

PS:
You can write lines 11 to 20 as:
1
2
floor = n1 <= n2 ? n1:n2;
ceil = n1 <= n2 ? n2:n1;
Last edited on
Topic archived. No new replies allowed.