excerpt: This covers the basic building blocks Modulo Operator, for loop and Counter. tags: modulo-operator for-loop counter

Write a program that prints the next 20 leap years.

Leap Year

  • If a year is divisible by 4, 100 and 400 then it is a leap year.
  • If a year is divisible by 4 but not divisible by 100 then it is a leap year

Check for Leap Year

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def leap(year)
  if (year % 4 == 0) && (year % 100 != 0)
    return true  
  end
   
  if (year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0)
    return true
  end
  
  return false
end

p leap(1972)

Next 20 Leap Years

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
def leap
  count = 0

  for i in (2021..2500)
    if count == 20
      break
    end

    if (i % 4 == 0) && (i % 100 != 0)
      count += 1
      p i
    end
   
    if (i % 4 == 0) && (i % 100 == 0) && (i % 400 == 0)
      count += 1
      p i
    end
  end
end

p leap

Building Blocks

  • Modulo Operator
  • for Loop
  • Counter