Docsity

C# Control Structures: Selection and Repetition, Slides of C programming

Toggle sidebar
bg1
1
CS 112 Introduction to
Programming
Lecture #8:
Simple Control Structures
http://flint.cs.yale.edu/cs112/
2
Sequential Programming Revisited
1 // Addition.cs
2 // An addition program.
3
4 usingSystem;
5
6classAddition
7 {
8 staticvoid Main( string[] args )
9 {
10 stringfirstNumber, // first string entered by user
11 secondNumber; // second string entered by user
12
13 intnumber1, // first number to add
14 number2, // second number to add
15 sum; // sum of number1 and number2
16
17 // prompt for and read first number from user as string
18 Console.Write( "Please enter the first integer: ");
19 firstNumber= Console.ReadLine();
20
21 // read second number from user as string
22 Console.Write( "\nPleaseenter the second integer: " );
23 secondNumber= Console.ReadLine();
24
25 // convert numbers from type string to type int
26 number1 = Int32.Parse( firstNumber);
27 number2 = Int32.Parse( secondNumber);
28
29 // add numbers
30 sum = number1 + number2;
31
32 // display results
33 Console.WriteLine( "\nThesum is {0}.", sum );
34
35 } // end method Main
36
37 }// end class Addition
17 // prompt for and read first number from user as string
18 Console.Write( "Please enter the first integer: " );
19 firstNumber = Console.ReadLine();
20
21 // read second number from user as string
22 Console.Write( "\nPlease enter the second integer: " );
23 secondNumber= Console.ReadLine();
24
25 // convert numbers from type string to type int
26 number1 = Int32.Parse( firstNumber );
27 number2 = Int32.Parse( secondNumber );
28
29 // add numbers
30 sum = number1 + number2;
31
32 // display results
33 Console.WriteLine( "\nThe sum is {0}.", sum );
3
Sequence Structure (Flowchart)
.
.
Each of these statements could be:
•a variable declaration
•an assignment statement
•a method call (e.g., Console.WriteLine( …); )
or more complex statements (to be covered later)
4
More Interesting: Control Statements
rSelection (a.k.a., conditional statements): decide whether or not to
execute a particular statement; these are also called the selection
statements or decision statements
•if selection (one choice)
•if/else selection (two choices)
–Also: the ternary conditional operator e1?e2:e3
•switch statement (multiple choices)
rRepetition (a.k.a., loop statements): repeatedly executing the same
statements (for a certain number of times or until a test condition is
satisfied).
•while structure
•do/while structure
•for structure
•foreach structure (Chapter 12)
5
Why Control Statements ?
rLast few classes: a sequence of
statements
mSequential programming
rMost programs need more flexibility in the
order of statement execution
rThe order of statement execution is called the
flow of control
6
Pseudocode & Flowcharts to
Represent Flow of Control
rPseudocode
mArtificial and informal language
mHelps programmers to plan an algorithm
mSimilar to everyday English
mNot an actual programming language
rFlowchart --- a graphical way of writing
pseudocode
mRectangle used to show action
mCircles used as connectors
mDiamonds used as decisions
pf3
pf4
pf5

Partial preview of the text

Download C# Control Structures: Selection and Repetition and more Slides C programming in PDF only on Docsity!

CS 112 Introduction to

Programming

Lecture #8:

Simple Control Structures

http://flint.cs.yale.edu/cs112/

Sequential Programming Revisited

1 // Addition.cs 2 // An addition program. 3 4 using System; 5 6 class Addition 7 { 8 static void Main( string[] args ) 9 { 10 string firstNumber, // first string entered by user 11 secondNumber; // second string entered by user 12 13 int number1, // first number to add 14 number2, // second number to add 15 sum; // sum of number1 and number 16 17 // prompt for and read first number from user as string 18 Console.Write( "Please enter the first integer: " ); 19 firstNumber = Console.ReadLine(); 20 21 // read second number from user as string 22 Console.Write( "\nPlease enter the second integer: " ); 23 secondNumber = Console.ReadLine(); 24 25 // convert numbers from type string to type int 26 number1 = Int32.Parse( firstNumber ); 27 number2 = Int32.Parse( secondNumber ); 28 29 // add numbers 30 sum = number1 + number2; 31 32 // display results 33 Console.WriteLine( "\nThe sum is {0}.", sum ); 34 35 } // end method Main 36 37 } // end class Addition

17 // prompt for and read first number from user as string

18 Console.Write( "Please enter the first integer: " );

19 firstNumber = Console.ReadLine();

21 // read second number from user as string

22 Console.Write( "\nPlease enter the second integer: " );

23 secondNumber = Console.ReadLine();

25 // convert numbers from type string to type int

26 number1 = Int32.Parse( firstNumber );

27 number2 = Int32.Parse( secondNumber );

29 // add numbers

30 sum = number1 + number2;

32 // display results

33 Console.WriteLine( "\nThe sum is {0}.", sum );

Sequence Structure (Flowchart)

. .

Each of these statements could be:

  • a variable declaration
  • an assignment statement
  • a method call (e.g., Console.WriteLine( …); )

or more complex statements (to be covered later)

More Interesting: Control Statements

r Selection (a.k.a., conditional statements): decide whether or not to

execute a particular statement; these are also called the selection

statements or decision statements

• if selection (one choice)

• if/else selection (two choices)

– Also: the ternary conditional operator e

?e 2 :e 3

• switch statement (multiple choices)

r Repetition (a.k.a., loop statements): repeatedly executing the same

statements (for a certain number of times or until a test condition is

satisfied).

• while structure

• do/while structure

• for structure

• foreach structure (Chapter 12)

Why Control Statements?

r Last few classes: a sequence of

statements

m Sequential programming

r Most programs need more flexibility in the

order of statement execution

r The order of statement execution is called the

flow of control

Pseudocode & Flowcharts to

Represent Flow of Control

r Pseudocode

m Artificial and informal language

m Helps programmers to plan an algorithm

m Similar to everyday English

m Not an actual programming language

r Flowchart --- a graphical way of writing

pseudocode

m Rectangle used to show action

m Circles used as connectors

m Diamonds used as decisions

Sequence Structure

add grade to total

add 1 to counter

total = total + grade;

counter = counter + 1;

C# Control Structures: Selection

T

F

if structure (single selection)

if/else structure (double selection) F T

switch structure (multiple selections)

.

.

break

break

break

break

T

T

T

F

F

F

.

C# Control Structures: Repetition

T

F

while structure

T

F

do/while structure F

T

for structure/foreach structure

if Statement

if ( )

< code executed if is true > ;

r The if statement

m Causes the program to make a selection

m Chooses based on conditional

• : any expression that evaluates to a bool type

• True : perform an action

• False : skip the action

m Single entry/exit point

m No semicolon after the condition

if Statement (cont’d)

if ( )

< code executed if is true > ;

< more code executed if is true > ;

m The body of the branch can also be a block

statement!

m No semicolon after the condition

m No semicolon after the block statement

if Statement (cont’d)

Grade >= 60 print ā€œPassedā€

true

false

if (studentGrade >= 60)

Console.WriteLine (ā€œPassedā€);

// beginning of the next statement

Unbalanced if-else Statements

Rule: An else clause is matched to the last unmatched if

(no matter what the indentation implies)

if (favorite == ā€œappleā€)

if (price <= 10 )

Console.WriteLine(ā€œ10ā€);

else

Console.WriteLine(ā€œ1ā€);

if (favorite == ā€œappleā€)

if (price <= 10 )

Console.WriteLine(ā€œ10ā€);

else

Console.WriteLine(ā€œnot my favoriteā€);

See IfElseMatch.cs

Ternary Conditional Operator (?:)

r Conditional Operator ( e

?e

:e

m C#’s only ternary operator

m Can be used to construct expressions

m Similar to an if/else structure

string result;

int numQ;

…………

result = (numQ==1)? ā€œQuarterā€ : ā€œQuartersā€;

// beginning of the next statement

while Statement

r The while statement has the following

syntax:

while ( condition )

statement ;

whilewhile is ais a

reserved wordreserved word

If the condition is true, the statement is executed.If the condition is true, the statement is executed.

Then the condition is evaluated again.Then the condition is evaluated again.

The statement (or a block of statements) is executedThe statement (or a block of statements) is executed

repetitively until the condition becomes false.repetitively until the condition becomes false.

while Statement

while ( )

< code to be repeated if is true > ;

r Repetition Structure

m An action is to be repeated

• Continues while is true

• Ends when is false

m Contains either a line or a body of code

while Statement (cont’d)

true

false

Product <= 1000 Product = 2 * product

int product;

product = 2;

while (product <= 1000)

product = 2 * product;

// beginning of the next statement

while Statement (cont’d)

true

false

Product <= 1000 Product = 2 * product

int product;

product = 2;

while (product <= 1000)

{

product = 2 * product;

}

// beginning of the next statement

while Statement

r Note that if the condition of a while statement

is false initially, the statement is never

executed

r Therefore, the body of a while loop will

execute zero or more times

Infinite Loops

r The body of a while loop must eventually make the

condition false

r If not, it is an infinite loop , which will execute until the

user interrupts the program

r See Forever.cs

r This is a common type of logical error

r You should always double check to ensure that your

loops will terminate normally

Recap: Loop Statements

r Loop statements allow us to execute a

statement multiple times

r They are often simply referred to as loops

r Like conditional statements, they are

controlled by boolean expressions

r C# has four kinds of loop statements: the

while loop , the do loop , the for loop, and the

foreach loop

r The programmer must choose the right kind

of loop for the situation

Example 1: Counter Controlled While Loop

r Control variable

• The variable used as a counter to determine whether or

not the loop should continue

r Three components

• Initial value of the counter

• Check whether or not the counter has reached target

– When the looping should continue

• Incrementing/decrementing of the counter

Outline

WhileCounter.cs

Program Output

1 // WhileCounter.cs 2 // Counter-controlled repetition. 3 4 using System; 5 6 class WhileCounter 7 { 8 static void Main( string[] args ) 9 { 10 int counter = 1; // initialization 11 12 while ( counter <= 5 ) // repetition condition 13 { 14 Console.WriteLine( counter ); 15 counter++; // increment 16 17 } // end while 18 19 } // end method Main 20 21 } // end class WhileCounter

This is where the counter variable is initialized. It is set to 1.

The loop will continue until counter is greater than five (it will stop once it gets to six)

The counter is incremented and 1 is added to it

Computing Class Average

Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.

Set total to zero

Set counter to one

While counter is less than or equal to ten

Input the next grade

Add the grade into the total

Add one to counter

Set the class average to the total divided by ten

Print the class average

Problem: Get 10 grades from the user and compute the average.

Outline

Average2.cs Program Output

Enter Integer Grade, -1 to Quit: 97 Enter Integer Grade, -1 to Quit: 88 Enter Integer Grade, -1 to Quit: 72 Enter Integer Grade, -1 to Quit: -

Class average is 85.

Loop-and-a-Half Idiom

Initialize total to zero

Initialize counter to zero

While (true)

Input the first grade (possibly the sentinel)

If ( the user has entered the sentinel)

break;

Add this grade into the running total

Add one to the grade counter

If the counter is not equal to zero

Set the average to the total divided by the counter

Print the average

Else

Print ā€œNo grades were enteredā€

Example 3: Program Condition

r Continuously change the value of a variable

until some conditions are met.

r Example: ReverseNumber.cs