温馨提示×

c语言如何输出数组元素

小亿
153
2023-12-15 21:07:24
栏目: 编程语言

在C语言中,可以使用循环语句来输出数组的元素。下面是两种常见的方式:

  1. 使用for循环:
#include <stdio.h>

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    int i;

    for (i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

输出结果:

1 2 3 4 5
  1. 使用while循环:
#include <stdio.h>

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    int i = 0;

    while (i < 5) {
        printf("%d ", arr[i]);
        i++;
    }

    return 0;
}

输出结果:

1 2 3 4 5

无论使用for循环还是while循环,都需要使用一个变量来作为数组的索引,利用这个索引来逐个输出数组的元素。

0