Home »
C++ Programs
C++ program to print the sum of all odd and even numbers in a range using class
Submitted by Shubh Pachori, on September 04, 2022
Problem statement
Given a range, we have to print the sum of all odd and even numbers in that range using the class and object approach.
Example:
Input:
Enter Range : 1 10
Output:
Sum of all even numbers is 30
Sum of all odd numbers is 25
C++ code to print the sum of all odd and even numbers in a range using the class and object approach
#include <iostream>
using namespace std;
// create a class
class OddEven {
// private data members
private:
int start, end;
// public member function
public:
// getRange() function to enter range
void getRange() {
cout << "Enter Range : ";
cin >> start >> end;
}
// sumOddEven() function to add all
// odd and even numbers
void sumOddEven() {
// initializing int type variables
// to perform operations
int index, sum_even = 0, sum_odd = 0;
// for loop to traverse all numbers in the range
for (index = start; index <= end; index++) {
// condition to check even numbers
if (index % 2 == 0) {
// adding all even numbers in the range
sum_even = sum_even + index;
}
// condition for odd numbers
else {
// adding all odd numbers in the range
sum_odd = sum_odd + index;
}
}
cout << "Sum of all even numbers is " << sum_even << "\n"
<< "Sum of all odd numbers is " << sum_odd << endl;
}
};
int main() {
// create a object
OddEven O;
// calling getRange() function to get range
O.getRange();
// sumOddEven() function to find
// sum of all even and odd numbers
O.sumOddEven();
return 0;
}
Output
Enter Range : 1 6
Sum of all even numbers is 12
Sum of all odd numbers is 9
Explanation
In the above code, we have created a class OddEven, two int type data members start and end to store the start and end of the range, and public member functions getRange() and sumOddEven() to store range and to print sum of the all odd and even numbers in between that given range.
In the main() function, we are creating an object O of class OddEven, reading a range by the user using getRange() function, and finally calling the sumOddEven() member function to print the sum of all odd and even numbers in the given range. The sumOddEven() function contains the logic to print the sum of all odd and even numbers in the given range and printing the result.
C++ Class and Object Programs (Set 2) »