Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to calculate the sum of numbers from 1 to 10

C++ Code Example — Loop Programs

ADVERTISEMENT

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

  1. Initialize an integer sum = 0.
  2. Start a for loop with i running from 1 to 10.
  3. Inside the loop, add the current value of i to the sum: sum = sum + i.
  4. 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 for loop is ideal when you know exactly how many times you want a block of code to repeat.
  • By updating the sum variable 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)
ADVERTISEMENT