The Program in C++ to add all the numbers from 1 to given number is given below:
#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
cout<< "Hello Codeauri Family, Please enter value of n :\n";
cin>>n;
for (int i = 1; i <= n; i++) {
sum += i;
}
cout << "The sum of the numbers from 1 to " << n << " is: " << sum << endl;
return 0;
}
Output:
Hello Codeauri Family, Please enter value of n :
5
The sum of the numbers from 1 to 5 is: 15
Pro-Tips💡
This program uses a variable ‘n’ to store the user input,
and a variable ‘sum’ initialized to 0, that will store the sum of all the numbers from 1 to ‘n’.
The for loop starts at 1 and ends at n, and at each iteration, add the current value of i to the sum.
Finally, the program will print the sum of the numbers from 1 to n.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.