Q4. Sum of elements in an array

Solution for calculating the sum of elements in an integer array

  • Understand how to iterate over arrays using for and while loops
  • Understand how to pass arrays to functions
/* SumOfArray.cpp */
 
#include <iostream>
using namespace std;
 
//function prototype declarations
int getSumOfArray(int arr[], int arrsize);
void printArray(int arr[], int arrsize);
 
int main(){
    int arr[] = {5, 6, 8, 3, 1};
 
    int sumOfArray = getSumOfArray(arr, 5);
 
    printArray(arr, 5);    
    cout << "Sum of array = " << sumOfArray << endl;
    cin.get();
}
 
int getSumOfArray(int arr[], int arrsize) {
    int sum = 0, idx = 0; //idx will be used for array index
 
    //using while loop to iterate and calculate the sum of elements in array
    while( idx < arrsize) {
        sum = sum + arr[idx];
        idx++;
    }
 
    return sum;
}
 
/* print all the elements in an array */
void printArray(int arr[], int arrsize) {
 
     cout << "[";
     //example of iterating an array using for loop
     for (int arrIdx = 0; arrIdx < arrsize; arrIdx++) { 
 
         if(arrIdx != (arrsize - 1) )
         cout << arr[arrIdx] << ",";
        else
         cout << arr[arrIdx];
 
     }
     cout << "]" << endl;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License