Break condition in iteration [duplicate] - c

This question already has answers here:
"break;" out of "if" statement?
(5 answers)
Closed 5 years ago.
Following is the insertion sort code i 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 the Array:-\n");
for (i = 0; i <= 9; i++)
scanf("%d", &a[i]);
for (i = 0; i <= 9; i++) // 1st for loop
{
temp = a[i];
for (j = 0; j <= i - 1; j++) // 2nd for loop
{
f = 0;
if (a[i]<a[j]) // if loop
{
for (k = i - 1; k >= j; k--) // 3rd for loop
a[k + 1] = a[k];
a[k + 1] = temp;
break; // break statement
}
}
}
printf("\nThe sorted array is:-\n");
for (i = 0; i <= 9; i++)
printf("%d\n", a[i]);
getch();
}
I was told that break statement stops that particular instant(nth time of currently running innermost loop & initiates its next instance ( n+1 time). So here I am confused that whether the break statement here will stop the 3rd loop or if condition. I was however told that it will affect the second loop.
Can anyone here please tell me on which for loop it is going to have its effect.

The break will stop the loop, not the if statement.
So here:
for (i = 0; i <= 9; i++) // 1st for loop
{
temp = a[i];
for (j = 0; j <= i - 1; j++) // 2nd for loop
{
f = 0;
if (a[i]<a[j]) // if STATEMENT
{
for (k = i - 1; k >= j; k--) // 3rd for loop
a[k + 1] = a[k];
a[k + 1] = temp;
break; // break statement
}
}
}
, assuming that i has the value 0, when the break gets executed, it will prevent the 2nd loop from executing again, and you will exit that loop. As a result, you will go again at the 1st loop, where a new iteration will start, with i equal to 1.
What you describe suggests the continue keyword, which again has to do with loops only, it's not something that affects an if statement directly.
In the code above, if a continue statement was used instead of a break one, then you would skip that iteration (meaning that nothing below continue would be executed), and move on with the next iteration of the 2nd loop (giving j its incremented by one value). However, in your code, there is nothing bellow that line, so it wouldn't make any difference.
PS:
This comment is wrong:
if (a[i]<a[j]) // if loop <-- WRONG
An if statement is not a loop.

Related

Which Statement will decide the termination of while loop in the given code?

while(1)
{
k = j + d;
if (k >= n)
k = k - n;
if (k == i)
break;
arr[j] = arr[k];
j = k;
}
I was going through "Juggling Algorithm" for Array Rotation and saw this piece of code there. Now i am confusing about which statement of code will terminate while loop.Is while(1) here making condition true for ever ?
It will will run forever unless it hits the break statement - which will exit the loop and in this case this happens when (k == i)
See here

For loop in C and how it works?

#include <stdio.h>
int main() {
int i, j;
for (i = 2; i < 20; i++) {
for (j = 2; j <= (i/j); j++) {
if (!(i%j)) break;
}
if (j > (i/j)) printf("%d\n", i);
}
return 0;
}
I am a Beginner at C and trying to understand how the for loop works. My question is at the 4th iteration, the condition in the nested loop will return TRUE
(j < (i/j)) // 2 <= 4/2
and the first if statement will also return TRUE because of NOT operator
(!(i%j)); // 4/2 = !(0)
so now the value of j = 3 because of incrementation, but why the second if statement did not print the output if it is TRUE?
(j > (i/j)); // 3 > 4/3
You're breaking out of the loop before j is incremented, so j is still 2, not 3
A break statement ends its nearest enclosing loop prematurely. Everything after it (and that includes the third statement of the for loop), will not occur.
So j is still 2 when the condition for printing is checked, like Mark answered.

continue statement inside nested for loop

I don't understand what exactly does the continue statement inside this for loop do. How is code any different if I remove it? Which lines does it skip if it's placed at the end of for loop?
int sum = 0, i, j, stop = 0;
for( i = 1; i <= 5 && !stop; i++)
{
for( j = 1; j <= 5 ; j++)
{
if (j%4 == 0)
{
stop = 1;
continue;
}
sum += i+j;
}
}
printf("%d\n", sum);
If you run this program the sum is going to be 15, and if you comment out countinue line then it's going to be 20.
It would be more clear if you would format the code. Let's consider the inner loop
for( j = 1; j <= 5 ; j++)
{
if ( j % 4 == 0)
{
stop = 1;
continue;
}
sum += i+j;
}
Thus as you see if j % 4 == 0 then statement
sum += i+j;
is skipped.
As for the code in whole then it has no any sense.:) It is a silly code.
In fact your code is equivalent to the following
int sum = 0, j;
for( j = 1; j <= 5 ; j++ )
{
if ( j != 4 ) sum += j + 1
}
printf("%d\n", sum);
So you will get sum 2 + 3 + 4 + 6 that is equal to 15.:)
The continue statement skips the remainder of the current loop. In the case of nested loops, it skips to the next iteration of the innermost loop.
In this case, if you didn't continue, you would execute sum += i+j; in every iteration, where it appears you only want it sometimes.
That being said, this is a very awkward loop to begin with. The whole stop variable is rather ill conceived from the get-go anyway.
The continue statement is used to start the next iteration of a loop,skipping everything in the loop,after the continue. In your case,once the execution of the program reaches the continue statement,then the next iteration of your inner loop starts,skipping whatever there was after the continue. It skips sum += i+j; as it is after the continue and the sum will not be added when j is 4 as j%4 will be 0. This is why you get 20 when you comment the continue and 15 when you uncomment it.
P.S: Your outer loop will execute only once as stop will be changed inside the if in your inner loop.
continue causes the enclosing for loop to begin the next iteration. As a more basic example, take the following code:
for(int i = 0; i < 50; i++)
{
if(i % 2 == 1) // If it's odd
continue;
printf("%d\n", i);
}
In this case, the continue statement will cause the for loop to immediately begin the next iteration if i is odd, hence this code will print the even numbers between 0 and 50.
int sum = 0, i, j, stop = 0;
for( i = 1; i <= 5 && !stop; i++)
{
for( j = 1; j <= 5 ; j++)
{
if (j%4 == 0) <===== is j divisible by 4 ?
{
stop = 1; <=== set stop flag, will continue for J loop
but stop next I loop and end the routine
continue; <==== skip the rest of the J loop for this itteration
}
sum += i+j;
}
}
printf("%d\n", sum);
http://msdn.microsoft.com/en-us/library/0ceyyskb.aspx explains the continue statement

How can I print a x by x matrix in C?

int main() {
char gameArea[][8] = {
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'}};
int i = 0; int j = 0;
while (i<8) {
while (j<8) {
printf("%c",gameArea[i][j]);
j++;
}
i++;
}
return 0;
}
Output:
XXXXXXXX
Process returned 0 (0x0) execution time : 0.563 s
Press any key to continue.
In theory, the i would run through the columns, and print all of it, but that's not what happened. I thank you very much for your help.
I think you want a for-loop:
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
printf("%c", gameArea[i][j]);
}
printf("\n");
}
This is the progression of your loops:
i = 0 and j = 0, print X and increment j.
...
i = 0 and j = 7, print X and increment j.
Since j = 8, stop j-loop and increment i.
i = 1 but j is still 8 as we cannot perform j-loop, so increment i.
...
i = 7 but j is still 8 as we cannot perform j-loop, so increment i.
Now i = 8 so stop i-loop.
What you want to do is after the j-loop when you increment i you also want to reset j to 0. Along with that, you want to print a new-line for the next row otherwise you'll end up with 64 consecutive Xs.
Using a for-loop:
for (/*initialization*/; /*condition*/; /*increment*/) {
/*loop body*/
}
Is a short-cut for doing this with a while-loop:
/*initialization*/
while(/*condition*/) {
/*loop body*/
/*increment*/
}
You need to set j back to zero after each inner loop
printf("%c",gameArea[i][j]);
j++;
}
j = 0;
i++;
But for loop is more suitable for your task, as stated in other answers.
After the first while (j<8) loop, nothing resets j to 0, similarly for i, so the loops only run once, hence only one row is printed.
Consider using for loops:
for (int i = 0; i < 8; i++)
Also, did you try debugging the code, i.e. setting breakpoints and stepping through the execution?
The j counter needs to be initialised at the start of each i loop.
What's happening is j is looped once, at the end j is 8 so the j loop is only iterated once.
while (i<8) {
int j = 0;
while (j<8) {
printf("%c",gameArea[i][j]);
j++;
}
i++;
}
Insert a j=0:
while (i<8) {
j = 0;
while (j<8) {
printf("%c",gameArea[i][j]);
j++;
}
i++;
}
Without it your inner loop will be executed only once, since j never changes after the first run and the loop condition is not met again.
As other users suggested, you might want to use for loops with sort of thing.
int i = 0; int j = 0;
while (i<8) {
while (j<8) {
printf("%c",gameArea[i][j]);
j++;
}
i++;
printf("\n")
}
You need to reset j to 0 at the beginning of the first while loop, so that on each iteration, you can still loop through the inner one. Otherwise, once j is equal to 8, the inner loop will not be entered anymore.

What is Innermost loop in imperfectly nested loops?

Helo, I'm a bit confused about the definition of an inner loop in the case of imperfectly nested loops. Consider this code
for (i = 0; i < n; ++i)
{
for (j = 0; j <= i - 1; ++j)
/*some statement*/
p[i] = 1.0 / sqrt (x);
for (j = i + 1; j < n; ++j)
{
x = a[i][j];
for (k = 0; k <= i - 1; ++k)
/*some statement*/
a[j][i] = x * p[i];
}
}
Here, we have two loops in the same nesting level. But, in the second loop which iterates over "j" starting from j+1, there is a again another nesting level. Considering the entire loop structure, which is the inner most loop in the code ?
Both j loops are nested inside i equally, k is the inner most loop
Lol I don't know how to explain this so i'll give it my best shot I recommend using a debugger! it may help you so much you won't even know
for (i = 0; i < n; ++i)
{
//Goes in here first.. i = 0..
for (j = 0; j <= i - 1; ++j) {
//Goes here second..
//Goes inside here and gets stuck until j is greater then (i- 1) (right now i = 0)
//So (i-1) = -1 so it does this only once.
/*some statement*/
p[i] = 1.0 / sqrt (x);
}
for (j = i + 1; j < n; ++j)
{
//Goes sixth here.. etc.. ..
//when this is done.. goes to loop for (i = 0; i < n; ++i)
//Goes here third and gets stuck
//j = i which is 0 + 1.. so, j == 1
//keeps looping inside this loop until j is greater then n.. idk what is n..
//Can stay here until it hits n.. which could be a while.
x = a[i][j];
for (k = 0; k <= i - 1; ++k) {
//Goes in here fourth until k > (i-1).. i is still 0..
//So (i-1) = -1 so it does this only once
/*some statement*/
a[j][i] = x * p[i];
}
//Goes here fifth.. which goes.... to this same loop!
}
}
I'd say that k is the inner-most loop, because if you count the number of loops required to reach it from the outside, it's three loops, and that's the most out of all four of the loops in your code.

Resources