SlideShare une entreprise Scribd logo
1  sur  87
Berhanu Fetene (MSc.)
Chapter Two:
C# (C-sharp) programming language
5/5/2021 1
C# Programming
 C# is an object-oriented programming language.
 In Object-Oriented Programming methodology, a program consists of various
objects that interact with each other by means of actions.
 The actions that an object may take are called methods.
 Objects of the same kind are said to have the same type or are said to be in the
same class.
 C# is case sensitive
 All statements and expression must end with a semicolon(;).
 The program execution starts at the main method.
 Unlike Java, program file name could be different from the class name.
5/5/2021 2
C# Program Structure
 A C# program consists of the following parts:
 Namespace declaration
 A class
 Class methods
 Class attributes
 A main method
 Statements and expressions
 Comments (optional)
5/5/2021 3
7
Sample C# program:
using System;
class HelloCSharp
{
static void Main()
{
Console.WriteLine("Hello, C#");
}
}
C# Code – How It Works?
using System;
class HelloCSharp
{
static void Main()
{
Console.WriteLine("Hello, C#");
}
}
Include the standard
namespace "System"
Define a class called
"HelloCSharp"
Define the Main()
method – the
program entry point
8
Print a text on the console by calling
the method "WriteLine" of the class
"Console"
C# Code Should Be Well
Formatted
using System;
class HelloCSharp
{
s
st
ta
at
ti
ic
c v
vo
oi
id
d M
Ma
ai
in
n(
()
)
{
{
C
Co
on
ns
so
ol
le
e.
.W
Wr
ri
it
te
eL
Li
in
ne
e(
("
"H
He
el
ll
lo
o,
, C
C#
#"
")
);
;
}
}
}
The {symbol should be
alone on a new line.
The block after the
{symbol should be
indented by a TAB.
The }symbol should be
under the
corresponding {.
Class names should use PascalCaseand
start with a CAPITALletter.
9
Important features of C#
 It is important to note the following points:
 C# is case sensitive.
 All statements and expression must end with a semicolon (;).
 The program execution starts at the Main method.
 Unlike Java, program file name could be different from the class name.
Compiling and Executing the Program
 If you are using Visual Studio. Net for compiling and executing C# programs,
take the following steps:
 Start Visual Studio.
 On the menu bar, choose File -> New -> Project.
5/5/2021 7
Compiling and Executing the Program (Cont’d)
 Choose Visual C# from templates, and then choose Windows.
 Choose Console Application.
 Specify a name for your project and click OK button. This creates a new
project in Solution Explorer.
 Write code in the Code Editor.
 Click the Run button or press F5 key to execute the project.
 A Command Prompt window appears that contains the line H
He
el
ll
lo
o,
, C
C#
#"
“.
5/5/2021 8
 The variables in C#, are categorized into one of the following three categories:
 Value types
 Refence types
 Pointer types
1. Value Type
 Value type variables can be assigned a value directly.
 They are derived from the class System.ValueType.
 The value types directly contain data.
5/5/2021 9
Data Types
 Some examples are int, char, and float which stores numbers, alphabets, and
floating point numbers respectively.
 When you declare an int type, the system allocates memory to store the value.
 The following table lists the available value types in C# .
5/5/2021 10
Data Types (Cont’d)
Type Represent Range Default Value
bool Boolean value True or False False
byte 8-bit unsigned integer 0 to 255 0
char 16-bit Unicode Character U +0000 to U +ffff '0'
decimal 128-bit precise decimal Values
with 28-29
significant digits
(-7.9 x 1028
to 7.9 x 1028
)
/ 100
to 1028 0.0M
5/5/2021 11
Data Types (Cont’d)
Type Represent Range Default Value
float 32-bit single-precision floating
point type
-3.4 x 1038
to + 3.4 x 1038 0.0F
int
32-bit signed integer type
-2,147,483,648 to
2,147,483,647
0
long
64-bit signed integer type
-923,372,036,854,775,808 to
9,223,372,036,854,775,807
0L
sbyte 8-bit signed integer type -128 to 127 0
short 16-bit signed integer type -32,768 to 32,767 0
uint 16-bit signed integer type 0 to 4,294,967,295 0
ulong 64-bit unsigned integer type
0 to
18,446,744,073,709,551,615
0
ushort
16-bit unsigned integer
type
0 to 65,535 0
 To get the exact size of a type or a variable on a particular platform, you can
use the sizeof method.
 The expression sizeof(type) yields the storage size of the object or type in
bytes.
 The following is an example to get the size of data types we defined in the
above tables.
5/5/2021 12
Data Types (Cont’d)
5/5/2021 13
using System;
namespace DataTypeSize{
class Program{
static void Main(string[] args){
Console.WriteLine("Size of bool is : {0}", sizeof(bool));
Console.WriteLine("Size of byte is : {0}", sizeof(byte));
Console.WriteLine("Size of char is : {0}", sizeof(char));
Console.WriteLine("Size of decimal is : {0}", sizeof(decimal));
Console.WriteLine("Size of float is : {0}", sizeof(float));
Console.WriteLine("Size of int is : {0}", sizeof(int));
Console.WriteLine("Size of long is : {0}", sizeof(long));
Console.WriteLine("Size of sbyte is : {0}", sizeof(sbyte));
Console.WriteLine("Size of short is : {0}", sizeof(short));
Console.WriteLine("Size of uint is : {0}", sizeof(uint));
Console.WriteLine("Size of ulong is : {0}", sizeof(ulong));
Console.WriteLine("Size of ushort is : {0}", sizeof(ushort));
Console.ReadKey();
}}}
5/5/2021 14
 When the above code is compiled and executed, it produces the following
result:
Size of bool is : 1
Size of byte is : 1
Size of char is : 2
Size of decimal is : 16
Size of float is : 4
Size of int is : 4
Size of long is : 8
Size of sbyte is : 1
Size of short is : 2
Size of uint is : 4
Size of ulong is : 8
Size of ushort is : 2
5/5/2021 15
2. Refence Type
 The reference types do not contain the actual data stored in a variable, but
they contain a reference to the variables.
 In other words, they refer to a memory location.
 Using multiple variables, the reference types can refer to a memory location.
 If the data in the memory location is changed by one of the variables, the
other variable automatically reflects this change in value.
 Example of built-in reference types are: object, dynamic, and string.
Data Types (Cont’d)
5/5/2021 16
A. Object Type
 The Object Type is the ultimate base class for all data types in C# Common
Type System (CTS). Object is an alias for System.Object class.
 The object types can be assigned values of any other types, value types,
reference types, predefined or user-defined types.
 However, before assigning values, it needs type conversion.
 When a value type is converted to object type, it is called boxing and on the
other hand, when an object type is converted to a value type, it is called
unboxing. Example:
Reference Types (Cont’d)
object obj;
obj = 100; // this is boxing
5/5/2021 17
B. Dynamic Type
 You can store any type of value in the dynamic data type variable.
 Type checking for these types of variables takes place at run-time.
 Syntax for declaring a dynamic type is:
 For example:
 Dynamic types are similar to object types except that type checking for object
type variables takes place at compile time, whereas that for the dynamic type
variables takes place at run time.
Reference Types (Cont’d)
dynamic number = 100;
dynamic <variable_name> = value;
5/5/2021 18
B. Dynamic Type
 The String Type allows you to assign any string values to a variable.
 The string type is an alias for the System.String class.
 It is derived from object type.
 The value for a string type can be assigned using string literals in two forms:
quoted and @quoted.
 For example:
 A @quoted string literal looks as follows:
 The user-defined reference types are: class, interface, or delegate. We will
discuss these types in later chapter in details.
Reference Types (Cont’d)
string name= “Rift Valley University";
@“Rift Valley University";
5/5/2021 19
2. Pointer Type
 Pointer type variables store the memory address of another type.
 Pointers in C# have the same capabilities as the pointers in C or C++.
 Syntax for declaring a pointer type is:
 For example:
 We will discuss more about pointer types in the subsections.
Data Types (Cont’d)
type* identifier;
char* cptr;
int* iptr;
 Keywords are reserved words predefined to the C# compiler.
 These keywords cannot be used as identifiers.
 However, if you want to use these keywords as identifiers, you may prefix
them with the @ character.
 In C#, some identifiers have special meaning in context of code, such as get
and set, these are called contextual keywords.
 The following TABLE lists the reserved keywords and contextual keywords
in C# .
5/5/2021 20
C# Keywords
5/5/2021 21
Reserved Keywords
abstract as base bool break byte case
catch char checked class const continue decimal
default delegate do double else enum event
explicit extern false finally fixed float for
foreach goto if implicit in volatile int
interface internal is lock long namespace new
null object operator out private override params
protected public readonly ref return sbyte while
sealed short sizeof stackalloc static string struct
switch this throw true try typeof uint
ulong unchecked unsafe ushort using virtual void
5/5/2021 22
Contextual Keywords
add alias ascending descending dynamic
from get global group into
join let orderby partial (type)
partial (method) remove select set
Identifiers
5/5/2021 23
 An identifier is a name used to identify a class, variable, function, or any
other user-defined item.
 The basic rules for naming identifiers in C# are as follows:
 A name must begin with a letter that could be followed by a sequence of letters,
digits (0 - 9), or underscore.
 The first character in an identifier cannot be a digit.
 It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ]
{ } . ; : " ' / and .
 However, an underscore ( _ ) can be used.
 It should not be a C# keyword.
digit.
C# Variables
5/5/2021 24
 A variable is a name given to a storage area that is used to store values of
various data types.
 Each variable in C# needs to have a specific type, which determines the size
and layout of the variable's memory.
 Based on the data type, specific operations can be carried out on the variable.
 One can declare multiple variables in a program.
 Example1: // age is variable that can store integer value.
// value 30 is assigned to variable age which is declared
before.
Example2: //mulptiple variable declaration
int age;
age =30;
int length, width, area;
C# Operators
5/5/2021 25
1. Arithmetic Operators
 are operators used for performing mathematic operations on numbers.
Below is the list of arithmetic operators available in C#.
Operator Description
+ Adds two operands
- Subtracts the second operand from the first
* Multiplies both operands
/ Divides the numerator by de-numerator
% Modulus Operator and a remainder of after an integer division
++ Increment operator increases integer value by one
-- Decrement operator decreases integer value by one
5/5/2021 26
// C# code to demonstrate the use of arithmetic operators
using System;
namespace ArithmeticOperator{
class Program {
static void Main(string[] args){
int a = 30, b=5;
Console.WriteLine("Sum of a and b is : {0}", a + b);
Console.WriteLine("Difference of a and b is : {0}", a - b);
Console.WriteLine("Product of a and b is : {0}", a * b);
Console.WriteLine("quetient of a and b is : {0}", a / b);
Console.WriteLine("Remander of a and b is : {0}", a % b);
Console.WriteLine("Incerement of a by 1 is : {0}", ++a); // pre-increment
Console.WriteLine("Decrement of b by 1 is : {0}", --b); // post-decrement
Console.WriteLine("Incerement of a by 1 is : {0}", a++); // post-increment
Console.WriteLine("Decrement of b by 1 is : {0}", b--); // post-decrement
Console.WriteLine("Press any key to continue ...");
Console.ReadKey();
} }}
5/5/2021 27
Sum of a and b is : 35
Difference of a and b is : 25
Product of a and b is : 150
quotient of a and b is : 6
Reminder of a and b is : 0
Increment of a by 1 is : 31
Decrement of b by 1 is : 4
Increment of a by 1 is : 31
Decrement of b by 1 is : 4
Press any key to continue ...
 When the above code is compiled and executed, it produces the following
result:
C# Operators(Cont’d)
5/5/2021 28
2. Relational Operators
 These are operators used for performing Relational operations on numbers.
 Below is the list of relational operators available in C#.
Operator Description
== Checks if the values of two operands are equal or not, if yes then condition becomes true.
!= Checks if the values of two operands are equal or not, if values are not equal then condition
becomes true.
> Checks if the value of left operand is greater than the value of right operand, if yes then
condition becomes true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition
becomes true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes
then condition becomes true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes
then condition becomes true.
5/5/2021 29
// C# code to demonstrate the use of Relational Operators
using System;
namespace RelationalOperator{
class Program{
static void Main(string[] args){
int a = 30, b = 5;
Console.WriteLine(" a is equal to b {0}", a==b);
Console.WriteLine(" a is not equal to b {0}", a!= b);
Console.WriteLine(" a is greater than b {0}", a>b);
Console.WriteLine(" a is less than b {0}", a<b);
Console.WriteLine(" a is greater than or equal to b {0}", a>=b);
Console.WriteLine(" a is less than or equal to b {0}", a<=b);
Console.WriteLine("Press any key to continue ...");
Console.ReadKey();
}}}
5/5/2021 30
a is equal to b False
a is not equal to b True
a is greater than b True
a is less than b False
a is greater than or equal to b True
a is less than or equal to b False
Press any key to continue ...
 When the above code is compiled and executed, it produces the following
result:
C# Operators (Cont’d)
5/5/2021 31
3. Logical Operators
 These are operators used for performing Logical operations on values.
 Below is the list of logical operators available in C#.
Operator Description
&& This is the Logical AND operator. If both the operands are
true, then condition becomes true.
|| This is the Logical OR operator. If any of the operands are
true, then condition becomes true.
! This is the Logical NOT operator.
5/5/2021 32
// C# code to demonstrate the use of Logical Operators
using System;
namespace RelationalOperator{
class Program{
static void Main(string[] args){
int a = 30, b = 5;
bool c = false;
Console.WriteLine(" Logical AND {0}", (a == b)&&(a!=b));
Console.WriteLine(" Logical OR {0}", (a != b)||(a>b));
Console.WriteLine(" Logical Negation {0}", !(c));
Console.WriteLine("Press any key to continue ...");
Console.ReadKey();
}}}
5/5/2021 33
 When the above code is compiled and executed, it produces the following
result:
Logical AND False
Logical OR True
Logical Negation True
Press any key to continue ...
5/5/2021 34
 An enumeration is used in any programming language to define a constant set
of values.
 For example, the days of the week can be defined as an enumeration and used
anywhere in the program.
 In C#, the enumeration is defined with the help of the keyword 'enum’.
 enum is a value type data type. The enum is used to declare a list of named
integer constants.
C# Enum Syntax:
enum enum_name{enumeration list}
 The enum is used to give a name to each constant so that the constant integer
can be referred using its name.
 In our example, we will define an enumeration called days, which will be
used to store the days of the week.
C# Enumeration
5/5/2021 35
// C# code to demonstrate the use of enumeration.
using System;
namespace Enumeration{ // enum declaration
enum days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } ;
class Program{
static void Main(string[] args){
Console.WriteLine("Value of Monday is " + (int)days.Monday);
Console.WriteLine("Value of Tuesday is " + (int)days.Tuesday);
Console.WriteLine("Value of Wednesday is " + (int)days.Wednesday);
Console.WriteLine("Value of Thursday is " + (int)days.Thursday);
Console.WriteLine("Value of Friday is " + (int)days.Friday);
Console.WriteLine("Value of Saturday is " + (int)days.Saturday);
Console.WriteLine("Value of Sunday is " + (int)days.Sunday);
Console.WriteLine("Press any key to continue ...");
Console.ReadKey();
}}}
5/5/2021 36
 When the above code is compiled and executed, it produces the following
result:
Value of Monday is 0
Value of Tuesday is 1
Value of Wednesday is 2
Value of Thursday is 3
Value of Friday is 4
Value of Saturday is 5
Value of Sunday is 6
Press any key to continue ...
Conditional Statements
5/5/2021 37
1. if statement
In c#, if statement or condition is used to execute the block of code or
statements when the defined condition is true.
Generally, in c# the statement that can be executed based on the condition is
known as a “Conditional Statement” and the statement is more likely a block
of code.
Syntax of C# if Statement:
The statements inside of if condition will be executed only when the
“expression” returns true otherwise the statements inside of if condition will
be ignored for execution.
if (expression) {
// Statements to Executed if condition is true
}
5/5/2021 38
 Following is the example of defining if statement in c# programming language to execute
the block of code or statements based on expression.
// C# code to demonstrate if statement.
using System;
namespace IfStatement{
class Program{
static void Main(string[] args){
int x = 20;
if(x>0)
Console.WriteLine(" x is positve number ");
Console.WriteLine(" Press any key to Exit...");
Console.ReadKey();
}}}
x is positve number
Press any key to Exit...
 When this code is compiled and executed,
it produces the following result:
Conditional Statements (Cont’d)
5/5/2021 39
2. if-else statement
In c#, if-else statement or condition is having an optional else statements and
these else statements will be executed whenever the if condition is fails to
execute.
 Generally, in c# if-else statement, whenever the expression returns true,
then if statements will be executed otherwise else block of statements will be
executed.
Syntax of C# if-else Statement
if (expression){
// Statements to Executed if expression is True
}
else {
// Statements to Executed if expression is False
}
5/5/2021 40
// C# code to demonstrate if-else statement
using System;
namespace IfElse{
class Program{
static void Main(string[] args){
int x = -20;
if(x>0)
Console.WriteLine(" x is Positve number ");
else
Console.WriteLine(" x is Negative number ");
Console.WriteLine(" Press any key to Exit...");
Console.ReadKey();
}}}
When this code is compiled and executed, it produces the following result:
x is Negative number
Press any key to Exit...
5/5/2021 41
3. if-else if statement (nested if-else statement)
In c#, if-else-if statement or condition is used to define multiple conditions
and execute only one matched condition based on our requirements.
Generally, in c# if statement or if-else statement is useful when we have a
one condition to validate and execute the required block of statements.
In case, if we have a multiple conditions to validate and execute only one
block of code, then if-else-if statement is useful.
Conditional Statements (Cont’d)
5/5/2021 42
Syntax of C# if Statement:
if (condition_1){
// Statements to Execute if condition_1 is True
}
else if (condition_2){
// Statements to Execute if condition_2 is True
}
....
else{
// Statements to Execute if all conditions are False
}
Syntax of C# if-else if Statement:
 The execution of if-else-if statement will starts from top to bottom and as soon as the
condition returns true, then the code inside of if or else if block will be executed and
control will come out of the loop.
 In case, if none of the conditions return true, then the code inside of else block will be
executed.
5/5/2021 43
// C# code to demonstrate nested if-else statement
using System;
namespace NestedIfElse{
class Program{
static void Main(string[] args){
int x = 0;
if(x>0)
Console.WriteLine(" x is Positve number ");
else if (x==0)
Console.WriteLine(" x is Zero ");
else
Console.WriteLine(" x is Negative number ");
Console.WriteLine(" Press any key to Exit...");
Console.ReadKey();
}}}
x is Negative number
Press any key to Exit...
When this code is compiled and executed, it
produces the following result:
5/5/2021 44
3. C# Ternary Operator (?:)
In c#, Ternary Operator (?:) is a decision making operator and it is a substitute of if-else-
if statement in c# programming language.
 By using Ternary Operator, we can replace multiple lines of if-else-if statement code into
single line in c# programming language.
 The Ternary operator we will help you to execute the statements based on the defined
conditions using decision making operator (?:).
In c#, the Ternary Operator will always work with 3 operands.
 Syntax of C# Ternary Operator:
In Ternary Operator, the condition expression must be evaluated to either true or false.
If condition is true, the first_expression result returned by the ternary operator.
In case, if condition is false, then the second_expression result returned by the operator.
Conditional Statements (Cont’d)
condition_expression ? first_expression : second_expression;
5/5/2021 45
x value less than y
Press any key to Exit...
// C# code to demonstrate C# Ternary Operator (?:)
using System;
namespace TernaryOperator{
class Program{
static void Main(string[] args){
int x =10, y=20;
string result;
result = (x > y) ? "x value greater than y" : (x < y) ? "x value less than y" : "x value equals to y";
Console.WriteLine(result);
Console.WriteLine(" Press any key to Exit...");
Console.ReadKey();
}}}  When this code is compiled and executed, it
produces the following result:
5/5/2021 46
4. Switch statement
In c#, Switch is a selection statement and it will execute a single case
statement from the list of multiple case statements based on the pattern match
with the defined expression.
 By using switch statement in c#, we can replace the functionality if –else if
statement to provide a better readability for the code.
Generally, in c# switch statement is a collection of multiple case statements
and it will execute only one single case statement based on the matching value
of expression.
Conditional Statements (Cont’d)
5/5/2021 47
switch(variable/expression){
case value1:
// Statements to Execute
break;
case value2:
//Statements to Execute
break;
....
default:
// Statements to Execute if No Case Matches
break;
}
Syntax of C# Switch Statement
5/5/2021 48
// C# code to demonstrate switch statement
using System;
namespace SwitchStatement{
class Program{
static void Main(string[] args){
char op;
int a=20, b=10;
int result=0;
Console.WriteLine("Enter an operator");
op = (char)Console.Read();
//op = Console.ReadLine();
switch (op){
case '+':
result = a + b;
Console.WriteLine("Sum of a and b is :{0} ",result);
break;
case '-':
result = a - b;
Console.WriteLine("Difference of a and b is :{0} ", result);
break; //code continue on the next page…..
.
Enter an operator
+
Sum of a and b is :30
Press any key to exit...
 When this code is compiled and executed,
it produces the following result:
5/5/2021 49
case '*':
result = a * b;
Console.WriteLine("Product of a and b is :{0} ", result);
break;
case '/':
result = a / b;
Console.WriteLine("Quetient of a and b is :{0} ", result);
break;
case '%':
result = a % b;
Console.WriteLine("Remiender of a and b is :{0} ", result);
break;
default:
Console.WriteLine("Invalid Operator");
break;
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}}}
5/5/2021 50
Looping statement are the statements execute one or more statement
repeatedly several number of times.
1. For Loop
for loop is useful to execute a statement or a group of statements repeatedly
until the defined condition returns true.
Generally, for loop is useful in c# applications to iterate and execute the
certain block of statements repeatedly until the specified number of times.
Syntax of C# For Loop
Looping Statements
for(initialization; test-condition; iterator(increment/decrement)){
//statements to execute
}
5/5/2021 51
1 2 3 4 5 6 7 8 9 10
Press any key to exit..
// C# code to demonstrate for loop statement
using System;
namespace ForLoop{
class Program {
static void Main(string[] args){
for (int i = 1; i <= 10; i++){
Console.Write(" "+i);
}
Console.WriteLine("n Press any key to exit..");
Console.ReadKey();
}}}
• If you observe this code,
• we defined a for loop to iterate
over 10 times to print the value of
variable i and following are the main
parts of for loop.
• Here,
• int i = 1 is the initialization part
• i <= 10 is the test-condition part
• i++ is the iterator part
When the above code is compiled and executed, it produces the following result:
5/5/2021 52
For Loop without Initialization & Iterators
Generally, the initializer, condition and iterator parameters are optional to
create for loop in c# programming language.
 Syntax of for loop without initialization and iterator
Following is the example of creating a for loop in c# programming language
without initializer and iterator. … on the next page…
Looping Statements(Cont’d)
initialization;
for(;test-condition;){
// statements to execute
iterator;
}
5/5/2021 53
// C# code to demonstrate for loop statement without initialization and iterator
using System;
namespace ForLoop1{
class Program{
static void Main(string[] args){
int i=1;
for (; i <= 10; ){
Console.Write(" " + i);
i++;
}
Console.WriteLine("n Press any key to exit..");
Console.ReadKey();
}}}
 When the above code is compiled and executed, it produces the following result:
1 2 3 4 5 6 7 8 9 10
Press any key to exit..
5/5/2021 54
C# Infinite For Loop
In case, if the condition parameter in for loop always returns true, then
the for loop will be an infinite and runs forever.
Even if we miss the condition parameter in for loop automatically that loop
will become an infinite loop.
 Following are the different ways to make for loop as an infinite loop in c#
programming language.
Looping Statements(Cont’d)
for (initializer; ; iterator) {
// Statements to Execute
}
or (initializer; ; iterator) {
// Statements to Execute
}
or
for ( ; ; ){
// Statements to Execute
}
5/5/2021 55
//Following is the example of making a for loop as an infinite in c# programming language.
using System;
namespace InfiniteForLoop{
class Program{
static void Main(string[] args){
for (int i = 1; i > 0; i++){
Console.Write(" " + i);
i++;
}
Console.WriteLine("n Press any key to exit..");
Console.ReadKey();
}}}
5/5/2021 56
C# Nested For Loop
In c#, we can create one for loop within another for loop based on our
requirements.
Looping Statements(Cont’d)
//Following is the example of creating a nested for loop in c# programming language.
using System;
namespace NestedForLoop{
class Program{
static void Main(string[] args){
for (int i = 1; i <=3; i++){
for (int j = 1; j <=2; j++){
Console.Write(" {0} {1}, ", i, j);
}}
Console.WriteLine("nPress Enter Key to Exit..");
Console.ReadKey();
}}}
1 1, 1 2, 2 1, 2 2, 3 1, 3 2,
Press Enter Key to Exit..
 When this code is compiled and executed, it
produces the following result:
Note: the inner for loop evaluated first. Until the test condition of
inner loop becomes false execution of code stay at inner loop.
5/5/2021 57
2. While Loop
In c#, While loop is used to execute a block of statements until the specified
expression return as a true.
 Generally, the for loop is useful when we are sure about how many times we
need to execute the block of statements. In case, if we are unknown about the
number of times to execute the block of statements, then while loop is the best
solution.
Syntax of C# While Loop:
 if expression returns true, then the statements inside of while loop will be
executed.
while (expression) {
// Statements to Execute
}
Looping Statements(Cont’d)
5/5/2021 58
//C# code to demonstrate while loop statement
using System;
namespace WhileLoop{
class Program{
static void Main(string[] args){
int i = 1;
while (i<=5){
Console.Write(" " + i);
i++;
}
Console.Write("nPress any key to exit...");
Console.ReadKey();
}}}
 When this code is compiled and executed,
it produces the following result:
1 2 3 4 5
Press any key to exit..
5/5/2021 59
3. Do While Loop
In c#, Do-While loop is used to execute a block of statements until the specified
expression return as a true.
 Generally, in c# the do-while loop is same as while loop but only the difference
is while loop will execute the statements only when the defined condition
returns true, but do-while loop will execute the statements at least once, because
first it will execute the block of statements and then it will checks the condition.
Syntax of C# Do-While Loop:
The body of do-while loop will be executed first, then the expression will be
evaluated. if expression returns true, then again the statements inside of do-while
loop will be executed.
In case, the expression is evaluated to false, then the do-while loop stops the
execution of statements and the program comes out of the loop.
do{
// Statements to Execute
}while (expression);
Looping Statements(Cont’d)
5/5/2021 60
// C# code to demonstrate do-while loop statement.
using System;
namespace WhileLoop{
class Program{
static void Main(string[] args){
int i = 1;
do{
Console.Write(" " + i);
i++;
}while (i<=5);
Console.Write("nPress any key to exit...");
Console.ReadKey();
}}}
 When this code is compiled and
executed, it produces the following
result:
1 2 3 4 5
Press any key to exit..
5/5/2021 61
4. Foreach Loop
In c#, Foreach loop is used to loop through an each item in array or collection
object to execute the block of statements repeatedly.
 Generally, in c# Foreach loop will work with the collection objects such as
arrays, list, etc. to execute the block of statements for each element in the array
or collection.
After completion of iterating through an each element in collection, control is
transferred to the next statement following the foreach block.
 In c#, we can use break, continue, goto and return statements
within foreach loop to exit or continue to the next iteration of the loop based on
our requirements.
Syntax of C# Foreach Loop:
Looping Statements(Cont’d)
foreach (Type var_name in Collection_Object) {
// Statements to Execute
}
5/5/2021 62
 When the above code is compiled
and executed, it produces the
following result:
//C# code to demonstrate foreach loop statement
using System;
namespace ForeachLoop{
class Program{
static void Main(string[] args){
string[] names = new string[4] { "Computer Science", "Accounting ",
"Economics","Information Technology" };
foreach (string name in names){
Console.WriteLine(name);
}
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}}}
5/5/2021 63
5.
1. Break Statement
In c#, Break statement is used to break or terminate the execution of loops (for,
while, do-while, etc.) or
 switch statement and the control is passed immediately to the next statements
that follows a terminated loops or statements.
 In c# nested loops also we can use break statement to stop or terminate the
execution of inner loops based on our requirements.
Syntax of C# Break Statement:
In our applications, we can use break statement whenever we want to stop the
execution of particular loop or statement based on our requirements.
Jumping Statements(Cont’d)
break;
5/5/2021 64
// C# code to demonstrate break statement with for loop statement
using System;
namespace BreakStatement{
class Program{
static void Main(string[] args){
for (int i = 1; i <= 5; i++){
if (i == 3)
break;
Console.Write(" " + i);
}
Console.WriteLine("n Press any key to exit..");
Console.ReadKey();
}}}
 When the above code is compiled
and executed, it produces the
following result:
1 2
Press any key to exit..
5/5/2021 65
6. Continue Statement
In c#, Continue statement is used to pass a control to the next iteration of loops
such as for, while, do-while or foreach from the specified position by skipping
the remaining code.
 The main difference between break statement and continue statement is,
the break statement will completely terminate the loop or statement execution
but the continue statement will pass a control to the next iteration of loop.
Syntax of C# Continue Statement:
In our applications, we can use continue statement whenever we want to skip
the execution of code from the particular position and send back the control to
next iteration of loop based on our requirements.
Looping Statements(Cont’d)
continue;
5/5/2021 66
// C# code to demonstrate continue statement with for loop statement
using System;
namespace BreakStatement{
class Program{
static void Main(string[] args){
for (int i = 1; i <=5; i++){
if (i == 3)
continue;
Console.Write(" " + i);
}
Console.WriteLine("n Press any key to exit..");
Console.ReadKey();
}}}
 When this code is compiled and
executed, it produces the
following result:
1 2 4 5
Press any key to exit..
5/5/2021 67
6. Goto Statement
In c#, Goto statement is used to transfer a program control to the defined labeled
statement and it is useful to get out of the loop or exit from a deeply nested loops
based on our requirements.
 Generally, in c# the defined labeled statement must always exists in the scope
of goto statement and we can define multiple goto statements in our application
to transfer the program control to specified labeled statement.
Syntax of C# goto Statement:
a goto statement by using goto keyword and with labeled_statement. Here
the labeled_statement is used to transfer the program control to
specified labeled_statement position.
Looping Statements(Cont’d)
goto labeled_statement;
5/5/2021 68
// C# code to demonstrate continue statement with for loop statement
using System;
namespace GotoStatement{
class Program{
static void Main(string[] args){
for (int i = 1; i <= 5; i++){
if (i == 3)
goto m;
Console.Write(" " + i);
}
m:Console.WriteLine("n The end");
Console.WriteLine("n Press any key to exit..");
Console.ReadKey();
}}}
 When the above code is compiled
and executed, it produces the
following result:
1 2
The end
Press any key to exit..
5/5/2021 69
6. Return Statement
 In c#, Return statement is used to terminate the execution of method in which
it appears and returns the control back to the calling method.
Generally, in c# the return statement is useful whenever we want to get a some
value from the other methods and we can omit the usage of return statement in
our methods by using void as a return type.
Syntax of C# return Statement:
Looping Statements(Cont’d)
return return_val;
5/5/2021 70
// C# code to demonstrate return statement with function or method
using System;
namespace ReturnStatement{
class Program{
static void Main(string[] args){
int i = 10, j = 20, result = 0;
result = add(i, j);
Console.WriteLine("Sum of i and J is : {0}", result);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadKey();
}
public static int add(int a, int b){
int x = a + b;
return x;
}}}
 When the above code is compiled
and executed, it produces the
following result:
Sum of i and J is : 30
Press Enter Key to Exit..
5/5/2021 71
A method (Function) is a group of statements that together perform a task.
Every C# program has at least one class with a method named Main.
Methods are generally the block of codes or statements in a program that
gives the user the ability to reuse the same code which ultimately saves the
excessive use of memory, acts as a time saver and more importantly, it
provides a better readability of code.
 So basically, a method is a collection of statements that perform some
specific task and return the result to the caller.
 A method can also perform some specific task without returning anything.
To use a method, you need to:
• Define the method
• Call the method
Method in C#
5/5/2021 72
Method Declaration
Method declaration means the way to construct method including its naming.
Syntax :
Method (Cont’d)
<access-modifier> <return-type> <method-name>([parameter-lists])
5/5/2021 73
In C# a method declaration consists of following components as follows :
Modifier : It defines access type of the method i.e. from where it can be
accessed in your application.
 In C# there are Public, Protected, Private, static access modifiers.
Name of the Method : It describes the name of the user defined method by
which the user calls it or refer it. Eg. add()
Return type: It defines the data type returned by the method.
It depends upon user as it may also return void value i.e return nothing
Body of the Method : It refers to the line of code of tasks to be performed
by the method during its execution.
 It is enclosed between braces.
Method (Cont’d)
5/5/2021 74
Parameter list : Comma separated list of the input parameters are defined,
preceded with their data type, within the enclosed parenthesis.
If there are no parameters, then empty parentheses () have to use out.
The Method Body : consists of statements of code which a user wants to perform.
After the method has been declared, it is dependent on the user whether to define
its implementation or not.
Not writing any implementation, makes the method not to perform any task.
 However, when the user wants to perform certain tasks using method then it must
write the statements for execution in the body of the method.
The below syntax describes the basic structure of the method body :
Method (Cont’d)
<return_type> <method_name>(<parameter_list>){
// Implementation of the method code goes here.....
}
5/5/2021 75
Method Calling
Method Invocation or Method Calling is done when the user wants to
execute the method.
 The method needs to be called for using its functionality.
A method returns to the code that invoked it when:
• It completes all the statements in the method
• It reaches a return statement
• Throws an exception
The next code example shows a function add that takes two integer values
and returns the sum of the two integers.
It has public access specifier, so it can be accessed from outside the class
using an instance of the class.
Method (Cont’d)
5/5/2021 76
// C# program to returns the sum of two numbers using method
using System;
namespace Method{
class Program {
public int add(int x, int y){
int result=0;
result = x + y;
return result;
}
static void Main(string[] args){
Program n=new Program();
int a = 10, b = 20, c=0;
c = n.add(a, b);
Console.WriteLine("The sum of a and b is: " + c);
Console.WriteLine("Press any key to exit..");
Console.ReadKey();
}}}
 When this code is compiled and
executed, it produces the
following result:
The sum of a and b is: 30
Press any key to exit..
5/5/2021 77
Advantages of using the Methods :
 Some of the advantages of methods are listed below:
It makes the program well structured.
Methods enhance the readability of the code.
It provides an effective way for the user to reuse the existing code.
It optimizes the execution time and memory space.
Method (Cont’d)
5/5/2021 78
Properties are named members of classes, structures, and interfaces.
 Member variables or methods in a class or structures are called Fields.
Properties are an extension of fields and are accessed using the same syntax.
They use accessors through which the values of the private fields can be read,
written or manipulated.
The accessor of a property contains the executable statements that helps in
getting (reading or computing) or setting (writing) the property.
The accessor declarations can contain a get accessor, a set accessor, or both.
C# Properties
5/5/2021 79
using System;
namespace Properties{
class Program {
private string code = "N.A";
private string name = "not known";
private int age = 0;
public string Code{ // Declare a Code property of type string:
get{
return code;
}
set{
code = value;
} }
public string Name{ // Declare a Name property of type string:
get {
return name;
}
set{
name = value;
}}
// code continue on the next page…
5/5/2021 80
public int Age{ // Declare a Age property of type int:
get{
return age;
}
set{
age = value;
}}
public override string ToString() {
return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
}}
class ExampleDemo {
public static void Main() {
Program s = new Program(); // Create a new Student object:
s.Code = "RET/858/02"; // Setting code, name and the age of the student
s.Name = "Lalise";
s.Age = 20;
Console.WriteLine("Student Info: {0}", s);
s.Age += 1;
Console.WriteLine("Student Info: {0}", s);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
} }}
 When this code is compiled and
executed, it produces the
following result:
Student Info: Code = RET/858/02, Name = Lalise, Age = 20
Student Info: Code = RET/858/02, Name = Lalise, Age = 21
Press any key to exit...
5/5/2021 81
Errors
 Programming errors are generally broken down into three types:
1. Design-time,
2. Runtime, and
3. Logic errors.
1. Design Time Errors
 A Design-time error is also known as a syntax error.
 These occur when the environment you're programming in doesn't understand your
code.
 These are easy to track down in C#, because you get a blue wiggly line pointing them
out.
 If you try to run the program, you'll get a dialogue box popping up telling you that there
were Build errors.
Exception (Error) Handling in C#
5/5/2021 82
2. Run Time Errors
 Runtime errors are a lot harder to track down. As their name suggests, these errors occur
when the program is running.
 They happen when your program tries to do something it shouldn't be doing.
 An example is trying to access a file that doesn't exist.
 Runtime errors usually cause your program to crash. You should write code to trap
runtime errors.
3. Logic Errors
 Logic errors also occur when the program is running.
 They happen when your code doesn't quite behave the way you thought it would.
 A classic example is creating an infinite loop of the type "Do While x is greater than 10".
If x is always going to be greater than 10, then the loop has no way to exit, and just keeps
going round and round.
 Logic errors tend not to crash your program. But they will ensure that it doesn't work
properly.
Exception…(Cont’d)
5/5/2021 83
Exceptions
 Are events which may be considered exceptional or unusual.
 They are conditions that are detected by an operation, that cannot be resolved within the
local context of the operation and must be brought to the attention of the operation
invoker.
Exception Handler
 Is a procedure or code that deals with the exceptions in your program.
Raising Exceptions
 The process of noticing exceptions, interrupting the program and calling the exception
handler.
Propagating the Exceptions
 Reporting the problem to higher authority (the calling program) in your program.
Handling the Exceptions
 The process of taking appropriate corrective action.
Exception…(Cont’d)
5/5/2021 84
Example of exceptions
1. Array out of bound
2. Divide by zero
3. Implicit type casting
4. Input/output exception
5. File not found exception
Structured Exception Handling
 C# has a built-in class that deals with errors.
 The class is called Exception. When an exception error is found, an exception object is
created. The exception object contains information relevant to the error exposed as
properties of the object.
 The object is an instance of a class that derived from a class named System.Exception.
 The coding structure C# uses to deal with such Exceptions is called the Try … Catch
structure.
Exception…(Cont’d)
5/5/2021 85
 Depends on several key words.
Try:
 Begins a section of a code in which an exception might be generated from a code error.
 This section is called the Try Block. And it means "Try to execute this code".
 A trapped exception is automatically routed to the Catch statement.
Catch:
 Begins an exception handler for a type of exception.
 One or more catch code blocks follow a try block, with each catch block catching a
different type of exception.
Finally:
 Contains code that runs when the try block finishes normally, or when a catch block
receives control then finishes.
 Is a block that always runs regardless of whether an exception is detected or not.
 Example: closing a database connection.
Exception…(Cont’d)
5/5/2021 86
Implementing Exception Handling
 Exception handlers are implemented for specific methods.
 The following three general steps are involved in creating exception handler.
 Wrap the code with which the handler will be associated in a Try block
 Add one or more Catch block to handle the possible exceptions
 Add any code that is always executed regardless of whether or not an exception is thrown to a Finally
block
 Structure
Try
' normal program code goes here
Catch
' catch block goes here (error handling)
Finally
' finally block goes here
End Try
Exception…(Cont’d)
5/5/2021 87
// C# divide by zero exception handling program
using System;
namespace ExceptionHandling{
class Program {
static void Main(string[] args){
try{
int x = 10, y = 0, result = 0;
result = x / y;
Console.WriteLine("Result = " + result);
}
catch{
}
finally{
Console.WriteLine("End of Execution");
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}}}
 When this code is compiled and
executed, it produces the
following result:
End of Execution
Press any key to exit...

Contenu connexe

Tendances

Tendances (20)

C# Basics
C# BasicsC# Basics
C# Basics
 
c# usage,applications and advantages
c# usage,applications and advantages c# usage,applications and advantages
c# usage,applications and advantages
 
C sharp
C sharpC sharp
C sharp
 
C# programming language
C# programming languageC# programming language
C# programming language
 
C# basics
 C# basics C# basics
C# basics
 
C# in depth
C# in depthC# in depth
C# in depth
 
Learn C# Programming - Data Types & Type Conversion
Learn C# Programming - Data Types & Type ConversionLearn C# Programming - Data Types & Type Conversion
Learn C# Programming - Data Types & Type Conversion
 
Advanced Programming C++
Advanced Programming C++Advanced Programming C++
Advanced Programming C++
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
 
C# Tutorial
C# Tutorial C# Tutorial
C# Tutorial
 
Introduction to programming with c,
Introduction to programming with c,Introduction to programming with c,
Introduction to programming with c,
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
C++ language basic
C++ language basicC++ language basic
C++ language basic
 
Lecture 1 introduction to vb.net
Lecture 1   introduction to vb.netLecture 1   introduction to vb.net
Lecture 1 introduction to vb.net
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language Course
 
.NET and C# Introduction
.NET and C# Introduction.NET and C# Introduction
.NET and C# Introduction
 
C++ string
C++ stringC++ string
C++ string
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net framework
 

Similaire à Chapter 2 c#

C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
Zafor Iqbal
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
MAHESHV559910
 

Similaire à Chapter 2 c# (20)

Dot net programming concept
Dot net  programming conceptDot net  programming concept
Dot net programming concept
 
LEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMTLEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMT
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.net
 
Unit 1 question and answer
Unit 1 question and answerUnit 1 question and answer
Unit 1 question and answer
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
 
Data Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# ProgrammingData Types, Variables, and Constants in C# Programming
Data Types, Variables, and Constants in C# Programming
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
C#
C#C#
C#
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
csharp.docx
csharp.docxcsharp.docx
csharp.docx
 
Objects and Types C#
Objects and Types C#Objects and Types C#
Objects and Types C#
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdf
 
C# note
C# noteC# note
C# note
 
434090527-C-Cheat-Sheet. pdf C# program
434090527-C-Cheat-Sheet. pdf  C# program434090527-C-Cheat-Sheet. pdf  C# program
434090527-C-Cheat-Sheet. pdf C# program
 
Basic Structure Of C++
Basic Structure Of C++Basic Structure Of C++
Basic Structure Of C++
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
 
c# at f#
c# at f#c# at f#
c# at f#
 
C# AND F#
C# AND F#C# AND F#
C# AND F#
 

Dernier

An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Dernier (20)

Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 

Chapter 2 c#

  • 1. Berhanu Fetene (MSc.) Chapter Two: C# (C-sharp) programming language 5/5/2021 1
  • 2. C# Programming  C# is an object-oriented programming language.  In Object-Oriented Programming methodology, a program consists of various objects that interact with each other by means of actions.  The actions that an object may take are called methods.  Objects of the same kind are said to have the same type or are said to be in the same class.  C# is case sensitive  All statements and expression must end with a semicolon(;).  The program execution starts at the main method.  Unlike Java, program file name could be different from the class name. 5/5/2021 2
  • 3. C# Program Structure  A C# program consists of the following parts:  Namespace declaration  A class  Class methods  Class attributes  A main method  Statements and expressions  Comments (optional) 5/5/2021 3
  • 4. 7 Sample C# program: using System; class HelloCSharp { static void Main() { Console.WriteLine("Hello, C#"); } }
  • 5. C# Code – How It Works? using System; class HelloCSharp { static void Main() { Console.WriteLine("Hello, C#"); } } Include the standard namespace "System" Define a class called "HelloCSharp" Define the Main() method – the program entry point 8 Print a text on the console by calling the method "WriteLine" of the class "Console"
  • 6. C# Code Should Be Well Formatted using System; class HelloCSharp { s st ta at ti ic c v vo oi id d M Ma ai in n( () ) { { C Co on ns so ol le e. .W Wr ri it te eL Li in ne e( (" "H He el ll lo o, , C C# #" ") ); ; } } } The {symbol should be alone on a new line. The block after the {symbol should be indented by a TAB. The }symbol should be under the corresponding {. Class names should use PascalCaseand start with a CAPITALletter. 9
  • 7. Important features of C#  It is important to note the following points:  C# is case sensitive.  All statements and expression must end with a semicolon (;).  The program execution starts at the Main method.  Unlike Java, program file name could be different from the class name. Compiling and Executing the Program  If you are using Visual Studio. Net for compiling and executing C# programs, take the following steps:  Start Visual Studio.  On the menu bar, choose File -> New -> Project. 5/5/2021 7
  • 8. Compiling and Executing the Program (Cont’d)  Choose Visual C# from templates, and then choose Windows.  Choose Console Application.  Specify a name for your project and click OK button. This creates a new project in Solution Explorer.  Write code in the Code Editor.  Click the Run button or press F5 key to execute the project.  A Command Prompt window appears that contains the line H He el ll lo o, , C C# #" “. 5/5/2021 8
  • 9.  The variables in C#, are categorized into one of the following three categories:  Value types  Refence types  Pointer types 1. Value Type  Value type variables can be assigned a value directly.  They are derived from the class System.ValueType.  The value types directly contain data. 5/5/2021 9 Data Types
  • 10.  Some examples are int, char, and float which stores numbers, alphabets, and floating point numbers respectively.  When you declare an int type, the system allocates memory to store the value.  The following table lists the available value types in C# . 5/5/2021 10 Data Types (Cont’d) Type Represent Range Default Value bool Boolean value True or False False byte 8-bit unsigned integer 0 to 255 0 char 16-bit Unicode Character U +0000 to U +ffff '0' decimal 128-bit precise decimal Values with 28-29 significant digits (-7.9 x 1028 to 7.9 x 1028 ) / 100 to 1028 0.0M
  • 11. 5/5/2021 11 Data Types (Cont’d) Type Represent Range Default Value float 32-bit single-precision floating point type -3.4 x 1038 to + 3.4 x 1038 0.0F int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0 long 64-bit signed integer type -923,372,036,854,775,808 to 9,223,372,036,854,775,807 0L sbyte 8-bit signed integer type -128 to 127 0 short 16-bit signed integer type -32,768 to 32,767 0 uint 16-bit signed integer type 0 to 4,294,967,295 0 ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615 0 ushort 16-bit unsigned integer type 0 to 65,535 0
  • 12.  To get the exact size of a type or a variable on a particular platform, you can use the sizeof method.  The expression sizeof(type) yields the storage size of the object or type in bytes.  The following is an example to get the size of data types we defined in the above tables. 5/5/2021 12 Data Types (Cont’d)
  • 13. 5/5/2021 13 using System; namespace DataTypeSize{ class Program{ static void Main(string[] args){ Console.WriteLine("Size of bool is : {0}", sizeof(bool)); Console.WriteLine("Size of byte is : {0}", sizeof(byte)); Console.WriteLine("Size of char is : {0}", sizeof(char)); Console.WriteLine("Size of decimal is : {0}", sizeof(decimal)); Console.WriteLine("Size of float is : {0}", sizeof(float)); Console.WriteLine("Size of int is : {0}", sizeof(int)); Console.WriteLine("Size of long is : {0}", sizeof(long)); Console.WriteLine("Size of sbyte is : {0}", sizeof(sbyte)); Console.WriteLine("Size of short is : {0}", sizeof(short)); Console.WriteLine("Size of uint is : {0}", sizeof(uint)); Console.WriteLine("Size of ulong is : {0}", sizeof(ulong)); Console.WriteLine("Size of ushort is : {0}", sizeof(ushort)); Console.ReadKey(); }}}
  • 14. 5/5/2021 14  When the above code is compiled and executed, it produces the following result: Size of bool is : 1 Size of byte is : 1 Size of char is : 2 Size of decimal is : 16 Size of float is : 4 Size of int is : 4 Size of long is : 8 Size of sbyte is : 1 Size of short is : 2 Size of uint is : 4 Size of ulong is : 8 Size of ushort is : 2
  • 15. 5/5/2021 15 2. Refence Type  The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables.  In other words, they refer to a memory location.  Using multiple variables, the reference types can refer to a memory location.  If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value.  Example of built-in reference types are: object, dynamic, and string. Data Types (Cont’d)
  • 16. 5/5/2021 16 A. Object Type  The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class.  The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types.  However, before assigning values, it needs type conversion.  When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing. Example: Reference Types (Cont’d) object obj; obj = 100; // this is boxing
  • 17. 5/5/2021 17 B. Dynamic Type  You can store any type of value in the dynamic data type variable.  Type checking for these types of variables takes place at run-time.  Syntax for declaring a dynamic type is:  For example:  Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time. Reference Types (Cont’d) dynamic number = 100; dynamic <variable_name> = value;
  • 18. 5/5/2021 18 B. Dynamic Type  The String Type allows you to assign any string values to a variable.  The string type is an alias for the System.String class.  It is derived from object type.  The value for a string type can be assigned using string literals in two forms: quoted and @quoted.  For example:  A @quoted string literal looks as follows:  The user-defined reference types are: class, interface, or delegate. We will discuss these types in later chapter in details. Reference Types (Cont’d) string name= “Rift Valley University"; @“Rift Valley University";
  • 19. 5/5/2021 19 2. Pointer Type  Pointer type variables store the memory address of another type.  Pointers in C# have the same capabilities as the pointers in C or C++.  Syntax for declaring a pointer type is:  For example:  We will discuss more about pointer types in the subsections. Data Types (Cont’d) type* identifier; char* cptr; int* iptr;
  • 20.  Keywords are reserved words predefined to the C# compiler.  These keywords cannot be used as identifiers.  However, if you want to use these keywords as identifiers, you may prefix them with the @ character.  In C#, some identifiers have special meaning in context of code, such as get and set, these are called contextual keywords.  The following TABLE lists the reserved keywords and contextual keywords in C# . 5/5/2021 20 C# Keywords
  • 21. 5/5/2021 21 Reserved Keywords abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in volatile int interface internal is lock long namespace new null object operator out private override params protected public readonly ref return sbyte while sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void
  • 22. 5/5/2021 22 Contextual Keywords add alias ascending descending dynamic from get global group into join let orderby partial (type) partial (method) remove select set
  • 23. Identifiers 5/5/2021 23  An identifier is a name used to identify a class, variable, function, or any other user-defined item.  The basic rules for naming identifiers in C# are as follows:  A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9), or underscore.  The first character in an identifier cannot be a digit.  It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' / and .  However, an underscore ( _ ) can be used.  It should not be a C# keyword. digit.
  • 24. C# Variables 5/5/2021 24  A variable is a name given to a storage area that is used to store values of various data types.  Each variable in C# needs to have a specific type, which determines the size and layout of the variable's memory.  Based on the data type, specific operations can be carried out on the variable.  One can declare multiple variables in a program.  Example1: // age is variable that can store integer value. // value 30 is assigned to variable age which is declared before. Example2: //mulptiple variable declaration int age; age =30; int length, width, area;
  • 25. C# Operators 5/5/2021 25 1. Arithmetic Operators  are operators used for performing mathematic operations on numbers. Below is the list of arithmetic operators available in C#. Operator Description + Adds two operands - Subtracts the second operand from the first * Multiplies both operands / Divides the numerator by de-numerator % Modulus Operator and a remainder of after an integer division ++ Increment operator increases integer value by one -- Decrement operator decreases integer value by one
  • 26. 5/5/2021 26 // C# code to demonstrate the use of arithmetic operators using System; namespace ArithmeticOperator{ class Program { static void Main(string[] args){ int a = 30, b=5; Console.WriteLine("Sum of a and b is : {0}", a + b); Console.WriteLine("Difference of a and b is : {0}", a - b); Console.WriteLine("Product of a and b is : {0}", a * b); Console.WriteLine("quetient of a and b is : {0}", a / b); Console.WriteLine("Remander of a and b is : {0}", a % b); Console.WriteLine("Incerement of a by 1 is : {0}", ++a); // pre-increment Console.WriteLine("Decrement of b by 1 is : {0}", --b); // post-decrement Console.WriteLine("Incerement of a by 1 is : {0}", a++); // post-increment Console.WriteLine("Decrement of b by 1 is : {0}", b--); // post-decrement Console.WriteLine("Press any key to continue ..."); Console.ReadKey(); } }}
  • 27. 5/5/2021 27 Sum of a and b is : 35 Difference of a and b is : 25 Product of a and b is : 150 quotient of a and b is : 6 Reminder of a and b is : 0 Increment of a by 1 is : 31 Decrement of b by 1 is : 4 Increment of a by 1 is : 31 Decrement of b by 1 is : 4 Press any key to continue ...  When the above code is compiled and executed, it produces the following result:
  • 28. C# Operators(Cont’d) 5/5/2021 28 2. Relational Operators  These are operators used for performing Relational operations on numbers.  Below is the list of relational operators available in C#. Operator Description == Checks if the values of two operands are equal or not, if yes then condition becomes true. != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
  • 29. 5/5/2021 29 // C# code to demonstrate the use of Relational Operators using System; namespace RelationalOperator{ class Program{ static void Main(string[] args){ int a = 30, b = 5; Console.WriteLine(" a is equal to b {0}", a==b); Console.WriteLine(" a is not equal to b {0}", a!= b); Console.WriteLine(" a is greater than b {0}", a>b); Console.WriteLine(" a is less than b {0}", a<b); Console.WriteLine(" a is greater than or equal to b {0}", a>=b); Console.WriteLine(" a is less than or equal to b {0}", a<=b); Console.WriteLine("Press any key to continue ..."); Console.ReadKey(); }}}
  • 30. 5/5/2021 30 a is equal to b False a is not equal to b True a is greater than b True a is less than b False a is greater than or equal to b True a is less than or equal to b False Press any key to continue ...  When the above code is compiled and executed, it produces the following result:
  • 31. C# Operators (Cont’d) 5/5/2021 31 3. Logical Operators  These are operators used for performing Logical operations on values.  Below is the list of logical operators available in C#. Operator Description && This is the Logical AND operator. If both the operands are true, then condition becomes true. || This is the Logical OR operator. If any of the operands are true, then condition becomes true. ! This is the Logical NOT operator.
  • 32. 5/5/2021 32 // C# code to demonstrate the use of Logical Operators using System; namespace RelationalOperator{ class Program{ static void Main(string[] args){ int a = 30, b = 5; bool c = false; Console.WriteLine(" Logical AND {0}", (a == b)&&(a!=b)); Console.WriteLine(" Logical OR {0}", (a != b)||(a>b)); Console.WriteLine(" Logical Negation {0}", !(c)); Console.WriteLine("Press any key to continue ..."); Console.ReadKey(); }}}
  • 33. 5/5/2021 33  When the above code is compiled and executed, it produces the following result: Logical AND False Logical OR True Logical Negation True Press any key to continue ...
  • 34. 5/5/2021 34  An enumeration is used in any programming language to define a constant set of values.  For example, the days of the week can be defined as an enumeration and used anywhere in the program.  In C#, the enumeration is defined with the help of the keyword 'enum’.  enum is a value type data type. The enum is used to declare a list of named integer constants. C# Enum Syntax: enum enum_name{enumeration list}  The enum is used to give a name to each constant so that the constant integer can be referred using its name.  In our example, we will define an enumeration called days, which will be used to store the days of the week. C# Enumeration
  • 35. 5/5/2021 35 // C# code to demonstrate the use of enumeration. using System; namespace Enumeration{ // enum declaration enum days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } ; class Program{ static void Main(string[] args){ Console.WriteLine("Value of Monday is " + (int)days.Monday); Console.WriteLine("Value of Tuesday is " + (int)days.Tuesday); Console.WriteLine("Value of Wednesday is " + (int)days.Wednesday); Console.WriteLine("Value of Thursday is " + (int)days.Thursday); Console.WriteLine("Value of Friday is " + (int)days.Friday); Console.WriteLine("Value of Saturday is " + (int)days.Saturday); Console.WriteLine("Value of Sunday is " + (int)days.Sunday); Console.WriteLine("Press any key to continue ..."); Console.ReadKey(); }}}
  • 36. 5/5/2021 36  When the above code is compiled and executed, it produces the following result: Value of Monday is 0 Value of Tuesday is 1 Value of Wednesday is 2 Value of Thursday is 3 Value of Friday is 4 Value of Saturday is 5 Value of Sunday is 6 Press any key to continue ...
  • 37. Conditional Statements 5/5/2021 37 1. if statement In c#, if statement or condition is used to execute the block of code or statements when the defined condition is true. Generally, in c# the statement that can be executed based on the condition is known as a “Conditional Statement” and the statement is more likely a block of code. Syntax of C# if Statement: The statements inside of if condition will be executed only when the “expression” returns true otherwise the statements inside of if condition will be ignored for execution. if (expression) { // Statements to Executed if condition is true }
  • 38. 5/5/2021 38  Following is the example of defining if statement in c# programming language to execute the block of code or statements based on expression. // C# code to demonstrate if statement. using System; namespace IfStatement{ class Program{ static void Main(string[] args){ int x = 20; if(x>0) Console.WriteLine(" x is positve number "); Console.WriteLine(" Press any key to Exit..."); Console.ReadKey(); }}} x is positve number Press any key to Exit...  When this code is compiled and executed, it produces the following result:
  • 39. Conditional Statements (Cont’d) 5/5/2021 39 2. if-else statement In c#, if-else statement or condition is having an optional else statements and these else statements will be executed whenever the if condition is fails to execute.  Generally, in c# if-else statement, whenever the expression returns true, then if statements will be executed otherwise else block of statements will be executed. Syntax of C# if-else Statement if (expression){ // Statements to Executed if expression is True } else { // Statements to Executed if expression is False }
  • 40. 5/5/2021 40 // C# code to demonstrate if-else statement using System; namespace IfElse{ class Program{ static void Main(string[] args){ int x = -20; if(x>0) Console.WriteLine(" x is Positve number "); else Console.WriteLine(" x is Negative number "); Console.WriteLine(" Press any key to Exit..."); Console.ReadKey(); }}} When this code is compiled and executed, it produces the following result: x is Negative number Press any key to Exit...
  • 41. 5/5/2021 41 3. if-else if statement (nested if-else statement) In c#, if-else-if statement or condition is used to define multiple conditions and execute only one matched condition based on our requirements. Generally, in c# if statement or if-else statement is useful when we have a one condition to validate and execute the required block of statements. In case, if we have a multiple conditions to validate and execute only one block of code, then if-else-if statement is useful. Conditional Statements (Cont’d)
  • 42. 5/5/2021 42 Syntax of C# if Statement: if (condition_1){ // Statements to Execute if condition_1 is True } else if (condition_2){ // Statements to Execute if condition_2 is True } .... else{ // Statements to Execute if all conditions are False } Syntax of C# if-else if Statement:  The execution of if-else-if statement will starts from top to bottom and as soon as the condition returns true, then the code inside of if or else if block will be executed and control will come out of the loop.  In case, if none of the conditions return true, then the code inside of else block will be executed.
  • 43. 5/5/2021 43 // C# code to demonstrate nested if-else statement using System; namespace NestedIfElse{ class Program{ static void Main(string[] args){ int x = 0; if(x>0) Console.WriteLine(" x is Positve number "); else if (x==0) Console.WriteLine(" x is Zero "); else Console.WriteLine(" x is Negative number "); Console.WriteLine(" Press any key to Exit..."); Console.ReadKey(); }}} x is Negative number Press any key to Exit... When this code is compiled and executed, it produces the following result:
  • 44. 5/5/2021 44 3. C# Ternary Operator (?:) In c#, Ternary Operator (?:) is a decision making operator and it is a substitute of if-else- if statement in c# programming language.  By using Ternary Operator, we can replace multiple lines of if-else-if statement code into single line in c# programming language.  The Ternary operator we will help you to execute the statements based on the defined conditions using decision making operator (?:). In c#, the Ternary Operator will always work with 3 operands.  Syntax of C# Ternary Operator: In Ternary Operator, the condition expression must be evaluated to either true or false. If condition is true, the first_expression result returned by the ternary operator. In case, if condition is false, then the second_expression result returned by the operator. Conditional Statements (Cont’d) condition_expression ? first_expression : second_expression;
  • 45. 5/5/2021 45 x value less than y Press any key to Exit... // C# code to demonstrate C# Ternary Operator (?:) using System; namespace TernaryOperator{ class Program{ static void Main(string[] args){ int x =10, y=20; string result; result = (x > y) ? "x value greater than y" : (x < y) ? "x value less than y" : "x value equals to y"; Console.WriteLine(result); Console.WriteLine(" Press any key to Exit..."); Console.ReadKey(); }}}  When this code is compiled and executed, it produces the following result:
  • 46. 5/5/2021 46 4. Switch statement In c#, Switch is a selection statement and it will execute a single case statement from the list of multiple case statements based on the pattern match with the defined expression.  By using switch statement in c#, we can replace the functionality if –else if statement to provide a better readability for the code. Generally, in c# switch statement is a collection of multiple case statements and it will execute only one single case statement based on the matching value of expression. Conditional Statements (Cont’d)
  • 47. 5/5/2021 47 switch(variable/expression){ case value1: // Statements to Execute break; case value2: //Statements to Execute break; .... default: // Statements to Execute if No Case Matches break; } Syntax of C# Switch Statement
  • 48. 5/5/2021 48 // C# code to demonstrate switch statement using System; namespace SwitchStatement{ class Program{ static void Main(string[] args){ char op; int a=20, b=10; int result=0; Console.WriteLine("Enter an operator"); op = (char)Console.Read(); //op = Console.ReadLine(); switch (op){ case '+': result = a + b; Console.WriteLine("Sum of a and b is :{0} ",result); break; case '-': result = a - b; Console.WriteLine("Difference of a and b is :{0} ", result); break; //code continue on the next page….. . Enter an operator + Sum of a and b is :30 Press any key to exit...  When this code is compiled and executed, it produces the following result:
  • 49. 5/5/2021 49 case '*': result = a * b; Console.WriteLine("Product of a and b is :{0} ", result); break; case '/': result = a / b; Console.WriteLine("Quetient of a and b is :{0} ", result); break; case '%': result = a % b; Console.WriteLine("Remiender of a and b is :{0} ", result); break; default: Console.WriteLine("Invalid Operator"); break; } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }}}
  • 50. 5/5/2021 50 Looping statement are the statements execute one or more statement repeatedly several number of times. 1. For Loop for loop is useful to execute a statement or a group of statements repeatedly until the defined condition returns true. Generally, for loop is useful in c# applications to iterate and execute the certain block of statements repeatedly until the specified number of times. Syntax of C# For Loop Looping Statements for(initialization; test-condition; iterator(increment/decrement)){ //statements to execute }
  • 51. 5/5/2021 51 1 2 3 4 5 6 7 8 9 10 Press any key to exit.. // C# code to demonstrate for loop statement using System; namespace ForLoop{ class Program { static void Main(string[] args){ for (int i = 1; i <= 10; i++){ Console.Write(" "+i); } Console.WriteLine("n Press any key to exit.."); Console.ReadKey(); }}} • If you observe this code, • we defined a for loop to iterate over 10 times to print the value of variable i and following are the main parts of for loop. • Here, • int i = 1 is the initialization part • i <= 10 is the test-condition part • i++ is the iterator part When the above code is compiled and executed, it produces the following result:
  • 52. 5/5/2021 52 For Loop without Initialization & Iterators Generally, the initializer, condition and iterator parameters are optional to create for loop in c# programming language.  Syntax of for loop without initialization and iterator Following is the example of creating a for loop in c# programming language without initializer and iterator. … on the next page… Looping Statements(Cont’d) initialization; for(;test-condition;){ // statements to execute iterator; }
  • 53. 5/5/2021 53 // C# code to demonstrate for loop statement without initialization and iterator using System; namespace ForLoop1{ class Program{ static void Main(string[] args){ int i=1; for (; i <= 10; ){ Console.Write(" " + i); i++; } Console.WriteLine("n Press any key to exit.."); Console.ReadKey(); }}}  When the above code is compiled and executed, it produces the following result: 1 2 3 4 5 6 7 8 9 10 Press any key to exit..
  • 54. 5/5/2021 54 C# Infinite For Loop In case, if the condition parameter in for loop always returns true, then the for loop will be an infinite and runs forever. Even if we miss the condition parameter in for loop automatically that loop will become an infinite loop.  Following are the different ways to make for loop as an infinite loop in c# programming language. Looping Statements(Cont’d) for (initializer; ; iterator) { // Statements to Execute } or (initializer; ; iterator) { // Statements to Execute } or for ( ; ; ){ // Statements to Execute }
  • 55. 5/5/2021 55 //Following is the example of making a for loop as an infinite in c# programming language. using System; namespace InfiniteForLoop{ class Program{ static void Main(string[] args){ for (int i = 1; i > 0; i++){ Console.Write(" " + i); i++; } Console.WriteLine("n Press any key to exit.."); Console.ReadKey(); }}}
  • 56. 5/5/2021 56 C# Nested For Loop In c#, we can create one for loop within another for loop based on our requirements. Looping Statements(Cont’d) //Following is the example of creating a nested for loop in c# programming language. using System; namespace NestedForLoop{ class Program{ static void Main(string[] args){ for (int i = 1; i <=3; i++){ for (int j = 1; j <=2; j++){ Console.Write(" {0} {1}, ", i, j); }} Console.WriteLine("nPress Enter Key to Exit.."); Console.ReadKey(); }}} 1 1, 1 2, 2 1, 2 2, 3 1, 3 2, Press Enter Key to Exit..  When this code is compiled and executed, it produces the following result: Note: the inner for loop evaluated first. Until the test condition of inner loop becomes false execution of code stay at inner loop.
  • 57. 5/5/2021 57 2. While Loop In c#, While loop is used to execute a block of statements until the specified expression return as a true.  Generally, the for loop is useful when we are sure about how many times we need to execute the block of statements. In case, if we are unknown about the number of times to execute the block of statements, then while loop is the best solution. Syntax of C# While Loop:  if expression returns true, then the statements inside of while loop will be executed. while (expression) { // Statements to Execute } Looping Statements(Cont’d)
  • 58. 5/5/2021 58 //C# code to demonstrate while loop statement using System; namespace WhileLoop{ class Program{ static void Main(string[] args){ int i = 1; while (i<=5){ Console.Write(" " + i); i++; } Console.Write("nPress any key to exit..."); Console.ReadKey(); }}}  When this code is compiled and executed, it produces the following result: 1 2 3 4 5 Press any key to exit..
  • 59. 5/5/2021 59 3. Do While Loop In c#, Do-While loop is used to execute a block of statements until the specified expression return as a true.  Generally, in c# the do-while loop is same as while loop but only the difference is while loop will execute the statements only when the defined condition returns true, but do-while loop will execute the statements at least once, because first it will execute the block of statements and then it will checks the condition. Syntax of C# Do-While Loop: The body of do-while loop will be executed first, then the expression will be evaluated. if expression returns true, then again the statements inside of do-while loop will be executed. In case, the expression is evaluated to false, then the do-while loop stops the execution of statements and the program comes out of the loop. do{ // Statements to Execute }while (expression); Looping Statements(Cont’d)
  • 60. 5/5/2021 60 // C# code to demonstrate do-while loop statement. using System; namespace WhileLoop{ class Program{ static void Main(string[] args){ int i = 1; do{ Console.Write(" " + i); i++; }while (i<=5); Console.Write("nPress any key to exit..."); Console.ReadKey(); }}}  When this code is compiled and executed, it produces the following result: 1 2 3 4 5 Press any key to exit..
  • 61. 5/5/2021 61 4. Foreach Loop In c#, Foreach loop is used to loop through an each item in array or collection object to execute the block of statements repeatedly.  Generally, in c# Foreach loop will work with the collection objects such as arrays, list, etc. to execute the block of statements for each element in the array or collection. After completion of iterating through an each element in collection, control is transferred to the next statement following the foreach block.  In c#, we can use break, continue, goto and return statements within foreach loop to exit or continue to the next iteration of the loop based on our requirements. Syntax of C# Foreach Loop: Looping Statements(Cont’d) foreach (Type var_name in Collection_Object) { // Statements to Execute }
  • 62. 5/5/2021 62  When the above code is compiled and executed, it produces the following result: //C# code to demonstrate foreach loop statement using System; namespace ForeachLoop{ class Program{ static void Main(string[] args){ string[] names = new string[4] { "Computer Science", "Accounting ", "Economics","Information Technology" }; foreach (string name in names){ Console.WriteLine(name); } Console.WriteLine("Press Enter Key to Exit.."); Console.ReadLine(); }}}
  • 63. 5/5/2021 63 5. 1. Break Statement In c#, Break statement is used to break or terminate the execution of loops (for, while, do-while, etc.) or  switch statement and the control is passed immediately to the next statements that follows a terminated loops or statements.  In c# nested loops also we can use break statement to stop or terminate the execution of inner loops based on our requirements. Syntax of C# Break Statement: In our applications, we can use break statement whenever we want to stop the execution of particular loop or statement based on our requirements. Jumping Statements(Cont’d) break;
  • 64. 5/5/2021 64 // C# code to demonstrate break statement with for loop statement using System; namespace BreakStatement{ class Program{ static void Main(string[] args){ for (int i = 1; i <= 5; i++){ if (i == 3) break; Console.Write(" " + i); } Console.WriteLine("n Press any key to exit.."); Console.ReadKey(); }}}  When the above code is compiled and executed, it produces the following result: 1 2 Press any key to exit..
  • 65. 5/5/2021 65 6. Continue Statement In c#, Continue statement is used to pass a control to the next iteration of loops such as for, while, do-while or foreach from the specified position by skipping the remaining code.  The main difference between break statement and continue statement is, the break statement will completely terminate the loop or statement execution but the continue statement will pass a control to the next iteration of loop. Syntax of C# Continue Statement: In our applications, we can use continue statement whenever we want to skip the execution of code from the particular position and send back the control to next iteration of loop based on our requirements. Looping Statements(Cont’d) continue;
  • 66. 5/5/2021 66 // C# code to demonstrate continue statement with for loop statement using System; namespace BreakStatement{ class Program{ static void Main(string[] args){ for (int i = 1; i <=5; i++){ if (i == 3) continue; Console.Write(" " + i); } Console.WriteLine("n Press any key to exit.."); Console.ReadKey(); }}}  When this code is compiled and executed, it produces the following result: 1 2 4 5 Press any key to exit..
  • 67. 5/5/2021 67 6. Goto Statement In c#, Goto statement is used to transfer a program control to the defined labeled statement and it is useful to get out of the loop or exit from a deeply nested loops based on our requirements.  Generally, in c# the defined labeled statement must always exists in the scope of goto statement and we can define multiple goto statements in our application to transfer the program control to specified labeled statement. Syntax of C# goto Statement: a goto statement by using goto keyword and with labeled_statement. Here the labeled_statement is used to transfer the program control to specified labeled_statement position. Looping Statements(Cont’d) goto labeled_statement;
  • 68. 5/5/2021 68 // C# code to demonstrate continue statement with for loop statement using System; namespace GotoStatement{ class Program{ static void Main(string[] args){ for (int i = 1; i <= 5; i++){ if (i == 3) goto m; Console.Write(" " + i); } m:Console.WriteLine("n The end"); Console.WriteLine("n Press any key to exit.."); Console.ReadKey(); }}}  When the above code is compiled and executed, it produces the following result: 1 2 The end Press any key to exit..
  • 69. 5/5/2021 69 6. Return Statement  In c#, Return statement is used to terminate the execution of method in which it appears and returns the control back to the calling method. Generally, in c# the return statement is useful whenever we want to get a some value from the other methods and we can omit the usage of return statement in our methods by using void as a return type. Syntax of C# return Statement: Looping Statements(Cont’d) return return_val;
  • 70. 5/5/2021 70 // C# code to demonstrate return statement with function or method using System; namespace ReturnStatement{ class Program{ static void Main(string[] args){ int i = 10, j = 20, result = 0; result = add(i, j); Console.WriteLine("Sum of i and J is : {0}", result); Console.WriteLine("Press Enter Key to Exit.."); Console.ReadKey(); } public static int add(int a, int b){ int x = a + b; return x; }}}  When the above code is compiled and executed, it produces the following result: Sum of i and J is : 30 Press Enter Key to Exit..
  • 71. 5/5/2021 71 A method (Function) is a group of statements that together perform a task. Every C# program has at least one class with a method named Main. Methods are generally the block of codes or statements in a program that gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, it provides a better readability of code.  So basically, a method is a collection of statements that perform some specific task and return the result to the caller.  A method can also perform some specific task without returning anything. To use a method, you need to: • Define the method • Call the method Method in C#
  • 72. 5/5/2021 72 Method Declaration Method declaration means the way to construct method including its naming. Syntax : Method (Cont’d) <access-modifier> <return-type> <method-name>([parameter-lists])
  • 73. 5/5/2021 73 In C# a method declaration consists of following components as follows : Modifier : It defines access type of the method i.e. from where it can be accessed in your application.  In C# there are Public, Protected, Private, static access modifiers. Name of the Method : It describes the name of the user defined method by which the user calls it or refer it. Eg. add() Return type: It defines the data type returned by the method. It depends upon user as it may also return void value i.e return nothing Body of the Method : It refers to the line of code of tasks to be performed by the method during its execution.  It is enclosed between braces. Method (Cont’d)
  • 74. 5/5/2021 74 Parameter list : Comma separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis. If there are no parameters, then empty parentheses () have to use out. The Method Body : consists of statements of code which a user wants to perform. After the method has been declared, it is dependent on the user whether to define its implementation or not. Not writing any implementation, makes the method not to perform any task.  However, when the user wants to perform certain tasks using method then it must write the statements for execution in the body of the method. The below syntax describes the basic structure of the method body : Method (Cont’d) <return_type> <method_name>(<parameter_list>){ // Implementation of the method code goes here..... }
  • 75. 5/5/2021 75 Method Calling Method Invocation or Method Calling is done when the user wants to execute the method.  The method needs to be called for using its functionality. A method returns to the code that invoked it when: • It completes all the statements in the method • It reaches a return statement • Throws an exception The next code example shows a function add that takes two integer values and returns the sum of the two integers. It has public access specifier, so it can be accessed from outside the class using an instance of the class. Method (Cont’d)
  • 76. 5/5/2021 76 // C# program to returns the sum of two numbers using method using System; namespace Method{ class Program { public int add(int x, int y){ int result=0; result = x + y; return result; } static void Main(string[] args){ Program n=new Program(); int a = 10, b = 20, c=0; c = n.add(a, b); Console.WriteLine("The sum of a and b is: " + c); Console.WriteLine("Press any key to exit.."); Console.ReadKey(); }}}  When this code is compiled and executed, it produces the following result: The sum of a and b is: 30 Press any key to exit..
  • 77. 5/5/2021 77 Advantages of using the Methods :  Some of the advantages of methods are listed below: It makes the program well structured. Methods enhance the readability of the code. It provides an effective way for the user to reuse the existing code. It optimizes the execution time and memory space. Method (Cont’d)
  • 78. 5/5/2021 78 Properties are named members of classes, structures, and interfaces.  Member variables or methods in a class or structures are called Fields. Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written or manipulated. The accessor of a property contains the executable statements that helps in getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both. C# Properties
  • 79. 5/5/2021 79 using System; namespace Properties{ class Program { private string code = "N.A"; private string name = "not known"; private int age = 0; public string Code{ // Declare a Code property of type string: get{ return code; } set{ code = value; } } public string Name{ // Declare a Name property of type string: get { return name; } set{ name = value; }} // code continue on the next page…
  • 80. 5/5/2021 80 public int Age{ // Declare a Age property of type int: get{ return age; } set{ age = value; }} public override string ToString() { return "Code = " + Code +", Name = " + Name + ", Age = " + Age; }} class ExampleDemo { public static void Main() { Program s = new Program(); // Create a new Student object: s.Code = "RET/858/02"; // Setting code, name and the age of the student s.Name = "Lalise"; s.Age = 20; Console.WriteLine("Student Info: {0}", s); s.Age += 1; Console.WriteLine("Student Info: {0}", s); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } }}  When this code is compiled and executed, it produces the following result: Student Info: Code = RET/858/02, Name = Lalise, Age = 20 Student Info: Code = RET/858/02, Name = Lalise, Age = 21 Press any key to exit...
  • 81. 5/5/2021 81 Errors  Programming errors are generally broken down into three types: 1. Design-time, 2. Runtime, and 3. Logic errors. 1. Design Time Errors  A Design-time error is also known as a syntax error.  These occur when the environment you're programming in doesn't understand your code.  These are easy to track down in C#, because you get a blue wiggly line pointing them out.  If you try to run the program, you'll get a dialogue box popping up telling you that there were Build errors. Exception (Error) Handling in C#
  • 82. 5/5/2021 82 2. Run Time Errors  Runtime errors are a lot harder to track down. As their name suggests, these errors occur when the program is running.  They happen when your program tries to do something it shouldn't be doing.  An example is trying to access a file that doesn't exist.  Runtime errors usually cause your program to crash. You should write code to trap runtime errors. 3. Logic Errors  Logic errors also occur when the program is running.  They happen when your code doesn't quite behave the way you thought it would.  A classic example is creating an infinite loop of the type "Do While x is greater than 10". If x is always going to be greater than 10, then the loop has no way to exit, and just keeps going round and round.  Logic errors tend not to crash your program. But they will ensure that it doesn't work properly. Exception…(Cont’d)
  • 83. 5/5/2021 83 Exceptions  Are events which may be considered exceptional or unusual.  They are conditions that are detected by an operation, that cannot be resolved within the local context of the operation and must be brought to the attention of the operation invoker. Exception Handler  Is a procedure or code that deals with the exceptions in your program. Raising Exceptions  The process of noticing exceptions, interrupting the program and calling the exception handler. Propagating the Exceptions  Reporting the problem to higher authority (the calling program) in your program. Handling the Exceptions  The process of taking appropriate corrective action. Exception…(Cont’d)
  • 84. 5/5/2021 84 Example of exceptions 1. Array out of bound 2. Divide by zero 3. Implicit type casting 4. Input/output exception 5. File not found exception Structured Exception Handling  C# has a built-in class that deals with errors.  The class is called Exception. When an exception error is found, an exception object is created. The exception object contains information relevant to the error exposed as properties of the object.  The object is an instance of a class that derived from a class named System.Exception.  The coding structure C# uses to deal with such Exceptions is called the Try … Catch structure. Exception…(Cont’d)
  • 85. 5/5/2021 85  Depends on several key words. Try:  Begins a section of a code in which an exception might be generated from a code error.  This section is called the Try Block. And it means "Try to execute this code".  A trapped exception is automatically routed to the Catch statement. Catch:  Begins an exception handler for a type of exception.  One or more catch code blocks follow a try block, with each catch block catching a different type of exception. Finally:  Contains code that runs when the try block finishes normally, or when a catch block receives control then finishes.  Is a block that always runs regardless of whether an exception is detected or not.  Example: closing a database connection. Exception…(Cont’d)
  • 86. 5/5/2021 86 Implementing Exception Handling  Exception handlers are implemented for specific methods.  The following three general steps are involved in creating exception handler.  Wrap the code with which the handler will be associated in a Try block  Add one or more Catch block to handle the possible exceptions  Add any code that is always executed regardless of whether or not an exception is thrown to a Finally block  Structure Try ' normal program code goes here Catch ' catch block goes here (error handling) Finally ' finally block goes here End Try Exception…(Cont’d)
  • 87. 5/5/2021 87 // C# divide by zero exception handling program using System; namespace ExceptionHandling{ class Program { static void Main(string[] args){ try{ int x = 10, y = 0, result = 0; result = x / y; Console.WriteLine("Result = " + result); } catch{ } finally{ Console.WriteLine("End of Execution"); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }}}  When this code is compiled and executed, it produces the following result: End of Execution Press any key to exit...