A C++ program to calculate and print sum of 1 to n numbers
Using loop access each element one by one and add them to the sum variable. Once the loop is terminated print the sum.
Code
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int sum=0;
for(int i=1;i<=n;i++){
sum=sum+i;
}
cout<<sum;
return 0;
}
Input
5
Output
15
0 Comments