Print Numbers Between them

Flow's Avatar, Join Date: Jan 2012
Newbie Member
Hi,
I've started learning C++ few hours ago, so this question might seem a bit stupid. Anyhow, I'm trying to write a program that will take two numbers (n, and n1) from the user, and then will print all the numbers between them. For instance, if n = 1 and n1 = 5, then the program will print: 1 2 3 4 5. Since it doesn't work, I must have done something wrong. Could you please try to help me? Here is the code:

Code:
#include "stdafx.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
int n, n2, i = 1;
cout << "Enter a number and press ENTER: "<< endl;
cin >> n;
cout << " Enter another a number" << endl;
cin >> n2;
while (n <= n2){
	
	cout << i << " " << endl;  
	i = n + 1;
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
>> it doesn't work

In what way exactly? Does it compile? If not what errors do you get? If it compiles and runs, what input did you give, what output did you expect and what output did you get?

There are two very obvious errors: the while loop and the main function are not terminated. So this code shouldn't even compile. Also using should go outside the main function.

Have a close look at i, what you initialise it to, and where it gets changed and to what.
0
Scripting's Avatar, Join Date: Jun 2010
John Hoder
Hehe, loop and main function are not terminated, Funny code .
0
k3y's Avatar, Join Date: Mar 2012
k3y
Go4Expert Member
Check this out:
Code:
#include <iostream>
using namespace std;
int main()
{
    int n1, n2;

    cout << "Please enter a number: " << endl;
    cin >> n1;
    cout << "Please enter a larger number: " << endl;
    cin >> n2;

    if (n1 >= n2)
    {
        cout << "Pleas enter a new value for your first value.";
        cin >> n1;
    }

    for (int i = n1 + 1; i <= n2; i++)
    {
        cout << i << " ";
    }
    return 0;
}