0% found this document useful (0 votes)
117 views124 pages

Programming1 Lecture Presentations

The document provides an introduction to computer programming concepts including: - What a program is and its basic components of variables and statements. - Different types of programming languages from low-level to high-level and their uses. - Key programming concepts such as algorithms, flowcharts, variables, operators, and loops. - Examples of algorithms, flowcharts, and programming problems are given to illustrate these concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
117 views124 pages

Programming1 Lecture Presentations

The document provides an introduction to computer programming concepts including: - What a program is and its basic components of variables and statements. - Different types of programming languages from low-level to high-level and their uses. - Key programming concepts such as algorithms, flowcharts, variables, operators, and loops. - Examples of algorithms, flowcharts, and programming problems are given to illustrate these concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 124

CHAPTER 1

Introduction to Computer Programming


What is a Program?

• An organized list of instructions that, when executed, causes the


computer to behave in a predetermined manner.
• A computer program, or just a program, is a sequence of
instructions, written to perform a specified task on a computer.
• A program is like a recipe. It contains a list of ingredients (called
variables) and a list of directions (called statements) that tell the
computer what to do with the variables. The variables can
represent numeric data, text, or graphical images.
• Without programs, computers are useless!
an app, application, software application or software program is
the most common software on the computer that performs a special
function or task. For example, Microsoft Word is a word processor
program that allows users to create and write documents and the
browser you are using to view this page is a program. Without
programs, a computer would still work with the operating system,
but you would not be able to do anything.
What is Programming?

• It is an act of making programs


App vs Program

• An App is an Apple term for program.


What is software?

• Generic
• General
• does not necessarily always mean "program" or "application" (e.g.
a software "library" or "framework" is not a "program" or
"application", but are used to facilitate the functional
requirements of "programs" or "applications").
Why do programmers make computer
programs?

• To simplify task
• Provide accurate result
• Aides in facilitating day to day activities
LLL vs HLL

• Low Level Language – language that can convert to machine code


without a compiler or interpreter, and the resulting code runs
directly on the CPU/Processor. (also known as the machine
language or assembly language – the zeros and ones (0,1))

• High Level Language – needs a compiler or interpreter to convert


the instruction into language that could be understood by
CPU/Processor.
What is CPU or Processor?

• “Brain” of the computer

• Executes commands or instructions


Compiler

• It is a program that converts high level language to low level


language that could be understood by the CPU (this process is
called “Compiling”)

• Commonly compiles instruction known as the “Code”


Interpreter

• It is a program that interprets(without undergoing the process of


compiling) high level language to low level language that could be
understood by the CPU.

• Commonly compiles instruction known as the “Script”


Types of Programming Language

• Web languages
• Software languages
• The different generations of languages
• Procedure oriented programming
• Object oriented programming
Web Languages

• HTML
• XML
• JAVASCRIPT
• VBSCRIPT
• PHP
• ASP
• JAVA
Software Languages

• C
• C++
• Visual Basic
• JAVA
The different generations of languages

• 1st Generation Language (1GL)


• 2nd Generation Language (2GL)
• 3rd Generation Language (3GL)
• 4th Generation Language (4GL)
First generation languages (abbreviated as
1GL)

• Represent the very early, primitive computer languages that


consisted entirely of 1's and 0's - the actual language that the
computer understands (machine language).
Second generation languages (2GL)

• Represent a step up from the first generation languages. Allow for


the use of symbolic names instead of just numbers. Second
generation languages are known as assembly languages. Code
written in an assembly language is converted into machine
language (1GL).
Third generation languages (3GL)

• With the languages introduced by the third generation of


computer programming, words and commands (instead of just
symbols and numbers) were being used. These languages
therefore, had syntax that was much easier to understand. Third
generation languages are known as "high level languages" and
include C, C++, Java, and Javascript, among others
Fourth generation languages (4GL)

• The syntax used in 4GL is very close to human language, an


improvement from the previous generation of languages. 4GL
languages are typically used to access databases and include SQL
and ColdFusion, among others.
Fifth generation languages (5GL)

• Fifth generation languages are currently being used for Neural


Networks. A Neural Network is a form of Artifical Intelligence that
attempts to imitate how the human mind works.
Example Code of Visual Basic
Python
C#
CHAPTER 2

Designing and Creating a Program


Algorithm

• A formula or set of steps for solving a particular problem. To be an


algorithm, a set of rules must be unambiguous and have a clear
stopping point. Algorithms can be expressed in any language, from
natural languages like English
• We use algorithms every day. For example, a recipe for baking a
cake is an algorithm. Most programs, with the exception of some
artificial intelligence applications, consist of algorithms. Inventing
elegant algorithms -- algorithms that are simple and require the
fewest steps possible -- is one of the principal challenges in
programming.
Examples of algorithm

• Cookbook
• Recipe Booklet
• Choreography

In the same way, algorithms executed by computer can


combine millions of elementary steps, such as additions,
subtractions, multiplications and divisions into complicated
mathematical calculations.
Here is one algorithm for the usual process of
saving a document in a disk.

1. Find a new or unused disk.


2. Insert the disk in drive A.
3. From the word environment, select file menus then select save as.
4. From the save as dialog box, select the directory where you save the
document. Select 3½ floppy disk.
5. Position the pointer inside the filename textbox then type the
filename of the document.
6. Then click the save button to formally save the document.
Sample Problem #1

Create an algorithm on how to kill a chicken.


Sample Problem #2

Create an algorithm on how to get the sum of two numbers.


Sample Problem #3

Create an algorithm on how to get the average of the three (3)


numbers.
Flowchart

• A flow chart is a graphical or symbolic representation of a process.


Each step in the process is represented by a different symbol and
contains a short description of the process step. The flow chart
symbols are linked together with arrows showing the process flow
direction.
Basic Symbols
Example of Flowchart
Notations Used in Flowchart

Notation Meaning
: comparison
& logical and
Y yes
N no
EOF End of File
Relational Test Operators

Notation Meaning
> is greater than
< is less than
<= or =< is less than or equal to
>= or => is greater than or equal to
<> or >< is not equal to
= is equal to
Arithmetic Operators

Notations Meaning

+ Addition
- Subtraction
* Multiplication
/ Division
() Grouping
** or ^ Exponentiation
Precedence of the Operators

The computer follows this order of priority

1. Grouping ()
2. Exponentiation
3. Multiplication or division
4. Addition or subtraction
When operators are all of equal priority, the computer
evaluate the expression from left to right.
When operators are of different priorities, the computer
performs those operations with higher priorities first.
Operations enclosed in parentheses will take place before other
operations. Note (if there are multiple parentheses, the innermost
parenthesis will be evaluated first).
Valid or Invalid?

Example #2.1
1+-2
Example #2.2
3/-2

Both are invalid because no two arithmetic operators may appear


side by side.
Write clearly the computation desired

Example #2.3
2L / 3G
Answer?
( 2 * L ) / (3 * G )
Sample Problem #4

Create a flowchart that would ask for a legal age to access a


particular porn site. If age is greater than or equal to 18 then print
“Yehey, you are allowed, happy Viewing”, otherwise, print “Totoy
ka palang”.
Sample Problem #5

Create a flowchart that would determine if the grade of student is


Passed or Failed. If grade is greater than or equal to 75, print “P”,
else “F”.
Sample Problem #6

Create a flowchart that would get the average of student’s grade


from 5 subjects (Math, Science, Social Sciences, Biology, P.E) and
determine whether the average is passed or failed. If the average is
greater than 75, display “Passed”, otherwise display “Failed”.
Loops and Counters

• Looping is used when it is desired to make the same calculation


on more than one set of data. It consists of repeating a program,
or a section of a program, and substituting new data for each
repetition.

• A counter is set up in a program loop to keep track of the number


of times the program segment is repeated.
Steps in Loop Control

1. Initialization – the value of a counter used is initially set equal to zero


(or one). This process is always done outside the loop.

2. Test for Limit Conditions – before logic flow gets out of the loop, a
loop – terminating condition must first be satisfied. The process of testing
is usually found either at the beginning or at the end of a loop.

3. Incrementation – after each loop is executed, 1 is added to the


counter. Thus the counter reflects the number of times the operation has
been performed. This process is always done within the loop.
Sample Problem #7

Draw a flowchart which will read and print the names and individual
scores of 40 students for a particular examination. Determine their
average and print it out.
The algorithm for this particular requirement
could be listed as follows:

1. Initialize the counter (ctr) and accumulator (sum) to zero.


2. Read in student’s name and score.
3. Print out the student’s name and score.
4. Accumulate the data value (score) into sum.
5. Test if the desired amount of data (40) has been reached.
6. If the value of counter (ctr) is less than 40, repeat steps 2 through 5.
However, if the desired amount of data has been reached (40), compute
the average score by dividing the sum by the value of counter.
7. Print out the average score.
Equivalent flowchart of the problem
Loops and Accumulators

It would often be required to determine the sum of certain


numerical quantities that are read or calculated one at a time. This
is accomplished by first choosing a variable, and initializing it to
zero. As the flow of logic through the flowchart loop is followed, a
repetitive operation is performed until the loop is terminated. The
variable used is thereby continuously accumulating the numerical
quantities and is thus called an accumulator. The final value
accumulated will be the sum of all the numerical quantities.
Sample Problem #8

Draw a flowchart to compute and print the sum of the squares of


positive integers from 1 to 100.
Sample Problem #9

Create a flowchart that would change the initial value of the


variable X which is 10 to 100 when the value of variable Y is 50.
Sample Problem #10

Draw a flowchart that would convert the a particular number to


words. Numbers may be from 1 to 5. Example, if the value is 1, then
it will display the word “One”, “Two” for 2 and so on…
Sample Problem #11

Find the amount to charge people of varying ages for a food ticket.
When the person is under 16, the charge is Php 7.00, when the
person is 65 or over, the charge is Php 5.00, all others are charged
Php 10.00. The conditions are the following:

Age Charge
<16 7
>=16 and <65 10
>=65 5
Sample Problem #12

Calculate the commission rate for a salesperson given the amount of


sales. When the salesperson has sold less than of equal to 2,000.00
worth of goods, the commission is 2%. When the sales total is more
than 2,000.00 and less than or equal 4,000.00 the commission is 4%.
When the sales total is more than 4,000.00 and less than or equal to
6,000.00, the commission is 7%. When the salesperson sold more
than 6,000.00, the commission is 10%.
Sample Problem #13

Create a flowchart that would determine if a particular number is


an Odd number. When the number is Odd, print “The Number is an
Odd”.
Sample Problem #14

Create a flowchart that would determine if a particular number is


an Even number. When the number is Even, print “The Number is an
Even”.
Sample Problem #15

Draw a flowchart that would count and display all the even and odd
numbers from 1 to 10.
“God has perfect timing: never early, never late,
it takes a little patience and a whole lot of
faith, but it’s worth the wait”
CHAPTER 3

The C# Programming Language


C# Overview

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


language developed by Microsoft and approved by Ecma and ISO.
• C# was developed by Anders Hejlsberg and his team during the
development of .Net Framework.
• 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 to be used on different
computer platforms and architectures.
The following reasons make C# a widely used
professional language:

• Modern, general-purpose programming language


• Object oriented.
• Component oriented.
• Easy to learn.
• Structured language.
• It produces efficient programs.
• It can be compiled on a variety of computer platforms.
• Part of .Net Framework.
C# Program Structure

• Namespace declaration
• A class
• Class methods
• Class attributes
• A Main method
• Statements & Expressions
• Comments
The C# Code

using System;

class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
Line #1: using System;
Line #2: class HelloWorld
Line #3: {
Line #4: static void Main(string[] args)
Line #5: {
Line #6: /* my first program in C# */
Line #7: Console.WriteLine("Hello World");
Line #8: Console.ReadKey();
Line #9: }
Line #10: }
Line #1: using System;

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.
Line #2: class HelloWorld

The next line has a class


declaration, the class
HelloWorld contains the data
and method definitions that
your program uses. Classes
generally would contain more
than one method. Methods
define the behavior of the
class. However, the
HelloWorld class has only
one method Main.
Line #4: static void Main(string[] args)

The next line defines


the Main method,
which is the entry
point for all C#
programs. The Main
method states what
the class will do when
executed
Line #6:/* my first program in C# */

The next line /*...*/ will be


ignored by the compiler and it
has been put to add additional
comments in the program.
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:

/*
This program demonstrates
The basic syntax of C# programming
Language
*/

}//end of class hello world


Line #7: 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.
Line #8: Console.ReadKey();

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.
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.
Identifiers
An identifier is a name used to identify a
class, variable, function, or any other user-
RULE #1: defined item.

A name must begin


with a letter that
could be followed by
a sequence of letters,
RULE #2:
digits (0 - 9) or
underscore. The first RULE #3:
It must not contain
character in an
any embedded space
identifier cannot be a It should not be a C#
or symbol like ? - +! @
digit. keyword.
#%^&*()[]{}.;:
" ' / and \. However,
an underscore ( _ )
can be used.
C# Keywords Sometimes called “RESERVED WORDS”
which have a special meaning in a
programming language

NEVER EVER
USE THEM AS IDENTIFIERS!
C# 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 in (generic int
modifier)
interface internal is lock long namespace new
null object operator out out (generic override params
modifier)

private protected public readonly ref return sbyte


sealed short sizeof stackalloc static string struct
switch This throw true try typeof uint
ulong unchecked unsafe ushort using virtual void
volatile While
Contextual Keywords
add Alias ascending descending dynamic from get
global group into join let orderby partial (type)

partial (method) remove select set


Concept of Variables

• It is a location inside the computer’s memory that allows us to


store information.
• It is like tiny box inside the computer’s memory.
• Its primary purpose is to store information like text, numbers,
date, time, objects.
• Text ( abc, 21programming, joe19, jane 03)
• Numbers (1,2,3,4,5,6,7,8,9,0)
• Date (07/19/1987)
• Time (9:00)
0 “joe” “CCSICT”
10:00 19

Computer’s Memory
sAge
sname
num1
deptName

mTime
Note: Every location has a
name and characteristic, in
short, a variable has a name
and data type
Rules in Naming Variables

• It must start with a letter


• It must not contain any special characters. (*,#,$,etc).
• It must not be a keyword or reserved word. (keywords/reserved words
– words that have special meaning in programming language.)
• It must not be long.

Note: ALL VARIABLES HAVE NAMES (identifier)


Valid Variable Names

• Abc
• abc123
• bahaykubokahitmunti
• walang_forever
• sum
• average
Valid or Invalid?

Rule #1: It must start with a letter


• 123
INVALID Rule #2: It must not contain any special characters.
• Joe_123 (*,#,$,etc).
VALID
• $engot Rule #3: It must not be a keyword or reserved word.
INVALID (keywords/reserved words – words that have special meaning in
• *kulangot programming language.)
INVALID
• Astig_#
Rule #4: It must not be long.
INVALID
• Takkiburistabbil
VALID Note: ALL VARIABLES HAVE NAMES (identifier)
• Determines
what the nature
of a value a
C# Datatypes variable can
hold
• Nature of values

Number
String

Signed Unsigned
Empty
Not empty
(-) (+) Or
Zero-length
“ISU”
“Joe”
“”
1 -60 “I love CCSICT”
Both 2 -98.2
5.0 -8
Available Datatypes in C#
Type Represents Range Default Value

1. bool Boolean value True or False False


2. byte 8-bit unsigned integer 0 to 255 0
3. char 16-bit Unicode character U +0000 to U +ffff '\0'
4. decimal 128-bit precise decimal values (-7.9 x 1028 to 7.9 x 1028) / 100 to 0.0M
with 28-29 significant digits 28

5. double 64-bit double-precision floating (+/-)5.0 x 10-324 to (+/-)1.7 x 10308 0.0D


point type
6. float 32-bit single-precision floating -3.4 x 1038 to + 3.4 x 1038 0.0F
point type
7. int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0
8. long 64-bit signed integer type -923,372,036,854,775,808 to 0L
9,223,372,036,854,775,807

9. sbyte 8-bit signed integer type -128 to 127 0


10. short 16-bit signed integer type -32,768 to 32,767 0
11. uint 32-bit unsigned integer type 0 to 4,294,967,295 0
12. ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615 0

13. ushort 16-bit unsigned integer type 0 to 65,535 0


Analogy
An operator is a
C# Operators symbol that tells
the compiler to
perform specific
mathematical or
logical
• Arithmetic Operators manipulations.
• Relational Operators
• Logical Operators
• Assignment Operators
Arithmetic Operators
Operator Description Example

+ Adds two operands A + B will give 30


- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200


Let
/ Divides numerator by de-numerator B / A will give 2
A = 10
% Modulus Operator and remainder of after an integer B % A will give 0
division B = 20

++ Increment operator increases integer value by one A++ will give 11

-- Decrement operator decreases integer value by one A-- will give 9


Relational Operators
Operator Description Example

== Checks if the values of two operands are equal or not, if (A == B) is not true.
yes then condition becomes true.
!= Checks if the values of two operands are equal or not, if (A != B) is true. Let
values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the (A > B) is not true. A = 10
value of right operand, if yes then condition becomes
true. B = 20
< Checks if the value of left operand is less than the value (A < B) is true.
of right operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or (A >= B) is not true.
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 (A <= B) is true.
to the value of right operand, if yes then condition
becomes true.
Logical Operators

Operator Description Example


Let
&& Called Logical AND operator. If both the (A && B) is false.
operands are non zero then condition A = true
becomes true.
|| Called Logical OR Operator. If any of the two (A || B) is true. B = false
operands is non zero then condition becomes
true.
! Called Logical NOT Operator. Use to reverses !(A && B) is true.
the logical state of its operand. If a condition
is true then Logical NOT operator will make
false.
Assignment Operators
Operator Description Example

= Simple assignment operator, Assigns values from right side operands to C = A + B will assign value of A + B into
left side operand C
+= Add AND assignment operator, It adds right operand to the left C += A is equivalent to C = C + A
operand and assign the result to left operand
-= Subtract AND assignment operator, It subtracts right operand from the C -= A is equivalent to C = C - A
left operand and assign the result to left operand
*= Multiply AND assignment operator, It multiplies right operand with the C *= A is equivalent to C = C * A
left operand and assign the result to left operand
/= Divide AND assignment operator, It divides left operand with the right C /= A is equivalent to C = C / A
operand and assign the result to left operand
%= Modulus AND assignment operator, It takes modulus using two C %= A is equivalent to C = C % A
operands and assign the result to left operand
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
Sample Problem #16

Create a C# program that would get and display the sum of two
integer numbers given by the user.
Solution to Problem #16
using System;
class my_app
{
static void Main(string[] args)
{
string Num1 = "";
string Num2 = "";
int Sum = 0;

Console.WriteLine("Enter the first number: ");


Num1 = Console.ReadLine();

Console.WriteLine("Enter the second number: ");


Num2 = Console.ReadLine();

Sum = int.Parse(Num1) + int.Parse(Num2);

Console.WriteLine("The sum of " + Num1 + " and " + Num2 + " is: " + Sum);
Console.ReadKey();

}
}
Sample Problem #17

Create a C# program that would get and display the quotient of two
numbers given by the user.
Solution to Problem #17
using System;
class my_app
{
static void Main(string[] args)
{
string Num1 = "";
string Num2 = "";
double Quotient = 0;

Console.WriteLine("Enter the first number: ");


Num1 = Console.ReadLine();

Console.WriteLine("Enter the second number: ");


Num2 = Console.ReadLine();

Quotient = double.Parse(Num1) / double.Parse(Num2);

Console.WriteLine("The quotient of " + Num1 + " and " + Num2 + " is: " + Quotient.ToString ("N2"));

Console.ReadKey();

}
}
“Have I not commanded you?be strong and
courageous. Do not be discouraged, for the Lord
your God will be with you wherever you go.”

Joshua 1:9
CHAPTER 3

Conditional Statements
When do we use conditional statements

• Decisions
• Evaluate a value
C# Conditional Statements

• if statement
• if…else statement
• else if statement
• switch statement
if statement

Syntax:

if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
Sample Problem #18

Create a C# program that would display “UNDER-AGE” if the age


entered is below 18.
Solution to Problem #18
using System;
class my_app
{
static void Main(string[] args)
{
string Age = "";

Console.WriteLine("Enter your age: ");


Age = Console.ReadLine();

if( int.Parse(Age) < 18 )


{
Console.WriteLine(“UNDER-AGE");
}

Console.ReadKey();

}
}
if…else statement

Syntax:

if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
Sample Problem #19

Create a C# program that would display “UNDER-AGE” if the age


entered is below 18, otherwise “OVER-AGE” if age above 18.
Solution to Problem #19
using System;
class my_app
{
static void Main(string[] args)
{
string Age = "";

Console.WriteLine("Enter your age: ");


Age = Console.ReadLine();

if( int.Parse(Age) < 18 )


{
Console.WriteLine(“UNDER-AGE");
}
else
{
Console.WriteLine(“OVER-AGE");
}

Console.ReadKey();

}
}
Nested if……

• It is used to evaluate multiple conditions


Sample Problem #20

Create a C# program that would display “UNDER-AGE” if the age


entered is below 18, if age is equal to 18 display “EXACT-AGE”,
otherwise “OVER-AGE” if age above 18.
Solution to Problem #20
using System;
class my_app
{
static void Main(string[] args)
{
string Age = "";

Console.WriteLine("Enter your age: ");


Age = Console.ReadLine();

if( int.Parse(Age) < 18 )


{
Console.WriteLine(“UNDER-AGE");
}
else if( int.Parse(Age) == 18 )
{
Console.WriteLine(“EXACT-AGE");
}
else
{
Console.WriteLine(“OVER-AGE");
}

Console.ReadKey();

}
}
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 form of a
loop statement in most of the
programming languages
Loop Types and Description
while Loop It repeats a statement or a group of statements while a given
condition is true. It tests the condition before executing the loop
body.
For loop It executes a sequence of statements multiple times and abbreviates
the code that manages the loop variable.
Do…while loop It is similar to a while statement, except that it tests the condition at
the end of the loop body
Nested loops You can use one or more loop inside any another while, for or
do..while loop.
C# - While Loop

• A while loop statement in C# repeatedly


executes a target statement as long as a
given condition is true.
• 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.
C# - For 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.
• 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.
C# - 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.
• 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.
C# - Nested Loop

• C# allows to use one loop inside another loop. Following section


shows few examples to illustrate the concept.

You might also like