Why isn't the for loop being executed even once in this code? Even when k=0 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why isn't the for loop being executed even once in this code? Even when k=0

What does the goto statement really do here? #include <stdio.h> int main() { int i = 0,k; if(i==0) goto label; for(k=0;k<3;k++) { printf("hi\n"); label: k=printf("%03d",i); } return 0; }

2nd May 2020, 11:05 AM
Priti Barman
Priti Barman - avatar
7 Answers
+ 2
When label executes k=000 so Loop becomes false and doesn't runs but 000 will be printed as it should Try changing %03d to %d and it will run the loop infinitely as 0hi ,0hi ..
2nd May 2020, 11:43 AM
Abhay
Abhay - avatar
+ 2
Yup looks like I don't know c so I can't tell how goto works but seems like label is also executed in for loop everytime , otherwise it would have just print for %d 0hi hi hi hi 0hi hi hi hi But that's not happening
2nd May 2020, 2:30 PM
Abhay
Abhay - avatar
+ 1
Int i= 0 that was the initialized value. Check for the condition If(i==0) Goto label; That's why it's not entering the loop. Try changing this value. Int i= something else...not zero.,k;
2nd May 2020, 11:14 AM
Vishal Srivastava
Vishal Srivastava - avatar
+ 1
Vishal Srivastava got that but after the label is executed i. e. after k is printed shouldn't it check if k<3 or not and print "hi"
2nd May 2020, 2:23 PM
Priti Barman
Priti Barman - avatar
+ 1
Because k=0 everytime label runs for %d
2nd May 2020, 2:24 PM
Abhay
Abhay - avatar
0
Abhay and again why does it run infinitely. Why not till k <3?
2nd May 2020, 2:24 PM
Priti Barman
Priti Barman - avatar
0
Abhay so the label statement gets executed even when there's no goto statement inside the loop?
2nd May 2020, 2:26 PM
Priti Barman
Priti Barman - avatar