C++ Program to calculate the sum of all odd numbers up to N


Getting series sum is one of the simplest practicing tasks while we are learning programming and logic build up. In mathematics, there are certain ways to find sum of series present in different progressions. In programming, we generate them one by one by implementing the logics, and repeatedly add them to get the sum otherwise perform any other operation if needed. In this article we shall cover techniques to get sum of all odd numbers up to N using C++.

There are two possible ways to get this sum with a little variation. Let us see these approaches one by one.

Algorithm

  • Take the number N as the upper limit.
  • Initialize sum as 0.
  • For i ranging from 1 to N.
    • If i is odd, then.
      • sum := sum + i.
    • End if.
  • Display the sum.

Example

#include <iostream> using namespace std; int solve( int n ) { int i; int sum = 0; cout << "Odd numbers are: "; for( i = 1; i <= n; i++ ) { if( i % 2 == 1 ) { cout << i << ", "; sum = sum + i; } } cout << endl; return sum; } int main(){ int sum = solve( 25 ); cout << "Sum is: " << sum; }

Output

Odd numbers are: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 
Sum is: 169

In this approach we are checking each number whether it is odd or even. When odd, print the number and add it to the sum variable. But we can ignore this checking by increasing the for loop by 2. The algorithm will be like below −

Algorithm

  • Take the number N as the upper limit.
  • Initialize sum as 0.
  • For i ranging from 1 to N, increase i by 2.
    • sum := sum + i.
  • Display the sum.

Example

#include <iostream> using namespace std; int solve( int n ) { int i; int sum = 0; cout << "Odd numbers are: "; for( i = 1; i <= n; i = i + 2 ) { cout << i << ", "; sum = sum + i; } cout << endl; return sum; } int main(){ int sum = solve( 75 ); cout << "Sum is: " << sum; }

Output

Odd numbers are: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 
Sum is: 1444

Conclusion

Finding series sum needs repetitive addition of numbers using loops in programs. In this problem we are trying to find the sum of numbers which are odd. So from 1 to N, we take the numbers one at a time, then check whether the number is odd or not using modulo operator by 2. When the remainder is 1 then it is odd and then display the number and also add this with the sum variable to get final sum. This process is straightforward and easy to understand. But we can think of it, the odd numbers are always increased by 2. So starting from 1, if we increase the number by 2 we get the odd numbers only. No additional checking is necessary in such cases.

Updated on: 17-Oct-2022

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements