How does a program run in c?

Viewed 92

I'm just learning programming with c. I wrote a program in c that had a bug in the body of the while loop I did not put {}. The program is as follows, but the question that came to me later is how to run the program in c? Why does error 2 not print while it is before the start of the while loop? If the c language is a compiler, why is it that the error of the whole program is not specified first, and up to line 15 the program is executed without any problems?

int main()
{

    int n ,k;
    float d ;
    printf("please write your arithmetic sequence sentences ");
    scanf("%d",&n);
    printf("\n");
    printf("please write your common differences");
    scanf("%d",&k);
    printf("\n");
    printf("please write your initial element ");
    scanf("%f",&d);
    printf("error 1");
    printf("\n");
    printf("error 2");
    printf("number \t sum");
    printf("erorr 3");
    int i = 0;
    int j = 0;
    int sum = 0;
    while (i < n)
        j = d + i*k;
        sum += j;
        printf("%d\t%d",j,sum);
        i++;

    return 0;
}
2 Answers

Firstly, the program enters an infinite loop:

while (i < n)
    j = d + i*k;

Since the values of i and n do not change, the condition never becomes false.

Secondly, the printing sequence:

printf("error 2");
printf("number \t sum");
printf("erorr 3");

does not display a line break at the end. The output is buffered (stored internally) waiting for the line break to be printed, which, naturally, never happens. Add \n at the end of "erorr 3" to see the difference.

#include <stdio.h>
int main()
{
    int n ,k;
    int i = 0;
    int j = 0;
    int sum = 0;
    float d ;

    // If the given values are not an integer, it wouldn't continue the sequence and end as an "error"
    printf("please write your arithmetic sequence sentences ");
    if(scanf("%d",&n)){
        printf("please write your common differences");
        if(scanf("%d",&k)){
            printf("please write your initial element ");
            if(scanf("%f",&d)){
                printf("Number \tSum\n");
            } else {
                printf("error");
            }
        } else{
            printf("error");
        }
    } else{
        printf("error");
    }

    // This is where the values get solved
    // You also forgot to add {} in your while statement
    while (i < n){
        j = d + i*k;
        sum += j;

        printf("%d\t%d",j,sum);
        i++;
    }

    return 0;
}
Related