Review of 1301 and C#

advertisement
Lecture 2
Review of 1301 and C#
Richard Gesick
Common data types
int, long, double, float, char, bool,
string
To declare a variable
<type> <name>;
Example:
int myNum;
You can also initialize it when you delcare it:
int myNum = 42;
string myString="josh";
Console I/O
Console.Write(X);
Console.WriteLine(X);
string A = Console.ReadLine();
Note that ReadLine() returns a string, so if you want
to get something else from the user (and int for
example), you would have to convert it. For 1302,
you may assume the user will give valid input, but
later in the course we will explore exception
handling.
Conversion
int myNum = Int32.Parse(Console.ReadLine());
This takes in input from the user (as a string) and then
passes this string to the Parse method of the Int32 class;
this Parse method returns an int, so this is a valid
assignment since now the left and the right side of the
assignment (=) operator are of the same type.
User interaction
string name;
Console.Write("What is your name? ");
name = Console.ReadLine();
Console.WriteLine("Hello " + name);
Notice in the above that the + operator
acts as string concatenation.
Conditionals
Console.Write("How old are you? ");
int age = Int32.Parse(Console.ReadLine());
if (age < 18)
Console.WriteLine("You cannot drink or vote.");
else if (age < 21)
Console.WriteLine("You can vote but not drink.");
else
Console.WriteLine("You can vote and drink, but
don't vote shortly after drinking!");
{ }
Notice in the previous that we don't have to use curlybrackets to define the block in the if-else because we
only want to control one line of code, but if you
wanted to do more than one statement, use { } to
mark the body of the if-else statement blocks.
Declaring Methods
You declare a method in C# using the following
pattern:
<return type> <name> (<parameter(s)>)
{
<body of method>
}
Method examples 1 a menu
void PrintMenu()
{
Console.WriteLine("1. Display result");
Console.WriteLine("2. Add a number");
Console.WriteLine("3. Delete a number");
Console.WriteLine("4. QUIT");
}
Method examples 2 choice
int GetChoice()
{
int choice;
do {
Console.Write("Enter your choice (1-4) : ");
choice = Int32.Parse(Console.ReadLine());
} while ((choice < 1) || (choice > 4));
return choice;
}
for loops
for(<initialize>; <conditional>; <post-activity>)
{
<body/work>
}
for ( int i=0; i < 100; i += 2)
{
Console.WriteLine(i);
}
do while loop
do {
<body/work>
} while (<conditional>);
int i = 10;
do {
Console.WriteLine(i);
i--;
} while (i > 0);
while loop
while (<conditional>)
{
<body/work>
}
int i = 0;
while (i != 0)
{
Console.WriteLine(i);
i -= 1;
}
Download