- C# Tutorial
- C# Tutorial
- C# Basic Syntax
- C# Operators
- C# if else
- C# switch
- C# Loops
- C# break Vs. continue
- C# Arrays
- C# Strings
- C# Methods
- C# Examples
- C# Add Two Numbers
- C# Swap Two Numbers
- C# Reverse a Number
- C# Reverse a String
- C# Celsius to Fahrenheit
- Computer Programming
- Learn Python
- Python Keywords
- Python Built-in Functions
- Python Examples
- Learn C++
- C++ Examples
- Learn C
- C Examples
- Learn Java
- Java Examples
- Learn Objective-C
- Web Development
- Learn HTML
- Learn CSS
- Learn JavaScript
- JavaScript Examples
- Learn SQL
- Learn PHP
C# program to add two numbers
This post is published to add two numbers in C#. First, I will approach a program that does not receive any input from the user. Then I will create another program that will allow the user to input two numbers, which will be added, and the addition result will be printed back on the output console.
Simple C# code to add two numbers
First, let me create a simple C# program that will add two numbers.
int a = 10; int b = 20; int sum = a + b; Console.WriteLine("Sum = " + sum);
The output should exactly be:
Sum = 30
The same program can also be created in this way.
int a = 10, b = 20; Console.WriteLine("Sum = {0}", a + b);
Caution: If you use "Sum = " + a + b," then both a and b will be treated as strings.
C# code to add two numbers entered by user
Now let me create another C# program that will add and print the addition result of two numbers entered by the user at run-time of the program.
Console.WriteLine("Enter the first number: "); int a = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the second number: "); int b = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("\nSum = {0}", a + b);
The snapshot given below shows the sample run of this C# example after providing the user input of 12 and 43 as two numbers.
I already defined how receiving inputs from a user occurs in C# on the main page of the C# tutorial, which you can easily find.
« CodesCracker.com Next Program »