Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count Odd and Even numbers in a range from L to R in C++
We are given a range starting from L to R of integer values and the task is to calculate the count of odd numbers and the even numbers in the range.
Input − L = 7, R = 17
Output − Count of Even numbers in a range from L to R are − 5
Count of Odd numbers in a range from L to R are − 6
Input − L = 1, R = 10
Output − Count of Even numbers in a range from L to R are − 5
Count of Odd numbers in a range from L to R are − 5
Approach used in the below program is as follows
Input the range starting from L to R
Pass the L and R values to the function to find out the even values and then we will calculate the odd values depending upon the return value.
Start loop FOR from i to L till R
Inside the loop, check IF i%2==0 then increment the even count by 1
Return the even count
Now to calculate the odd count set odd as (R - L + 1) - even
Example
#include <iostream>
using namespace std;
int Odd_Even(int L, int R){
int even = 0;
for(int i = L ;i < R ;i++){
if(i%2==0){
even++;
}
}
return even;
}
int main(){
int L = 7, R = 17;
int even = Odd_Even(L, R);
int odd = (R - L + 1) - even;
cout<<"Count of Even numbers in a range from L to R are: "<<even<<endl;
cout<<"Count of Odd numbers in a range from L to R are: "<<odd;
return 0;
}
Output
If we run the above code it will generate the following output −
Count of Even numbers in a range from L to R are: 5 Count of Odd numbers in a range from L to R are: 6