Write a program that reads the dimension N of an integer array T (maximum dimension: 50 components), fills the array with values entered on the keyboard and displays the array.
Calculate and then display the sum of the elements of the array.
Then delete all occurrences of the value 0 in the table T and tamp the remaining elements. Display the resulting array.
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<math.h>
#include<conio.h>
#define SIZE 50
void main()
{
// error int T[];
// error int N=50;
// error int T[N];
// 1st solution
//int N;
//int T[50];
//2nd solution
int N; // nb of elements
int T[SIZE]; // array of maximum size 50
int i, sum = 0, j = 0;
do {
printf("Enter N: ");
scanf("%d", &N);
} while (N<0 || N>50);
for (i = 0; i < N; i++)
{
printf("Enter T[%d]: ", i);
scanf("%d", &T[i]);
//sum += T[i];
}
printf("\n\nPrinting the elements\n");
for (i = 0; i < N; i++)
{
printf("T[%d]=%d\n", i, T[i]);
//sum += T[i];
}
for (i = 0; i < N; i++)
{
sum += T[i];
}
printf("\nSum=%d\n", sum);
// wrong solution
printf("\n\nPrinting non zero elements - wrong solution\n");
for (i = 0; i < N; i++)
{
if (T[i] != 0)
printf("T[%d]=%d\n", i, T[i]);
}
// wrong solution
printf("\n\nPrinting non zero elements - wrong solution\n");
for (i = 0; i < N; i++)
{
if (T[i] != 0)
printf("T[%d]=%d\n", j++, T[i]);
}
//correct solution
j = 0;
for (i = 0; i < N; i++)
{
if (T[i] != 0)
{
T[j] = T[i];
j++;
}
}
printf("\n\nPrinting non zero elements\n");
for (i = 0; i < j; i++)
{
printf("T[%d]=%d\n", i, T[i]);
}
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Program output 4