您所在的位置:首页 - 百科 - 正文百科

c语言数据求和程序

北玉
北玉 05-20 【百科】 272人已围观

摘要**Title:C语言编程:表格按列求和**```c#include#defineROWS3#defineCOLS4//Functiontocalculatethesumofeachcolumnina

Title: C语言编程:表格按列求和

```c

include

define ROWS 3

define COLS 4

// Function to calculate the sum of each column in a 2D array

void calculateColumnSum(int arr[ROWS][COLS]) {

int sum[COLS] = {0}; // Initialize an array to store column sums

// Iterate through each column

for (int j = 0; j < COLS; j ) {

// Iterate through each row of the current column

for (int i = 0; i < ROWS; i ) {

// Add the current element to the sum of the current column

sum[j] = arr[i][j];

}

}

// Display the sums of each column

printf("Sum of each column:\n");

for (int j = 0; j < COLS; j ) {

printf("Column %d: %d\n", j 1, sum[j]);

}

}

int main() {

int arr[ROWS][COLS] = {{1, 2, 3, 4},

{5, 6, 7, 8},

{9, 10, 11, 12}};

// Display the original array

printf("Original Array:\n");

for (int i = 0; i < ROWS; i ) {

for (int j = 0; j < COLS; j ) {

printf("%d ", arr[i][j]);

}

printf("\n");

}

// Calculate and display the sum of each column

calculateColumnSum(arr);

return 0;

}

```

Explanation:

This C program calculates the sum of each column in a 2D array (or table). Here's a breakdown of the code:

1.

Defining Constants

: `ROWS` and `COLS` are defined to represent the number of rows and columns in the 2D array, respectively.

2.

calculateColumnSum Function

: This function takes a 2D array as input and calculates the sum of each column. It initializes an array `sum` to store the sums of each column to zero. It then iterates through each column and within each column, iterates through each row to accumulate the sum of elements in that column.

3.

Main Function

:

Initializes a 2D array `arr` with sample data.

Prints the original array.

Calls the `calculateColumnSum` function to calculate and print the sum of each column.

4.

Output

:

The original array is displayed.

The sums of each column are printed.

This program provides a basic framework for calculating column sums in a 2D array, and it can be expanded or modified as needed for specific applications.

Tags: 爱相随攻略 虐杀原形2黑匣子 小游戏2121 搜狗高速浏览器 我国古人过年时蚂蚁庄园

上一篇: 并发编程的三大原因

下一篇: 变成囹圄

最近发表

icp沪ICP备2023033053号-25
取消
微信二维码
支付宝二维码

目录[+]