Write a program that reads N whole numbers on the keyboard and displays their sum, product, and average. Choose an appropriate type for the values to display. The number N is to enter on the keyboard. Solve this problem,

  • using while,
  • using do - while,
  • using for.
  • Which of the three variants is the most natural for this problem?
  • Complete the 'best' of the three versions:
    Repeat the introduction of the number N until N has a value between 1 and 15. What repetitive structure do you use? Why?

Difficulty level
Video recording
This exercise is mostly suitable for students
********************
** USING    WHILE **
********************
#include <stdio.h>

int main()
{
	int N; 
 	int NB; 
 	int I;   
 	long SUM;     
 	double PROD;  

	do{
 		printf("Enter the number of values: ");
 		scanf("%d", &N);
	}while(N<=0);

 	SUM=0;
 	PROD=1;
 	I=1;
 	while(I<=N)
    	{
     		printf("Enter number %d : ", I);
     		scanf("%d", &NB);
     		SUM  += NB;
     		PROD *= NB;
     		I++;
    	}
 
 	printf("The sum     of %d numbers is equal to %ld \n", N, SUM);
 	printf("The product of %d numbers is equal to %.0f\n", N, PROD);
 	printf("The average of %d numbers is equal to %.4f\n", N, (float)SUM/N);

	return 0;
}

********************
** USING DO WHILE **
********************

#include <stdio.h>

int main()
{
	int N; 
 	int NB; 
 	int I;   
 	long SUM;     
 	double PROD;  

	do{
 		printf("Enter the number of values: ");
 		scanf("%d", &N);
	}while(N<=0);

 	SUM=0;
 	PROD=1;
 	I=1;
 	do
    	{
     		printf("Enter number %d : ", I);
     		scanf("%d", &NB);
     		SUM  += NB;
     		PROD *= NB;
     		I++;
    	}while(I<=N);
 
 	printf("The sum     of %d numbers is equal to %ld \n", N, SUM);
 	printf("The product of %d numbers is equal to %.0f\n", N, PROD);
 	printf("The average of %d numbers is equal to %.4f\n", N, (float)SUM/N);

	return 0;
}



********************
** USING   FOR    **
********************
#include <stdio.h>
int main()
{
	int N; 
 	int NB; 
 	int I;   
 	long SUM;     
 	double PROD;  

	do{
 		printf("Enter the number of values: ");
 		scanf("%d", &N);
	}while(N<=0);

 	for (SUM=0, PROD=1, I=1 ; I<=N ; I++)
    	{
     		printf("Enter number %d : ", I);
     		scanf("%d", &NB);
     		SUM  += NB;
     		PROD *= NB;
    	}
 
 	printf("The sum     of %d numbers is equal to %ld \n", N, SUM);
 	printf("The product of %d numbers is equal to %.0f\n", N, PROD);
 	printf("The average of %d numbers is equal to %.4f\n", N, (float)SUM/N);

	return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Number pattern 5