Home »
C++ Programs
C++ program to print odd numbers in a range using class
Submitted by Shubh Pachori, on August 14, 2022
Problem statement
Given a range, we have to print all odd numbers in that range using the class and object approach.
Example:
Input:
Enter Range: 3 9
Output:
Odd Numbers in the range 3 to 9 are
3 5 7 9
C++ code to print odd numbers in a range using class and object approach
#include <iostream>
using namespace std;
// create a class
class IsOdd {
// declare private data members
private:
int start, end;
// public functions
public:
// getRange() function to insert range
void getRange() {
cout << "Enter Range:";
cin >> start >> end;
}
// isOdd() function to print odd numbers in between range
void isOdd() {
// initilaize int type variable for indexing
int index;
cout << "Odd Numbers in the range " << start << " to " << end << " are "
<< endl;
// for loop to search odd number in the range
for (index = start; index <= end; index++) {
// if the index_1 is completely divided by 2
if (index % 2 != 0) {
cout << index << " ";
}
}
}
};
int main() {
// create a object
IsOdd O;
// calling getRange() function to insert range
O.getRange();
// isOdd() function search odd numbers in the range
O.isOdd();
return 0;
}
Output
RUN 1:
Enter Range:1 10
Odd Numbers in the range 1 to 10 are
1 3 5 7 9
RUN 2:
Enter Range:1 11
Odd Numbers in the range 1 to 11 are
1 3 5 7 9 11
Explanation
In the above code, we have created a class IsOdd, two int type data members start and end to store the start and end of the range, and public member functions getRange() and isOdd() to store and print odd numbers in between that given range.
In the main() function, we are creating an object O of class IsOdd, reading a range by the user using getRange() function, and finally calling the isOdd() member function to print the odd numbers in the given range. The isOdd() function contains the logic to print odd numbers in the given range and printing the result.
C++ Class and Object Programs (Set 2) »