如何在 C 语言中对数组执行算术运算?
数组是具有单个名称存储的一组相关数据项。
例如,int student[30]; //student 是一个数组名称,它使用一个变量名称保存了 30 个数据项的集合
数组操作
查找 − 用于查找是否出现特定元素
排序 − 它帮助以升序或降序排列数组中的元素。
遍历 − 它按顺序处理数组中的每个元素。
插入 − 它帮助在数组中插入元素。
删除 − 它帮助删除数组中的元素。
在数组中执行所有算术运算的逻辑如下 −
for(i = 0; i < size; i ++){
add [i]= A[i] + B[i];
sub [i]= A[i] - B[i];
mul [i]= A[i] * B[i];
div [i] = A[i] / B[i];
mod [i] = A[i] % B[i];
}程序
以下是针对数组进行算术运算的 C 程序 −
#include<stdio.h>
int main(){
int size, i, A[50], B[50];
int add[10], sub[10], mul[10], mod[10];
float div[10];
printf("enter array size:
");
scanf("%d", &size);
printf("enter elements of 1st array:
");
for(i = 0; i < size; i++){
scanf("%d", &A[i]);
}
printf("enter the elements of 2nd array:
");
for(i = 0; i < size; i ++){
scanf("%d", &B[i]);
}
for(i = 0; i < size; i ++){
add [i]= A[i] + B[i];
sub [i]= A[i] - B[i];
mul [i]= A[i] * B[i];
div [i] = A[i] / B[i];
mod [i] = A[i] % B[i];
}
printf("
add\t sub\t Mul\t Div\t Mod
");
printf("------------------------------------
");
for(i = 0; i <size; i++){
printf("
%d\t ", add[i]);
printf("%d \t ", sub[i]);
printf("%d \t ", mul[i]);
printf("%.2f\t ", div[i]);
printf("%d \t ", mod[i]);
}
return 0;
}输出
当执行以上程序时,将产生以下结果 −
Run 1: enter array size: 2 enter elements of 1st array: 23 45 enter the elements of 2nd array: 67 89 add sub Mul Div Mod ------------------------------------ 90 -44 1541 0.00 23 134 -44 4005 0.00 45 Run 2: enter array size: 4 enter elements of 1st array: 89 23 12 56 enter the elements of 2nd array: 2 4 7 8 add sub Mul Div Mod ------------------------------------ 91 87 178 44.00 1 27 19 92 5.00 3 19 5 84 1.00 5 64 48 448 7.00 0
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP