Write a program that generates a 10-elements array full of random integer number
ID: 3622519 • Letter: W
Question
Write a program that generates a 10-elements array full of random integer numbers ranging from 0-10 and prints it on the first row of the screen.After the array random generation, the program displays the following:
A[verage] S[quare]
Please select an option:
Then, if the user selects:
-A (lowercase or uppercase): the program calls a user-defined function void average (int vector[]) that :
*Calculates the average of the 10 elements and displays the result on the screen
with an appropriate message;
*Calculates the average of the NON-ZERO elements and displays the result
on the screen with an appropriate message;
-S (lowercase or uppercase): the program calls a user-defined function int square(char vector[]) that :
*displays the squared value of each element of vector[];
*returns the maximum square element;
*After the function calling, the main() function saves the returned value on a
file (e.g. "C:inal.txt")
Please help to complete this code, i'm a beginner and want to review as much as possible to get a better understanding of how to write such codes.
Thank you
Explanation / Answer
#include<stdlib.h>
#include<time.h>
#include<conio.h>
#include<iostream.h>
#include<fstream.h>
void average(int a[]);
int square(int a[]);
int main()
{
int a[10],p;
char x;
srand((unsigned)time(0));
for(int index=0; index<10; index++)
a[index] = (rand()%10)+1;
for(int i=0; i<10; i++)
cout << a[i]<< " " ;
cout<<"A[vergae] S[quare]"<<endl;
cout << "Please Enter Your Choice :" << endl;
cin >> x;
switch(x)
{
case 'A':
case 'a': average (a); break;
case 'S':
case 's': p = square(a); break;
default: cout<< "Invalid Choice";
}
ofstream myfile;
myfile.open ("example.txt");
myfile << p<<endl;;
myfile.close();
getch();
return 0;
}
void average(int a[])
{
double sum = 0;
double avg;
for(int i=0; i<10; i++)
sum = sum+a[i];
avg = sum/10;
cout << "Average of Given Numbers is by" << avg << endl;
}
int square(int a[])
{
int sq[10];
for(int i=0; i<10; i++) {
sq[i] = a[i]*a[i]; cout << sq[i] << " "; }
int max = sq[0];
for(i=0; i<10; i++)
{
if (sq[i]>max)
{
max=sq[i];
}
}
return(max);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.