数组的赋值与输出:
# include <stdio.h> int main(void) { int a[5] = {1, 2, 3, 4, 5}; //数组名a后跟中括号[],赋值用大括号{},并以逗号隔开。5表示数组a中有5个元素, int i; //其分别用a[0], a[1], a[2], a[3], a[4]表示。注意第一个元素从0开始! for (i=0; i<5; ++i) { printf("a[%d] = %d\n", i, a[i]); } return 0; } /* 输出结果: a[0] = 1 a[1] = 2 a[2] = 3 a[3] = 4 a[4] = 5 Press any key to continue */
练习1:
# include <stdio.h> int main(void) { int a[5]; //数组若不初始化,其值皆为垃圾值。 int i; for (i=0; i<5; ++i) { printf("a(%d) = %d\n", i+1, a[i]); } return 0; }
练习2:
# include <stdio.h> int main(void) { int a[5] = {100}; //只赋值给了a[0]元素。 printf("%d\n", a[0]); return 0; }
数组的人工赋值:
# include <stdio.h> int main(void) { int a[5]; int i; for (i=0; i<5; ++i) { printf("请输入第"); printf("%d", i+1); printf("个数组元素的值:"); scanf("%d", &a[i]); } for (i=0; i<5; ++i) printf("a[%d] = %d\n", i, a[i]); return 0; }
运行示例:
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/lfhappypain/article/details/47187353