C语言数组和switch
时间: 2024-02-27 08:48:43 浏览: 30
C语言数组和switch的用法如下:
1. 数组
数组是一种存储相同类型数据的集合。在C语言中,数组的声明方式为:类型 数组名[元素个数]。例如,声明一个长度为5的整型数组可以写成int arr。数组的下标从0开始,可以通过下标访问数组中的元素。例如,访问arr数组中的第3个元素可以写成arr。
2. switch
switch语句是一种多分支选择结构,用于根据不同的条件执行不同的代码块。switch语句的基本语法如下:
```
switch (表达式) {
case 常量1:
代码块1;
break;
case 常量2:
代码块2;
break;
...
default:
代码块n;
break;
}
```
switch语句中的表达式的值会依次与每个case后面的常量进行比较,如果匹配成功,则执行对应的代码块。如果没有匹配成功,则执行default后面的代码块。在每个case后面必须加上break语句,否则会继续执行下一个case中的代码块。
相关问题
c语言switch数组
在 C 语言中,可以使用 switch 语句来根据一个变量的值,执行不同的代码块。如果这个变量只有一些固定的取值,我们可以使用数组来代替这个变量。
举个例子,假设我们有一个数字数组,每个数字代表一个星期几(1 表示星期一,2 表示星期二,以此类推)。我们想根据这个数字来输出对应的星期几的英文名称。我们可以这样写:
```c
#include <stdio.h>
int main() {
int week_day = 3; // 假设今天是星期三
char* week_days[] = {"", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
printf("Today is %s.\n", week_days[week_day]);
return 0;
}
```
这里我们定义了一个 `week_days` 数组,其中下标对应的是数字,数组元素对应的是星期几的英文名称。在程序中,我们使用 switch 语句来处理用户输入的数字,然后使用数组来输出对应的英文名称。
需要注意的是,数组下标从 0 开始,所以我们在定义数组时需要把第一个元素留空(或者用一个无意义的字符串占位)。
c语言数组运算器程序
以下是一个简单的C语言数组运算器程序,它可以对两个数组进行加法、减法和乘法运算,并将结果输出到屏幕上:
```c
#include <stdio.h>
#define MAX_SIZE 100
void add(int a[], int b[], int c[], int n);
void subtract(int a[], int b[], int c[], int n);
void multiply(int a[], int b[], int c[], int n);
int main()
{
int a[MAX_SIZE], b[MAX_SIZE], c[MAX_SIZE];
int n, i, op;
printf("Enter the size of the arrays (up to %d): ", MAX_SIZE);
scanf("%d", &n);
printf("Enter the elements of array a: ");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("Enter the elements of array b: ");
for (i = 0; i < n; i++) {
scanf("%d", &b[i]);
}
printf("Enter the operation to perform (1=add, 2=subtract, 3=multiply): ");
scanf("%d", &op);
switch (op) {
case 1:
add(a, b, c, n);
printf("Result of addition: ");
break;
case 2:
subtract(a, b, c, n);
printf("Result of subtraction: ");
break;
case 3:
multiply(a, b, c, n);
printf("Result of multiplication: ");
break;
default:
printf("Invalid operation.\n");
return 1;
}
for (i = 0; i < n; i++) {
printf("%d ", c[i]);
}
printf("\n");
return 0;
}
void add(int a[], int b[], int c[], int n)
{
int i;
for (i = 0; i < n; i++) {
c[i] = a[i] + b[i];
}
}
void subtract(int a[], int b[], int c[], int n)
{
int i;
for (i = 0; i < n; i++) {
c[i] = a[i] - b[i];
}
}
void multiply(int a[], int b[], int c[], int n)
{
int i;
for (i = 0; i < n; i++) {
c[i] = a[i] * b[i];
}
}
```