Flow Control Write a program to read four double precision numbers from a text f
ID: 3871942 • Letter: F
Question
Flow Control Write a program to read four double precision numbers from a text file in the same directory named "numbers.txt" (this part of the code is given to you), then make the following decisions and output accordingly. (do not use the average function in C library) If then num1 == 0 Output "No need for any processing" Output "the result is__", where is the value of num1 num1 == 1 Output "the result is__",whereis the value of (num1+num2)/2 Output "the result is_", where is the value of (num1+num2+num3)/3 num1 == 2 num1 3Explanation / Answer
#include <stdio.h>
#include <math.h>
#include<string.h>
int main()
{
double arr[4] = {0};
int arr_size =0;
double data,avg=0.0;
char file1[20];
strcpy(file1,"numbers.txt");
FILE *fp;
fp = fopen(file1,"r+");
if (fp == NULL) // if file not opened return error
{
perror("Unable to open file");
return -1;
}
else
{
fscanf (fp, "%lf", &data);
arr[arr_size]=data;
arr_size++;
while (!feof (fp))
{
fscanf (fp, "%lf", &data);
arr[arr_size]=data;
arr_size++;
}
}
int i=0;int flag=0;
printf(" Numbers read from the file are :");
for(i=0;i<arr_size;i++)
printf(" %lf",arr[i]);
if(arr[0]==0.0)
{
flag=1;
printf(" No need for any Processing");
}
else if(arr[0]==1.0)
avg=arr[1];
else if(arr[0]==2.0)
avg=(arr[1]+arr[2])/2;
else if(arr[0]==3.0)
avg=(arr[1]+arr[2]+arr[3])/3;
if(flag==0)
printf(" The result is %lf",avg);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.