w3resource

C#: Get the century from a year


Find Century of Year

Write a C# program to get the century of a year.

Sample Solution:

C# Sharp Code:

using System;

public class Exercise
{
    // Function to calculate the century from a given year
    public static int centuryFromYear(int year)
    {
        // Calculation of the century by dividing the year by 100 and adding 1 if there's a remainder
        return (int)(year / 100) + ((year % 100 == 0) ? 0 : 1);
    }

    public static void Main()
    {
        // Testing the centuryFromYear function with various year inputs and verifying the results
        Console.WriteLine(centuryFromYear(1799) == 18); // Verifies if the century for year 1799 is 18
        Console.WriteLine(centuryFromYear(1900) == 19); // Verifies if the century for year 1900 is 19
        Console.WriteLine(centuryFromYear(1901) == 19); // Verifies if the century for year 1901 is 19
        Console.WriteLine(centuryFromYear(1901) == 20); // This line seems to have an incorrect expectation (1901 can't be both 19th and 20th century)
        Console.WriteLine(centuryFromYear(1806) == 19); // Verifies if the century for year 1806 is 19
        Console.WriteLine(centuryFromYear(1568) == 20); // Verifies if the century for year 1568 is 20
        Console.WriteLine(centuryFromYear(2010) == 21); // Verifies if the century for year 2010 is 21
    }
}

Sample Output:

True
True
False
True
True
False
True 

Flowchart:

Flowchart: C# Sharp Exercises - Get the century from a year

For more Practice: Solve these Related Problems:

  • Write a C# program to determine if a given year is the first year of a century.
  • Write a C# program to check whether two different years belong to the same century.
  • Write a C# program that takes a year and returns the century in Roman numerals.
  • Write a C# program to count how many centuries are there between two given years.

Go to:


PREV : Check Odd Number in Array.
NEXT : Max Product of Adjacent Elements.

C# Sharp Code Editor:



What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.