Like Tree2Likes

how to come out of double loop

This is a discussion on how to come out of double loop within the C Programming forums, part of the General Programming Boards category; This is the code that I have written.. what I need is when the if statement will become true.. it ...

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    113

    how to come out of double loop

    This is the code that I have written..
    what I need is when the if statement will become true.. it should break out of the whole loop I mentioned in Italic
    how to do it..

    Code:
    for(i=0; i<3; i++)
       {
         for(j=0; j<3; j++)
         {
           scanf("%d",&sudoku[i][j]);
         }
       }
       
       for(i=0; i<3; i++)
       {
         for(j=0; j<3; j++)
         {
           if ( check_rows(i,j) == 0 ) 
             printf("<<%d, %d>>",i,j);
         }
       }

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Some languages allow you to label loops (eg, "inner" and "outer") and break out of nests that way. C kind of does that via goto, but it is generally discouraged as bad style. You can accomplish much the same thing if you place the nest in a function by itself and use return, but that is not always desirable.

    So a normative way is via a control variable or "flag":

    Code:
    	int i, j, flag = 0;
    	for (i = 0; i < 3; i++) {
    		for (j = 0; j < 3; j++) {
    			printf("%d %d\n", i, j);
    			if (i + j == 3) {
    				flag = 1;
    				break;
    			}
    		}
    		if (flag) break;
    	}
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    Or you could just reuse your if statement in the outer loop:
    Code:
    for(i=0; i<3; i++)
       {
         for(j=0; j<3; j++)
         {
           if ( check_rows(i,j) == 0 ) 
             printf("<<%d, %d>>",i,j);
             break;
         }
       if( check_rows(i,j)==0)
            break; 
    }
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  4. #4
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,047
    break won't take a numerical argument, so you might have to use a goto unless you can drum up something w/o it.

  5. #5
    Registered User
    Join Date
    Jun 2011
    Posts
    2,374
    Quote Originally Posted by AndrewHunter View Post
    Or you could just reuse your if statement in the outer loop:
    Code:
    for(i=0; i<3; i++)
       {
         for(j=0; j<3; j++)
         {
           if ( check_rows(i,j) == 0 ) 
             printf("<<%d, %d>>",i,j);
             break;
         }
       if( check_rows(i,j)==0)
            break; 
    }
    Pardon me for nitpicking, but you forgot the braces around the statements controlled by "if()."

    Code:
    for(i=0; i<3; i++)
       {
         for(j=0; j<3; j++)
         {
           if ( check_rows(i,j) == 0 ) {
             printf("<<%d, %d>>",i,j);
             break;
             }
         }
       if( check_rows(i,j)==0)
            break; 
    }

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,555
    Or perhaps
    Code:
    for ( i = 0 ; i < 3 && !flag ; i++ ) {
      for ( j = 0 ; j < 3 && !flag ; j++ ) {
        // something sets flag to true, both loops will then exit
        // but the side effect is i and j will be incremented anyway (unlike say break or goto)
      }
    }
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  7. #7
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    @Matticus - Thanks for catching that, didn't see it when I was typing up the answer.

    @OP - These are all valid suggestions, as MK27 said I would do what you can to stay away from goto. It is a poor programming practice.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  8. #8
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,832
    Bad idea, AndrewHunter. If the test fails in the j loop, that is, the loop completes, then the check outside will have j exceed array bounds.
    I'd say this is a perfect example of where a goto is acceptable. Any other solution is ugly and uses more variables.
    itCbitC likes this.

  9. #9
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,047
    I'd have to agree with nonoob, as this is one of the "exceptions to the norm" where only a goto would do.

  10. #10
    Registered User
    Join Date
    Jun 2011
    Posts
    2,374
    Salem's solution seemed like a good clean idea without the need for a "goto," unless the side effect they mentioned (the values of 'i' and 'j' being changed) had a detrimental effect on any code further down the line. I was originally going to suggest updating 'i' and 'j' to values that would fail the "for" loop comparison if the "if()" was executed, but did not for this very reason.

  11. #11
    Registered User
    Join Date
    Jan 2011
    Posts
    113
    seems like I got many suggestions here. Thanks, I'll check them and reply again.
    Last edited by suryak; 07-05-2011 at 12:16 PM.

  12. #12
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,304
    The best option is to put it in its own function and use a return.

    Failing that, the next most efficient option (excluding goto because I would not stoop that low) is to do this:
    Code:
       for(i=0; i<3; i++)
       {
         for(j=0; j<3; j++)
         {
            if ( check_rows(i,j) == 0 ) 
            {
                i = 3;
                break;
            }
         }
       }
    CommonTater likes this.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  13. #13
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,866
    Quote Originally Posted by nonoob View Post
    Bad idea, AndrewHunter. If the test fails in the j loop, that is, the loop completes, then the check outside will have j exceed array bounds.
    I'd say this is a perfect example of where a goto is acceptable. Any other solution is ugly and uses more variables.
    Thanks for pointing that out; I didn't even consider that.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  14. #14
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by nonoob View Post
    and uses more variables.
    Code:
    for( x = 0; x < this; x++ )
    {
        for( y = 0; y < that; y++ )
        {
            if( something )
            {
                x = this;
                y = that;
            }
        }
    }
    As long as you don't require the loop control values outside of the loop, you don't need more variables. You don't even need break.


    Quzah.
    Hope is the first step on the road to disappointment.

  15. #15
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    Personally I prefer to use a flag as Salem has suggested. If side effects are an issue you should be able to get around it with a few extra break statements or "if(flag) break" statements. That's just a general rule, of course you should be flexible depending on exactly what the loop is doing . . . .

    Setting the loop control variables to their upper bounds seems like a bad idea to me though. First, it might require more maintenance, especially if the "this/that" boundary expressions are complicated. And a compiler optimizer which would otherwise see a perfect loop with nicely striding loop variables could get confused by your meddling with the control variables. You might get less optimized code as a result.

    Finally: using a goto to break out of the outer loop works as well. It's the most socially acceptable use of a goto, but still, it's a goto. I'd use a return statement in a heartbeat but probably not a goto. Although either of these would probably be good in terms of compiler optimization.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Double Hashing Infinite Loop
    By jlangfo5 in forum C++ Programming
    Replies: 4
    Last Post: 03-06-2011, 06:48 PM
  2. Replies: 6
    Last Post: 11-04-2010, 04:33 PM
  3. fprintf in a double while loop
    By wyoui in forum C Programming
    Replies: 2
    Last Post: 06-01-2010, 12:31 PM
  4. a double linked list loop
    By elton_fan in forum C Programming
    Replies: 1
    Last Post: 10-01-2007, 11:26 AM

Tags for this Thread


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