c - Break condition in iteration -


this question has answer here:

following insertion sort code wrote

#include<stdio.h> #include<conio.h> void main() {     int i, j, a[10], temp, f = 0, k = 0;     clrscr();     printf("\n\t\t\t\tinsertion sort\nenter array:-\n");     (i = 0; <= 9; i++)         scanf("%d", &a[i]);     (i = 0; <= 9; i++)                  // 1st loop     {         temp = a[i];         (j = 0; j <= - 1; j++)               // 2nd  loop         {             f = 0;             if (a[i]<a[j])                      //  if loop             {                 (k = - 1; k >= j; k--)            //   3rd loop                     a[k + 1] = a[k];                 a[k + 1] = temp;                 break;                              // break statement             }         }     }     printf("\nthe sorted array is:-\n");     (i = 0; <= 9; i++)         printf("%d\n", a[i]);     getch(); } 

i told break statement stops particular instant(nth time of running innermost loop & initiates next instance ( n+1 time). here confused whether break statement here stop 3rd loop or if condition. told affect second loop.

can here please tell me on loop going have effect.

the break stop loop, not if statement.

so here:

for (i = 0; <= 9; i++)                 // 1st loop {     temp = a[i];     (j = 0; j <= - 1; j++)         // 2nd  loop     {         f = 0;         if (a[i]<a[j])                   //  if statement         {             (k = - 1; k >= j; k--) //   3rd loop                 a[k + 1] = a[k];             a[k + 1] = temp;             break;                      // break statement         }     } } 

, assuming i has value 0, when break gets executed, prevent 2nd loop executing again, , exit loop. result, go again @ 1st loop, new iteration start, i equal 1.

what describe suggests continue keyword, again has loops only, it's not affects if statement directly.

in code above, if continue statement used instead of break one, skip iteration (meaning nothing below continue executed), , move on next iteration of 2nd loop (giving j incremented 1 value). however, in code, there nothing bellow line, wouldn't make difference.


ps:

this comment wrong:

if (a[i]<a[j])  //  if loop  <-- wrong 

an if statement not loop.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -