Thread: Modifying a while loop

  1. #1
    Registered User
    Join Date
    Sep 2006
    Location
    Kansas City
    Posts
    76

    Modifying a while loop

    How can this loop be modified so that the statement "Please select an item from the list." is only repeated 3 times, and after the third unsecessful try a new message is displayed, ex. " You can't follow instructions, Good Bye"

    Code:
    while ((item != 1) && (item != 2) && (item != 3) && (item != 4))
     {
        cout << "Please select an item from the list." << endl ;
        cin >> item;
     }

  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
    Add a counter called numGuesses, which gets incremented each time.

    Code:
    while ( numGuesses < 3 && (item != 1) && (item != 2) && (item != 3) && (item != 4))
     {
        cout << "Please select an item from the list." << endl ;
        cin >> item;
        numGuesses++;
     }
    Use the value to alter your prompt
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. My loop within loop won't work
    By Ayreon in forum C Programming
    Replies: 3
    Last Post: 03-18-2009, 10:44 AM
  2. While loop misbehaving (or misunderstanding)
    By mattAU in forum C Programming
    Replies: 2
    Last Post: 08-28-2006, 02:14 AM
  3. while loop help
    By bliznags in forum C Programming
    Replies: 5
    Last Post: 03-20-2005, 12:30 AM
  4. loop issues
    By kristy in forum C Programming
    Replies: 3
    Last Post: 03-05-2005, 09:14 AM
  5. when a while loop will stop ?
    By blue_gene in forum C Programming
    Replies: 13
    Last Post: 04-20-2004, 03:45 PM