Input Birth Year and Display Age in CSharp

Input Birth Year and Display Age

Introduction

In computer programming, one of the most important skills to master is handling user input and program output. Input allows users to interact with a program by providing data, while output displays results based on the program’s logic. In C#, the Console.ReadLine() method is commonly used to receive text input from the keyboard, and type conversion is applied to transform this input into different data types, such as integers or floating-point numbers.

In this lesson, we will create a simple yet practical program that asks the user to input their birth year and then displays their age. This activity will help you understand how to capture user input, convert it to the correct type, and perform basic calculations. It is a fundamental step toward building more interactive and meaningful programs.


Learning Objectives

The objectives of this lesson are divided into four levels based on Outcome-Based Education (OBE). By the end of this lesson, you will be able to:

Introduction to Objectives:
The objectives of this lesson focus on helping learners gain a deeper understanding of handling input and output operations in C#, while also developing their skills in type conversion and logic building. These outcomes guide students from comprehension to application.

  1. Understand – Explain the purpose and usage of Console.ReadLine() and type conversion in C# programming.
  2. Learn – Identify the steps needed to process user input and convert data types effectively.
  3. Practice – Write and test a program that inputs a birth year and calculates the current age of the user.
  4. Apply – Modify and enhance the basic program to handle potential errors and improve user interaction.

Step-by-Step Tutorial

Step 1: Create a New C# Project

  1. Open Visual Studio or Visual Studio Code.
  2. Create a new Console Application project.
  3. Name the project: BirthYearCalculator.

Step 2: Write the Code

Here is the beginner-friendly C# source code:

using System;

namespace BirthYearCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            // Display a message to the user
            Console.WriteLine("Welcome to the Age Calculator!");

            // Ask the user to input their birth year
            Console.Write("Please enter your birth year: ");
            string birthYearInput = Console.ReadLine(); // Capture input as a string

            // Convert the string input to an integer
            int birthYear = Convert.ToInt32(birthYearInput);

            // Get the current year automatically
            int currentYear = DateTime.Now.Year;

            // Calculate the age
            int age = currentYear - birthYear;

            // Display the calculated age
            Console.WriteLine("You are approximately " + age + " years old.");

            // Wait for user to press Enter before closing
            Console.WriteLine("Press Enter to exit...");
            Console.ReadLine();
        }
    }
}

Step 3: Example Output

Input:

Welcome to the Age Calculator!
Please enter your birth year: 2000

Output:

You are approximately 25 years old.
Press Enter to exit...

Code Explanation

  • Console.WriteLine() – Displays messages to the screen.
  • Console.ReadLine() – Captures user input as a string.
  • Convert.ToInt32() – Converts the string input into an integer for calculations.
  • DateTime.Now.Year – Automatically retrieves the current year.
  • Calculation Logic – Subtracts the birth year from the current year to get the user’s age.

Summary

In this lesson, we learned how to handle input and output in C# using the Console.ReadLine() method and type conversion. By creating a program that calculates a user’s age based on their birth year, we applied the concepts of string handling, type conversion, and arithmetic operations. These fundamental skills form the basis of interactive programming and prepare you for more complex applications in the future.


Multiple-Choice Questions (Bloom’s Taxonomy)

  1. Remembering:
    Which method is used in C# to receive user input from the keyboard?
    A. Console.WriteLine()
    B. Console.ReadLine()
    C. Console.Input()
    D. Console.Scan()

  1. Understanding:
    Why is type conversion necessary when using Console.ReadLine()?
    A. To print the output in uppercase.
    B. Because Console.ReadLine() only returns strings.
    C. To automatically detect data types.
    D. It is not necessary.

  1. Applying:
    If the current year is 2025 and the user enters 1995 as their birth year, what is their age?
    A. 20
    B. 25
    C. 30
    D. 35

  1. Analyzing:
    What will happen if a user enters text like “hello” instead of a number?
    A. The program will display age as zero.
    B. The program will ignore the input and continue.
    C. The program will throw a runtime error.
    D. The program will automatically convert text to a number.

  1. Evaluating:
    Which of the following is the best practice to prevent errors in user input?
    A. Ignore invalid inputs.
    B. Assume all inputs are correct.
    C. Use error handling like try-catch.
    D. Avoid asking for user input.

Exercises, Assessment, and Lab Exam

Introduction

To strengthen your understanding, it is essential to practice beyond the basic example. The following exercises and assessments are designed to enhance your programming skills and ensure you can apply input/output handling and type conversion concepts effectively.


Exercises:

  1. Modify the program to:
    • Display a personalized message using the user’s name and age.
    • Example: “Hello John! You are 25 years old.”
  2. Add a feature to check if the user has already celebrated their birthday this year.
  3. Handle errors gracefully if the user enters invalid input such as letters or symbols.

Assessment:

Create a program that:

  • Asks the user for their name, birth year, and birth month.
  • Calculates and displays the user’s exact age in years and months.
  • Includes error handling using try-catch blocks to avoid crashes.

Criteria for Assessment:

  • Correct use of Console.ReadLine() and type conversion.
  • Proper validation and error handling.
  • Clear and user-friendly output.

Lab Exam:

Develop a Student Registration System (Console-based) that:

  1. Accepts student details: name, age, and course.
  2. Validates that the age is a number and within a reasonable range (e.g., 16–60).
  3. Displays the entered information in a formatted output.

Additional Requirements:

  • Include comments explaining each part of the code.
  • Implement at least one error handling mechanism.

You may visit our Facebook page for more information, inquiries, and comments. Please subscribe also to our YouTube Channel to receive free capstone projects resources and computer programming tutorials.

Hire our team to do the project.

, , , , , , , , , ,

Post navigation