C++ Program to calculate the number of odd days in given number of years


Given with the positive integer value n and the task is to generate the number of odd days till the given year n.

Example

Input-: days = 500
Output-: number of odd days are: 5
Input-: days = 400
Output-: number of odd days are: 0

How to calculate the number of odd days in given number of years

For calculating the number of odd days the first thing we need to check is whether the given year is a leap year or not because if it’s a leap year than the number of odd days will get changed. If the year is divisible by 100 or 400 but not by 4 then the year will be the leap year else it will be the ordinary year. If we find out the modulus of total number of days with 7 i.e. the number of days in a week. So, ordinary year comprises of 1 odd day and leap year comprises of 2 odd days.

Approach we are using in the given program is as follow

  • Input the number of days as an input
  • Check whether the year is a leap year or an ordinary day
  • Calculate the odd days by dividing the total number of days with modulus
  • Display the final result as the number of days in a year from 1 to n

ALGORITHM

Start
Step 1-> Declare function to calculate number of odd days in a given year
   int cal_odd(int days)
   declare int cal_1 = days / 100
   declare int cal_2 = days / 400
   declare int check_leap = days >> 2
   declare int temp = days - check_leap
   IF (cal_1)
      set temp += cal_1
      Set check_leap -= cal_1
   End
   IF (cal_2)
      Set temp -= cal_2
      Set check_leap += cal_2
   End
   declare int final_days = temp + check_leap * 2
   Declare int odd = final_days % 7
   return odd
step 2->In main()
   Declare int days = 500
   call cal_odd(days)
Stop

Example

#include <iostream>
using namespace std;
//calculate number of odd days in a given year
int cal_odd(int days) {
    int cal_1 = days / 100;
    int cal_2 = days / 400;
    int check_leap = days >> 2;
    int temp = days - check_leap;
    if (cal_1) {
        temp += cal_1;
        check_leap -= cal_1;
    }
    if (cal_2) {
        temp -= cal_2;
        check_leap += cal_2;
    }
    int final_days = temp + check_leap * 2;
    int odd = final_days % 7;
    return odd;
}
int main() {
    int days = 500;
    cout<<"number of odd days are : "<<cal_odd(days);
    return 0;
}

Output

number of odd days are : 5

Updated on: 20-Nov-2019

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements