Followers

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.

No comments:

Post a Comment

Program to Find the Length of a String

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