0% found this document useful (0 votes)
57 views

PROG103 Madrid - Advance Computer Programming 2 C

Uploaded by

MA R GA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

PROG103 Madrid - Advance Computer Programming 2 C

Uploaded by

MA R GA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

ST.

IGNATIUS
TECHNICAL INSTITUTE OF BUSINESS AND ARTS

BACHELOR IN TECHNICAL TEACHER EDUCATION


Major in Computer Programming

ADVANCE COMPUTER PROGRAMMING 2


Lesson 1
Advance Computer Programming 2
Introduction to C#

C# is a simple, modern, general-purpose, object-oriented programming


language developed by Microsoft within its .NET initiative led by Anders
Hejlsberg. This tutorial will teach you basic C# programming and will also take
you through various advanced concepts related to C# programming language.

C# (C-Sharp) is a programming language developed by Microsoft that runs on


the .NET Framework.

C# is used to develop web apps, desktop apps, mobile apps, games and much
more.

C# is a modern, general-purpose, object-oriented programming language


developed by Microsoft and approved by European Computer Manufacturers
Association (ECMA) and International Standards Organization (ISO).

C# is designed for Common Language Infrastructure (CLI), which consists of


the executable code and runtime environment that allows use of various high-
level languages on different computer platforms and architectures.

The following reasons make C# a widely used professional language −

 It is a modern, general-purpose programming language


 It is object oriented.
 It is component oriented.
 It is easy to learn.
 It is a structured language.
 It produces efficient programs.
 It can be compiled on a variety of computer platforms.
 It is a part of .Net Framework.
Prerequisites
C# programming is very much based on C and C++ programming languages,
so if you have a basic understanding of C or C++ programming, then it will be
fun to learn C#.
What is C#?

C# is pronounced "C-Sharp".

It is an object-oriented programming language created by Microsoft that runs


on the .NET Framework.

C# has roots from the C family, and the language is close to other popular
languages like C++ and Java.

The first version was released in year 2002. The latest version, C# 8, was
released in September 2019.

C# is used for:

 Mobile applications
 Desktop applications
 Web applications
 Web services
 Web sites
 Games
 VR
 Database applications
 And much, much more!

Strong Programming Features of C#

Although C# constructs closely follow traditional high-level languages, C and


C++ and being an object-oriented programming language. It has strong
resemblance with Java, it has numerous strong programming features that
make it endearing to a number of programmers worldwide.
Following is the list of few important features of C# −

 Boolean Conditions
 Automatic Garbage Collection
 Standard Library
 Assembly Versioning
 Properties and Events
 Delegates and Events Management
 Easy-to-use Generics
 Indexers
 Conditional Compilation
 Simple Multithreading
 LINQ and Lambda Expressions
 Integration with Windows
C# - Environment
In this chapter, we will discuss the tools required for creating C#
programming. We have already mentioned that C# is part of .Net framework
and is used for writing .Net applications. Therefore, before discussing the
available tools for running a C# program, let us understand how C# relates to
the .Net framework.

The .Net Framework

The .Net framework is a revolutionary platform that helps you to write the
following types of applications −

 Windows applications
 Web applications
 Web services
The .Net framework applications are multi-platform applications. The
framework has been designed in such a way that it can be used from any of
the following languages: C#, C++, Visual Basic, Jscript, COBOL, etc. All these
languages can access the framework as well as communicate with each other.
The .Net framework consists of an enormous library of codes used by the
client languages such as C#. Following are some of the components of the .Net
framework −

 Common Language Runtime (CLR)


 The .Net Framework Class Library
 Common Language Specification
 Common Type System
 Metadata and Assemblies
 Windows Forms
 ASP.Net and ASP.Net AJAX
 ADO.Net
 Windows Workflow Foundation (WF)
 Windows Presentation Foundation
 Windows Communication Foundation (WCF)
 LINQ
For the jobs each of these components perform, please see ASP.Net -
Introduction, and for details of each component, please consult Microsoft's
documentation.

Integrated Development Environment (IDE) for C#

Microsoft provides the following development tools for C# programming −

 Visual Studio 2010 (VS)


 Visual C# 2010 Express (VCE)
 Visual Web Developer
The last two are freely available from Microsoft official website. Using these
tools, you can write all kinds of C# programs from simple command-line
applications to more complex applications. You can also write C# source code
files using a basic text editor, like Notepad, and compile the code into
assemblies using the command-line compiler, which is again a part of the
.NET Framework.
Visual C# Express and Visual Web Developer Express edition are trimmed
down versions of Visual Studio and has the same appearance. They retain
most features of Visual Studio. In this tutorial, we have used Visual C# 2010
Express.
You can download it from Microsoft Visual Studio. It gets installed
automatically on your machine.
Note: You need an active internet connection for installing the express edition.

Writing C# Programs on Linux or Mac OS

Although the.NET Framework runs on the Windows operating system, there


are some alternative versions that work on other operating systems. Mono is
an open-source version of the .NET Framework which includes a C# compiler
and runs on several operating systems, including various flavors of Linux and
Mac OS. Kindly check Go Mono.
The stated purpose of Mono is not only to be able to run Microsoft .NET
applications cross-platform, but also to bring better development tools for
Linux developers. Mono can be run on many operating systems including
Android, BSD, iOS, Linux, OS X, Windows, Solaris, and UNIX.
Activity No. 1 (10.pts)
Identify the questions below

____________1. It is a programming language developed by Microsoft that runs


on the .NET Framework.

____________2. C# is a modern, general-purpose, object-oriented programming


language developed by____________.

____________3. C# is Object oriented programming? Write True or False.

____________4. C# is initiative led by and his team during the development of


.Net Framework.

____________5. The latest version of C# was released in?


Lesson 2
Advance Computer Programming 2
C# Program Structure

Before we study basic building blocks of the C# programming language, let us


look at a bare minimum C# program structure so that we can take it as a
reference in upcoming chapters.

Creating Hello World Program

A C# program consists of the following parts −

 Namespace declaration
 A class
 Class methods
 Class attributes
 A Main method
 Statements and Expressions
 Comments
Let us look at a simple code that prints the words "Hello World"

Sample code Compiled output

Let us look at the various parts of the given program −


 The first line of the program using System; - the using keyword is used
to include the System namespace in the program. A program generally
has multiple using statements.
 The next line has the namespace declaration. A namespace is a
collection of classes. The HelloWorldApplication namespace contains the
class HelloWorld.
 The next line has a class declaration, the class HelloWorld contains the
data and method definitions that your program uses. Classes generally
contain multiple methods. Methods define the behavior of the class.
However, the HelloWorld class has only one method Main.
 The next line defines the Main method, which is the entry point for all
C# programs. The Main method states what the class does when
executed.
 The next line /*...*/ is ignored by the compiler and it is put to
add comments in the program.
 The Main method specifies its behavior with the
statement Console.WriteLine("Hello World");
WriteLine is a method of the Console class defined in
the System namespace. This statement causes the message "Hello,
World!" to be displayed on the screen.
 The last line Console.ReadKey(); is for the VS.NET Users. This makes
the program wait for a key press and it prevents the screen from
running and closing quickly when the program is launched from Visual
Studio .NET.
WriteLine or Write

The most common method to output something in C# is WriteLine(), but you can
also use Write().

The difference is that WriteLine() prints the output on a new line each time,
while Write() prints on the same line (note that you should remember to add
spaces when needed, for better readability):

Note: Every C# statement ends with a semicolon ;.

Note: C# is case-sensitive: "MyClass" and "myclass" has different meaning.


Activity No. 2 (15pts)
Test I
Identify the question below
_____________1. The next line will be ignored by the compiler and it has been
put to add additional comments in the program. So such lines are called
comments in the program

_____________2. The first line of the program - the using keyword is used to include
the namespace in the program. A program generally has multiple using statements.

_____________3. This is a collection classes. The HelloWorldApplication


namespace contains the class HelloWorld.

_____________4. This is the method which is the entry point for all c# programs.

_____________5. This metyhod specifies its behavior with the statement to write
the output.

Test II

Insert the missing part of the code below to output "Hello World!".
Lesson 3
Advance Computer Programming 2
C# Basic Syntax and Comments

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.
For example, let us consider a Rectangle object. It has attributes such as
length and width. Depending upon the design, it may need ways for accepting
the values of these attributes, calculating the area, and displaying details.
Let us look at implementation of a Rectangle class and discuss C# basic
syntax −
Sample Output

The using Keyword

The first statement in any C# program is

The using keyword is used for including the namespaces in the program. A
program can include multiple using statements.

The class Keyword

The class keyword is used for declaring a class.


C# Comment
Comments are used for explaining code. Compilers ignore the comment
entries. The multiline comments in C# programs start with /* and terminates
with the characters */ as shown below

Single-line comments are indicated by the '//' symbol. For example,

Member Variables

Variables are attributes or data members of a class, used for storing data. In
the preceding program, the Rectangle class has two member variables
named length and width.
Member Functions

Functions are set of statements that perform a specific task. The member
functions of a class are declared within the class. Our sample class Rectangle
contains three member functions: AcceptDetails, GetArea and Display.

Instantiating a Class

In the preceding program, the class ExecuteRectangle contains


the Main() method and instantiates the Rectangle class.

Identifiers

An identifier is a name used to identify a class, variable, function, or any other


user-defined item. The basic rules for naming classes 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 such as? - + ! @ # %
^ & * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.
 It should not be a C# keyword.

C# Keywords

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 the keyword with the @ character.
In C#, some identifiers have special meaning in context of code, such as get
and set are called contextual keywords.
The following table lists the reserved keywords and contextual keywords in C#
Activity No. 3 (10pts)
Lesson 4
Advance Computer Programming 2
C# Variables

C# Variables

Variables are containers for storing data values.

In C#, there are different types of variables (defined with different keywords),
for example:

 int - stores integers (whole numbers), without decimals, such as 123 or -


123
 double - stores floating point numbers, with decimals, such as 19.99 or -
19.99
 char - stores single characters, such as 'a' or 'B'. Char values are
surrounded by single quotes
 string - stores text, such as "Hello World". String values are surrounded
by double quotes
 bool - stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Where type is a C# type (such as int or string), and variableName is the name
of the variable (such as x or name). The equal sign is used to assign values to
the variable.

To create a variable that should store text, look at the following example:
Sample Output

To create a variable that should store a number, look at the following example:

Note that if you assign a new value to an existing variable, it will overwrite the
previous value:
Constants

However, you can add the const keyword if you don't want others (or yourself)
to overwrite existing values (this will declare the variable as "constant", which
means unchangeable and read-only):

Other Types

A demonstration of how to declare variables of other types:


Display Variables

The WriteLine() method is often used to display variable values to the console
window.

To combine both text and a variable, use the + character:

You can also use the + character to add a variable to another variable:
Declare Many Variables

To declare more than one variable of the same type, use a comma-separated
list:

C# Identifiers

All C# variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).

Note: It is recommended to use descriptive names in order to create


understandable and maintainable code:
Sample Output

The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits and the underscore character (_)
 Names must begin with a letter
 Names should start with a lowercase letter and it cannot contain
whitespace
 Names are case sensitive ("myVar" and "myvar" are different variables)
 Reserved words (like C# keywords, such as int or double) cannot be used
as names

Activity No. 4

Identify the questions below:

___________1. This Variable stores integers (whole numbers), without decimals,


such as 123 or -123

___________2. This Variable stores values with two states: true or false.

___________3. This Variable stores single characters, such as 'a' or 'B'. Char
values are surrounded by single quotes

___________4. This variable stores floating point numbers, with decimals, such
as 19.99 or -19.99

___________5. This Variable stores text, such as "Hello World". String values
are surrounded by double quotes.

Application: 5pts
Lesson 5
Advance Computer Programming 2
C# Data Types

The variables in C#, are categorized into the following types −

 Value types
 Reference types
 Pointer types
C# Data Types

As explained in the variables chapter, a variable in C# must be a specified data


type:

Sample
Sample Output

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. 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.
A data type specifies the size and type of variable values. It is important to use
the correct data type for the corresponding variable; to avoid errors, to save
time and memory, but it will also make your code more maintainable and
readable. The most common data types are:
Numbers

Number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or -


456), without decimals. Valid types are int and long. Which type you should
use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing
one or more decimals. Valid types are float and double.

Integer Types
Int

The int data type can store whole numbers from -2147483648 to
2147483647. In general, and in our tutorial, the int data type is the preferred
data type when we create variables with a numeric value.

Example:

Long

The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the
value. Note that you should end the value with an "L":
Floating Point Types

You should use a floating point type whenever you need a number with a
decimal, such as 9.99 or 3.14515.

Float

The float data type can store fractional numbers from 3.4e−038 to 3.4e+038.
Note that you should end the value with an "F":

Double

The double data type can store fractional numbers from 1.7e−308 to 1.7e+308.
Note that you can end the value with a "D" (although not required):
Reference 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.

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.

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.

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,

Booleans

A boolean data type is declared with the bool keyword and can only take the
values true or false:

Example

Boolean values are mostly used for conditional testing, which you will learn
more about in a later chapter.

Characters

The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':
Strings

The string data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes:

Example

String 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.
Activity No. 5 (15pts.)

_____________ 1. This data types directly contain data. Some examples are int,
char, and float, which stores numbers, alphabets, and floating point numbers,
respectively.

______________2. This data types do not contain the actual data stored in a
variable, but they contain a reference to the variables.

______________3. This data types represents numbers with a fractional part,


containing one or more decimals. Valid types are float and double.

______________4. This data type is declared with the bool keyword and can only
take the values true or false:

______________5. This data type is used to store a single character. The


character must be surrounded by single quotes, like 'A' or 'c':

Application:

6 – 10. Add the correct data type for the following variables:

11-15. Create a greeting variable, and display the value of it:


Lesson 6
Advance Computer Programming 2
C# Type Conversion / Type Casting

Type Conversion Methods


Type conversion is converting one type of data to another type. It is also
known as Type Casting. In C#, type casting has two forms –

It is also possible to convert data types explicitly by using built-in methods,


such
as Convert.ToBoolean, Convert.ToDouble, Convert.ToString, Convert.ToInt32 (i
nt) and Convert.ToInt64 (long):

 Implicit type conversion − These conversions are performed by C# in a


type-safe manner. For example, are conversions from smaller to larger
integral types and conversions from derived classes to base classes.
 Explicit type conversion − These conversions are done explicitly by
users using the pre-defined functions. Explicit conversions require a
cast operator.
The following example shows an explicit type conversion −

C# Type Conversion Methods

C# provides the following built-in type conversion methods


Example
C# Type Casting

Type casting is when you assign a value of one data type to another type.

In C#, there are two types of casting:

 Implicit Casting (automatically) - converting a smaller type to a larger


type size
char -> int -> long -> float -> double

 Explicit Casting (manually) - converting a larger type to a smaller size


type
double -> float -> long -> int -> char

Implicit Casting

Implicit casting is done automatically when passing a smaller size type to a


larger size type:

Example:

Explicit Casting

Explicit casting must be done manually by placing the type in parentheses in


front of the value:
Activity No. 6 (10pts.)

Identify the following question 2pts. each

____________1. This These conversions are done explicitly by users using the
pre-defined functions.

____________2. This type of conversion methods converts a type to a small


floating point number.

____________3. This type of conversion methods converts a floating point or


integer type to a decimal type.

____________4. This type of conversion methods converts onverts a type to an


unsigned big integer.

____________5. These conversions are performed by C# in a type-safe manner.


Lesson 7
Advance Computer Programming 2
C# User Inputs

Get User Input

You have already learned that Console.WriteLine() is used to output (print)


values. Now we will use Console.ReadLine() to get user input.

In the following example, the user can input his or hers username, which is
stored in the variable userName. Then we print the value of userName:

Sample Output
User Input and Numbers

The Console.ReadLine() method returns a string. Therefore, you cannot get


information from another data type, such as int.

Like the error message says, you cannot implicitly convert type 'string' to 'int'.

Luckily, for you, you just learned from the previous chapter (Type Casting),
that you can convert any type explicitly, by using one of
the Convert.To methods:
Activity No. 7 (10pts.)

Application: Fill out the missing codes.

1. Fill in the missing parts to get user input, stored in the variable userName:

2. Fill in the missing parts to print a number put in by the user:


Lesson 8
Advance Computer Programming 2
C# Operators

An operator is a symbol that tells the compiler to perform specific


mathematical or logical manipulations. C# has rich set of built-in operators
and provides the following type of operators −

Operators are used to perform operations on variables and values.

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
 Comparison Operators

This lesson explains the arithmetic, relational, logical, bitwise, assignment, and
other operators one by one.

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations:


Sample Program Sample Output

Relational Operators

Following table shows all the relational operators supported by C#. Assume
variable A holds 10 and variable B holds 20, then
Bitwise Operators

Bitwise operator works on bits and perform bit by bit operation. The truth
tables for &, |, and ^ are as follows:

Assume if A = 60; and B = 13; then in the binary format they are as follows −
A = 0011 1100
B = 0000 1101
-------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C# are listed in the following table.
Assume variable A holds 60 and variable B holds 13, then
Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:

There are following assignment operators supported by C#


Sample Program Sample Output

Sample Program Sample Output


Miscellaneous Operators

There are few other important operators including sizeof, typeof and ?
: supported by C#.

C# Comparison Operators

Comparison operators are used to compare two values:


Logical Operators

Logical operators are used to determine the logic between variables or values:

Operator Precedence in C#

Operator precedence determines the grouping of terms in an expression. This


affects evaluation of an expression. Certain operators have higher precedence
than others; for example, the multiplication operator has higher precedence
than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator *
has higher precedence than +, so the first evaluation takes place for 3*2 and
then 7 is added into it.
Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators are evaluated first.
Assessment No. 8 (15pts)

Test I. Give the types of Operators

1.

2.

3.

4.

5.

6.

7.

Test II Application

Write the missing codes


Lesson 9
Advance Computer Programming 2
C# Decision Making

Decision making structures requires the programmer to specify one or more


conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and
optionally, other statements to be executed if the condition is determined to be
false.
Following is the general form of a typical decision making structure found in
most of the programming languages
C# provides following types of decision making statements.
Assessment No. 9

Draw the decision making structure of the most programming languages.


(20pts.)
Lesson 10
Advance Computer Programming 2
C# Strings

C# Strings

Strings are used for storing text.

A string variable contains a collection of characters surrounded by double


quotes:

Sample Program

String Length

A string in C# is actually an object, which contain properties and methods that


can perform certain operations on strings. For example, the length of a string
can be found with the Length property:

Sample Program
Sample Output

Other Methods

There are many string methods available, for example ToUpper() and ToLower(),
which returns a copy of the string converted to uppercase or lowercase:

Sample Program

Sample Output
String Concatenation

The + operator can be used between strings to combine them. This is


called concatenation:

Sample Program Sample Output

You can also use the string.Concat() method to concatenate two strings:

String Interpolation

Another option of string concatenation is string interpolation, which


substitutes values of variables into placeholders in a string. Note that you do
not have to worry about spaces, like with concatenation:
Sample Program

Sample Output

Access Strings

You can access the characters in a string by referring to its index number
inside square brackets [].

This example prints the first character in myString:


Sample Program Sample Output

Special Characters

Because strings must be written within quotes, C# will misunderstand this


string, and generate an error:

The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string
characters:

The sequence \" inserts a double quote in a string:


Sample Program

Sample Output

The sequence \' inserts a single quote in a string:

Sample Program Sample Output


The sequence \\ inserts a single backslash in a string:

Sample Program Sample Output

Other useful escape characters in C# are:

Adding Numbers and Strings

Sample Sample Output


If you add two strings, the result will be a string concatenation:

Sample Program Sample Output


Activity No. 10

1. Fill in the missing part to create a greeting variable of type string and
assign it the value Hello.

2. Use the string interpolation method to concatenate two strings:

3. Use the string interpolation method to concatenate two strings:

4. Access the first character (H) in myString and print the result:
Lesson 11
Advance Computer Programming 2
C# Booleans

C# Booleans

Very often, in programming, you will need a data type that can only have one of
two values, like:

 YES / NO
 ON / OFF
 TRUE / FALSE

For this, C# has a bool data type, which can take the values true or false.

Boolean Values

A boolean type is declared with the bool keyword and can only take the
values true or false:

Sample Program Sample Output

However, it is more common to return boolean values from boolean


expressions, for conditional testing (see below).
Boolean Expression

A Boolean expression is a C# expression that returns a Boolean


value: True or False.

You can use a comparison operator, such as the greater than (>) operator to
find out if an expression (or a variable) is true:

Sample Program

Sample Output

Or even easier:

Sample Program
Sample Output

In the examples below, we use the equal to (==) operator to evaluate an


expression:

Sample program

Sample Output

Sample Program
Sample Output
Activity No. 11

1. Fill in the missing parts to print the values True and False:

2. Fill in the missing parts to print the value True:


Lesson 12
Advance Computer Programming 2
C# If … Else

C# Conditions and If Statements

C# supports the usual logical conditions from mathematics:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

You can use these conditions to perform different actions for different
decisions.

C# has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is


true
 Use else to specify a block of code to be executed, if the same condition is
false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of C# code to be executed if a condition


is True.

Syntax

In the example below, we test two values to find out if 20 is greater than 18. If the
condition is True, print some text:
Sample Program Sample Output

We can also test variables:

Sample Program Sample Output

Example explained

In the example above we use two variables, x and y, to test whether x is greater
than y (using the > operator). As x is 20, and y is 18, and we know that 20 is
greater than 18, we print to the screen that "x is greater than y".
The else Statement

Use the else statement to specify a block of code to be executed if the


condition is False.

Syntax

Program Sample Sample Output

Example explained

In the example above, time (20) is greater than 18, so the condition is False.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".
The else if Statement

Use the else if statement to specify a new condition if the first condition
is False.

Syntax

Sample Program Sample Output


Example explained

In the example above, time (22) is greater than 10, so the first
condition is False. The next condition, in the else if statement, is also False,
so we move on to the else condition since condition1 and condition2 is
both False - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

Short Hand If...Else (Ternary Operator)

There is also a short-hand if else, which is known as the ternary


operator because it consists of three operands. It can be used to replace
multiple lines of code with a single line. It is often used to replace simple if else
statements:

Syntax

Sample Program Sample Output


You can simply write:

Sample Program Sample Output


Activity No. 12 (10 pts.)

1. Print "Hello World" if x is greater than y.

2. Print "Hello World" if x is equal to y.


Lesson 13
Advance Computer Programming 2
C# Switch

C# Switch Statements

Use the switch statement to select one of many code blocks to be executed.

Syntax

This is how it works:

 The switch expression is evaluated once


 The value of the expression is compared with the values of each case
 If there is a match, the associated block of code is executed
 The break and default keywords will be described later in this chapter

The example below uses the weekday number to calculate the weekday name:
Sample Program Sample Output

The break Keyword

When C# reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no
need for more testing.

The default Keyword

The default keyword is optional and specifies some code to run if there is no
case match:

Sample Program Sample Output


Activity No. 13 (10 pts.)

1. Insert the missing parts to complete the following switch statement.

2. Complete the switch statement, and add the correct keyword at the end to
specify some code to run if there is no case match in the switch statement.
Lesson 14
Advance Computer Programming 2
C# Loops

There may be a situation, when you need to execute a block of code several
number of times. In general, the statements are executed sequentially: The
first statement in a function is executed first, followed by the second, and so
on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or a group of statements
multiple times and following is the general from of a loop statement in most of
the programming languages
C# provides following types of loop to handle looping requirements. Click the
following links to check their detail.

Loop Control Statements

Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed.
C# provides the following control statements.

Infinite Loop

A loop becomes infinite loop if a condition never becomes false. The for loop is
traditionally used for this purpose. Since none of the three expressions that
form the for loop are required, you can make an endless loop by leaving the
conditional expression empty.
Example:

When the conditional expression is absent, it is assumed to be true. You may


have an initialization and increment expression, but programmers more
commonly use the for(;;) construct to signify an infinite loop.
Assessment No. 14 (10 pts.)

Test I.

_____________1. It executes a sequence of statements multiple times and


abbreviates the code that manages the loop variable.

_____________2 It is similar to a while statement, except that it tests the


condition at the end of the loop body

_____________3. It terminates the loop or switch statement and transfers


execution to the statement immediately following the loop or switch.

_____________4. It repeats a statement or a group of statements while a given


condition is true. It tests the condition before executing the loop body.

_____________5. It Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
Lesson 15
Advance Computer Programming 2
C# While Loop /Do While Loop
A while loop statement in C# repeatedly executes a target statement as long as a given
condition is true.

Syntax

The syntax of a while loop in C# is

Here, statement(s) may be a single statement or a block of statements.


The condition may be any expression, and true is any non-zero value. The loop
iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.
Flow Diagram

Here, key point of the while loop is that the loop might not ever run. When the
condition is tested and the result is false, the loop body is skipped and the
first statement after the while loop is executed.
In the example below, the code in the loop will run, over and over again, as
long as a variable (i) is less than 5:
Sample Program Sample Output

The Do/While Loop


Unlike for and while loops, which test the loop condition at the start of the
loop, the do...while loop checks its condition at the end of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.

The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop
as long as the condition is true.

Syntax

The syntax of a do...while loop in C# is


Notice that the conditional expression appears at the end of the loop, so the
statement(s) in the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the
statement(s) in the loop execute again. This process repeats until the given
condition becomes false.

Sample Program Sample Output


Assessment No. 15 (20 pts.)

Test I. Draw the flow chart that contains while conditions.

Test II. Fill out the missing programming codes


Lesson 16
Advance Computer Programming 2
C# For Loop / Nested Loop

A for loop is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.

Syntax

The syntax of a for loop in C# is

Here is the flow of control in a for loop


 The init step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required to
put a statement here, as long as a semicolon appears.
 Next, the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of
control jumps to the next statement just after the for loop.
 After the body of the for loop executes, the flow of control jumps back up
to the increment statement. This statement allows you to update any
loop control variables. This statement can be left blank, as long as a
semicolon appears after the condition.
 The condition is now evaluated again. If it is true, the loop executes and
the process repeats itself (body of loop, then increment step, and then
again testing for a condition). After the condition becomes false, the for
loop terminates.
Flowchart Sample

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

Sample Program Sample Output


Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If
the condition is true, the loop will start over again, if it is false, the loop will
end.

Statement 3 increases a value (i++) each time the code block in the loop has
been executed.

Sample Program Sample Output

Nested Loop

C# allows using one loop inside another loop. Following section shows few
examples to illustrate the concept.

Syntax

The syntax for a nested for loop statement in C# is as follows


The syntax for a nested while loop statement in C# is as follows

The syntax for a nested do...while loop statement in C# is as follows

A final note on loop nesting is that you can put any type of loop inside of any
other type of loop.
Assessment No. 16 (10 pts.)

Test I. Draw the diagram using the for loop condition.

Test II. Fill out the missing codes

2. Print i as long as I is less than 6.


Lesson 17
Advance Computer Programming 2
C# Break / Continue

The break statement in C# has following two usage −


 When the break statement is encountered inside a loop, the loop is
immediately terminated and program control resumes at the next
statement following the loop.
 It can be used to terminate a case in the switch statement.
If you are using nested loops (i.e., one loop inside another loop), the break
statement will stop the execution of the innermost loop and start executing the
next line of code after the block.

Syntax

The syntax for a break statement in C# is as follows:

Sample Flow Chart

You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.


This example jumps out of the loop when i is equal to 4:

Sample Program Sample Output

C# Continue

The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.

This example skips the value of 4:


Sample Program Sample Output

Break and Continue in While Loop

You can also use break and continue in while loops:

Sample Program Sample Out


Continue Example
Sample Program Sample Output
Activity No. 17 (10 pts.)

1. Draw the diagram using the break condition.

You might also like