C# Programing
Fundamentals
Fundamentals
  • C# Fundamental concepts
    • Introduction to C#.NET
    • Variables and Types
    • User Input
    • Strings
    • Methods
    • Date and Time
    • Conditions
    • Loops
    • Arrays
  • Problem based learning
    • P1: Arithmetic Calculator
    • P2: Number Guessing
    • P3: Print Patterns
    • P4: Grade Average
    • P5: Calculate Age
  • Practice Problems
    • W3Schools
    • Edabit
Powered by GitBook
On this page
  • User Input
  • Exercise
  • Exercise
  1. C# Fundamental concepts

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!");        
    }
}
PreviousVariables and TypesNextStrings

Last updated 2 years ago