简体   繁体   中英

Understanding the arrays in C

I'm new to C and need some help to understand how this piece of code works. I know that it reads the values that the user writes, puts them into an array, and then prints them out.

But I don't understand why I need two "counters" ( i and j ) to do this. Can someone help me to figure it out?

#include<stdio.h>
int main ()
{                               
int A[5];
int i=0;
int j=0;

while (i < 5)                
i++;
printf("Enter your %d number\n", i);
scanf("%d", &A[i]);
}

while (j < 5)               
{
j++;
    printf ("\n%d\n", A[j]);
}
}

You don't need it, you can simply reset the first and reuse it. However you must increment your index only after having using it otherwise you will overflow the limit of the array :

#include<stdio.h>
int main ()
{                               
    int A[5];
    int i=0;


    while (i < 5) {               
        printf("Enter your %d number\n", i);
        scanf("%d", &A[i]); // the last must be 4 not 5
        i++;                //<== increment here
    }

    i=0;
    while (i < 5)               
    {
        printf ("\n%d\n", A[i]); //idem
        i++;
    }
}

Technically, what you have aren't two counters, but two loops. If you wanted, to, you could just reuse i for the second loop as well, by doing something like this:

while (i < 5)                
i++;
printf("Enter your %d number\n", i);
scanf("%d", &A[i]);
}

i = 0;
while (i < 5)               
{
i++;
    printf ("\n%d\n", A[i]);
}

As for why you have two loops, the reason is simple. The first loop (using i in your code), reads the 5 integers into the array A. After the first loop concludes, your array A holds the 5 int values, which you could've used however you wanted. In your case, you want to print those values. So what you do is use a loop for looping over the array elements and printing the values to the screen, one by one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM