A 2d-array calculator for C

A 2d-array calculator for C

ccc

This program will calculate a sum for all values introduced in a [5][5] array. I'll post the full code at the end or it can be found at github.com 

The program starts with the introduction of variables and the array in question.

 

 

 

 

int z = 0;

int x = 0;

int totalsum = 0;

int sum_matrix[5][5];

/*Introduce the array and all the values*/

int matrix[5][5] =

{

4, 6, 25, 88, 5,

34, 5, 300, 4, 65,

78, 43, 11, 90, 125,

98, 585, 12, 63, 21,

45, 35, 9, 5, 1

};

The introduction of the two variables z and x are important to introduce here. The printing process uses two for-loops one inside the other. The variables will rotate around the two numbers specified in the [5][5] part of the array. So if the array was [4][5][6] we'd need three variables and three loops.

 

printf("The 2D Array printed:\n");

/* Two for loops for both variables defined earlier */

/* This is to make both loops run through both sets of 5's */

for(int z = 0; z < 5; z++){

for(x = 0; x < 5; x++){

sum_matrix[z][x]= matrix[z][x];

/* adds the values together on each line*/

totalsum += sum_matrix[z][x];

if(x==4){

/* Controls on which value a new line is introduced */

printf("%d \n",sum_matrix[z][x]);

}

else{

/* This just prints the values on the current row */

printf("%d ", sum_matrix[z][x]);

}

}

}

printf("\nThe sum of the table is %d%s", totalsum,"\n");

I wrote some explanations for myself for everything in the comments of the code.

The two loops that run through the 2D array

 

for(int z = 0; z < 5; z++){

for(x = 0; x < 5; x++){

The next one adds together each line in the table.

 

totalsum += sum_matrix[z][x];

The if-statement pushes the print to a new row and the else statement prints the row.

if(x==4){

printf("%d \n",sum_matrix[z][x]);

}

else{

printf("%d ", sum_matrix[z][x]);

}

The code below the total sum.

 

printf("\nThe sum of the table is %d%s", totalsum,"\n");

And that's it. Running this should result in something like this.

matrixworks

The full code:

 

#include <stdio.h>

int main(){

/*Print out and ount together values in a 2D array*/

 

int z = 0;

int x = 0;

int totalsum = 0;

int sum_matrix[5][5];

/*Introduce the array and all the values*/

int matrix[5][5] =

{

4, 6, 25, 88, 5,

34, 5, 300, 4, 65,

78, 43, 11, 90, 125,

98, 585, 12, 63, 21,

45, 35, 9, 5, 1

};

printf("The 2D Array printed:\n");

/* Two for loops for both variables defined earlier */

/* This is to make both loops run through both sets of 5's */

for(int z = 0; z < 5; z++){

for(x = 0; x < 5; x++){

sum_matrix[z][x]= matrix[z][x];

/* adds the values together on each line*/

totalsum += sum_matrix[z][x];

if(x==4){

/* Controls on which value a new line is introduced */

printf("%d \n",sum_matrix[z][x]);

}

else{

/* This just prints the values on the current row */

printf("%d ", sum_matrix[z][x]);

}

}

}

printf("\nThe sum of the table is %d%s", totalsum,"\n");

}