You are on page 1of 51

Chapter 2

Language in C#.Net

Compiled By Abrham Y. 1
Contents

• Variable types and identifiers


• Constants
• Number types, strings
• Operators and operator precedence
• Type Conversion/ Casting

Compiled By Abrham Y. 2
Variable types and identifiers
• Identifier: is a name given to variables, class, function, constants
and others that identifies the items from others in the computer
program.
• All identifiers must obey the following rules
– An identifier is a sequence of characters that consists of letters, digits,
underscores (_), and dollar signs ($)
– An identifier must start with a letter, an underscore (_), or a dollar
sign ($). It cannot
start with a digit.
– An identifier cannot be a reserved word.
– An identifier cannot be true, false, or null.
– An identifier can be of any length

Compiled By Abrham Y. 3
cont…….
• Variables : are used to store values to be used later in a program. They
are called variables because their values can be changed.
• Is an identifier that denoted a storage location in memory
• Variables are for representing data of a certain type. To use a variable,
you declare it by telling the compiler its name as well as what type of
data it can store.
• The variable declaration tells the compiler to allocate appropriate
memory space for the variable based on its data type. The syntax for
declaring a variable is:
datatype variableName;
• Here are some examples of variable declarations:
int count; // Declare count to be an integer variable;
double radius; // Declare radius to be a double variable;
double interestRate; // Declare interestRate to be a double
variable; Compiled By Abrham Y. 4
Constants
• The value of a variable may change during the
execution of a program, but a named constant
or simply constant represents permanent data
that never changes.
• For example PI is a constant 3.14159;
• Syntax for declaring a constant:
const datatype CONSTANTNAME = VALUE;
const float PI=3.14159;

Compiled By Abrham Y. 5
Data Type in C#.Net

• A data type is a classification of the type of


data that a variable or object can hold(store)

Compiled By Abrham Y. 6
Cont…

Compiled By Abrham Y. 7
Cont…

8
Compiled By Abrham Y.
String type
• The string type enables you to assign string
value to the variable of string type.

Compiled By Abrham Y. 9
Declaring of variable

• In C#.Net all variables must be declared


before the can use
– Syntax
– Data_type valid_identifer

Compiled By Abrham Y. 10
Key word in C#.net

• Keywords are predefined reserved


identifiers that have special meaning to the
compiler
• Keywords can’t be used as variable in your
programming.

Compiled By Abrham Y. 11
Cont..

Compiled By Abrham Y. 12
Data type conversion in C#.net

• There are two methods available for type


conversion
1. Target data type.parse(“value”)
E.g int.parse(“10”).=>10
double.parse(“10.5”)=>10.5
2. Convert.to target data type class(“value”).
E.G Convert.ToInt32(“10”).=>10
convert.toDouble(“10.5”).=>10.5

Compiled By Abrham Y. 13
Operators
• Arithmetic Operators

+ addition
- subtraction
* multiplication
/ Division
% modulo
Compiled By Abrham Y. 14
Cont…

== Assignment
++ Increase operator
-- decreasing

Compiled By Abrham Y. 15
Cont…
• Compound assignment
expression Is equivalent to

x+=y x=x+y
x-=y x=x-y

x/=y x=x/y
X*=y x=x*y

x++ x=x+1
y-- y=y-1
16
Compiled By Abrham Y.
Cont…
• Relational and equality operators
== Equale to
!= Not equal to
> Greater than
< Less than
>= Greater than or
equal
<= Less than or equal

Compiled By Abrham Y. 17
Cont….
• Logical operator

&& Conditional and


|| Conditional or
! Conditional not

Compiled By Abrham Y. 18
Control statements and loop

Compiled By Abrham Y. 19
Contents

• If statement
• Switch statement
• For loop
• While, Do while loop

Compiled By Abrham Y. 20
If statement
• C#.net has several types of if statements:
one-way if statements,
two-way if statements,
nested if statements,
 A one-way if statement executes an action if and only if
the condition is true. The syntax for a one-way if
statement is shown below:
if (boolean-expression)
{
statement(s);
}
Compiled By Abrham Y 22
If statement cont…

Compiled By Abrham Y 23
If statement cont…
• Two-Way if Statements: in this statement the system performs the
operation in the if statement when the boolean expression is true
otherwise the else block os statements are excuted. That is the
operation is performed based on the values of the boolean
experesion. Here is the syntax for a two-way if statement:
if (boolean-expression)
{
statement(s)-for-the-true-case;
}
else
{
statement(s)-for-the-else-case;
}
Compiled By Abrham Y 24
If statement cont…

Compiled By Abrham Y 25
If ….else…if
• A common program construct that is based on upon a sequence of nested

Syntax
if (boolean_exp1) {
statement(s)1;
}
else if (boolean_exp2) {
statement(s)2;
}
..
..
else
statement(s)n;

Compiled By Abrham Y 26
Nested if Statements
• Nested if Statements: both if or if ... else statement can be any legal
Java statement, including another if or if ... else statement.
• The inner if statement is said to be nested inside the outer if
statement.
• The inner if statement can contain another if statement; in fact,
there is no limit to the depth of the nesting.
Syntax
if (boolean_exp1)
if (boolean_exp2)
else
else
if (boolean_exp3)
else

Compiled By Abrham Y 27
switch Statements
• Switch is one of a selection statement in Java programming language.
Syntax
switch (switch-expression)
{
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
} Compiled By Abrham Y 28
C#.net console program Exercises

1. Write a C# program, that receive a number and


determine whether it is odd or even.
2. Write a C# program; that receive a number and
determine whether it is positive, negative or zero.
3. Write a C# program; obtain two numbers from
the keyboard, and determine and display which
(if either) is the larger of the two numbers.
4. Write a C# program; Find the maximum and
minimum, of three numbers given by the user.

Compiled By Abrham Y 30
Type of iteration statement(loop)
• For loop
• While loop
• Do while loop
• For each loop

Compiled By Abrham Y 31
The for Loop
Syntax
for (initial-action; loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
Statement(s);
}

Compiled By Abrham Y
32
The while Loop

• The syntax for the while loop is as follows:


while (loop-continuation-condition) {
// Loop body
Statement(s);
}
• The part of the loop that contains the statements to be repeated is called
the loop body. A one-time execution of a loop body is referred to as an
iteration of the loop.
• Each loop contains a loop-continuation-condition, a Boolean expression
that controls the execution of the body.
• It is valuated each time to determine if the loop body is executed. If its
evaluation is true, the loop body is executed; if its evaluation is false, the
entire loop terminates and the program control turns to the statement that
follows the while loop.

Compiled By Abrham Y 34
The while loop cont…..

Compiled By Abrham Y 35
The do-while Loop
• The do-while loop is a variation of the while loop. Its syntax is given below:
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
• The loop body is executed first. Then the loop-continuation-condition is
evaluated.
• If the evaluation is true, the loop body is executed again; if it is false, the
do-while
loop terminates.
• The difference between a while loop and a do-while loop is the order
inwhich the loop-continuation-condition is evaluated and the loop body
executed.
• The while loop and the do-while loop have equal expressive power.
Sometimes one is a more convenient choice than the other.
36
Compiled By Abrham Y
The do-while Loop cont…..

Compiled By Abrham Y 37
For each loop

• For each loop is a different kind of looping


construct in c#.Net programming does not
include initialization ,termination and
increment /decrement characteristics
• If use collection to take value one by one
then process them
For(String name in array_name)
{
} Compiled By Abrham Y 38
Nested Loop

• That is one loop may be inside another


e.g for (initial-action; loop-continuation-condition; action-after-each-iteration) {
while (loop-continuation-condition) {
// Loop body
Statement(s);
}

Compiled By Abrham Y 39
C#.net console program Exercises

1. Write a C# program; Add the numbers from 1 to 100 and


display the sum.
2. Write a C# program; Add the even numbers between 0
and any positive integer number given by the user.
3. Write a C# program; read 10 integers from the keyboard
in the range 0 - 100, and count how many of them are
larger than 50, and display this result.
4. Write C# programs; which get a natural value, n, as its
input and calculates sum of odd numbers equal or less
than n.

Compiled By Abrham Y 40
Cont…
.
5.Write C# program to print out multiplication table in the following manner

Compiled By Abrham Y 41
Arrays

Array is simply group of data of the same type


Array is created using “new” keyword implying that it is
an object (or a reference type)
1. Declaring an Array:
o<datatype>[]
E.g. int[] x;
<arrayReference>;

char[] y;
o NB: no mentioning size during declaration
2. Creating an Array:
o created using “new” keyword
o <arrayReference> = new <datatype>[size];
E.g. x = new int[5];
y = new char[20];
 Declaring and Creating can be done in one line as
follow:
int[] x = new int[5];
char[] y = new char[20];
Compiled By Abrham Y 42
Initializing Array (one dimensional)
• C# has a shorthand notation, known as the array initializer, which
combines in one statement declaring an array, creating an array, and
initializing, using the following syntax:
Syntax
dataType[] arrayRefVar = {value0, value1, ..., valuek};
Example: int [] stsAge={21,20,18,19,19,20,32};
This array initializer statement is equivalent with the following java line of
code:
int [] stsAge;
stsAge=new int [10];
stsAge[0]=21; stsAge[0]=19; stsAge[0]=32;
stsAge[1]=20; stsAge[0]=19;
stsAge[2]=18; stsAge[0]=20;
Compiled By Abrham Y 43
Accessing Array element using
loop
• When processing array elements, you 1. Initializing arrays with
will often use a for loop—for two input values
reasons: java.util.Scanner input = new
– All of the elements in an array java.util.Scanner(System.in);
are of the same type. They are System.out.print("Enter " +
evenly processed in the same myList.length + " values: ");
fashion repeatedly using a loop. for (int i = 0; i <
– Since the size of the array is myList.length; i++)
known, it is natural to use a for myList[i] =
loop. input.nextDouble();
• Assume the array is created as 2. Displaying arrays
follows:
for (int i = 0; i <
double[] myList = new double[10]; myList.length; i++) {
Here are some examples of processing System.out.print(myList[i] +
arrays: " ");
Compiled By Abrham Y 44
}
Accessing Array element using
for each loop
• String []arr={“bereket”,”eyole”,”mekdes”};
foreach(String name in arr)
{console.writeLine(name);
}

Compiled By Abrham Y 45
Two Dimensional Array
1. Declaring an Array:
o <datatype>[][] <arrayReference>; //<datatype>
<arrayReference>[][];
E.g. int[][] x;
char[][] y;
o NB: no mentioning size during declaration
2. Creating an Array:
o created using “new” keyword
o <arrayReference> = new <datatype>[size1][size2];
E.g. x = new int[5][5];
y = new char[20][5];
 Declaring and Creating can be done in one line as follow:
int[][] x = new int[5][20];
char[][] y = new char[20][5];

Compiled By Abrham Y 46
Initializing Two Dimensional Array

Syntax
<datatype> [][] <referenceName> ={{v1,v2….vn},
{v1,v2….vn}, {v1,v2….vn},…{v1,v2….vn}};
Example:
int[][]matrix={
{1,4,5,6},
{11,22,11,9},
{12,9,13,15},
{11,20,5,6}
};
Compiled By Abrham Y 47
Jagged Array

• The element of jagged array can be of


different dimensions and size
• A jagged array is known as array of array
• E.g

50 20 40 10 60 30

Compiled By Abrham Y 48
Jagged array

Compiled By Abrham Y 49
Example1 jagged Array

int [][]arr=new int[4][];


arr[0]=new int [3];
arr[1]=new int [2];
arr[2]=new int [5];
arr[3]=new int [1];

Compiled By Abrham Y 50
Compiled By Abrham Y 51
Example2 jagged Array

int [][]jaggedArray=new int[3][];


jaggedArray[0]=new int [5];
jaggedArray[1]=new int [4];
jaggedArray[2]=new int [2];

Compiled By Abrham Y 52
Exmple3 jagged array

• Write a program that display the element of


the following jagged array using loop
int [][]jaggedArray=new int[][]{
new int[]{1,3,5,7,9},
new int []{0,2,4,6},
new int []{11,22}
};

Compiled By Abrham Y 53
C#.net console program Exercises
1. Write a C# program that finds the smallest and largest number in an array.
2. Write a C# program that accepts the name of a person and then counts
how many vowels the person’s name have.
3. Write a program that adds two arrays and store the result in third array.
4. Write a program; that accepts an array of non-negative integers and
returns the second largest integer in the array. Return -1 if there is no
second largest.
5. Write a program; that takes an array of integers as input and returns a
value based on the sums of the event and odd numbers in the array.
6. Write a program; that takes an array of integers as input and search any
key element.
7. Write C++ program; that takes an array of integers as input and sort the
elements of the array

Compiled By Abrham Y 54

You might also like