Our next example is to write some programs that does mathematical
computations. But before that can be effectively we have to talk about
variables and constants.
What is a variable?
A variable is a storage location in your computer memory where data
can be stored and retrieved.
A variable name can be any combination of letters, letters and
numbers, etc, but cannot have spaces e.g. fashion90, car, la2k, etc. Do not
begin variable name with number. Like 5kay, 100weo, are all wrong variable
names. And remember that a variable name does not allow spaces instead use
underscore sign (_).
The major types of variable types used in C# are:
1.
Int:
These includes numbers without decimal part.
2.
Double:
these includes numbers with decimal part.
3.
Float:
same with double.
4.
String:
used to display strings of characters.
5.
Char:
same as string.
The various types in C# are enormous but we are going to discuss the
few above.
What are constants?
Unlike variables constants are data storage location. As the name
implies constants do not change.
Now let us demonstrate the above concepts with programs that multiply
two numbers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace myfirstprogram
{
class Program
{
static void Main(string[] args)
{
double num1, num2, result;
Console.WriteLine("Enter
the value for num1");
num1 = Convert.ToDouble(Console.ReadLine()); //
assigning value to num1
Console.WriteLine("Enter
the value for num2");
num2 = Convert.ToDouble(Console.ReadLine());//
assigning value to num1
result = num1 * num2; //mutiply two numbers
Console.WriteLine("Result="
+ result);
}
}
}
The program above shows the use of variables. You will notice that
the user can input any value for num1 and num2. The result will always be
different.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace myfirstprogram
{
class Program
{
static void Main(string[] args)
{
double num1, num2, result;
num1 = 3; // assigning value to num1
num2 = 4;// assigning value to num1
result = num1 * num2; //mutiply two numbers
Console.WriteLine("Result=" + result);
}
}
}
The program shows the use of constant. Like I said earlier on that
constant do not change. You will notice that when you run the program several
time, it will always display the same result (12);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace myfirstprogram
{
class Program
{
static void Main(string[] args)
{
string a;
Console.WriteLine("what
is your name?");
a=Convert.ToString(Console.ReadLine());
Console.WriteLine("Hello"
+ a);
}
}
}
Study the program above and tell me what it does. You are free to
copy the code into your C# environment.