和数组有关的选择结构和循环结构程序设计并运用if else语句、switch case语句、for语句、while语句及do while语句
时间: 2023-06-14 09:06:42 浏览: 75
以下是一个使用不同选择和循环结构的数组程序设计:
```c
#include <stdio.h>
int main() {
int arr[5] = {3, 7, 2, 1, 8};
// if-else语句
if(arr[0] < arr[1]) {
printf("%d is less than %d\n", arr[0], arr[1]);
}
else {
printf("%d is greater than or equal to %d\n", arr[0], arr[1]);
}
// switch-case语句
switch(arr[2]) {
case 1:
printf("The value at index 2 is 1\n");
break;
case 2:
printf("The value at index 2 is 2\n");
break;
case 3:
printf("The value at index 2 is 3\n");
break;
default:
printf("The value at index 2 is not 1, 2, or 3\n");
}
// for循环
printf("The array contains: ");
for(int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// while循环
int i = 0;
while(i < 5) {
printf("The value at index %d is %d\n", i, arr[i]);
i++;
}
// do-while循环
int j = 0;
do {
printf("The value at index %d is %d\n", j, arr[j]);
j++;
} while(j < 5);
return 0;
}
```
输出:
```
3 is less than 7
The value at index 2 is 2
The array contains: 3 7 2 1 8
The value at index 0 is 3
The value at index 1 is 7
The value at index 2 is 2
The value at index 3 is 1
The value at index 4 is 8
The value at index 0 is 3
The value at index 1 is 7
The value at index 2 is 2
The value at index 3 is 1
The value at index 4 is 8
```
阅读全文