Need help: Leap-Year project

Hey, I’ve been interested in C++ for a long time now and started using this service to learn it but now I’m stuck on this exercise. Not sure if my math is wrong or the output is :sweat_smile: . (I also used this resource to further assist me on the math, https://docs.microsoft.com/en-us/office/troubleshoot/excel/determine-a-leap-year ) Thanks to anyone who’s willing to help. Edit: I added the second else if just for “making sure” purposes although It’s probably unnecessary.

Here’s code:

#include <iostream>

int main() {
  // Variables
  int y;

  // Store input Data
  std::cout << "Enter year: ";
  std::cin >> y;

  // Calculation

  if (y < 1000 or y > 9999) {
      
      // Testifies if year is four-digit
    std::cout << "Invalid Year.\n";

  } else if (y / 4 == 0 and y / 100 == 0 and y / 400 == 0) {
      
      // if y is divisible by 4, 100 and 400, then it's a year leap.
    std::cout << y;
    std::cout << " falls on a leap year.\n";
  
  } else if (y / 4 == 0 and y / 100 != 0) {
      
      // if y is divisble by 4 and not 100 then it's a year leap.
    std::cout << y;
    std::cout << " falls on a leap year.\n";
  
  } else {
    // else it isn't a year leap.
    std::cout << y;
    std::cout << " isn't a leap year.\n";
  
  }
}

Hello @system8222641569, welcome to the forums! Are you sure you want to use the / operator (divided by). Shouldn’t you use the modulo operator?

What is the modulo operator, and what does it do?

The modulo operator is used in similar fashion to the / operator, however returns the remainder of the division. So, if I have 5 modulo 4, it should return 1, as 5 divided by 4 equals 1 remainder 1.

This is the modulo operator: %


Aside, why do you need this line:

if this line will also do:

It seems like you have the condition if the year is divisible by 4, and by 100, and by 400, then do the following code:. But since 100 and 400 are both divisible by 4, why do you need them in the condition at all?

1 Like

Ah! Thank you! @codeneutrino, I used the wrong operation, should’ve been using this " % " instead of this " / ". Also, I added that line for the sake of my own sanity, I kept peeping at forums with this exercise, but they had more serious questions then mine, I feel dumb now. Ha, well, thanks for your help. (For some reason, I already suspected that was the issue, but my brain-cells were dead at that moment so I didn’t want to think much about it). Have a good day, and thank you for the warm welcome too.

1 Like