C# Program to Input Two Numbers and Display their Sum.

In this C# programming example, we will learn how to take input from the user for two numbers, calculate their sum, and display the result. This basic program will help you understand how to interact with the user and perform simple arithmetic operations in C#.

Sum of Two Numbers

Problem Statement: Write a C# program that takes two numbers as input from the user, calculates their sum, and displays the result.

Example:

Enter the first number: 5
Enter the second number: 7
The sum of 5 and 7 is: 12


C# Code to Find the Sum of Two Numbers.

//C-sharp code to print sum of two number
using System;

namespace SumCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter the first number: ");
            //coverting input string to integer value
            int num1 = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter the second number: ");
            int num2 = Convert.ToInt32(Console.ReadLine());

            int sum = num1 + num2;

            Console.WriteLine($"The sum of {num1} and {num2} is: {sum}");
        }
    }
}
Output:
Enter the first number: 12
Enter the second number: 10
The sum of 12 and 10 is: 22

Code Explanation:

Inside the Main method of the above C# code:
  • Console.Write("Enter the first number: "); displays a message asking the user to enter the first number.
  • int num1 = Convert.ToInt32(Console.ReadLine()); reads the user's input and converts it to an integer.
  • Similar steps are followed to get the second number.
  • int sum = num1 + num2; calculates the sum of the two numbers.
  • Console.WriteLine($"The sum of {num1} and {num2} is: {sum}"); displays the result using string interpolation.

Key Points:
  • The Convert.ToInt32() method is used to convert the user's input (which is a string) into an integer.
  • The $ symbol is used for string interpolation, which allows us to embed expressions within strings for dynamic output.
  • The Console.ReadLine() method reads the entire line of text entered by the user, including spaces.

This program demonstrates how to interact with the user, perform arithmetic operations, and output results in C#.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS