Sie sind auf Seite 1von 60

Lesson 02:

Introduction to C#

Objectives
What you will learn...
How to do imperative programming using C#.
C# control structures and data structures

Lesson 2: Introduction to C#

The Hello World program in C


Step 1
Open any text editor and copy the following code lines
exactly. Notepad would be a good choice for the task
Step 2
Save the file as HelloWorld.cs

Lesson 2: Introduction to C#

Running the Hello World in C#


Step 3
After saving the file, open the command prompt and navigate to the
directory containing the file.
Step 4
In the command prompt type csc HelloWorld.cs and press enter.
Step 5
To run HelloWorld, simply execute the generated exe file.

Lesson 2: Introduction to C#

Explaining the Hello World Program


using System;

This line is required because it


tells the compiler that we
will use the System
namespace.
The System namespace is
needed since we will be
displaying items to the
command line.
Namespaces will be discussed
in later chapters.

using System;
class MyClass
{
static void Main() {
Console.WriteLine("Hello
World!");
}
}

Lesson 2: Introduction to C#

Explaining the Hello World Program


class HelloWorld

HelloWorld is a user given


name used label the class
using the class keyword.
RULE # 1
We will define what a class is in
module3 but for now let us just
make it a rule to place all the
codes in the following manner.
class ClassName
{
place your codes here...
}

using System;
class MyClass
{
static void Main() {
Console.WriteLine("Hello
World!");
}
}

Lesson 2: Introduction to C#

Explaining the Hello World Program


static void Main()

This line determines which


codes are to be the
starting point of the
program should the class
be executed.
This will be further in this
module under the
methods part.

using System;
class MyClass
{
static void Main() {
Console.WriteLine("Hello
World!");
}
}

Lesson 2: Introduction to C#

Explaining the Hello World Program


Console.WriteLine("Hello
World!");

This line is the one


responsible for printing
the "Hello World"
statement in the
command line.

using System;
class MyClass
{
static void Main() {
Console.WriteLine("Hello
World!");
}
}

Lesson 2: Introduction to C#

Explaining the Hello World Program


{ and }

These symbols are used top


group together lines falling
under the same group.
So far all of are lines are singular
so there is no evident reason
for this but we will later see its
importance.
Rule # 2
The number of { must much the
number of } in every source
code.

using System;
class MyClass
{
static void Main() {
Console.WriteLine("Hello
World!");
}
}

Lesson 2: Introduction to C#

What are variables?


Variables are data storages for information
which will be used throughout the execution of
the program.
Normally a variable has two parts, the variable
name and its value but it is possible for us to
have a variable without a name. An example will
be shown later.

Lesson 2: Introduction to C#

10

Variable Declaration
Format
{Datatype} variable_name;
{Datatype} variable_name = value;
{Datatype} variable_name1, variable_name1;
Example
int number1 = 1;
int number1, number2, number3;
string hello = hello world;

Lesson 2: Introduction to C#

11

Basic Data Types


Int
Holds a signed numeric value somewhere between -2 billion to
+2billion
It is the basic data type used to hold numeric values.

Char
Holds a Unicode character (i.e. a, 1, _)
Character data types are used to hold 1 ASCII value.

String
A string is a special data type which can hold a group of
characters as text. A string can also be treated as an array of
characters. Arrays will be discussed shortly.

(i.e. Hello World, I am good., 1234)


Lesson 2: Introduction to C#

12

Rules for Naming Variables


Variable names must
only be composed of
letters, numbers and
underscores (_).
Variable names must
begin with either a letter
or an underscore.
Keywords must not be
used as variable
names.

Valid Variable Names


Number1
X9y
_message
Hello
Invalid Variable Names
Main
Static
4love
tel#

Lesson 2: Introduction to C#

13

Rules for Naming Variables


main and static are invalid variable names because they
are keywords.
4love is an invalid variable name because it starts with a
number instead of either a letter or underscore
tel# is an invalid variable name because # is neither an
alphanumeric character nor an underscore and is
therefore not allowed in being part of a variable name

Lesson 2: Introduction to C#

14

Constants
Constants are special kinds of variable in that their value
cannot be changed and is known at compile time.
Values of constants must be defined explicitly and
cannot be changed during run-time.
To declare constants, we simply place the const keyword
before the variable type.
Ex. public const pi_value = -3.14;
public string hello = hello;

Lesson 2: Introduction to C#

15

Types of Variable According to Scope


Global Variable
A global variable is a variable declared in the class definition
level. It is declared outside of any method and as such can be
accessed by any method belonging to the class.
Ex.
class{
int global_Num;
static void method1(){
..}
static int method2(){
..}
}
The variable global_Num can be accessed by all methods
including both method1 and method2.
Lesson 2: Introduction to C#

16

Types of Variable According to Scope cont


Local Variable
A local variable is a variable declared in a method definition.
A local variable can only be accessed in the method it is defined
in.
Ex.
class{
static void method1(){
int local_Num;
..}
static int method2(){
..}
}
The variable local_Num can only be accessed by method1 and
not method2.
Lesson 2: Introduction to C#

17

Types of Variable According to Scope cont


Block Variable
A block variable is a variable declared in a code block such as a
case block, if block, then block and others. A block can be
viewed as a code between the { and } symbols. Block variables
can only be accessed in the block it is declared in.
Ex.
class{
static void method1(){
if (true){
int block_Num;
.} // it can be accessed up to here
..}
}
The variable block_Num can only be accessed by codes
following it and before the first succeeding }.
Lesson 2: Introduction to C#

18

What is an array?
An array is a collection of variables of 1 specific data
type.
It can be likened to a train, each cart being a separate
variable but become linked together with other similar
carts.
Array members can be accessed directly like normal
variable.
Arrays provide an important way for accessing different
variables in a loop. Loops will be discussed later in this
module.
Lesson 2: Introduction to C#

19

Declaring Arrays
Unlike declaring the data types discussed earlier,
declaring arrays take a slightly longer approach.
{datatype}[] var_name = new {datatype}[size];
Ex int[] num1 = new int[10];
Declares an array of 10 integers.
string[] msg1 = new string[1];
Declares an array of 1 string.

Lesson 2: Introduction to C#

20

Accessing Array Content

To access a content of an element of an array, we need


to specify the array name as well the index of the
element whose content we need.

var_name[index] = value;
num_array[0] = 10;
string_array[10] = hello;

Lesson 2: Introduction to C#

21

Accessing Arrays

Note that array indexing starts at 0, therefore if you


declared an array of n values, you can access up to
index n -1.

Ex. int[] num_array = new int[10];


You can access variables from num_array[0] to
num_array[9] which totals to 10 elements.

Lesson 2: Introduction to C#

22

What are Operators?

Operators are integral parts of any programming


language. They are the key to data manipulation
as well as program flow manipulation.
Operators are used to store, edit and process
information during program execution.

Lesson 2: Introduction to C#

23

Assignment Operator
The assignment operator is used to assign a value to a
variable. It is an operator that is applicable to all kinds of
data types.
It is arguably the most used operator.
Ex num1 = 100;
num2 = num1 + 1;
string msg = hello;
yes = true;

Lesson 2: Introduction to C#

24

Note on Assigning Values


Whenever we deal with string values we have to enclose
the value in and otherwise it will be treated as a
variable and would possibly produce a variable not found
error.
By enclosing numbers in and , we declare the as string
and as such cannot be used to perform arithmetic
operations without returning it to a numeric form.
Ex. The value 123 is different from the value 123.
123 is treated as a number while 123 is treated as
a string.
Lesson 2: Introduction to C#

25

Numerical Operators
Basic Numerical Operators include
addition (+)
subtraction (-)
multiplication (*)
division (/)

Numerical operators hold for byte, short, int, long, single,


double, decimal and their unsigned counterparts.

Lesson 2: Introduction to C#

26

Numerical Operators

The precedence rule for basic numerical operators is


similar to that of mathematics, PEMDAS.
Parenthesis, Exponent, Multiplication and Division, then
Addition and Subtraction. Numerical expressions are
evaluated in this order.
Multiplication and division

Lesson 2: Introduction to C#

27

Numerical Operators
Examples 1
5 + 8 * (9 7) / 4
5+8*2/4
5 + 16 / 4
5+4
9

Example 2
(10 - (5 + 7) / 3 ) * 2
(10 12 / 3) * 2
(10 4) * 2
6*2
12

Lesson 2: Introduction to C#

28

Numerical Operators
Other Numerical Operators
Increment (++)
Adds 1 to the value of a variable
Ex. num1++, ++num1
Placing ++ before the variable adds the value before evaluating the
expression while placing it after would result in evaluation before adding
the value
Ex.

int num1 = 10;


int num2 = num1++;
Console.WriteLine(num1);
Console.WriteLine(num2);

Note 11 and 10 would be printed respectively

Lesson 2: Introduction to C#

29

Numerical Operators
Other Numerical Operators
Decrement (--)
Works exactly the same way as increment but subtracts 1
instead of adding 1.

Modulo Division (%)


Returns the remainder of a division operation
12 % 10 would return 2

Lesson 2: Introduction to C#

30

String Operator
string concatenation (+)
Appends concatenates strings.
Ex.

string str1 = love;


string str2 = peace;
str1 = str1 + str2;
Console.WriteLine(str1);

Note lovepeace would be displayed

Lesson 2: Introduction to C#

31

Boolean Operators
Boolean Operators (cont)
and (&)
Returns true only if both operands are true
Ex
true & true = true
false & true = false

or (|)
Returns true if at least one operand is true
Ex.
true | false = true
false | false = false

not (!)
Negates an operand
Ex.
(!true) = false
(!false) = true
Lesson 2: Introduction to C#

32

Comparison Operators
Numerical Comparison Operators
Greater than (>)
Less than (<)
Greater than or equal (>=)
Less than or equal (<=)
Equal (==)
Not equal (!=)

Returns true if the mathematical equations holds true


otherwise returns false.
Lesson 2: Introduction to C#

33

Comparison Operators
String Comparison Operator
Equal (==)
Returns true if the two string operators hold exactly the same value.

Not equal (!=)


Returns true if the two strings are different

Boolean Comparison Operator


Equal (==)
Returns true if the operands hold the same value

Not Equal (!=)


Returns true if the operands have different value

Lesson 2: Introduction to C#

34

Type Conversion

A question of converting types will surely arise as we


program and while typecasting and coercion mostly
solve our problems, there is a systematic way of doing
this.
There is a class under the System namespace that
serves this purpose, the Convert class.

Lesson 2: Introduction to C#

35

Example of the Convert Class


int x = 90909;
string y = Convert.ToString(x);
Console.WriteLine(y);
Note: This would print 90909 as a string.

string y = "123";
int x = Convert.ToInt16(y);
Note: This would convert y into the number 123

string y = "123a";
long x = Convert.ToInt64(y);
Note: This would produce an exception because of it cannot convert
123a into a number.
Lesson 2: Introduction to C#

36

What are branching statements?


Branching statements are statements that serve to
control program flow.
Based on a given condition it will direct which program
statements will be executed and which ones will be
ignored.
Branching statements are important for handling different
things differently.

Lesson 2: Introduction to C#

37

Types of Branching Statements

If-then-else statements
More comprehensive branching statement capable of
representing just about every kind of branching need.

Case statements
A case statement is good option for checking ordinal values
(i.e. A-Z)

Lesson 2: Introduction to C#

38

If-Then-Else Construct at a glance


if (num1 > 0)
Console.WriteLine(Number is +);
else
Console.WriteLine(Number is );
Suppose num1 is a predefined integer.
Given different values for num1, the program would print
different messages.

Lesson 2: Introduction to C#

39

Parts of the If-Then-Else Construct

The Condition
The condition is a vital part in the If-Then-Else construct.
Should it evaluate to true it would tell the program to
execute the succeeding statements. Otherwise the
statements would be skipped.
The condition above was (num1 > 0).

Lesson 2: Introduction to C#

40

Parts of the If-Then-Else Construct


The then part
The then part refers to the statements after the condition
statements.
These are the statements to be executed should the condition
return true.
The then part above was Console.WriteLine(Number is +);
Should there be more than one line, the symbol { and } is
placed before the first line and after the last line respectively.

Lesson 2: Introduction to C#

41

Parts of the If-Then-Else Construct


The else part
Unlike the first two parts, the else part is optional
The statements in the else part is executed whenever the
condition returns false, otherwise it is skipped.
The { and } symbols are also used for more than 1
statement.

Lesson 2: Introduction to C#

42

A Slightly Complex Example


If (num1 > num2)
{
if (num1 > num3)
Console.WriteLine(Num1 is largest);
else if (num3 > num1)
Console.WriteLine(Num3 is largest);
}
else (num2 > num1)
{
if (num2 > num3)
Console.WriteLine(Num2 is largest);
else if (num3 > num2)
Console.WriteLine(Num3 is largest);
}
Lesson 2: Introduction to C#

43

Case Statement In a Glance


num1 is a predefined integer

Format

switch(num1)
{
case 1
Console.WriteLine(one)
break;
case 2
Console.WriteLine(two)
break;
case 3
Console.WriteLine(three)
break;
}

switch(variable_name)
{
case constant1
Statements
break;
case constant2
Statements
break;
case constant3
Statements
break;
}
Lesson 2: Introduction to C#

44

Case Statements
In a case statement, you basically place the variable to be test
for in the switch statement.
What follows is the list of possible values preceded by the
case keywords and followed by the corresponding lines and a
break statement.
The statements following the case containing the matched
constant are executed.
Note that only constants can be placed after the case
keywords. Variables cannot be used.
Lesson 2: Introduction to C#

45

While Loop
int num = 10;
while(num>0)
{
Console.WriteLine(num--);
}
The loop will continue until
num becomes 0, at which
point it will not enter the
loop and jump to the end.

Program Output:
10
9
8
7
6
5
4
3
2
1

Lesson 2: Introduction to C#

46

Do-While Variant
int num = 0;
do {
Console.WriteLine(num--);
} while(num>0)
Program Output
0
The difference of the loop above to the last one is that the
statements are executed even before the condition is
tested.
You are guaranteed at least one run of the codes in the
loop.
Lesson 2: Introduction to C#

47

For Loop
The for loop construct is the stricter of the looping
constructs.
In loop definition we have the initialization part, the
condition part and the increment per run. The
statements follow the loop initialization.
The loop continues as long as the condition part
holds true.

Lesson 2: Introduction to C#

48

For Loop Template


for(variable_dec; condition; increment)
{
Place codes here
}
Note: variable_dec and increment parts are completely
optional but the condition part is required.

Lesson 2: Introduction to C#

49

For loop example


for( int num1=0; num1<10;
num1++)
Console.WriteLine(num1);
Note: This code will return the
exact same output.

int num1=0;
for(; num1<10;)
{
Console.WriteLine(num1);
num1 = num1 + 1;
}

Program Output
0
1
2
3
4
5
6
7
8
9
Lesson 2: Introduction to C#

50

Loops and Arrays


Suppose we have an array of string with n
elements named string_array
The code to the right displays the first 10 elements
of the string array.
for(int x=0;x>10;x++)
Console.WriteLine(string_array[x]);

Lesson 2: Introduction to C#

51

Console Output
We have shown plenty of examples that print information
on the command line. This is done through the use of the
Console.WriteLine() command.
This command accepts any data type and prints it into
the command line.
Ex Console.WriteLine(Love and Peace);
This would print Love and Peace in the console.

Lesson 2: Introduction to C#

52

Console Input
Console input is done through the use of the
Console.ReadLine() command.
It reads a string input from the user by waiting
for the Carriage Return to be pressed.
To use the input as other data types, the Convert
class is needed.

Lesson 2: Introduction to C#

53

Console Input
Example of storing a string:
string msg = Console.ReadLine();
Example of storing an integer:
string msg = Console.ReadLine();
int num1 = Convert.ToInt32(msg);

Lesson 2: Introduction to C#

54

Method Declaration
A method requires a method name, a return type
and a method definition.
Return types may be any data type, void or
objects. Void defines the method to return
nothing. Objects will be discussed further in the
next module. The value to be returned is marked
by the return keyword.

Lesson 2: Introduction to C#

55

Methods with Return Value

A method with a return type other than void


requires the use of the return keyword followed
by the value to be returned. Without the use of a
return statement, an error will occur.

Lesson 2: Introduction to C#

56

Static Methods
Methods are bound to objects but since we have yet
to discuss objects we will employ the use of static
methods.
Static methods can be called without instantiating
objects but we will change this approach in the next
module.
Static methods are declared as such but adding the
static keyword before stating the return type of the
method.
Lesson 2: Introduction to C#

57

Calling Static Methods


Calling static methods greatly differ from calling non-static
methods but for now we will stick top calling static methods.
Format for calling a static method:
ClassName.MethodName(paramaters);
ClassName is the name given to the class where the method
belongs.
MethodName is name of the method.
Parameters are the values required by a method. The need for
parameters depend on the method. Actual parameters must
match the formal parameters in the method definition and note
that parameter order does matter.
Lesson 2: Introduction to C#

58

Example of Static Method Calls


class MyClass{
static int getNumber(){
String input = Console.ReadLine();
return Convert.ToInt32(input);
}
static int adder(int num1, int num2){
return num1 + num2;
}
static void printer(string message){
Console.WriteLine(message);
}

Lesson 2: Introduction to C#

59

Example of A Method Call cont.


static void Main(string[] args){
Console.Write("Enter First Number : ");
int number1 = MyClass.getNumber();
Console.Write("Enter Second Number: ");
int number2 = MyClass.getNumber();
int answer = MyClass.adder(number1, number2);
Console.Write("The Sum is ");
MyClass.printer(Convert.ToString(answer));
Console.Write("Press any key to continue...");
Console.ReadLine();
}
}

Lesson 2: Introduction to C#

60

Das könnte Ihnen auch gefallen