Home > Blockchain >  c-fill a one dimensional array with for loop
c-fill a one dimensional array with for loop

Time:10-16

I can understand the first solution.But in the second solution i am confused about the way scanf, accept 4 values at the same time and apply them to the for loop.

//first solution
#include <stdio.h>

int main() {
    int pin[4],i;
    
    for(i=0; i<4; i  ){
        printf("Give value: ");
        scanf("%d", &pin[i]);
    }
  
    return 0;
}
//second solution
#include <stdio.h>

int main() {
    int pin[4],i;
    
    printf("Give 4 values: ");
    
    for(i=0; i<4; i  ){
        
        scanf("%d", &pin[i]);
    }
  
    return 0;
}

CodePudding user response:

The difference is only that in the first example there is a printf that asks you for the input values at every iteration of the cycle while in the first example there is a printf (only one) before the cycle.

The operation that matters (the scanf) is exactly the same in the two examples.

CodePudding user response:

The scanf commamd does not read four values at the same time.

This is an example of a loop: a piece of code that does the same thing multiple times.

for(i=0; i<4; i  ){
    
    scanf("%d", &pin[i]);
}

What the for statement does is, first initialize i to zero, then check that i is less than four, then, execute the code within its curly braces. That's the scanf statement, which attempts to read an integer to the address specified by &pin[i]. Since i is zero, that means, the address of pin[0], which is the first element of the array pin.

After the scanf executes (and whether or not it succeeds, which is something you may want to look into) the for statement increments the value of i, checks that it is still less than four, and executes the block of code between the braces again. This time, the scanf statement attempts to read to pin[1].

The loop executes two more times, potentially storing integers in pin[2] and pin[3] before terminating just after incrementing i to 4.

  • Related