how the continue statement works in for loop in C? - c

I have the following code in C:
#include <stdio.h>
int main()
{
int i = 1;
while(i)
{
int index = 0;
printf("while begin\n");
for(index = 0; index < 10; index++)
{
if(index == 2)
{
continue;
}
printf("within for\n");
}
printf("while end\n");
}
printf("returned from while");
}
does the continue effect the for loop or the while loop directly? looks like once the continue is called, for loop will start to run from the beginning, should not the while loop start to run from the beginning?

continue will cause the remaining portion of the enclosing for or while loop body to be skipped. In your case, the for is the "enclosing" loop of continue and the while loop is the "enclosing" scope of the for loop.
According to (unofficial) documentation
The continue statement causes a jump, as if by goto to the end of the
loop body (it may only appear within the loop body of for, range-for,
while, and do-while loops).

To understand what continue is you should know what break does too.
So the following peace of code shows you how break and continue works:
#include <stdio.h>
int main(void){
int hours = 10;
int i=0;
for(i=0;i<hours;i++){
if(i==5){
break;
}
printf("%d ",i);
}
return 0;
}
Output:
0 1 2 3 4
As you can see, when i reaches 5 (i==5) the loop breaks.
Now let's take a look of what does continue if we replace break using the same code:
#include <stdio.h>
int main(void){
int hours = 10;
int i=0;
for(i=0;i<hours;i++){
if(i==5){
continue;
}
printf("%d ",i);
}
return 0;
}
Output:
0 1 2 3 4 6 7 8 9
As you can see it doesn't leave the loop (like when using break), instead when i reach 5 (i==5) ignore the rest of the body making the loop to start over from the point where i was last time seen.
The number 5 *is missing.

The simplest way to think about it is to say : "it goes back to the top of the loop" anything AFTER the continue won't be processed.

Related

2 while loops in a function in C

Is it possible to run 2 while loops in the same function?
Only one of the while loops works. If I remove the first the one, the second one will work and if I remove the second one, the first one will work.
#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "results.txt"
void analyseText(int character[], int i, FILE *fptr, int *sum, int a)
{
while ((i = fgetc(fptr)) != EOF)
{
if (i >= 'a' && i <= 'z')
character[(i - 'a')]++;
if (i >= 'A' && i <= 'Z')
character[(i - 'A')]++;
for (int i = 0; i < 26; i++)
{
printf("%c: %d\n", i + 'a', character[i]);
}
while (1)
{
int result = fscanf(fptr, "%d", &a);
if (result == EOF) {
break;
}
else if (result == 1) {
*sum += a;
}
else {
fscanf(fptr, "%*c");
}
}
}
}
I've ran your program and it seems the second while loop terminates the function. The second while loop will read the characters from the file and will do so until it reach the end, then will exit. Both while loop executes, but the first one executes only once and the second executes till will reach the end of the file. Maybe it is a logic bug there?
Also, are you trying to read some numbers in the second loop, the result will never pe 1 if there are only characters in the file.
You have an (almost) infinite loop inside an (almost) infinite loop, with just about the same stop condition for both.
One of them will run "forever" and when it triggers the stop condition the other will also stop, giving the appearance of just one of the loops running.
2 loops
enter infinite loop1
do some stuff one once
enter infinite loop2
do some stuff two "forever"
when you remove the inner loop
enter infinite loop1
do some stuff one "forever"
when you remove the outer loop
enter infinite loop2
do some stuff two "forever"

Is having a while loop inside a for loop considered a nested while loop?

Can having a while loop inside a for loop be considered a nested while loop?
How can I do this same problem using do while?
#include <stdio.h>
#define NUMS 3
int main() {
// insert code here...
int highVal;
int lowVal;
int i;
printf("---=== IPC Temperature Analyzer ===---\n");
for (i=1;i<=NUMS;i++){
printf("Enter the high value for day %d: ",i);
scanf("%d",&highVal);
printf("Enter the low value for day %d: ",i);
scanf("%d",&lowVal);
while((highVal < lowVal)||(highVal >= 41 || lowVal <= -41)){
printf("Incorrect values,temperature must be in the range -40 to 40,high must be greater than low\n");
i--;
highVal=1;
lowVal=0;
}
}
return 0;
}
I am getting the results I need to be getting but the assignment calls for using a nested while loop (or do while) as well as for loop to prompt the user.
Can having a while loop inside a for loop be considered a nested while loop?
No, it'd just be a nested loop, the same as this would be a nested loop:
foo:
z = baz();
x++;
bar:
y++;
if(x < 100) goto bar;
if(y < 100) goto foo;
Note that you can convert a for() into a while by separating out the pieces. For example, this:
for (i=initial; i<=MAX; i++) {
do_something();
}
..is equivalent to this:
i=initial;
while (i<=MAX) {
do_something();
i++;
}
In a similar way you can convert while() into if and goto fairly easily (and therefore can convert for() into if and goto too). For example, the previous for() and while() examples are equivalent to this:
i=initial;
start:
if( !(i<=MAX) ) goto end;
do_something();
i++;
goto start;
end:

I don't understand why this loop doesn't execute it's block

While playing with code in the following program I assumed that the star should be printed on screen but it exits the loop without printing anything. Why at least one star is not printing when it enters the loop?
#include<stdio.h>
void main()
{
int i,sum_sq=0, sq_sum=0;
for(i=0;i<=10&&(sum_sq+=i*i)&&(sq_sum+=i);++i)
{
printf("*");
}
printf("%d",sq_sum*sq_sum - sum_sq);
}
((i<=10)&&(sum_sq+=i*i)&&(sq_sum+=i)) this condition is false. the output
true && 0 && 0 = false;
finally, compiler identifiesfalse. So the star is printed. U try mine below code.
int i,sum_sq=0, sq_sum=0;
for(i=0;((i<=10)&&(sum_sq+=(i+1)*(i+1))&&(sq_sum=i+2));++i)
{
sum_sq += i*i;
printf("%d ",sum_sq);
sq_sum+=i;
printf("%d ",sum_sq);
printf(" *\n");
}
for loop every time if condtion true or false.

a c iterations while skipping given values in a do while loop

I have a very simple problem in C. I am trying to write a simple program that outputs multiples of 10 between 10 and 100, inclusive (ie: on the closed interval [10,100]) that skips 30 and 70 and outputs the values vertically.
Here is my code:
#include<stdio.h>
main()
{
int i=10;
do {
if(i==30||i==70)
continue;
printf("\n %d",i);
i++;
} while(i<100);
return 0;
}
The program stops at 29 skips 30 and continues into a never ending loop. What is wrong?
The problem is that when you hit the if statement, you are now skipping the increment of i. So you never reach 100!
#include<stdio.h>
main()
{
int i=10;
do {
if(i==30||i==70)
continue; //!!!! This will skip the i increment
printf("\n %d",i);
i++;
} while(i<100);
return 0;
}
I recommend a for loop:
main()
{
for (i = 10; i < 100; i++) {
if(i==30||i==70)
continue; // The for loop will do the i++ on the "continue"
printf("\n %d",i);
}
return 0;
}
mbratch correctly pointed out your problem, but you might want to consider a for loop for this sort of thing. It would have prevented this particular problem, since the increment is automatic.
I won't do the whole thing for you, since you're obviously trying to learn, but this ought to get you started:
for (i=0; i<100; i+= 1)
You'll have to change some of the numbers in that line, but hopefully you'll understand what they mean when you change them.
When i reaches 30 the continue statements moves back to the start of the loop.
And so the loop continues endlessly as i is not incremented from this point.
Your code's doing exactly what it's written to do. The continue skips the increment instruction, so the value hits 30 and gets stuck there. Move the increment to the start of the loop body, or better yet, use a for instead of a while.
Don't use continue. Instead print out the value as long as != to 30 and 70. Also iterate by 10 instead of 1 to output multiples 10.
#include<stdio.h>
main()
{
int i = 10;
do
{
if (i != 30 && i != 70)
printf("\n %d", i);
i += 10;
}
while (i <= 100); // if you want to print 100
return 0;
}
Output:
10
20
40
50
60
80
90
100
Use while (i <= 100); if you need to also print 100.
It loops forever because you continue but don't increment i.
if(i==30||i==70) {
i++;
continue;
}
or you could use a for loop like so,
#include<stdio.h>
int main()
{
int i=10;
for (; i < 100; i++)
{
if(i==30 || i==70) {
continue;
}
printf("\n %d",i);
}
return 0;
}
The reason is that i is never incremented after 30 inside the body of do..while. You'd need to increment it.
if (i == 30 || i == 70){
i++;
continue;
}

what is wrong with the loops

I am solving a problem of adding the last digits of numbers lying between a range (for ex. between 'm' and 'n' where m < n).I have coded this
#include <stdio.h>
int main()
{
int t=0;
long int m=0,n=0,num=0,sum=0,lsum=0,i=0;
scanf("%d",&t);
while(t--){
scanf("%ld%ld",&m,&n);
i=m;
while(i<=n){
while(i!=0){
num=i%10;
i/=10;
}
lsum=lsum+(sum%10);
i++;
}
}
printf("\n%ld",lsum);
return 0;
}
Here t=No of Test Cases. m and n is the range. I don't know why it is running infinitely in the terminal. I am using gcc(4.3.2) compiler.How can I optimize it for speed ,or is it the case where the while conditions are never terminated, but why?
You are dividing the i: i/=10. This means that i is always set back to 1 at the end of the loop. You should use a temporary variable for the dividing.
Like this:
while(i<=n){
int temp = i;
while(temp !=0){
num=temp %10;
temp /=10;
}
lsum=lsum+(sum%10);
i++;
}
P.S. There are many other errors in your code. But they are not connected with the infinite looping.
There is an infinite loop int the code :
while(i<=n)
{
while(i!=0)
{
num=i%10;
i/=10;
}
lsum=lsum+(sum%10);
i++;
}
the first while(1<= n) is always true : the second loop makes i = 0 or i = 1 !

Resources