Followers

Showing posts with label sum. Show all posts
Showing posts with label sum. Show all posts

Tuesday, April 11, 2023

Program To Calculate The Sum of Positive Integers Up To An Upper Limit

Program:
 #include <iostream>    
 using namespace std;    
 int main() {    
  int upper_Limit = 0 , sum = 0;  
  cout<<"The highest positive integer you want to add upto: ";  
  cin>>upper_Limit;  
  for(int i=1; i<=upper_Limit; i++){  
      sum = sum + i;  
  }  
  cout<<"The sum of positive integer from 1-"<<upper_Limit<<" is "<<sum<<endl; 
  return 0;   
 }   
Output: 






Working Of The Program:
The program works as follows:
1. The program begins by including the iostream library, which contains the necessary functions for input/output operations.
3. The 'using namespace std' line declares that the code will use the standard namespace, which contains the standard C++ library functions.
4. The main function is the entry point of the program.
5. The program initializes two integer variables, 'upper_Limit' and 'sum', to 0.
6. The program prompts the user to enter the highest positive integer they want to add up to, and stores the value in the 'upper_Limit' variable using the 'cin' function.
7. A 'for' loop is used to iterate from 1 to the user input 'upper_Limit'.
8. In each iteration of the loop, the value of 'i' is added to the 'sum' variable.
9. Once the loop has finished iterating, the program outputs the sum of positive integers from 1 to the user input 'upper_Limit'.
10. The program ends with the 'return 0' statement, indicating that the program has been completed successfully.

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.

Program to Find the Length of a String

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