Thread: Beginner question about 'while'

  1. #1
    Registered User
    Join Date
    May 2012
    Posts
    3

    Beginner question about 'while'

    Hello everyone, this is my first post here so I'll give a little background about myself. I know next to nothing about programming but I am attempting to teach myself C++ using lecture notes and assignments from MIT's CS department.

    With that out of the way, here is my question. This program won't compile and I'm not sure why since I declared my variable 'N.' Do I need to declare it within the while loop? If so I don't understand why. Thanks!

    Code:
    #include <iostream>
    using namespace std;
    
    
    int main () {
            int N=0;
            cin >> N;
    
    
            while(N>0)
            {
                    cout << N%5 == 0 && N%-1 ? N/5 : -1 << "\n";
            }
            return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2012
    Posts
    28
    It'll compile at least, if you simply add parentheses here: (N%5 == 0 && N%-1 ? N/5 : -1) But I'm not sure if that's what you'd like it to do. I'm also a beginner.

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    3
    Hmm interesting that worked, why is that?

  4. #4
    Registered User
    Join Date
    May 2012
    Posts
    28
    The code after 'cout <<' is performing operations (ie checking if variables are equal ==, etc), so you need parentheses to let the compiler know the formatting so it knows exactly what you want between the <<s - else it might misinterpret things as other errors. If it was just single variables or basic math, of course you won't need parentheses.

  5. #5
    Registered User
    Join Date
    May 2012
    Posts
    3
    Very helpful, much appreciated!

  6. #6
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    The parentheses are required because of operator precedence. If the statement were left alone, the bit shifting operator that the stream uses actually takes precedence over the ?: expression, so you have to use parens to get the order of operations correct. The compiler rarely gets confused.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. % vs. / beginner question
    By rokraja in forum C++ Programming
    Replies: 2
    Last Post: 07-06-2010, 04:28 AM
  2. beginner question
    By ShaiAdar in forum C Programming
    Replies: 7
    Last Post: 03-24-2009, 04:55 AM
  3. Beginner's Question
    By Micawberish in forum C++ Programming
    Replies: 3
    Last Post: 03-05-2009, 11:24 AM
  4. Beginner Question
    By Chobo in forum C++ Programming
    Replies: 13
    Last Post: 01-23-2007, 11:16 PM
  5. beginner question
    By Barrot in forum C++ Programming
    Replies: 4
    Last Post: 08-19-2005, 02:17 PM