We are asked to write a program that inputs three different integers from the keyboard, then prints the sum, the average, the product, the smallest and the largest of these numbers. The program does not have to account for invalid input (for instance, entering the same integer three times rather than using three different integers).
Here is an example of how the output of the program should look, with the integers 13 27 and 14:
Input three different integers: 13 27 14
Sum is 54
Average is 18
Product is 4914
Smallest is 13
Largest is 27
Is there an easier way (i.e. less lines of code) to code the same thing? Here is the code I have used, in-between the dotted lines:
--------------------------------------...
#include "stdio.h"
int main ()
{
int a,b,c,sum,avg,prod;
printf("Input three different integers: ");
scanf("%d%d%d",%26amp;a,%26amp;b,%26amp;c);
sum = a + b + c;
printf("Sum is %d\n",sum);
avg = (a + b +c) / 3;
printf("Average is %d\n",avg);
prod = a*b*c;
printf("Product is %d\n",prod);
if(a %26lt; b %26amp; a %26lt; c) {
printf("Smallest is %d\n",a);
}
if(b %26lt; a %26amp; b %26lt; c) {
printf("Smallest is %d\n",b);
}
if (c %26lt; a %26amp; c %26lt; b) {
printf("Smallest is %d\n",c);
}
if(a %26gt; b %26amp; a %26gt; c) {
printf("Largest is %d\n",a);
}
if(b %26gt; a %26amp; b %26gt; c) {
printf("Largest is %d\n",b);
}
if (c %26gt; a %26amp; c %26gt; b) {
printf("Largest is %d\n",c);
}
}
--------------------------------------...
C programming language: is there an easier way to code the same thing?
Put your input data into an array. You can then do all your calculations in one loop.
#include "stdio.h"
#include "limits.h"
int main ()
{
int i;
int array[3];
int sum = 0;
int avg = 0;
int prod = 1;
int smallest = INT_MAX;
int largest = 0;
printf("Input three different integers: ");
scanf("%d%d%d",%26amp;array[0], %26amp;array[1], %26amp;array[2]);
for (i = 0; i %26lt; 3; i++)
{
sum += array[i];
prod *= array[i];
if (array[i] %26gt; largest)
{
largest = array[i];
}
if (array[i] %26lt; smallest)
{
smallest = array[i];
}
}
printf("Sum is %d\n",sum);
avg = sum / 3;
printf("Average is %d\n",avg);
printf("Product is %d\n",prod);
printf("Smallest is %d\n", smallest);
printf("Largest is %d\n", largest);
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment