简体   繁体   English

理解 C 中的数组

[英]Understanding the arrays in C

I'm new to C and need some help to understand how this piece of code works.我是 C 新手,需要一些帮助来理解这段代码的工作原理。 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.但我不明白为什么我需要两个“计数器”( ij )来做到这一点。 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:如果您愿意,也可以通过执行以下操作将i用于第二个循环:

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.第一个循环(在您的代码中使用i )将 5 个整数读入数组 A。在第一个循环结束后,您的数组 A 保存了 5 个 int 值,您可以随意使用这些值。 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.所以你要做的是使用一个循环来遍历数组元素并将值一个一个地打印到屏幕上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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