Write a program that initializes values in a one-dimensional array. It passes the array as argument to a function which computes the sum of the array. The function should return the calculated sum to the calling function.
So let’s Write Code:
Let’s build logic First:
Algorithm for code:
- Step 1: Start
- Step 2: Declare an array and variable i for loop.
- Step 3: Initialize array.
- Step 4: Defining function for sum int sum(int x[]).
- Step 5: add s + x[ i ] until i< =4 and store in s.
- Step 6: Return s.
- Step 7: Calling the function int sum( int [] );
- Step 8: Print Result.
- Step 9: End Program
Code:
Write a program that initializes values in a one-dimensional array. It passes the array as an argument to a function that computes the sum of the array. The function should return the calculated sum to the calling function.
#include<iostream>
using namespace std;
main()
{
int arr[5] = {4,6,3,4,7}, i;
int sum(int []);
cout<<"Values of array\n";
for(i = 0; i<=4; i++)
cout<<arr[i]<<endl;
cout<<"\nSum of array ="<<sum(arr);
}
// definition of sum() function
int sum(int x[])
{
int s = 0;
for(int i = 0; i<=4; i++)
s = s + x[i];
return s;
}
Hope You will learn Something. Happy Coding.
Visit my YouTube Channel as Well๐ https://www.youtube.com/watch?v=JuIHQ9cLSEw&list=PLbIhkHxfUIItTdcyCb34uRIrPJbXBndIl&index=4
Click on the below Links for more Programming Exercises:
Conditional Structure Exercises: ๐https://myustaadg.com/category/programming-exercises/conditional-structures-exercises/
Array Exercises: ๐https://myustaadg.com/category/programming-exercises/arrays-exercises/