Professional Documents
Culture Documents
02 Basics
02 Basics
Objectives
2
Class
3
Main
class MyApplication
{
entry point static void Main()
{
...
}
}
4
Simple types
class MyApplication
{
static void Main()
{
variables double area;
char grade;
int x, y, z;
string name;
...
}
}
6
Local variable initialization
int x;
error, x not set int y = x * 2;
...
}
}
7
Type conversion
int i = 5;
double d = 3.2;
implicit conversion d = i;
8
Input
9
Output
int System.Console.WriteLine(i);
double System.Console.WriteLine(d);
class MyApplication
{
static void Main()
{
string s = Console.ReadLine();
short names
int i = Convert.ToInt32(s);
...
}
}
11
Comments
Operator Description
+ addition
- subtraction
* multiplication int x = 5;
int y = 3;
/ division
% remainder addition int z = x + y;
<< left shift
>> right shift
& bitwise and
| bitwise or
^ bitwise xor
~ bitwise complement
13
Combination assignment
Operator Description
+= add / assign
-= subtract / assign
%= remainder / assign
++ pre/post increment
-- pre/post decrement
?: conditional
int x = 5; int x = 5;
int y = 3;
int max;
post-increment
int y = x++; max set to
y = 5, x = 6
greater of max = x > y ? x : y;
x and y
pre-increment
int z = ++x;
x = 7, z = 7
15
Array
a[0] = 17;
element access a[1] = 32;
int x = a[1];
16
Array element values
17
If statement
18
If/else statement
int x = 3;
int y = 5;
int min;
if (x < y)
min = x;
else part else
min = y;
19
Code block
int x = 3;
int y = 5;
int min, max;
if (x < y)
block {
min = x;
max = y;
}
else
block {
min = y;
max = x;
}
20
Comparison and logical operators
int x;
char c;
== equal
both must be true if (x > 0 && x < 10) != not equal
...
<, <= less
either can be true if (c == 'y' || c == 'Y')
... >, >= greater
21
Switch statement
22
Switch type
switch (color)
{
strings case "red" : Console.WriteLine("red"); break;
case "blue" : Console.WriteLine("blue"); break;
case "green": Console.WriteLine("green"); break;
}
23
Multiple labels
switch (grade)
{
case 'A':
case 'B':
pass case 'C':
Console.WriteLine("pass");
break;
case 'D':
case 'F':
no pass Console.WriteLine("no pass");
break;
}
24
Multiple actions
switch (level)
{
case "silver":
priorityCheckIn = true;
break;
forward control
case "gold":
to other case
priorityUpgrade = true;
goto case "silver";
case "platinum":
useOfLounge = true;
goto case "gold";
}
25
while loop
int i = 0;
26
do-while loop
int x;
do do
{
string s = System.Console.ReadLine();
x = System.Convert.ToInt32(s);
}
test done
while (x < 0);
after body
27
for loop
28
foreach loop
29
Break
int i = 0;
bool error;
while (i < 5)
{
...
if (error)
break break;
...
}
30
Continue
int i = 0;
bool skip;
while (i < 5)
{
...
if (skip)
continue continue;
...
}
31
Goto
label error:
Console.WriteLine("Error");
...
32
Summary
33