Advertisement
janac

Determine if its a leap year

Jan 5th, 2022
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1.  
  2.  
  3. // Determine if a year is a leap year or not.
  4.  
  5. #include <iostream>
  6. #include <string>
  7.  
  8. using namespace std;
  9.  
  10. // This function returns true if a
  11. // year is a leap year, otherwise false.
  12. int is_leap(int year)
  13. {
  14.     if (year % 100 == 0) // If it's divisible by 100,
  15.     {
  16.         if (year % 400 == 0) // And divisible by 400.
  17.         {
  18.             return true; // It's a leap year.
  19.         }
  20.         else // If it's divisible by 100 but not 400,
  21.         {
  22.             return false; // It's not leap year.
  23.         }
  24.     }
  25.     else // Else if it's not divisible by 100,
  26.     {
  27.         if (year % 4 == 0) // If it's divisible by 4,
  28.         {
  29.             return true; // It's a leap year.
  30.         }
  31.         else // Else if it's not divisible by 4,
  32.         {
  33.             return false; // It's not a leap year.
  34.         }
  35.     }
  36. }
  37.  
  38. int main()
  39. {
  40.     bool successful_conversion = false; // Is the user's input an integer?
  41.     bool is_a_leap_year = false; // Is the year a leap year?
  42.     string year; // User's input.
  43.     int converted_srting_input = 0; // User's input converted to an integer.
  44.  
  45.     cout << "This program will determine if a year is a leap year.\n";
  46.  
  47.     while (!successful_conversion) // While the user's input is not an integer,
  48.     {
  49.         cout << "\nWhat year do you want to check? ";
  50.         cin >> year; // Get user input.
  51.  
  52.         try // Prepare to handle if the user's input is not an integer.
  53.         {
  54.             converted_srting_input = stoi(year); // Try to convert input to integer.
  55.             successful_conversion = true; // Input was an integer.
  56.         }
  57.         catch (...) // If the string input can't be converted to an integer,
  58.         {
  59.             cout << "Something is wrong with the year you entered.\n"
  60.                 "Try again.\n\n";
  61.         }
  62.     }
  63.  
  64.     is_a_leap_year = is_leap(converted_srting_input); // Determine if it's a leap year.
  65.  
  66.     // Announce the result.
  67.     cout << "\nThe year " << converted_srting_input << " is ";
  68.     if (!is_a_leap_year)
  69.     {
  70.         cout << "not ";
  71.     }
  72.     cout << "a leap year.\n";
  73.  
  74.     return 0; // End the program.
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement