Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Print Numbers Between them (http://www.go4expert.com/forums/print-t27589/)

Flow 13Jan2012 10:59

Print Numbers Between them
 
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;


xpi0t0s 14Jan2012 04:54

Re: Print Numbers Between them
 
>> 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.

Scripting 9Feb2012 23:15

Re: Print Numbers Between them
 
Hehe, loop and main function are not terminated, Funny code .

k3y 10Mar2012 01:35

Re: Print Numbers Between them
 
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;
}



All times are GMT +5.5. The time now is 22:00.