Thread: Breaking out of a FOR loop

  1. #1
    Registered User
    Join Date
    Nov 2019
    Posts
    7

    Arrow Breaking out of a FOR loop

    for(int i=0; i<k; i++)
    bool matchName = matches (contact[i]. name, key);
    bool matchNum = matches (contact[i].number, key);

    if (matchName || matchNumber)
    printf("%s%s\n", contact[i].name, contact[i].number);

    // here I want to implement ELSE, so that in case nothing is found, program simply prints "Not found", but without looping. The code I put is part of a phonebook program, which looks for numbers and names. Simply, after IF I would like to implement ELSE with printing: "printf ("Not found.")" but without looping for a size of "k" in FOR loop.

    Thanks for advise in advance!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Do that, followed by a statement (also in the else block) with the break keyword.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. breaking a for loop
    By begginer in forum C Programming
    Replies: 6
    Last Post: 03-23-2011, 02:26 PM
  2. Breaking while loop with CIN
    By muffinman8641 in forum C++ Programming
    Replies: 4
    Last Post: 03-17-2011, 07:38 AM
  3. Breaking out of a loop
    By kiros88 in forum C Programming
    Replies: 5
    Last Post: 09-01-2009, 11:49 AM
  4. Breaking out of the loop
    By ICool in forum C Programming
    Replies: 5
    Last Post: 09-24-2007, 08:27 AM
  5. breaking a loop
    By phantom in forum C++ Programming
    Replies: 6
    Last Post: 01-31-2003, 08:43 AM

Tags for this Thread