Sum of Elements in an array in C++ Programming


This program allows the user to enter the size of an array and its elements, and then calculates the sum of all the elements:

  • Declare an integer array a with a maximum size of 100, and integer variables n, i, and sum.
  • Ask the user to enter the size of the array and store it in n.
  • Use a for loop to iterate through each index of the array up to n.
  • For each index, ask the user to enter the corresponding element of the array and store it in a[i].
  • Add the value of a[i] to the current value of sum.
  • After the loop completes, print the value of sum to the console.

Source Code

#include<iostream>
using namespace std;
//Program to find Sum of element in an array.
int main()
{
    int a[100],n,i,sum=0;
    cout<<"\nEnter The Limit : ";
    cin>>n;
    for(i=0;i<n;i++)
    {
        cout<<"\nEnter The Value : ";
        cin>>a[i];
        sum+=a[i];//sum=sum+a[i];
    }
    printf("\nSum : %d",sum);
    return 0;
}
 

Output

Enter The Limit : 5

Enter The Value : 11

Enter The Value : 12

Enter The Value : 13

Enter The Value : 14

Enter The Value : 15

Sum : 65
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples