Print Numbers Between them

Discussion in 'C++' started by Flow, Jan 13, 2012.

  1. Flow

    Flow New Member

    Joined:
    Jan 13, 2012
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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;
    
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    >> 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.
     
  3. Scripting

    Scripting John Hoder

    Joined:
    Jun 29, 2010
    Messages:
    421
    Likes Received:
    57
    Trophy Points:
    0
    Occupation:
    School for life
    Location:
    /root
    Hehe, loop and main function are not terminated, Funny code .
     
  4. k3y

    k3y New Member

    Joined:
    Mar 9, 2012
    Messages:
    14
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    Student
    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;
    }
    
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice