Write a C++ Program to find the sum of odd numbers from 0 to n. This C++ program allows you to enter the maximum odd number. Next, we used the for loop (for(number = 1; number <= maximum; number++)) to iterate numbers from 1 to maximum. We used the If condition (if ( number % 2 != 0 ) ) within the loop to check whether the number % 2 not equals 0. If true, add that odd number to the sum value, and print it as the odd number. Next, it prints the sum of the odd numbers as a result.
#include<iostream>
using namespace std;
int main()
{
int number, maximum, sum = 0;
cout << "\nPlease Enter the Odd Numbers Maximum Limit = ";
cin >> maximum;
cout <<"\n\nOdd Numbers between 0 and " << maximum << " = ";
for(number = 1; number <= maximum; number++)
{
if ( number % 2 != 0 )
{
cout << number << " ";
sum = sum + number;
}
}
cout << "\nThe Sum of All Odd Numbers upto " << maximum << " = " << sum;
return 0;
}
C++ Program to find Sum of Odd Numbers Example 2
In this C++ program to calculate the sum of odd Numbers, we altered the for loop (for(number = 1; number <= maximum; number = number + 2)) to remove the If condition. As you can see, we incremented the number by 2 (instead of 1 number++). As we know, every number starts from 1 with an increment of 2 (1 + 2 = 3) will be an odd number. So, we add that odd number to the sum and print the sum as a result.
#include<iostream>
using namespace std;
int main()
{
int number, maximum, sum = 0;
cout << "\nPlease Enter the Odd Numbers Maximum Limit = ";
cin >> maximum;
cout <<"\n\nOdd Numbers between 0 and " << maximum << " = ";
for(number = 1; number <= maximum; number = number + 2)
{
sum = sum + number;
cout << number << " ";
}
cout << "\nThe Sum of All Odd Numbers upto " << maximum << " = " << sum;
return 0;
}
This C++ sum of odd numbers example allows the user to enter the minimum and maximum value. Next, it will calculate the sum of odd numbers from minimum to maximum.
#include<iostream>
using namespace std;
int main()
{
int number, minimum, maximum, sum = 0;
cout << "\nPlease Enter the Odd Numbers Minimum Limit = ";
cin >> minimum;
cout << "\nPlease Enter the Odd Numbers Maximum Limit = ";
cin >> maximum;
cout <<"\n\nOdd Numbers between " << minimum << " and " << maximum << " = ";
for(number = minimum; number <= maximum; number++)
{
if ( number % 2 != 0 )
{
cout << number << " ";
sum = sum + number;
}
}
cout << "\nThe Sum of All Odd Numbers from " << minimum << " to " << maximum << " = " << sum;
return 0;
}