a. Write a function makeFile that takes two parameters an integer n and a string
ID: 3622297 • Letter: A
Question
a. Write a function makeFile that takes two parameters an integer n and a string fileName. The function prompts the user to input n integers and stores them in the file whose name is contained in the string.b. Write a function fillArray, which takes a string filename as an input parameter, an array size n, and an integer array as an output parameter. The function must read n integers from the file provided by the string and store them in the array.
c. Write a function that takes an array of integers and its size and returns an average of the array elements as a floating point number.
d. Write the main function
i. Use the function makeFile from Step a) to create a file “data” containing 10 integers.
ii. Declare an integer array of size 10 and use the function fillArray from Step b) to fill the array.
iii. Use function from Step c) to compute the average of the array elements and print the result on the screen.
Explanation / Answer
#include<stdio.h>
#include<conio.h>
#include<string.h>
FILE *fp;
void makeFile(char str[],int );
void fillArray(char str[],int a[],int );
float Average(int a[],int );
int main()
{
char str[20];
int a[10];
int k=10; // no of integers.
printf("Enter File name : ");
scanf("%s",str);
makeFile(str,k);
fillArray(str,a,k);
printf("average of numbers given by %f",Average(a,10));
getch();
return 0;
}
void makeFile(char str[], int k)
{
int a,i;
fp = fopen(str,"w+");
for(i=0; i<k; i++)
{
scanf("%d",&a);
fprintf(fp,"%d ",a);
}
fclose(fp);
}
void fillArray(char str[],int a[],int p)
{
char st[10];
int k,i=0;
fp = fopen(str,"r");
while(fgets(st,10,fp)!=NULL)
{
sscanf(st,"%d",&k);
a[i++]=k;
if(i==p)
break;
}
fclose(fp);
}
float Average(int a[],int p)
{
float sum=0;
int i;
for(i=0; i<p; i++)
sum+=a[i];
return sum/10;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.