+ 2

Why this for loop is not working?

i am not able to understand why this for loop is not working... https://code.sololearn.com/cThUJMpoWxq2/?ref=app

4th Apr 2018, 5:16 PM
Abhishek Singh Negi
Abhishek Singh Negi - avatar
5 Answers
+ 5
Abhishek Singh Negi for(variable; condition; increment/decrement){ } for(int i = 10; i ==1; i--){ } int i is declared as 10; the condition to run the loop is when i == 1; As i is 10 it does not equal 1 so it's false; so i-- never runs. For the for loop to run at least once the condition must be true.
4th Apr 2018, 5:42 PM
Lord Krishna
Lord Krishna - avatar
+ 4
Because the condition of your for loop is false it never runs so i is never reduced. Change i == 1 to i >=1 in for loop #include <stdio.h> int main() { for(int i=10;i>=1;i--) printf("%d",i); return 0; }
4th Apr 2018, 5:28 PM
Lord Krishna
Lord Krishna - avatar
+ 2
Lord Krishna isn't i==1 a condition statement.I am getting a little confused here.The syntax of for loop goes like first initialization than condition and than increment.
4th Apr 2018, 5:37 PM
Abhishek Singh Negi
Abhishek Singh Negi - avatar
+ 2
yes i==1 is a condition, but you start with i=10. The loop would run 1 time if i starts at 1, then i would get 0 and the loop breaks.
4th Apr 2018, 5:41 PM
Alex
Alex - avatar
+ 2
rami0x1 I think using i!=1 will solve the problem i was having.Thanx for you help guys.Lord Krishna Alex
4th Apr 2018, 5:48 PM
Abhishek Singh Negi
Abhishek Singh Negi - avatar