In: Computer Science
Only Program in C for this. No other programming language is allowed.
Using a function, we will add a range of values of an array. The range is going to be determined by the user. In this example, if you put the following array down as:
1.5 -5.6 8.9 4.6 7.8 995.1 45.1 -5964.2
… and the user tells you to add from the 3rd element to the 6th element, your program is going to need to add the values:
8.9, 4.6, 7.8 and 995.1.
For this to work, I HIGHLY recommend using these guidelines:
1. Ask the user for the length of the array.
2. Ask the user for the starting and ending points.
3. Use the scan and print functions to populate the array.
4. Be sure to call the “adding values” function. This function must accept by 4 parameters: array’s length, the array, the starting point, and the ending point.
5. Inside your function, use these parameters to find the sum (use a loop! It's required, and any kind is fine).
6. When done, return the sum to main.
7. Print the returned value in main.
The C code:
#include<stdio.h>
//addingvalues function declaration
float addingvalues(int n,float arr[n],int start,int end)
{
int j;
float sum1=0.0;//initialization of sum1 to 0
for(j=start-1;j<end;j++) //for loop for adding the
values
{
sum1=sum1+arr[j]; //adding the
array values
}
return sum1;//returns the final sum
}
int main()
{
int n,i; //declaring n and i
printf("Enter the length of the array:");
scanf("%d",&n);//takes the length of the array
from user
float arr[n];//arr is declared as float
printf("Enter the array values:");
for(i=0;i<n;i++) //for loop for array values
{
scanf("%f",&arr[i]);
}
int l,r;//l for starting value and r for ending
value
printf("Enter the starting and ending points:");
scanf("%d %d",&l,&r);//scans the input l,r
from user
float sum; //sum is declared as float
sum=addingvalues(n,arr,l,r); //function calling
printf("The sum is %.4f.",sum);//final sum
printing
}
code snippet:
The output results:
for the given example
for another array
please see the code snippet for the indentation.
Please upvote this..