How to Calculate the Sum of Odd Numbers in C++ Language


C++ is the powerful programming language that has all of the features needed to write comprehensive programs, including object-oriented programming tools. To test if the number is odd or even using the programming approach, divide the number by two. The remainder of this operation is zero for even numbers and larger than zero for odd numbers. C++ includes a special operator ("%") that allows you to evaluate the remainder.

  • Initialize the sum of numbers to zero using the command:

    int sum = 0;

  • Generate the integer numbers in the required range using the C++ loop "for." For example, to get numbers from 1 to 50, use the following command:

    for (int i=1; i<50; i++){

  • Check if the number is odd using the following statement:

    if (i%2 > 0)

    Note that this "if" statement is true only if the remainder is larger than zero, which is the case for odd numbers.

  • Add the current odd number to the sum with the command:


    Thus, the complete "if" statement is

    if (i%2 > 0) {


  • Print the sum of the odd numbers using the command:

    std::cout <<sum;

    In this example, the sum of odd numbers in the range between 1 and 50 is 625.

Related Searches


Promoted By Zergnet


You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!