Noob problem with "for" statement

This is a discussion on Noob problem with "for" statement within the C++ Programming forums, part of the General Programming Boards category; Or it might be a problem elsewhere? I am doing an exercise from a recommended book, in which I am ...

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    7

    Noob problem with "for" statement

    Or it might be a problem elsewhere?

    I am doing an exercise from a recommended book, in which I am trying to get the program to print all numbers from n1 to n2 .

    Here is what I have come up with:

    Code:
    #include <iostream>
    using namespace std;
    
    int main() 
    {
        int n1, n2, i;
        
        cout << "Please enter a number: ";
        cin >> n1;
        cin.ignore();
        cout << "Please enter a higher number: ";
        cin >> n2;
        cin.ignore();
        for (i = n1 ; i <= n2; i++);
             cout << i << " ";
        cin.get();
        return 0;
    }
    Instead of getting the increments, it simply adds 1 to n2. I have looked for an example on the accompanying CD (that came with the book), but it doesn't have a sample for the exercise.

    Where did I go wrong?

  2. #2
    Registered User
    Join Date
    May 2006
    Posts
    903
    It looks somehow fine to me. What numbers do you input ?

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    7
    Any numbers i enter, with the first being lower, of course. If I enter '1' and '20', the result is

    '21'

    If i enter '20' and '100,' I get

    '101'


    I just tried reversing my input by entering a higher number first and lower 2nd. What it then does is just state the higher number. For example, if I put in '10' and then '5,' it gives me

    '10'

    I feel like I must be missing something really simple here.
    Last edited by Ultraman; 05-15-2006 at 10:23 PM.

  4. #4
    Registered User
    Join Date
    May 2006
    Posts
    903
    Oh ! Ahah ! It just jumped in my face. You put a semi-colon after the for() statement.

  5. #5
    Registered User
    Join Date
    May 2006
    Posts
    7
    Doh!

    Thanks for the quick replies Desolation. All is now well.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. noob problem in code
    By Dadude in forum C Programming
    Replies: 12
    Last Post: 02-07-2009, 10:28 AM
  2. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 03:51 PM
  3. Problem calculating average with "for"...
    By davidvoyage200 in forum C++ Programming
    Replies: 3
    Last Post: 10-25-2002, 11:02 AM
  4. If statement re-do problem
    By RoD in forum Windows Programming
    Replies: 5
    Last Post: 09-11-2002, 05:46 PM
  5. having a problem with a FOR statement
    By jonesy in forum C Programming
    Replies: 3
    Last Post: 10-01-2001, 02:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21