Thursday, March 9, 2017

Lesson 2: Input and Output in C#

Input and Output

WRITE A PROGRAM THAT ASKS A USER WHAT HIS/HER NAME IS AND THEN DISPLAYS THE FOLLOWING TEXT TO THE CONSOLE:
                         Hello, <Name>

Brief Notes: 

  • In C#, every code is written inside a class. A class is a blueprint for creating an object; an object is an instance of a class.
  • The execution of any C# program starts in a special method called the main method.
  • The main method has the following syntax:

                The main method in C#

  • To output text to the console we use Write or WritleLine method of the Console class; for example, 
    • Console.Write("Enter Your Name:");
    • Above code outputs the text Enter Your Name to the console.
  • To input data from the console, for instance, name, we first create a variable (a storage location in memory to hold the name) and then we use the ReadLine method of the Console class. For  example: 
    • string name = Console.ReadLine();
  • Every statement in C# ends in semicolon (;)

Note: We will discuss variables, classes and objects in the coming lessons.


Here is the complete program:
/* 
  * Author: Temesghen Tekeste 
  * email: mail.temesghen.tekeste@gmail.com 
  * */
using System;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("What is your name?");
            string name = Console.ReadLine();
            Console.WriteLine();
            Console.WriteLine("Hello, " + name);
            Console.WriteLine("Press any key to exit ...");
            Console.ReadKey();
        }
    }

}
Download Source Code



OUTPUT: 

      

No comments:

Post a Comment