In: Computer Science
MUST BE DONE IN C (NOT C++)
In this task, using a function, we will add a range of values of an array. The range will be determined by the user. For example, if I have the following array …
1.5 -5.6 8.9 4.6 7.8 995.1 45.1 -5964.2
… and the user tells me to add from the 3rd element to the 6th element, my program would add the values 8.9, 4.6, 7.8 and 995.1. To do so, please follow these guidelines:
- Ask the user for the length of the array.
- Ask the user for the starting and ending points.
- Use the scan and print functions to populate the array.
- Call the “adding values” function. This function must accept 4 parameters: array’s length, the array, the starting point and the ending point.
- Inside your function, use these parameters to find the sum (you must use a loop, whichever one you prefer).
- When done, return the sum to main.
- Print the returned value in main.
#include <stdio.h>
double adding_values(int length,double arr[],int start,int
end)
{
double sum=0;
for(int i=(start-1);i<end;i++) //(start-1) because array starts
from 0
{
sum=sum+arr[i];
}
return sum;
}
int main()
{
double arr[100];
int n,start,end,i;
printf("Enter the length of array ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter array elements for location %d : ",(i+1));
scanf("%lf",&arr[i]); //%lf for double data type
}
printf("Enter the starting point: ");
scanf("%d",&start);
printf("Enter the ending point: ");
scanf("%d",&end);
double sum=adding_values(n,arr,start,end); //calling function
printf("sum is %lf ",sum);
return 0;
}
DON'T FORGET TO HIT LIKE.
THANKS BY HEART.
COMMENT DOWN IF ANY PROBLEM.