WAP to calculate the sum of numbers from 1 to 10
Objective
Write a C++ program to calculate the sum of numbers from 1 to 10.
Algorithm / Approach
- Initialize an integer
sum = 0. - Start a
forloop withirunning from 1 to 10. - Inside the loop, add the current value of
ito thesum:sum = sum + i. - Print the final sum.
main.cpp
#include<iostream>
using namespace std;
int main() {
int sum =0;
for(int i =0;i<=10;i++) {
sum = sum+i;
}
cout<<"Sum = "<< sum;
return 0;
}
Expected Output
Sum = 55
Explanation of the Program
- A
forloop is ideal when you know exactly how many times you want a block of code to repeat. - By updating the
sumvariable on every single iteration of the loop, it acts as an accumulator that gradually builds up the final total.
Complexity
Time Complexity
O(1) - The loop runs exactly 10 times, which is a constant.
Space Complexity
O(1)