Hey yall,
ive been working on my homework and have to do a problem, without using the conio.h library (it's not in the course agenda), and don't really know how to go around that.
The problem reads:
Write a program you can read up to 20 integers into an array. A negative value ends the input
loop and the negative value is not part of the array.
Then by using a switch statement, pressing a (and return) computes the average of the array
(and prints the result), h prints the highest number in the array, l prints the minimal number in
the array, s prints the sum of all elements in the array and n prints the number of elements in the
array. Use functions for each task. The result of these functions must be printed from the main()
function.
Hint: The prototype to compute the average looks like this:
double compute_avg(int arr[], int num);
That's my work:
Code:
#include <conio.h>
#include <stdio.h>
double compute_avg(int a[],int n) {
int x,s=0;
for(x=0;x<n;x++) s+=a[x];
return (double)s/(n);
}
int compute_max(int a[],int n) {
int x,max=0;
for(x=0;x<n;x++) if(a[x]>max) max=a[x];
return max;
}
int compute_min(int a[],int n) {
int x,min=6200;
for(x=0;x<n;x++) if(a[x]<min) min=a[x];
return min;
}
int compute_sum(int a[],int n) {
int x,sum=0;
for(x=0;x<n;x++) sum+=a[x];
return sum;
}
int main() {
int a[20];
int i=1;
scanf("%d",&a[0]);
if(a[0]<0) return 0;
while((a[i-1]>=0)&&(i<20)) {
scanf("%d",&a[i]);
i++;
}
if(a[i-1]<0) i--;
//if last entered value was invalid,we adjust the number of elements
printf(" Enter command and press return. a computes average, h prints highest number,l prints minimum, s prints sum, n prints number of elements.\n");
char c;
while(1) {
getchar();
scanf("%c",&c);
switch(c) {
case 'a':
printf("The average is: %f\n",compute_avg(a,i));
break;
case 'h':
printf("The maximum is: %d\n",compute_max(a,i));
break;
case 'l':
printf("The minimum is: %d\n",compute_min(a,i));
break;
case 's':
printf("The sum is: %d\n",compute_sum(a,i));
break;
case 'n':
printf("The number of elements is: %d\n",i);
break;
default:
printf("Invalid input\n");
}
}
return 0;
}