Thread: while loop question

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    46

    while loop question

    If I had the following while loop:

    Code:
    int count = 0;
    cin >> value;
    while (value < 0 && count < 5)
    {
         cout <<"Value must be non-negative;"
         <<"enter value again. " <<endl;
         cin >>value;
         count++;
    }
    What would the value of count after the loop is executed with the following data keyed in:

    -1
    -2
    -1
    0
    3


    --Would it be 3, b/c when it enters 0 then it jumps out?

    thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    The simple answer would be to compile it and run it
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Oct 2004
    Posts
    3
    It is 3. That in my opinion is really poor programming though as it's going to increase the count even after you enter 0. In glancing over it you expect it to STOP counting when the value is not less than 0 but it counts one more. I would suggest the do while loop.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. For loop question
    By JuzMe in forum C++ Programming
    Replies: 11
    Last Post: 04-20-2009, 08:39 AM
  2. Loop question
    By kwood965 in forum C Programming
    Replies: 6
    Last Post: 10-29-2008, 11:12 PM
  3. simple for loop function question
    By felicityxiv in forum C Programming
    Replies: 7
    Last Post: 05-06-2006, 11:43 PM
  4. Please don't laugh...SIMPLE loop question!
    By the_lumin8or in forum C++ Programming
    Replies: 5
    Last Post: 03-31-2006, 01:08 PM
  5. A question about while loop
    By Arooj in forum C++ Programming
    Replies: 5
    Last Post: 02-16-2003, 10:56 PM