Tutorialspoint
Problem
Solution
Submissions

Sum of All Even Numbers

Certification: Basic Level Accuracy: 100% Submissions: 5 Points: 5

Write a C++ program to compute the sum of even numbers in the range [1, n].

Example 1
  • Input: n = 10
  • Output: 30
  • Explanation:
    • Step 1: Identify the even numbers in the range [1, 10]: 2, 4, 6, 8, 10
    • Step 2: Calculate the sum of these even numbers: 2 + 4 + 6 + 8 + 10 = 30
    • Step 3: Return the sum: 30
Example 2
  • Input: n = 15
  • Output: 56
  • Explanation:
    • Step 1: Identify the even numbers in the range [1, 15]: 2, 4, 6, 8, 10, 12, 14
    • Step 2: Calculate the sum of these even numbers: 2 + 4 + 6 + 8 + 10 + 12 + 14 = 56
    • Step 3: Return the sum: 56
Constraints
  • 1 ≤ n ≤ 10^6
  • Note: You can optimize using the formula: sum of first k even numbers = k(k+1)
  • Time Complexity: O(1) when using the formula, O(n) for iterative approach
  • Space Complexity: O(1)
NumberVariables and Data TypesCapgeminiZomato
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use arithmetic series formula: k * (k + 1) where k = n//2
  • Iterate with step size 2 for optimization
  • Return 0 if n < 2

Steps to solve by this approach:

 Step 1: Initialize a sum variable to 0.

 Step 2: Loop from 2 up to n, incrementing by 2 each time.
 Step 3: Add each even number to the running sum.
 Step 4: Continue until all even numbers up to n are processed.
 Step 5: Return the final sum of all even numbers.

Submitted Code :