#include <stdio.h> int main() { int n; for(n=7;n!=0;n--) { printf ("n = %d",n--);} getchar(); return 0; } | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 2

#include <stdio.h> int main() { int n; for(n=7;n!=0;n--) { printf ("n = %d",n--);} getchar(); return 0; }

Can someone please explain why it is running infinitely? I found this somewhere I don't remember. And also I don't know what's this getchar() doing here!

11th Jan 2019, 3:05 PM
Devasheesh
Devasheesh - avatar
4 Answers
- 1
Next time please don't post the code in the question title. You can paste it in the Code Playground and share the link.
11th Jan 2019, 6:10 PM
Diego
Diego - avatar
+ 8
Because in each iteration, the n-- in printf decrement n once, and then after each iteration, the n-- as step also decrement n by one, so each time is decrement 2. So n is 7, 5, 3, 1, -1, -3,... Forever since n!=0 is not met The getchar() won't get executed as the for loop runs infinitely
11th Jan 2019, 3:25 PM
Gordon
Gordon - avatar
+ 2
.
16th Jun 2021, 9:56 AM
AKHIL MIRYALA
AKHIL MIRYALA - avatar
+ 1
As Gordon up here said n!=0 was not met so it runs forever as your taking 2 away everyone because of n--(you see it 2 times in your code). Also please try at all means to understand, don't rely solely on memory as it always leads to confusion. Then the cycle of you asking these type of questions continue. So take your time and play around with the code then you will understand just by looking :).
12th Jan 2019, 2:57 AM
Pirate_Programmer
Pirate_Programmer - avatar