1523. Count Odd Numbers in an Interval Range solution in c++
Here is a solution in C++ to count the number of odd numbers in an interval range. I will provide explanations for each step of the code.
#include <iostream>
int countOddNumbers(int start, int end) {
int count = 0; // Initialize a counter variable to keep track of the number of odd numbers
for (int i = start; i <= end; i++) { // Iterate through each number in the given interval range
if (i % 2 != 0) { // Check if the number is odd
count++; // Increment the counter if the number is odd
}
}
return count; // Return the final count of odd numbers
}
int main() {
int start, end;
std::cout << "Enter the start of the interval range: ";
std::cin >> start; // Read the start of the interval range from the user
std::cout << "Enter the end of the interval range: ";
std::cin >> end; // Read the end of the interval range from the user
int oddCount = countOddNumbers(start, end); // Call the countOddNumbers function to count the odd numbers
std::cout << "The number of odd numbers in the interval range is: " << oddCount << std::endl; // Print the result
return 0;
}
Explanation of each step:
The code starts by including the necessary header file
iostream
, which provides input and output stream classes in C++.The
countOddNumbers
function is defined with two parametersstart
andend
representing the start and end of the interval range.Inside the
countOddNumbers
function, an integer variablecount
is initialized to 0. This variable will be used to keep track of the number of odd numbers in the range.A
for
loop is used to iterate through each number in the given interval range. The loop starts at thestart
value and continues until it reaches theend
value.Inside the loop, an
if
statement is used to check if the current numberi
is odd. This is done by checking if the remainder ofi
divided by 2 is not equal to 0.If the number is odd, the
count
variable is incremented by 1.After the loop finishes, the final count of odd numbers is returned from the
countOddNumbers
function.In the
main
function, integer variablesstart
andend
are declared.The user is prompted to enter the start and end of the interval range using
std::cout
andstd::cin
statements.The
countOddNumbers
function is called with thestart
andend
values as arguments, and the returned count is stored in theoddCount
variable.Finally, the result is printed to the console using
std::cout <<
statement, along with the value ofoddCount
. Thestd::endl
statement is used to insert a newline character.The program ends by returning 0 from the
main
function, indicating successful execution.