Write a program that reads the R and C dimensions of a two-dimensional array T of type int (maximum dimensions: 50 rows and 50 columns). Fill in the array with values entered on the keyboard and display the array and the sum of all its elements.
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<math.h>
#include<conio.h>
#define SIZE 50
void main()
{
int A[SIZE][SIZE];
int R, C; // dimension of the array
int i, j; // counters
int sum = 0;
do {
printf("Enter the number of rows: ");
scanf("%d", &R);
} while (R <= 0 || R > 50);
do {
printf("Enter the number of columns: ");
scanf("%d", &C);
} while (C <= 0 || C > 50);
for (i = 0; i<R; i++)
for (j = 0; j < C; j++)
{
printf("Enter A[%d][%d]=", i, j);
scanf("%d", &A[i][j]);
//sum+=A[i][j];
}
printf("\n\nPrinting the array\n");
for (i = 0; i < R; i++)
{
for (j = 0; j < C; j++)
{
printf("%4d", A[i][j]);
//sum += A[i][j]; // correct
}
printf("\n");
//sum+=A[i][j]; // WRONG because j will be equal to C
// A[i][C] will be out of bound
}
for (i = 0; i<R; i++)
for (j = 0; j < C; j++)
sum += A[i][j];
printf("Sum=%d\n", sum);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Length of a full name (using 2 strings)