Exercise 1 – Get two numbers from the user and add them

It’s time for some code writing to practice what we have learnt in the previous tutorials. Here we will write code to ask two numbers from the user, add them and print their sum. The classes and methods we will be using in the exercise are

Console.ReadLine() – This function will be used to read the user input. Remember that it gives you a string input and you will have to convert it to integer type before performing the addition operations.

Convert.ToInt32 – This function will be used to convert the string type input we will get from Console.ReadLine() method and convert it to an integer type

Console.Write and Console.WriteLine – These functions will be used to print the output on the console window and ask use to perform some operations.

Step 1 – Create a console application

Open your Visual Studio and click on File->New Project from the top menu and create a new Console Application. Make sure that you choose the language of coding as C# and all the files in the Console application which you have created have their extensions as .cs and not .vb.

Step 2 – Write this code in the Main function

Write this code in your Main function

static void Main(string[] args)  {          // Get the first number from the user            // Print this message          Console.Write("Enter first number : ");            // Store the user input in a string variable          string str = Console.ReadLine();            // Convert it into integer type and store in          // an integer variable.          int firstNumber = Convert.ToInt32(str);            // Ask for the second number          Console.Write("Enter second number : ");            // Store the user input in a string variable          str = Console.ReadLine();            // Convert it into integer type and store in          // an integer variable          int secondNumber = Convert.ToInt32(str);            // Add the two number and store the sum          int sum = firstNumber + secondNumber;            // Print the final sum          Console.Write("The sum is : " + sum);  }

Read the comments in the code to understand what we are doing. The output of this program is shown below

C# - Exercise 1 output

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp