Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my loop not going infinite

Tags:

c

cs50

#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?

like image 613
Patrick Tulej Avatar asked Nov 28 '22 03:11

Patrick Tulej


1 Answers

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.

like image 65
Maroun Avatar answered Jan 09 '23 04:01

Maroun