c语言如何输出数组元素

414
2024/1/1 21:07:24
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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循环,都需要使用一个变量来作为数组的索引,利用这个索引来逐个输出数组的元素。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c语言string的使用方法是什么