Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Convert a given year to century

C++ Date: Exercise-3 with Solution

Write a C++ program to convert a given year to century.

Note: A century is a period of 100 years. Centuries are numbered ordinally in English and many other languages. The word century comes from the Latin centum, meaning one hundred. Century is sometimes abbreviated as c.

Sample Solution-1:

C++ Code:

#include <iostream>
#include <cmath>
 
using namespace std;

double year_to_century(int y) {

        return floor((y-1)/100+1);
    }

int main(){
   int y;
   y = 1900;
   cout << "Year: " << y << ",  Century of the year: "<<year_to_century(y);
   y = 1999;
   cout << "\nYear: " << y << ",  Century of the year: "<<year_to_century(y);
   y = 2000;
   cout << "\nYear: " << y << ",  Century of the year: "<<year_to_century(y);
   y = 2010;
   cout << "\nYear: " << y << ",  Century of the year: "<<year_to_century(y);
   y = 2020;
   cout << "\nYear: " << y << ",  Century of the year: "<<year_to_century(y);      
}

Sample Output:

Year: 1900,  Century of the year: 19
Year: 1999,  Century of the year: 20
Year: 2000,  Century of the year: 20
Year: 2010,  Century of the year: 21
Year: 2020,  Century of the year: 21

Flowchart:

Flowchart: Convert a given year to century.

Sample Solution-2:

C++ Code:

#include <iostream>

using namespace std;
double year_to_century(int y) {

        return (y - 1) / 100 + 1;
    }

int main()
{
   int y;
   y = 1900;
   cout << "Year: " << y << ",  Century of the year: "<<year_to_century(y);
   y = 1999;
   cout << "\nYear: " << y << ",  Century of the year: "<<year_to_century(y);
   y = 2000;
   cout << "\nYear: " << y << ",  Century of the year: "<<year_to_century(y);
   y = 2010;
   cout << "\nYear: " << y << ",  Century of the year: "<<year_to_century(y);
   y = 2020;
   cout << "\nYear: " << y << ",  Century of the year: "<<year_to_century(y);      
}

Sample Output:

Year: 1900,  Century of the year: 19
Year: 1999,  Century of the year: 20
Year: 2000,  Century of the year: 20
Year: 2010,  Century of the year: 21
Year: 2020,  Century of the year: 21

Flowchart:

Flowchart: Convert a given year to century.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Get the day of the week from a given date.
Next: Check whether a given year is a leap year not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.