Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How did this line repeatedly got its values even without using any loops?

Question 1: How did this line repeatedly got its values even without using any loops?
Question 2: How did z get its values?
I just saw this program on an app but I simplified it to understand the logic clearer but I still can’t. I am new to c and programming as a whole. Please help me.

# include <stdio.h>

int main()
{
    int x, y, z, sum = 0;

    printf("Enter 4 integers:\n"); // Question 1

    for (y=1; y<=4; y++)
    {
        scanf("%d", &z); // Question 2
        sum = sum + z;
    }

    printf("The sum of the entered integers is = %d\n", sum);
    return 0;
}

Output:

Enter 4 integers:
1
2
3
4
The sum of the entered integers is = 10

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

printf is a statement that prints the string of text you have entered into the terminal. So when you type

printf("Enter 4 integers:\n");

It is not actually accepting any input from the user, it prints "Enter 4 integers:" and then a newline character which causes the terminal to begin printing any further characters to the next line in the terminal

In your for loop

for (y=1; y<=4; y++)
{
    scanf("%d", &z); // Question 2
    sum = sum + z;
}

scanf accepts the user input and stores it in the address for variable z. Each time the program reaches this line of code it will halt execution of the program and await user input.

It then adds it to sum, which was initialized earlier in your program as zero.

So with your input of 1,2,3,4 that adds up to 10 and is then printed in your final printf statement.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading