Visual C# Guide
Data Types Examples

Example 1

Create a new console application called SumTotal. Copy the following code into the program and press the F5 key to compile and run.

int firstNumber;
int secondNumber;
int total;
Console.Write("Enter the first number ");
firstNumber = System.Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the second number ");
secondNumber = System.Convert.ToInt32(Console.ReadLine());
total = firstNumber + secondNumber;
Console.WriteLine("{0} + {1} = {2}", firstNumber, secondNumber, total);

Study the code carefully. Notice that the input we get from the keyboard has to be converted into the data type we are working with (in this case, whole numbers). It comes in the form of a string. If we don't do the conversion, we get an error from the compiler.

You should also look at how we output information to the screen. The curly braces {} are used to show where variables are included in the output. A comma-separated list of the variables appears after the double quotes.

Having A Go

  1. Change the program so that it
    1. subtracts the second number from the first
    2. multiplies the numbers together
    3. divides the first number by the second
  2. Change the program so that it performs all of the operations in one program, displaying the results in a useful way.
  3. Write a program that allows the user to input the radius of a circle and get the area and circumference. (π = 3.14159, area = πr2, circumference = 2πr)
  4. A class has four exams in one term. Write a program that reads in these scores and returns the student's average mark.
  5. A temperature in degrees Celsius can be converted to degrees Fahrenheit using the formula F = (9/5) * C + 32. Write a program that allows the user to input a temperature in Celsius and output the equivalent in degrees Fahrenheit.
  6. Write a program that converts temperatures from degrees Fahrenheit to degrees Celsius.