Followers

Monday, April 10, 2023

Program To Calculate The Sum Of All Elements Of An Array

Program:
 #include <iostream>  
 using namespace std;  
 int main() {  
   int arr[5] = {1, 2, 3, 4, 5}, sum = 0;  
   for(int i=0; i<5; i++){  
        sum = sum + arr[i];  
      }  
      cout<<"The sum of the array [1, 2, 3, 4, 5] is "<<sum<<endl;  
 }  
Output: 







Working Of The Program:
The working of the program is as follows:
1. The code defines a C++ program that calculates the sum of an array of integers.
2. The program begins by declaring an integer array arr of size 5, and initializes its elements to the values {1, 2, 3, 4, 5}.
3. The program also declares an integer variable sum and initializes it to 0.
4. The program then enters a for loop that iterates over each element of the array, using loop counter variable i.
5. Inside the loop, the program adds the current element of the array arr[i] to the sum variable.
6. After the loop completes, the program outputs the sum of the array to the console using cout.
7. The output message includes the phrase "The sum of the array", followed by the array elements in square brackets and the calculated sum.
8. Finally, the program terminates.

1 comment:

Program to Find the Length of a String

Program: #include <iostream> using namespace std; int main() { string a; cout<<"Enter the string...