in c++ write a program to return sum of n element using array
Answers
Explanation:
#include <stdio.h>
int arraysum(int array[],int sizeofarray) //declaration of function that require two arguments
{
int i,sum = 0; //declaring all the variables required for this function
//i for loop and sum to store the sum of elements
for(i=0; i<=sizeofarray; i++) //looping through the array passed as parameter
{
sum+=array[i]; //adding each element of the array in previous value of sum.
}
return sum; //returning the sum of elements
}
int main() //start of main function
{
int size,i,total,arr[10]; //declaring all the required variables
//size for size of array, i for loop, total to store the result
printf("Enter the size of array:"); //printing a message
scanf("%d",&size); //taking the size of array from user
printf("Enter the elements of array:"); //printing message
for(i = 0; i<size; i++) //looping through the array
{
scanf("%d",&arr[i]); //taking input the elements of array
}
//there is no need of total variable. The result could also be printed by following statement
//printf("The sum of all the elements is: %d",arraysum(arr,size));
total = arraysum(arr,size); //calling the arraysum() function and assigning the sum to total
printf("The sum of all the elements is: %d",total); //printing the result
}