यहाँ पर हम एक array element के total को calculate करेंगे। program में array size 10 दिया गया है जिसमे हम केवल 6 element store करेंगे।
int arr[10],num,sum=0;
इसका program नीचे दिया गया है –
Program add array elements in C++
#include<iostream.h>
#include<conio.h>
void main()
{
int arr[10],num,sum=0;
clrscr();
cout<<"how much element you want to enter: \n";
cin>>num;
cout<<"Enter "<<num<<" Element: ";
for(int i=0;i<num;i++)
cin>>a[i]; // store values in variable a[]
cout<<"Your Element is: \n";
for(int j=0; j<n;j++)
{
cout<<a[j]<<" "; // print array element
sum=sum+a[j]; // sum of array element
}
//Print sum of array element
cout<<"\nTotal of These Element are: "<<sum;
getch();
}
OUTPUT
how much element you want to enter:: 6
Enter 6 Element:
4 8 9 1 4 2
Your element is: 4 8 9 1 4 2
Total of These Element are : 28
user द्वारा input किये गए 6 element इस प्रकार स्टोर होंगे –
arr[0] = 4
arr[1] = 8
arr[2] = 9
arr[3] = 1
arr[4] = 4
arr[5] = 2
यहाँ पर ध्यान दें variable sum को 0 initialize किया गया है परन्तु क्यों ? ऊपर दिया गया program का execution, इसकी व्याख्या करता है।अगर हमें elements को एक दूसरे से multiply करना होता तो हम variable sum को 1 से initialize करते है। जैसा कि real world में होता है।
Related exercise,
- Passing Array to a Function in C++
- Array with function in C++
- Sorting Array Elements as Ascending and Descending Order in C++
- Searching Element in Array List in C++
- class with a multidimensional array in C++