- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- Count of numbers from range[L, R] whose sum of digits is Y in C++
- Count of all even numbers in the range [L, R] whose sum of digits is divisible by 3 in C++
- Python program to Count Even and Odd numbers in a List
- Even numbers at even index and odd numbers at odd index in C++
- Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime in C++
- Count and Print the alphabets having ASCII value in the range [l, r] in C++
- Count even and odd digits in an Integer in C++
- Program to count odd numbers in an interval range using Python
- Count and Print the alphabets having ASCII value not in the range [l, r] in C++
- Largest Even and Odd N-digit numbers in C++
- Count subarrays with same even and odd elements in C++
- Count of Numbers in a Range divisible by m and having digit d in even positions in C++
- Program to find count of numbers having odd number of divisors in given range in C++
- Count rotations of N which are Odd and Even in C++
- Swift Program to Get Odd and Even Numbers From the Array
