Home > Mobile >  Why is the 'if' statement used in this code?
Why is the 'if' statement used in this code?

Time:03-19

#include <stdio.h>

int sum(int n){
    int sum = n;

    while(n>0){
        sum  = n;
        n /= 10;
    }
    return sum;
}

int main(){

    int check,i;
    int arr[10001];

    for(i=1;i<10001;i  ){
        check = sum(i);
        if(check<10001) // this code 
            arr[check] = 1;

    }
    for(i=1;i<10001;i  ){
        if(arr[i]!=1)
            printf("%d\n",i);
    }
}

I don't understand why 'if(check<10001)' used

CodePudding user response:

Check out this last 10 outputs made without the if(check<10001) arr[check] = 1;: 9990 9991 9993 9994 9995 9996 9997 9998 9999

On the other hand, this one contains if(check<10001) arr[check] = 1;: 9903 9914 9925 9927 9938 9949 9960 9971 9982 9993

I assume that the second output is the one you wish to get. As you see, the sum() function would not work as intended without if(check<10001) arr[check] = 1; as the "stopper", otherwise it will print every check calculated in the i loop.

  •  Tags:  
  • c
  • Related