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

07 Iterations and Decisions PDF

Uploaded by

zeuces37
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

07 Iterations and Decisions PDF

Uploaded by

zeuces37
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

CPP225

Object Oriented
Programming I

Iterations
and
Decisions

Öğr. Gör.
İhsan Can İÇİUYAN
2 Object Oriented Programming

Contents
 Iteration Constructs
 The for Loop
 The foreach Loop
 The while Loop
 The do/while Loop

 Decision Constructs
 Equality and Relational Operators
 The if/else Statement
 The Conditional Operator
 Logical Operators
 The switch Statement
3 Object Oriented Programming

Iteration Constructs
 Iteration constructs → to repeat blocks of code until a terminating
condition has been met

 C# provides four iteration constructs:


 for loop

 foreach loop

 while loop

 do/while loop

 Iteration Statements, Microsoft Learn: Link


4 Object Oriented Programming

The for Loop


 for → to iterate over a block of code a fixed number of times

 Consider the following example:

for (int i = 0; i < 4; i++)


{
Console.WriteLine("Number is: {0} ", i);
}

 Note that i is only visible within the scope of the for loop.

 You can
 create complex terminating conditions,
 build endless loops,
 loop in reverse (via the -- operator),
 use the goto, continue and break jump keywords.
5 Object Oriented Programming

The foreach Loop


 foreach → to iterate over all items in a container without the need
to test for an upper limit

 The foreach loop will walk the container in a linear (n+1) fashion.

 You cannot go backward through the container, skip every third


element, etc.

 Perfect choice when you need to walk a collection item by item.

 The data type before the in keyword represents the type of data in
the container.
6 Object Oriented Programming

The foreach Loop


 Consider the following example:

string[] carTypes = { "Ford", "BMW", "Renault", "Honda" };


foreach (string c in carTypes)
{
Console.WriteLine(c);
}

int[] myInts = { 10, 20, 30, 40 };


foreach (int i in myInts)
{
Console.WriteLine(i);
}

 NB: The item after the in keyword can be a simple array or any
class implementing the IEnumerable interface.
7 Object Oriented Programming

The while Loop


 while → to execute a block of statements until some terminating
condition has been reached

 Within the scope of a while loop, you will need to ensure this
terminating event is established; otherwise, you will be stuck in an
endless loop.

 Consider the following example:


string userIsDone = "";

while (userIsDone.ToLower() != "yes")


{
Console.WriteLine("In while loop");
Console.Write("Are you done? [yes] [no]: ");
userIsDone = Console.ReadLine();
}
8 Object Oriented Programming

The do/while Loop


 do/while → to perform some action an undetermined number of
times

 Guaranteed to execute the corresponding block of code at least


once.

 Consider the following example:

string userIsDone = "";

do
{
Console.WriteLine("In do/while loop");
Console.Write("Are you done? [yes] [no]: ");
userIsDone = Console.ReadLine();
} while (userIsDone.ToLower() != "yes");
9 Object Oriented Programming

Iteration Constructs
 A scope is created using curly braces.

 The iteration and decision constructs also operate in a scope.

 Consider the following example:


for (int i = 0; i < 4; i++)
{
Console.WriteLine("Number is: {0} ", i);
}

 For these constructs, it is permissible to not use curly braces.

 The following code is exactly the same as the previous example:


for (int i = 0; i < 4; i++)
Console.WriteLine("Number is: {0} ", i);
10 Object Oriented Programming

Iteration Constructs
 The following two examples are NOT the same:

for (int i = 0; i < 4; i++)


{
Console.WriteLine("Number is: {0} ", i);
Console.WriteLine("Number plus 1 is: {0} ", i + 1);
}

for (int i = 0; i < 4; i++)


Console.WriteLine("Number is: {0} ", i);
Console.WriteLine("Number plus 1 is: {0} ", i + 1);

 The additional line of code generates a compilation error, since the


variable i is only defined in the scope of the for loop.
11 Object Oriented Programming

Decision Constructs
 Decision constructs → to control the flow of program execution

 C# provides two decision constructs:


 The if/else statement

 The switch statement

 Selection Statements, Microsoft Learn: Link


12 Object Oriented Programming

Equality and Relational Operators


 The if/else statements typically involve the use of the operators
shown in the following table:
13 Object Oriented Programming

The if/else Statement


 The if/else statement in C# operates only on Boolean expressions,
not on values such as 1 or 0.

 Testing a condition for a value not equal to zero will not work in C#:

string stringData = "My textual data";

if (stringData.Length)
{
Console.WriteLine("string is greater than 0 characters.");
}
else
{
Console.WriteLine("string is not greater than 0 characters.");
}

 This is illegal, given that Length returns an int, not a bool.


14 Object Oriented Programming

The if/else Statement


 You need to modify the conditional expression to resolve to a
Boolean:

string stringData = "My textual data";

if (stringData.Length > 0)
{
Console.WriteLine("string is greater than 0 characters.");
}
else
{
Console.WriteLine("string is not greater than 0 characters.");
}

 This is legal, as this resolves to either true or false.


15 Object Oriented Programming

The Conditional Operator


 Conditional operator (? :) → a shorthand method of writing a
simple if-else statement

 Also known as the Ternary Conditional Operator.

 The syntax works like this:

condition ? first_expression : second_expression;

 The condition is the conditional test.

 If the test evaluates to


 true → the code after the question mark (?) is executed
 false → the code after the colon (:) is executed
16 Object Oriented Programming

The Conditional Operator


 Consider the following example:
string stringData = "My textual data";
Console.WriteLine(stringData.Length > 0
? "string is greater than 0 characters."
: "string is not greater than 0 characters.");

 There are some restrictions to the conditional operator:


 Both types of first_expression and second_expression must
have implicit conversions from one to another.
 The conditional operator can be used only in assignment
statements.

 The following code will result in a compiler error:


stringData.Length > 0
? Console.WriteLine("string is greater than 0 characters.")
: Console.WriteLine("string is not greater than 0 characters.");
17 Object Oriented Programming

Logical Operators
 To build complex expressions, C# offers a set of logical operators:

 Consider the following example:


bool t = true;
bool f = false;
Console.WriteLine($"{t.ToString()} && {t.ToString()} = {t && t}"); //true
Console.WriteLine($"{t.ToString()} && {f.ToString()} = {t && f}"); //false
Console.WriteLine($"{t.ToString()} || {t.ToString()} = {t || t}"); //true
Console.WriteLine($"{t.ToString()} || {f.ToString()} = {t || f}"); //true
Console.WriteLine($"{f.ToString()} || {f.ToString()} = {f || f}"); //false
Console.WriteLine($"!{t.ToString()} = {!t}"); //false
Console.WriteLine($"!{f.ToString()} = {!f}"); //true
18 Object Oriented Programming

The switch Statement


 switch → to handle program flow based on a predefined set of
choices

 EX: A program to print a specific string message based on one of


two possible selections.
 Code: 46_Switch.cs
Output:
1 [C#], 2 [VB]
Please pick your language preference: 1
Good choice, C# is a fine language.

Output:
1 [C#], 2 [VB]
Please pick your language preference: 3
Well...good luck with that!
19 Object Oriented Programming

The switch Statement


 You can evaluate char, string, bool, int, long, and enum data
types.

 EX: A program to print a specific string message based on one of


two possible selections.
 Code: 47_SwitchOnString.cs
Output:
C# or VB
Please pick your language preference: C#
Good choice, C# is a fine language.

Output:
C# or VB
Please pick your language preference: Java
Well...good luck with that!
20 Object Oriented Programming

The switch Statement


 It is also possible to switch on an enumeration data type.

 EX: A program to perform a switch test on the System.DayOfWeek


enum.
 Code: 48_SwitchOnEnum.cs

Output:
Enter your favorite day of the week: Tuesday
At least it is not Monday.

Output:
Enter your favorite day of the week: Saturday
Great day indeed.
21 Object Oriented Programming

The switch Statement


 Falling through from one case statement to another case statement
is not allowed.

 Multiple case statements can be combined, as the following code


demonstrates:
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
Console.WriteLine("It’s the weekend!");
break;

 If any code was included between the case statements, the


compiler would throw an error.

C# demands that each case (including default) that contains


executable statements have a terminating return, break, or goto
to avoid falling through to the next case.
22 Object Oriented Programming

The switch Statement


 The switch statement also supports using a goto to exit a case
condition and execute another case statement:
var foo = 3;
switch (foo)
{
case 1:
//do something
goto case 2;
case 2:
//do something else
break;
case 3:
//yet another action
goto default;
default:
//default action
break;
}
23 Object Oriented Programming

References
 Iteration statements, https://learn.microsoft.com/en-
us/dotnet/csharp/language-reference/statements/iteration-
statements

 Selection statements, https://learn.microsoft.com/en-


us/dotnet/csharp/language-reference/statements/selection-
statements

 Jump statements, https://learn.microsoft.com/en-


us/dotnet/csharp/language-reference/statements/jump-
statements
24 Object Oriented Programming

That’s all for


today!

You might also like