#include <iostream>
usingnamespace std;
//prototypes
void intro();
int getYear(int);
bool leapYear(int);
bool showYear(int,bool);
int main()
{
int date;
bool leapyear;
intro();
date = getYear(date);
leapyear = leapYear(date);
showYear(date,leapyear);
return 0;
}
void intro()
{
cout << "\tThis will show you if a year is a leap year or not\n\n";
return;
}
int getYear(int)
{
int year;
cout << "Enter a year: ";
cin >> year;
return year;
}
bool leapYear(int year)
{
bool leap;
int leap_year;
int leap4;
int leap100;
int leap400;
leap4 = year / 4;
leap100 = year / 100;
if (leap4 == year/4)
{
if (leap100 == year/100)
{
leap = true;
}
else
leap = false;
}
return leap;
}
bool showYear (int year,bool leap)
{
if (leap == true)
cout << year << " is a leap year";
else
cout << year << " is not a leap year";
return leap;
}
i was wondering if i am on the right track with all the if/else statements or if there is a simpler way?
Look at it this way:
If year / 4 has a remainder then its NOT a leap year.
Otherwise if year/100 has a remainder then it IS a leap year
otherwise if year/400 has a remainder then it is NOT a leap year
otherwise it is a leap year.
You can use the % operator for remainder. e.g. year % 4 gives the remainder after dividing year by 4 (assuming year is positive).
He’s using boolean expressions, which have a value of 0 or 1.
You should use some if statements, just like in dhayden’s answer.
For example, you can tell if a number is ODD or EVEN:
If the number is evenly divisible by 2, then it is EVEN otherwise it is ODD
This translates very cleanly to a function:
1 2 3 4 5
bool is_odd( int n )
{
if ((n % 2) == 0) returnfalse; // it is even if (n / 2) has a remainder of 0
elsereturntrue; // it is odd
}
Making a function to determine whether a year is a leap year works on the very same principle:
1 2 3 4 5 6 7
bool is_leap_year( int year )
{
if (...) // if (year / 4) has a non-zero remainder then NOT a leap year
elseif (...) // if (year / 100) has a non-zero remainder then IS a leap year
elseif (...) // if (year / 400) has a non-zero remainder then NOT a leap year
else // IS a leap year
}