Write a program that will read five values of type double from the keyboard and
ID: 3779730 • Letter: W
Question
Write a program that will read five values of type double from the keyboard and store them in an array. Calculate the reciprocal of each value (the reciprocal of a value x is 1.0/x) and store it in a separate array. Output the values of the reciprocals, and calculate and output the sum of the reciprocals.
Write the language in C and use exciting template to complete the excersise not adding anything extra
GIVEN CODE:
/*Exercise 1 Summing reciprocals of five values */
#include <stdio.h>
int main(void)
{
const int nValues = 5; /* Number of data values */
double data[nValues]; /* Stores data values */
double reciprocals[nValues];
double sum = 0.0; /* Stores sum of reciprocals */
int i;
printf("Enter five values separated by spaces: ");
// Your Code Hete
printf(" You entered the values: ");
// Your Code Hete
return 0;
}
Explanation / Answer
#include <stdio.h>
int main(void)
{
const int nValues = 5; /* Number of data values */
double data[nValues]; /* Stores data values */
double reciprocals[nValues];
double sum = 0.0; /* Stores sum of reciprocals */
int i;
printf("Enter five values separated by spaces: ");
// Your Code Hete
for(i=0; i<nValues; i++){
scanf("%lf", &data[i]);
}
printf(" You entered the values: ");
// Your Code Hete
for(i=0; i<nValues; i++){
printf("%lf ", data[i]);
}
for(i=0; i<nValues; i++){
reciprocals[i] = 1.0/data[i];
}
for(i=0; i<nValues; i++){
sum = sum + reciprocals[i];
}
printf(" Sum is %lf ",sum);
return 0;
}
Output:
sh-4.2$ gcc -o main *.c
sh-4.2$ main
Enter five values separated by spaces:
1 2 3 4 5
You entered the values:
1.000000 2.000000 3.000000 4.000000 5.000000
Sum is 2.283333
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.