kumar - 1 year ago 65
C Question

# break in side for loop -after break statement not printing anything outside the for loop

Why doesn't the following for loop does not execute beyond 1st iteration
can anyone help me out regarding this.

The Output:

Enter the Range of Numbers

Enter the First Number: 2

Enter the Last Number: 30

The non-prime numbers between 2 and 30 are:

.start for loop...............i=2

.p....=3

end of for loop: i....=2

.start for loop...............i=3

AFTER THIS THE FOR LOOP DOES NOT EXECUTE ANY MORE. WHY?

``````#include <stdio.h>

int main(void)
{

int start, end, i, remain, k, p, count = 0;
printf("\nEnter the Range of Numbers\n\n");
printf("Enter the First Number: ");
scanf("%d", &start);
printf("Enter the Last Number: ");
scanf("%d", &end);

int flag;
printf("The non-prime numbers between %d and %d are:\n", start, end);
for (i = start; i <= end; i++)
{
printf("\n.start for loop...............i=%d\n", i);
// p = 2;
for (p = 2; p<i;)
{
remain = i%p;
if (remain == 0)
break;
//p++;
}
p++;
printf("\n.p....=%d \n", p);

if (i == p)
//  if(remain==0)
{
printf("%d ", i);
count++;
}
printf("\n end of for loop: i....=%d\n", i);
}
printf("\n............\n");
}
``````

``````    for (p = 2; p<i;)
{
remain = i%p;
if (remain == 0)
break;
//p++;
}
``````

is incomplete.

`p` not changeable in the `for` statement and `p++` in the body is commented. As a result you will probably have infinite loop.

Consider the following change:

``````    remain = 1;
for (p = 2; p<i && remain; p++)
{
remain = i % p;
}
``````

or even (without `remain`)

``````for (p = 2; p < i && i%p; p++);
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download