#include <stdio.h>
#include <cs50.h>
int main(void)
{
int n;
printf("Please give me an integer greater than zero!\n");
n=GetInt();
if(n<0)
{
printf("You are giving me a bad value!\n");
return 1;
}
for(int i=n-1;i<n;n--)
printf("%d\n",n);
return 0;
}
I would like to know why the loop is not going to infinity if the user enters in a number for n
. Lets say that the user puts in 40 for n
; wouldn't i
always be n-1
, so 39 and n
being 40, then i
becomes 38 when n
becomes 39 and so on — so wouldn't that make an infinite loop?
for(int i=n-1;i<n;n--)
Lets draw a (really short) table for n = 40
:
i | n
-----+-----
39 | 40 i < n ? true
39 | 39 i < n ? false
Thus, we'll exit the loop after the 1st iteration.
Clarification:
I guess you're confused because you think that i
is updated in each iteration, but that's the point - it doesn't, its value is fixed and only n
is changing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With