07 Iterations and Decisions PDF
07 Iterations and Decisions PDF
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
foreach loop
while loop
do/while loop
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 will walk the container in a linear (n+1) fashion.
The data type before the in keyword represents the type of data in
the container.
6 Object Oriented Programming
NB: The item after the in keyword can be a simple array or any
class implementing the IEnumerable interface.
7 Object Oriented Programming
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.
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.
Iteration Constructs
The following two examples are NOT the same:
Decision Constructs
Decision constructs → to control the flow of program execution
Testing a condition for a value not equal to zero will not work in C#:
if (stringData.Length)
{
Console.WriteLine("string is greater than 0 characters.");
}
else
{
Console.WriteLine("string is not greater than 0 characters.");
}
if (stringData.Length > 0)
{
Console.WriteLine("string is greater than 0 characters.");
}
else
{
Console.WriteLine("string is not greater than 0 characters.");
}
Logical Operators
To build complex expressions, C# offers a set of logical operators:
Output:
1 [C#], 2 [VB]
Please pick your language preference: 3
Well...good luck with that!
19 Object Oriented Programming
Output:
C# or VB
Please pick your language preference: Java
Well...good luck with that!
20 Object Oriented Programming
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
References
Iteration statements, https://learn.microsoft.com/en-
us/dotnet/csharp/language-reference/statements/iteration-
statements