User Input

User Input

To accept input from user, We use Console class Console has a function called ReadLine() which tells the OS to ask for user input. We shall discuss using and classes later:

using System; 

Console.ReadLine();

After we read it, we can convert the data into required format using Convert class:

Convert.ToInt32(Console.ReadLine())

Exercise

Ask the user for two his birth year in yyyy format and calculate his age and display:

using System;

 class Program
 {
    static void Main(string[] args)
    {
        Console.WriteLine("Enter your YOB:");
        int yob = Convert.ToInt32(Console.ReadLine());
        

        //Do not modify code below!
        int age = 2022 - yob;
        Console.WriteLine($"You are {age} years old!");        
    }
}

We could do the same for a decimal type number as well:

Convert.ToDouble(Console.ReadLine());

Exercise

Ask the user his weight and display it:

using System;

 class Program
 {
    static void Main(string[] args)
    {
        Console.WriteLine("Enter your weight:");
        double weight =  /*todo - get from user */

        //do not change code below:       
        Console.WriteLine($"You are {weight} kgs!");        
    }
}

Last updated