Statements: Part Pearson Education, Inc. All rights reserved.

Size: px
Start display at page:

Download "Statements: Part Pearson Education, Inc. All rights reserved."

Transcription

1 1 6 Control Statements: Part 2

2 2 Who can control his fate? William Shakespeare, Othello The used key is always bright. Benjamin Franklin Not everything that can be counted counts, and not every thing that counts can be counted. Albert Einstein Every advantage in the past is judged in the light of the final issue. Demosthenes

3 3 OBJECTIVES In this chapter you will learn: The essentials of counter-controlled controlled repetition. To use the For Next, Do Loop While and Do Loop Until repetition statements to execute statements in a program repeatedly. To perform multiple selection using the Select Case selection statement.

4 4 OBJECTIVES To use the Exit statement to break out of a repetition statement. To use the Continue statement to break out of the current iteration of a repetition statement. To use logical operators to form more complex conditions.

5 5 6.1 Introduction 6.2 Essentials of Counter-Controlled Repetition 6.3 For Next Repetition Statement 6.4 Examples Using the For Next Statement 6.5 GradeBook Case Study: Select Case Multiple-Selection Statement Do Loop While Repetition i Statement 6.7 Do Loop Until Repetition Statement 6.8 Using Exit in Repetition Statements 6.9 Using Continue in Repetition Statements 6.10 Logical Operators 6.11 (Optional) Software Engineering Case Study: Identifying Objects States and Activities in the ATM System

6 6.2 Essentials of Counter-Controlled Repetition 6 Counter-controlled repetition requires the name of the control variable the initial value the increment (or decrement)value the condition that tests for the final value

7 Outline 7 The example in Fig. 6.1 uses counter-controlledcontrolled repetition to display the even integers in the range WhileCounter.vb 1 ' Fig. 6.1: WhileCounter.vb 2 ' Using the While statement to demonstrate counter-controlled repetition. 3 Module WhileCounter 4 Sub Main() 5 Dim counter As Integer = 2 ' name and initialize loop counter 6 7 While counter <= 10 ' test final value of loop counter 8 Console.Write("{0} ", counter) 9 counter += 2 ' increment counter 10 End While Console.WriteLine() 13 End Sub ' Main 14 End Module ' WhileCounter Initializing counter before the loop Fig. 6.1 Counter-controlled repetition with the While End While statement Pearson Education, Inc. All rights reserved.

8 In this For...Next statement, counter (Fig. 6.2) is used to print even numbers from 2 to ' Fig. 6.2: ForCounter.vb 2 ' Using the For...Next statement for counter-controlled repetition. 3 Module ForCounter 4 Sub Main() 5 ' initialization, repetition condition and 6 ' incrementing are all included in For...Next statement 7 For counter As Integer = 2 To 10 Step 2 8 Console.Write("{0} ", counter) 9 Next Console.WriteLine() 12 End Sub ' Main 13 End Module ' ForCounter Outline ForCounter.vb ( 1 of 2 ) 8 Fig. 6.2 Counter-controlled repetition with the For Next statement. Good Programming Practice 6.1 Place a blank line before and after each control statement to make it stand out in the program Pearson Education, Inc. All rights reserved.

9 Good Programming Practice 6.2 Vertical spacing above and below control statements, as well as indentation of the bodies of control statements, gives programs a two-dimensional appearance that enhances readability. Error-Prevention Tip 6.1 Use a For...Next loop for counter-controlled repetition. Off-by-one errors (which occur when a loop is executed for one more or one less iteration i than is necessary) tend to disappear, because the terminating value is clear. Outline ForCounter.vb ( 2 of 2 ) Pearson Education, Inc. All rights reserved.

10 6.3 For Next Repetition Statement (Cont.) 10 The first line of the For Next statement sometimes is called the For Next header (Fig. 63) 6.3). Fig. 6.3 For...Next header components.

11 6.3 For Next Repetition Statement (Cont.) The general form of the For Next statement is For initializationi i i To finalvalue l Step increment statement Next A For Next statement can be represented by an equivalent While statement: initialization While variable <= finalvalue statement increment End While 11

12 6.3 For Next Repetition Statement (Cont.) The counter variable may be declared before the For Next statement: Dim counter As Integer For counter = 2 To 10 Step 2 Console.Write("{0} ", counter) Next Values of a For Next statement header may contain arithmetic expressions (evaluated at start). If the loop-continuation condition is initially false, the For Next s body is not performed. 12

13 6.3 For Next Repetition Statement (Cont.) 13 Common Programming Error 6.1 Counter-controlled loops should not be controlled with floating-point i variables. Floating-point i values are represented only approximately in the computer s memory; this can lead to imprecise counter values and inaccurate tests for termination.

14 6.3 For Next Repetition Statement (Cont.) 14 Error-Prevention Tip 6.2 Although the value of the control variable can be changed in the body of a For Next loop, avoid doing so, because this practice can lead to subtle errors. Common Programming Error 6.2 In nested For Next loops, the use of the same control-variable name in more than one loop is a compilation error.

15 6.3 For Next Repetition Statement (Cont.) 15 For counter As Integer = 1 To 10 Step 2 The activity diagram for a For Next statement (Fig. 6.4) is similar to a While statement. Fig. 6.4 For...Next repetition statement activity diagram.

16 6.3 For Next Repetition Statement (Cont.) 16 Local type inference infers a local variable s type based on the context of initialization. Dim x = 7 The compiler infers type Integer. Dim y = The compiler infers type Double.

17 6.3 For Next Repetition Statement (Cont.) 17 For counter As Integer = 1 To 10 The preceding For Next header can now be written as: For counter = 1 To 10 In this case, counter is of type Integer because it is initialized iti with a whole number (1). Local type inference can be used on any variable that is initialized in its declaration.

18 The program in Fig. 6.5 uses a For...Next statement to sum the even integers from 2 to 100. Remember to add a reference to System.Windows.Forms.dll. 1 ' Fig. 6.5: Sum.vb 2 ' Using For...Next statement to demonstrate summation. 3 Imports System.Windows.Forms 4 5 Module Sum 6 Sub Main() 7 Dim sum As Integer = ' add even numbers from 2 to For number = 2 To 100 Step 2 11 sum += number 12 Next MessageBox.Show("The sum is " & sum, _ 15 "Sum even integers from 2 to 100", _ 16 MessageBoxButtons.OK, MessageBoxIcon.Information) 17 End Sub ' Main 18 End Module ' Sum Outline Sum.vb ( 1 of 2 ) Method MessageBox.Show can take four arguments. 18 Fig. 6.5 For Next statement used for summation. (Part 1 of 2.) 2009 Pearson Education, Inc. All rights reserved.

19 Outline 19 Sum.vb ( 2 of 2 ) Title bar text MessageBoxIcon.Information Message text MessageBoxButtons.OK Fig. 6.5 For Next statement used for summation. (Part 2 of 2.) 2009 Pearson Education, Inc. All rights reserved.

20 6.4 Examples Using the For Next Statement (Cont.) 20 Method MessageBox.Show can take four arguments. The first two arguments are the text and title bar. The third argument indicates which button(s) to display. The fourth argument indicates which h icon appears.

21 6.4 Examples Using the For Next Statement (Cont.) 21 MessageBoxIcon constants Icon Description MessageBoxIcon.Warning or MessageBoxIcon.Exclamation Used to caution the user against potential problems. MessageBoxIcon.Information Used to display information about the state of the application. MessageBoxIcon.None No icon is displayed. MessageBoxIcon.Error Used to alert the user to errors or critical situations. Fig. 6.6 Message dialog icon constants.

22 6.4 Examples Using the For Next Statement (Cont.) 22 MessageBoxButton constants Description MessageBoxButtons.OK s OK button. Allows the user to acknowledge a message. Included by default. MessageBoxButtons.OKCancel MessageBoxButtons.YesNo OK and Cancel buttons. Allow the user to either continue or cancel an operation. Yes and No buttons. Allow the user to respond to a question. Fig. 6.7 Message dialog button constants. (Part 1 of 2.)

23 6.4 Examples Using the For Next Statement (Cont.) 23 MessageBoxButton constants MessageBoxButtons.YesNoCancel MessageBoxButtons.RetryCancel MessageBoxButtons.AbortRetryIgnore Description Yes, No and Cancel buttons. Allow the user to respond to a question or cancel an operation. Retry and Cancel buttons. Allow the user to retry or cancel an operation that has failed. Abort, Retry and Ignore buttons. When one of a series of operations has failed, these buttons allow the user to abort the entire sequence, retry the failed operation or ignore the failed operation and continue. Fig. 6.7 Message dialog button constants. (Part 2 of 2.)

24 6.4 Examples Using the For Next Statement (Cont.) 24 Consider the following problem statement: A person invests $ in a savings account that yields 5% interest. Calculate the amount of money in the account at the end of each year over a period of 10 years. Use the following formula: a=p(1+r) n

25 1 ' Fig. 6.8: Interest.vb 2 ' Calculating compound interest. 3 Imports System.Windows.Forms 4 5 Module Interest 6 Sub Main() 7 Dim amount As Decimal ' dollar amounts on deposit 8 Dim principal As Decimal = ' amount invested 9 Dim rate As Double = 0.05 ' interest rate ' amount after each year 12 Dim output As String = _ 13 "Year" & vbtab & "Amount on deposit" & vbnewline e ' calculate amount after each year 16 For yearvalue = 1 To amount = principal * (1 + rate) ^ yearvalue 18 output &= yearvalue & vbtab & String.Format( Format("{0:C}", amount) _ 19 & vbnewline 20 Next ' display output 23 MessageBox.Show(output, "Compound Interest", _ 24 MessageBoxButtons.OK, MessageBoxIcon.Information) 25 End Sub ' Main 26 End Module ' Interest Outline Interest.vb ( 1 of 3 ) amount and principal are declared as type Decimal Calculating interest for each year String.Format formats text as directed 25 Fig. 6.8 For Next statement used to calculate compound interest. (Part 1 of 2.) 2009 Pearson Education, Inc. All rights reserved.

26 Outline 26 Interest.vb ( 2 of 3 ) Fig. 6.8 For Next statement used to calculate compound dinterest. t (Part t2 of f2) 2.) 2009 Pearson Education, Inc. All rights reserved.

27 Outline 27 Error-Prevention e o Tip 6.3 Do not use variables of type Single or Double to perform precise monetary calculations. The imprecision of ffloating-point i tnumbers can cause errors that tresult ltin incorrect monetary values. Use the type Decimal for monetary calculations. Interest.vb ( 3 of 3 ) Performance Tip 6.1 Avoid placing inside a loop the calculation of an expression whose value does not change each time through the loop. Such an expression should be evaluated only once and prior to the loop Pearson Education, Inc. All rights reserved.

28 The GradeBook class now uses the Select...Case multiple-selection statement (Fig. 69) 6.9). 1 ' Fig. 6.9: GradeBook.vb 2 ' GradeBook class uses Select...Case statement to count letter grades. 3 Public Class GradeBook 4 Private coursenamevalue As String ' name of course 5 Private total As Integer ' sum of grades 6 Private gradecounter As Integer ' number of grades entered 7 Private acount As Integer ' count of A grades 8 Private bcount As Integer ' count of B grades 9 Private ccount As Integer ' count of C grades 10 Private dcount As Integer ' count of D grades 11 Private fcount As Integer ' count of F grades 12 Private perfectscorecount As Integer ' count of perfect scores ' constructor initializes course name; 15 ' Integer instance variables are initialized to 0 by default 16 Public Sub New(ByVal name As String) 17 CourseName = name ' initializes CourseName 18 End Sub ' New 19 Outline GradeBook.vb ( 1 of 6 ) 28 Fig. 6.9 GradeBook class uses Select Case statement to count A, B, C, D and df grades. (Part t1 of f6) 6.) 2009 Pearson Education, Inc. All rights reserved.

29 Outline ' property that gets and sets the course name; the Set accessor 21 ' ensures that the course name has at most 25 characters 22 Public Property CourseName() As String 23 Get ' retrieve coursenamevalue 24 Return coursenamevalue 25 End Get Set(ByVal value As String) ' set coursenamevalue 28 If value.length <= 25 Then ' if value has 25 or fewer characters 29 coursenamevalue = value ' store the course name in the object 30 Else ' if name has more than 25 characters 31 ' set coursenamevalue to first 25 characters of parameter name 32 ' start at 0, length of coursenamevalue = value.substring(0, 25) Console.WriteLine( _ 36 "Course name (" & value & ") exceeds maximum length (25).") 37 Console.WriteLine( _ 38 "Limiting course name to first 25 characters." & vbnewline) 39 End If 40 End Set 41 End Property ' CourseName GradeBook.vb ( 2 of 6 ) Fig. 6.9 GradeBook class uses Select Case statement to count A, B, C, D and F grades. (Part 2 of 6.) 2009 Pearson Education, Inc. All rights reserved.

30 Outline ' display a welcome message to the GradeBook user 44 Public Sub DisplayMessage() 45 Console.WriteLine("Welcome to the grade book for " _ 46 & vbnewline & CourseName & "!" & vbnewline) 47 End Sub ' DisplayMessage ' input arbitrary number of grades from user 50 Public Sub InputGrades() 51 Console.Write( _ 52 "Enter the grades in the range 0-100, negative value to quit: ") 53 Dim grade As Integer = Console.ReadLine() ' input first grade ' loop until user enters a sentinel value 56 While grade >= 0 57 total += grade ' add grade to total 58 gradecounter += 1 ' increment number of grades 59 GradeBook.vb ( 3 of 6 ) Fig. 6.9 GradeBook class uses Select Case statement to count A, B, C, D and F grades. (Part 3 of 6.) 2009 Pearson Education, Inc. All rights reserved.

31 Outline ' call method to increment appropriate counter 61 IncrementLetterGradeCounter(grade) ' input next grade 64 Console.Write("Enter the grades in the range 0-100, " & _ 65 "negative value to quit: ") 66 grade = Console.ReadLine() 67 End While 68 End Sub ' InputGrades ' add 1 to appropriate counter for specified grade 71 Private Sub IncrementLetterGradeCounter(ByVal grade As Integer) 72 Select Case grade ' determine which grade was entered 73 Case 100 ' perfect score 74 perfectscorecount += 1 ' increment perfectscorecount 75 acount += 1 ' increment acount 76 Case 90 To 99 ' grade was between 90 and acount += 1 ' increment acount GradeBook.vb ( 4 of 6 ) Using a Select...Case statement to determine which counter to increment. Fig. 6.9 GradeBook class uses Select Case statement to count A, B, C, D and F grades. (Part 4 of 6.) 2009 Pearson Education, Inc. All rights reserved.

32 Outline Case 80 To 89 ' grade was between 80 and bcount += 1 ' increment bcount 80 Case 70 To 79 ' grade was between 70 and ccount += 1 ' increment ccount 82 Case 60 To 69 ' grade was between 60 and dcount += 1 ' increment dcount 84 Case Else ' grade was less than fcount += 1 ' increment fcount 86 End Select 87 End Sub ' IncrementLetterGradeCounter ' display a report based on the grades entered by user 90 Public Sub DisplayGradeReport() p 91 Console.WriteLine(vbNewLine & "Grade Report:") ' if user entered at least one grade 94 If (gradecounter > 0) Then 95 ' calculate average of all grades entered 96 Dim average As Double = total / gradecounter GradeBook.vb ( 5 of 6 ) Fig. 6.9 GradeBook class uses Select Case statement to count A, B, C, D and F grades. (Part 5 of 6.) 2009 Pearson Education, Inc. All rights reserved.

33 Outline ' output summary of results 99 Console.WriteLine("Total of the {0} grades entered is {1}", _ 100 gradecounter, total) 101 Console.WriteLine("Class average is {0:F2}", average) 102 Console.WriteLine("Number of students who received each grade:") 103 Console.WriteLine("A: " & acount) ' display number of A grades 104 Console.WriteLine( WriteLine("B: " & bcount) ' display number of B grades 105 Console.WriteLine("C: " & ccount) ' display number of C grades 106 Console.WriteLine("D: " & dcount) ' display number of D grades 107 Console.WriteLine("F: " & fcount) ' display number of F grades 108 Console.WriteLine(vbNewLine & "Number of students who " & _ 109 "received perfect scores: " & perfectscorecount) 110 Else ' no grades were entered, so output appropriate message 111 Console.WriteLine("No grades were entered") 112 End If 113 End Sub ' DisplayGradeReport 114 End Class ' GradeBook GradeBook.vb ( 6 of 6 ) Fig. 6.9 GradeBook class uses Select Case statement to count A, B, C, D and F grades. (Part 6 of 6.) 2009 Pearson Education, Inc. All rights reserved.

34 6.5 GradeBook Case Study: Select Case Multiple-Selection Statement (Cont.) Select Case grade The expression following the keywords Select Case is called the controlling expression. 34 If a matching Case is found for the controlling expression, the code in that Case executes, then program control proceeds to the first statement after the Select Case statement.

35 6.5 GradeBook Case Study: Select Case Multiple-Selection Statement (Cont.) 35 Common Programming Error 6.3 Duplicate Case statements tt t are logic errors. At run time, the first matching Case is executed. Common Programming Error 6.4 If the value on the left side of the To keyword in a Case statement is larger than the value on the right side, the Case is ignored.

36 6.5 GradeBook Case Study: Select Case Multiple-Selection Statement (Cont.) 36 If no match occurs between the controlling expression s s value and a Case label, the optional Case Else executes. Case Else must be the last Case. Case statements can use relational operators. Case Is < 0 Multiple values can be tested in a Case statement: Case 0, 5 To 9 The controlling expression also may be a String or Object.

37 6.5 GradeBook Case Study: Select Case Multiple-Selection Statement (Cont.) 37 Error-Prevention Tip 6.4 Provide a Case Else in Select...Case statements. tt t Cases not handled in a Select...Case statement are ignored unless a Case Else is provided. The inclusion of a Case Else statement can facilitate the processing of exceptional conditions.

38 Module GradeBookTest (Fig. 6.10) outputs a report based on the grades entered. 1 ' Fig. 6.10: GradeBookTest.vb 2 ' Create GradeBook object, input grades and display grade report. 3 Module GradeBookTest 4 Sub Main() 5 ' create GradeBook object gradebook1 and 6 ' pass course name to constructor t 7 Dim gradebook1 As New GradeBook("CS101 Introduction to VB") 8 9 gradebook1.displaymessage() ' display welcome message 10 gradebook1.inputgrades() ' read grades from user 11 gradebook1.displaygradereport() ' display report based on grades 12 End Sub ' Main 13 End Module ' GradeBookTest Outline GradeBookTest.vb ( 1 of 2 ) 38 Fig GradeBookTest creates a GradeBook object and invokes its methods. (Part 1 of 2.) 2009 Pearson Education, Inc. All rights reserved.

39 Outline 39 Welcome to the grade book for CS101 Introduction to VB! Enter a grade in the range 0-100, negative value to quit: 99 Enter a grade in the range 0-100, negative value to quit: 92 Enter a grade in the range 0-100, negative value to quit: 45 Enter a grade in the range 0-100, negative value to quit: 57 Enter a grade in the range 0-100, negative value to quit: 63 Enter a grade in the range 0-100, negative value to quit: 71 Enter a grade in the range 0-100, negative value to quit: 76 Enter a grade in the range 0-100, negative value to quit: 85 Enter a grade in the range 0-100, negative value to quit: 90 Enter a grade in the range 0-100, negative value to quit: 100 Enter a grade in the range 0-100, negative value to quit: -1 GradeBookTest.vb ( 2 of 2 ) Grade Report: Total of the 10 grades entered is 778 Class average is Number of students who received each grade: A: 4 B: 1 C: 2 D: 1 F: 2 Number of students who received a perfect score: 1 Fig GradeBookTest creates a GradeBook object and invokes its methods. (Part 2 of 2.) 2009 Pearson Education, Inc. All rights reserved.

40 6.5 GradeBook Case Study: Select Case Multiple-Selection Statement (Cont.) 40 Methods declared Private can be called only by other members of the class in which the Private methods are declared. Such Private methods are commonly referred to as utility methods or helper methods.

41 6.5 GradeBook Case Study: Select Case Multiple-Selection Statement (Cont.) 41 TheWith statement allows you to make multiple references to the same object. With gradebook1.displaymessage() ' display welcome message.inputgrades() ' read grades from user.displaygradereport() ' display report based on grades End With These lines of code are collectively known as a With statement t tblock.

42 6.5 GradeBook Case Study: Select Case Multiple-Selection Statement (Cont.) Figure 6.11 shows the UML activity diagram for the general Select...Case statement. 42 Fig Select Case multiple-selection statement UML activity diagram.

43 The Do...Loop While repetition statement is similar to the While statement. The program in Fig uses a Do...Loop While statement to output the values ' Fig. 6.12: DoLoopWhile.vb 2 ' Demonstrating the Do...Loop While repetition statement. 3 Module DoLoopWhile 4 Sub Main() 5 Dim counter As Integer = ' print values 1 to 5 8 Do 9 Console.Write("{0} ", counter) 10 counter += 1 11 Loop While counter <= Console.WriteLine() 14 End Sub ' Main 15 End Module ' DoLoopWhile Outline DoLoopWhile.vb ( 1 of 2 ) Condition tested after loop body executes 43 Fig Do Loop While repetition statement Pearson Education, Inc. All rights reserved.

44 Outline 44 Error-Prevention Tip 6.5.Infinite loops occur when the loop-continuation condition in a While, Do While...Loop or Do...Loop While statement never becomes false. DoLoopWhile.vb ( 2 of 2 ) 2009 Pearson Education, Inc. All rights reserved.

45 6.6 Do Loop While Repetition Statement (Cont.) 45 The Do Loop While UML activity diagram (Fig. 6.13) illustrates that t the loop-continuation condition is not evaluated until after the statement body. Fig Do Loop While repetition statement activity diagram.

46 Figure 6.14 uses a Do...Loop Until statement to print the numbers from 1 to 5. Outline DoLoopUntil.vb 46 1 ' Fig. 6.14: DoLoopUntil.vb 2 ' Using Do...Loop Until repetition statement. 3 Module DoLoopUntil 4 Sub Main() 5 Dim counter As Integer = ' print values 1 to 5 8 Do 9 Console.Write("{0} ", counter) 10 counter += 1 11 Loop Until counter > Console.WriteLine() 14 End Sub ' Main 15 End Module ' DoLoopUntil Condition tested after loop body executes Fig Do Loop Until repetition statement Pearson Education, Inc. All rights reserved.

47 6.7 Do...Loop Until Repetition Statement (Cont.) Common Programming Error 6.5 Including an incorrect relational loperator or an incorrect final value for a loop counter in the condition of any repetition statement can cause off-by-one errors. 47 Error-Prevention Tip 6.6.Infinite loops occur when the loop-termination condition in a Do Until...Loop or Do...Loop Until statement never becomes true.

48 6.7 Do...Loop Until Repetition Statement (Cont.) Error-Prevention Tip 6.7 In a counter-controlled t dloop, ensure that t the control variable is incremented (or decremented) appropriately in the body of the loop to avoid an infinite loop. 48

49 6.8 Using Exit in Repetition Statements 49 An Exit statement causes the program to exit immediately from a repetition statement. The Exit Do statement can be executed in any Do statement. Exit For and Exit While cause immediate exit from For Next and While End While loops. These statements are used to alter a program s flow of control.

50 Figure 6.15 demonstrates Exit statements. Outline 50 1 ' Fig. 6.15: ExitTest.vb 2 ' Using the Exit statement in repetition statements. 3 Module ExitTest 4 Sub Main() 5 Dim counter As Integer ' loop counter 6 7 ' exit For...Next statement 8 For counter = 1 To 10 9 ' skip remaining code in loop only if counter = 5 10 If counter = 5 Then 11 Exit For ' break out of loop 12 End If Console.Write("{0} ", counter) ' output counter 15 Next 16 ExitTest.vb ( 1 of 3 ) Fig Exit statement in repetition statements. (Part 1 of 3.) 2009 Pearson Education, Inc. All rights reserved.

51 Outline Console.WriteLine(vbNewLine & _ 18 "Broke out of For...Next at counter = " & counter & vbnewline) 19 counter = 1 ' reset counter ' exit Do Until...Loop statement 22 Do Until counter > ' skip remaining code in loop only if counter = 5 24 If counter = 5 Then 25 Exit Do ' break out of loop 26 End If Console.Write("{0} ", counter) ' output counter 29 counter += 1 ' increment counter 30 Loop Console.WriteLine(vbNewLine & "Broke out of Do Until...Loop " & _ 33 " at counter = " & counter & vbnewline) 34 counter = 1 ' reset counter ' exit While statement ExitTest.vb ( 2 of 3 ) Fig Exit statement in repetition statements. (Part 2 of 3.) 2009 Pearson Education, Inc. All rights reserved.

52 Outline While counter <= ' skip remaining code in loop only if counter = 5 39 If counter = 5 Then 40 Exit While ' break out of loop 41 End If Console.Write("{0} ", counter) ' output counter 44 counter += 1 ' increment counter 45 End While Console.WriteLine( _ 48 vbnewline & "Broke out of While at counter = " & counter) 49 End Sub ' Main 50 End Module ' ExitTest ExitTest.vb ( 3 of 3 ) Broke out of For...Next at counter = Broke out of Do Until...Loop at counter = Broke out of While at counter = 5 Fig Exit statement in repetition statements. (Part 3 of 3.) 2009 Pearson Education, Inc. All rights reserved.

53 6.9 Using Continue in Repetition Statements 53 The Continue statement skips to the next iteration of the loop. The Continue Do statement can be executed in any Do statement. Continue For and Continue While are used in For... Next and While loops. Continue For increments the control variable by the Step value.

54 Figure 6.16 demonstrates the Continue statements. Outline 54 1 ' Fig. 6.16: ContinueTest.vb 2 ' Using the Continue statement in repetition statements. 3 Module ContinueTest 4 Sub Main() 5 Dim counter As Integer ' loop counter 6 7 ' skipping an iteration of a For...Next statement 8 For counter = 1 To 10 9 If counter = 5 Then 10 Continue For ' skip to next iteration of loop if counter = 5 11 End If Console.Write("{0} ", counter) ' output counter 14 Next Console.WriteLine(vbNewLine & _ 17 "Skipped printing in For...Next at counter = 5" & vbnewline) 18 counter = 0 ' reset counter 19 ContinueTest.vb ( 1 of 3 ) Fig Continue statement in repetition statements. (Part 1 of 3.) 2009 Pearson Education, Inc. All rights reserved.

55 Outline ' skipping an iteration of a Do Until...Loop statement 21 Do Until counter >= counter += 1 ' increment counter If counter = 5 Then 25 Continue Do ' skip to next iteration of loop if counter = 5 26 End If Console.Write("{0} ", counter) ' output counter 29 Loop Console.WriteLine(vbNewLine & _ 32 "Skipped printing in Do Until...Loop at counter = 5" & vbnewline) 33 counter = 0 ' reset counter ' skipping an iteration of a While statement 36 While counter < counter += 1 ' increment counter If counter = 5 Then 40 Continue While ' skip to next iteration of loop if counter = 5 41 End If ContinueTest.vb ( 2 of 3 ) Fig Continue statement in repetition statements. (Part 2 of 3.) 2009 Pearson Education, Inc. All rights reserved.

56 Outline Console.Write("{0} ", counter) ' output counter 44 End While Console.WriteLine( _ 47 vbnewline & "Skipped printing in While at counter = 5") 48 End Sub ' Main 49 End Module ' ContinueTest ContinueTest.vb ( 3 of 3 ) Skipped printing in For...Next at counter = Skipped printing in Do Until...Loop at counter = Skipped printing in While at counter = 5 Fig Continue statement in repetition statements. (Part 3 of 3.) 2009 Pearson Education, Inc. All rights reserved.

57 Logical Operators The logical And operator can be used as follows: If gender = "F" And age >= 65 Then seniorfemales += 1 End If The If Then statement considers the combined condition: gender = "F" And age >= 65 Figure 6.17 is a truth table for the And operator. expression1 expression2 expression1 And expression2 False False False False True False True False False True True True Fig Truth table for the logical And operator.

58 Logical Operators (Cont.) Logical Or Operator The Or operator is used in the following segment: If (semesteraverage >= 90 Or finalexam >= 90) Then Console.WriteLine("Student grade is A") End If Figure 6.18 provides a truth table for the Or operator. expression1 expression2 expression1 Or expression2 False False False False True True True False True True True True Fig Truth table for the logical Or operator.

59 6.10 Logical Operators (Cont.) 59 Logical AndAlso and OrElse Operators AndAlso and OrElse are similar to the And and Or operators. (gender = "F" AndAlso age >= 65) The preceding expression stops evaluation immediately if gender is not equal to "F"; this is called short-circuit evaluation. Performance Tip 6.2 In expressions using operator AndAlso, if the separate conditions are independent of one an-other, place the condition most likely to be false as the leftmost condition. In expres-sions using operator OrElse, make the condition most likely to be true the leftmost condition. Each of these suggestions can reduce a program s execution time.

60 6.10 Logical Operators (Cont.) 60 AndAlso and OrElse operators can be used in place of And and Or. An exception to this rule occurs when the right operand of a condition produces a side effect: Console.WriteLine("How old are you?") If (gender = "F" And Console.ReadLine() >= 65) Then Console.WriteLine("You are a female senior citizen.") End If Error-Prevention Tip 6.8 Avoid expressions with side effects in conditions, because side effects often cause subtle errors.

61 Logical Operators (Cont.) Logical Xor Operator A condition i containing i the logical lexclusive OR( (Xor) operator is true if and only if one of its operands results in a true value and the other results in a false value. Figure 6.19 presents a truth table for the Xor operator. expression1 expression2 expression1 Xor expression2 False False False False True True True False True True True False Fig Truth table for the logical exclusive OR (Xor) operator.

62 Logical Operators (Cont.) Logical Not Operator The Not operator enables you to reverse the meaning of a condition. The logical l negation operator is a unary operator, requiring only one operand. If Not (grade = sentinelvalue) Then Console.WriteLine("The next grade is " & grade) End If The parentheses are necessary because Not has a higher precedence than the equality operator.

63 Logical Operators (Cont.) You can avoid using Not by expressing the condition differently: If grade <> sentinelvalue Then Console.WriteLine("The next grade is " & grade) End If Figure 6.20 provides a truth table for Not. expression False True Not expression True False Fig Truth table for operator Not (logical negation).

64 Figure 6.21 demonstrates the logical operators by displaying their truth tables. Outline 64 1 ' Fig. 6.21: LogicalOperators.vb 2 ' Using logical operators. 3 Module LogicalOperators 4 Sub Main() 5 ' display truth table for And 6 Console.WriteLine("And" & vbnewline & _ 7 "False And False: " & (False And False) & vbnewline & _ 8 "False And True: " & (False And True) & vbnewline & _ 9 "True And False: " & (True And False) & vbnewline & _ 10 "True And True: " & (True And True) & vbnewline) ' display truth table for Or 13 Console.WriteLine("Or" i " & vbnewline & _ 14 "False Or False: " & (False Or False) & vbnewline & _ 15 "False Or True: " & (False Or True) & vbnewline & _ 16 "True Or False: " & (True Or False) & vbnewline & _ 17 "True Or True: " & (True Or True) & vbnewline) 18 LogicalOperators.vb (1of4) Fig Logical operator truth tables. (Part 1 of 4.) 2009 Pearson Education, Inc. All rights reserved.

65 Outline ' display truth table for AndAlso 20 Console.WriteLine("AndAlso" & vbnewline & _ 21 "False AndAlso False: " & (False AndAlso False) & vbnewline & _ 22 "False AndAlso True: " & (False AndAlso True) & vbnewline & _ 23 "True AndAlso False: " & (True AndAlso False) & vbnewline & _ 24 "True AndAlso True: " & (True AndAlso True) & vbnewline) ' display truth table for OrElse 27 Console.WriteLine("OrElse" & vbnewline & _ 28 "False OrElse False: " & (False OrElse False) & vbnewline & _ 29 "False OrElse True: " & (False OrElse True) & vbnewline & _ 30 "True OrElse False: " & (True OrElse False) & vbnewline & _ 31 "True OrElse True: " & (True OrElse True) & vbnewline) ' display truth table for Xor 34 Console.WriteLine("Xor" & vbnewline & _ 35 "False Xor False: " & (False Xor False) & vbnewline & _ 36 "False Xor True: " & (False Xor True) & vbnewline & _ 37 "True Xor False: " & (True Xor False) & vbnewline & _ 38 "True Xor True: " & (True Xor True) & vbnewline) LogicalOperators.vb (2of4) Fig Logical operator truth tables. (Part 2 of 4.) 2009 Pearson Education, Inc. All rights reserved.

66 Outline ' display truth table for Not 41 Console.WriteLine("Not" & vbnewline & "Not False: " & _ 42 (Not False) & vbnewline & "Not True: " & (Not True) & vbnewline) 43 End Sub ' Main 44 End Module ' LogicalOperators LogicalOperators.vb (3of4) And False And False: False False And True: False True And False: False True And True: True Or False Or False: False False Or True: True True Or False: True True Or True: True AndAlso False AndAlso False: False False AndAlso True: False True AndAlso False: False True AndAlso True: True (continued on next page...) Fig Logical operator truth tables. (Part 3 of 4.) 2009 Pearson Education, Inc. All rights reserved.

67 Outline 67 And False And False: False False And True: False True And False: False True And True: True Or False Or False: False False Or True: True True Or False: True True Or True: True AndAlso False AndAlso False: False False AndAlso True: False True AndAlso False: False True AndAlso True: True (continued from previous page ) LogicalOperators.vb (4of4) 4 Fig Logical operator truth tables. (Part 4 of 4.) 2009 Pearson Education, Inc. All rights reserved.

68 6.10 Logical Operators (Cont.) 68 Figure 6.22 displays the operators in decreasing order of precedence. Operators Type ^ exponentiation + - unary plus and minus * / multiplicative operators \ integer division Mod modulus + - additive operators Fig Precedence of the operators discussed so far. (Part 1 of 2.)

69 6.10 Logical Operators (Cont.) 69 Operators Type & concatenation < <= > >= = <> relational and equality Not And AndAlso Or OrElse Xor logical NOT logical AND logical inclusive OR logical exclusive OR = += -= *= /= \= ^= &= assignment Fig Precedence of the operators discussed so far. (Part 2 of 2.)

70 6.11 Software Engineering Case Study: Identifying Objects States and Activities in the ATM System Each object in a system goes through h a series of discrete states. State machine diagrams model key states of an object and show under what circumstances the object changes state. Figure 6.23 models some of the states of an ATM object. 70 Fig State machine diagram for some of the states of the ATM object.

71 6.11 Software Engineering Case Study: Identifying Objects States and Activities in the ATM System (Cont.) An activity diagram models an object s workflow. The activity diagram in Fig models the actions involved in executing a BalanceInquiry transaction. 71 Fig Activity diagram for a BalanceInquiry transaction.

72 6.11 Software Engineering Case Study: Identifying Objects States and Activities in the ATM System (Cont.) 72 Figure 6.25 shows a more complex activity diagram for a Withdrawal. Fig Activity diagram for a Withdrawal transaction.

Control Statements: Part Pearson Education, Inc. All rights reserved.

Control Statements: Part Pearson Education, Inc. All rights reserved. 1 5 Control Statements: Part 2 2 Not everything that can be counted counts, and not every thing that counts can be counted. Albert Einstein Who can control his fate? William Shakespeare The used key is

More information

Control Statements: Part Pearson Education, Inc. All rights reserved.

Control Statements: Part Pearson Education, Inc. All rights reserved. 1 5 Control Statements: Part 2 2 Not everything that can be counted counts, and not every thing that counts can be counted. Albert Einstein Who can control his fate? William Shakespeare The used key is

More information

Chapter 4 C Program Control

Chapter 4 C Program Control 1 Chapter 4 C Program Control Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 4 C Program Control Outline 4.1 Introduction 4.2 The Essentials of Repetition

More information

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M Control Structures Intro. Sequential execution Statements are normally executed one

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All for repetition statement do while repetition statement switch multiple-selection statement break statement continue statement Logical

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 2.11 Assignment Operators 2.12 Increment and Decrement Operators 2.13 Essentials of Counter-Controlled Repetition 2.1 for Repetition Structure 2.15 Examples Using the for

More information

Introduction to C Programming

Introduction to C Programming 1 2 Introduction to C Programming 2.6 Decision Making: Equality and Relational Operators 2 Executable statements Perform actions (calculations, input/output of data) Perform decisions - May want to print

More information

C Program Control. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

C Program Control. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan C Program Control Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline The for repetition statement switch multiple selection statement break

More information

Control Statements. Musa M. Ameen Computer Engineering Dept.

Control Statements. Musa M. Ameen Computer Engineering Dept. 2 Control Statements Musa M. Ameen Computer Engineering Dept. 1 OBJECTIVES In this chapter you will learn: To use basic problem-solving techniques. To develop algorithms through the process of topdown,

More information

Chapter 4 C Program Control

Chapter 4 C Program Control Chapter C Program Control 1 Introduction 2 he Essentials of Repetition 3 Counter-Controlled Repetition he for Repetition Statement 5 he for Statement: Notes and Observations 6 Examples Using the for Statement

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 Outline 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure

More information

Chapter 2 - Control Structures

Chapter 2 - Control Structures Chapter 2 - Control Structures 1 2.1 Introduction 2.2 Algorithms 2.3 Pseudocode 2.4 Control Structures 2.5 if Selection Structure 2.6 if/else Selection Structure 2.7 while Repetition Structure 2.8 Formulating

More information

Programming for Engineers Iteration

Programming for Engineers Iteration Programming for Engineers Iteration ICEN 200 Spring 2018 Prof. Dola Saha 1 Data type conversions Grade average example,-./0 class average = 23450-67 893/0298 Grade and number of students can be integers

More information

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I AL GHURAIR UNIVERSITY College of Computing CSC 209 JAVA I week 3- Control Statements: Part I Objectives: To use the if and if...else selection statements to choose among alternative actions. To use the

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved. 1 6 Functions and an Introduction to Recursion 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare

More information

بسم اهلل الرمحن الرحيم

بسم اهلل الرمحن الرحيم بسم اهلل الرمحن الرحيم Fundamentals of Programming C Session # 10 By: Saeed Haratian Fall 2015 Outlines Examples Using the for Statement switch Multiple-Selection Statement do while Repetition Statement

More information

Fundamentals of Programming Session 9

Fundamentals of Programming Session 9 Fundamentals of Programming Session 9 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition 5.2 Q1: Counter-controlled repetition requires a. A control variable and initial value. b. A control variable

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Introduction to C++ Programming Pearson Education, Inc. All rights reserved. 1 2 Introduction to C++ Programming 2 What s in a name? that which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the

More information

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3 Programming - 1 Computer Science Department 011COMP-3 لغة البرمجة 1 011 عال- 3 لطالب كلية الحاسب اآللي ونظم المعلومات 1 1.1 Machine Language A computer programming language which has binary instructions

More information

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of Basic Problem solving Techniques Top Down stepwise refinement If & if.. While.. Counter controlled and sentinel controlled repetition Usage of Assignment increment & decrement operators 1 ECE 161 WEEK

More information

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4. Introduction to Visual Basic and Visual C++ Arithmetic Expression Lesson 4 Calculation I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Arithmetic Expression Using Arithmetic Expression Calculations

More information

2.11 Assignment Operators. Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator

2.11 Assignment Operators. Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator 2.11 Assignment Operators 1 Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator Statements of the form variable = variable operator expression;

More information

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018. Week 2 Branching & Looping Gaddis: Chapters 4 & 5 CS 5301 Spring 2018 Jill Seaman 1 Relational Operators l relational operators (result is bool): == Equal to (do not use =)!= Not equal to > Greater than

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Chapter 3 Structured Program Development

Chapter 3 Structured Program Development 1 Chapter 3 Structured Program Development Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 3 - Structured Program Development Outline 3.1 Introduction

More information

Deeper Look Pearson Education, Inc. All rights reserved.

Deeper Look Pearson Education, Inc. All rights reserved. 1 7 Methods: A Deeper Look 2 The greatest invention of the nineteenth century was the invention of the method of invention. Alfred North Whitehead ead Form ever follows function. Louis Henri Sullivan Call

More information

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement Last Time Let s all Repeat Together 10/3/05 CS150 Introduction to Computer Science 1 1 We covered o Counter and sentinel controlled loops o Formatting output Today we will o Type casting o Top-down, stepwise

More information

Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2016

Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2016 Introduction to 2 VISUAL BASIC 2016 edition Copyright HKTA Tang Hin Memorial Secondary School 2016 Table of Contents. Chapter....... 1.... More..... on.. Operators........................................

More information

Conditionals and Loops

Conditionals and Loops Conditionals and Loops Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing steps in a loop Chapter 5 focuses on: boolean expressions conditional

More information

Microsoft Visual Basic 2005: Reloaded

Microsoft Visual Basic 2005: Reloaded Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 4 Making Decisions in a Program Objectives After studying this chapter, you should be able to: Include the selection structure in pseudocode

More information

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved. 1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases. Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 2: Sentinel-Controlled Repetition In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability.

More information

Unit 3. Operators. School of Science and Technology INTRODUCTION

Unit 3. Operators. School of Science and Technology INTRODUCTION INTRODUCTION Operators Unit 3 In the previous units (unit 1 and 2) you have learned about the basics of computer programming, different data types, constants, keywords and basic structure of a C program.

More information

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved. 1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators Course Name: Advanced Java Lecture 2 Topics to be covered Variables Operators Variables -Introduction A variables can be considered as a name given to the location in memory where values are stored. One

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

More information

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad Outline 1. The if Selection Structure 2. The if/else Selection Structure 3. The switch Multiple-Selection Structure 1. The if Selection

More information

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions. Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate

More information

5. Selection: If and Switch Controls

5. Selection: If and Switch Controls Computer Science I CS 135 5. Selection: If and Switch Controls René Doursat Department of Computer Science & Engineering University of Nevada, Reno Fall 2005 Computer Science I CS 135 0. Course Presentation

More information

Control Statements: Part 1

Control Statements: Part 1 4 Let s all move one place on. Lewis Carroll Control Statements: Part 1 The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert Frost All

More information

Repeating Instructions. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Repeating Instructions. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies 6 Repeating Instructions C# Programming: From Problem Analysis to Program Design 2nd Edition David McDonald, Ph.D. Director of Emerging Technologies Chapter Objectives Learn why programs use loops Write

More information

Unit 7. Lesson 7.1. Loop. For Next Statements. Introduction. Loop

Unit 7. Lesson 7.1. Loop. For Next Statements. Introduction. Loop Loop Unit 7 Loop Introduction So far we have seen that each instruction is executed once and once only. Some time we may require that a group of instructions be executed repeatedly, until some logical

More information

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

Control Statements: Part Pearson Education, Inc. All rights reserved.

Control Statements: Part Pearson Education, Inc. All rights reserved. 1 5 Control Statements: Part 2 5.2 Essentials of Counter-Controlled Repetition 2 Counter-controlled repetition requires: Control variable (loop counter) Initial value of the control variable Increment/decrement

More information

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance. 2.1 Introduction (No questions.) 2.2 A Simple Program: Printing a Line of Text 2.1 Which of the following must every C program have? (a) main (b) #include (c) /* (d) 2.2 Every statement in C

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

Chapter 4: Control Structures I (Selection)

Chapter 4: Control Structures I (Selection) Chapter 4: Control Structures I (Selection) 1 Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean) expressions Discover

More information

COMP 202 Java in one week

COMP 202 Java in one week CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

More information

CS110D: PROGRAMMING LANGUAGE I

CS110D: PROGRAMMING LANGUAGE I CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 5&6: Loops Lecture Contents Why loops?? While loops for loops do while loops Nested control structures Motivation Suppose that you need

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 1 2 Introduction to Classes and Objects You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

Repetition Structures

Repetition Structures Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

More information

Introduction to C# Applications Pearson Education, Inc. All rights reserved.

Introduction to C# Applications Pearson Education, Inc. All rights reserved. 1 3 Introduction to C# Applications 2 What s in a name? That which we call a rose by any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the

More information

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

More information

Course Outline. Introduction to java

Course Outline. Introduction to java Course Outline 1. Introduction to OO programming 2. Language Basics Syntax and Semantics 3. Algorithms, stepwise refinements. 4. Quiz/Assignment ( 5. Repetitions (for loops) 6. Writing simple classes 7.

More information

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d. Chapter 4: Control Structures I (Selection) In this chapter, you will: Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

Object Oriented Programming with Visual Basic.Net

Object Oriented Programming with Visual Basic.Net Object Oriented Programming with Visual Basic.Net By: Dr. Hossein Hakimzadeh Computer Science and Informatics IU South Bend (c) Copyright 2007 to 2015 H. Hakimzadeh 1 What do we need to learn in order

More information

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Contents 1 Introduction...2 2 Lexical Conventions...2 3 Types...3 4 Syntax...3 5 Expressions...4 6 Declarations...8 7 Statements...9

More information

How to engineer a class to separate its interface from its implementation and encourage reuse.

How to engineer a class to separate its interface from its implementation and encourage reuse. 1 3 Introduction to Classes and Objects 2 OBJECTIVES In this chapter you ll learn: What classes, objects, member functions and data members are. How to define a class and use it to create an object. How

More information

Chapter 2: Using Data

Chapter 2: Using Data Chapter 2: Using Data Declaring Variables Constant Cannot be changed after a program is compiled Variable A named location in computer memory that can hold different values at different points in time

More information

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

COP 2000 Introduction to Computer Programming Mid-Term Exam Review he exam format will be different from the online quizzes. It will be written on the test paper with questions similar to those shown on the following pages. he exam will be closed book, but students can

More information

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Copyright 2011 Pearson Addison-Wesley. All rights reserved.

More information

Fundamentals of Programming Session 25

Fundamentals of Programming Session 25 Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Chapter 2, Part III Arithmetic Operators and Decision Making

Chapter 2, Part III Arithmetic Operators and Decision Making Chapter 2, Part III Arithmetic Operators and Decision Making C How to Program, 8/e, GE 2016 Pearson Education, Ltd. All rights reserved. 1 2016 Pearson Education, Ltd. All rights reserved. 2 2016 Pearson

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

You will have mastered the material in this chapter when you can:

You will have mastered the material in this chapter when you can: CHAPTER 6 Loop Structures OBJECTIVES You will have mastered the material in this chapter when you can: Add a MenuStrip object Use the InputBox function Display data using the ListBox object Understand

More information

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029 Programming Basics and Practice GEDB029 Decision Making, Branching and Looping Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029 Decision Making and Branching C language possesses such decision-making capabilities

More information

Computer Programming C++ (wg) CCOs

Computer Programming C++ (wg) CCOs Computer Programming C++ (wg) CCOs I. The student will analyze the different systems, and languages of the computer. (SM 1.4, 3.1, 3.4, 3.6) II. The student will write, compile, link and run a simple C++

More information

An overview about DroidBasic For Android

An overview about DroidBasic For Android An overview about DroidBasic For Android from February 25, 2013 Contents An overview about DroidBasic For Android...1 Object-Oriented...2 Event-Driven...2 DroidBasic Framework...2 The Integrated Development

More information

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Quick Reference Guide

Quick Reference Guide SOFTWARE AND HARDWARE SOLUTIONS FOR THE EMBEDDED WORLD mikroelektronika Development tools - Books - Compilers Quick Reference Quick Reference Guide with EXAMPLES for Basic language This reference guide

More information

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++ Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

More information

Lecture 10 Online Portal http://structuredprogramming.wikispaces.com/ Menus A menu is a list of functions that a program can perform; the user chooses the desired function from the list. E.g., 1 convert

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

More information

Computer Programming C++ Classes and Objects 6 th Lecture

Computer Programming C++ Classes and Objects 6 th Lecture Computer Programming C++ Classes and Objects 6 th Lecture 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 Eom, Hyeonsang All Rights Reserved Outline

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Fundamentals of Programming. Lecture 3: Introduction to C Programming Fundamentals of Programming Lecture 3: Introduction to C Programming Instructor: Fatemeh Zamani f_zamani@ce.sharif.edu Sharif University of Technology Computer Engineering Department Outline A Simple C

More information

Dept. of CSE, IIT KGP

Dept. of CSE, IIT KGP Control Flow: Looping CS10001: Programming & Data Structures Pallab Dasgupta Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Types of Repeated Execution Loop: Group of

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input Loops / Repetition Statements Repetition s allow us to execute a multiple times Often they are referred to as loops C has three kinds of repetition s: the while loop the for loop the do loop The programmer

More information

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017 Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls

More information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

More information

Control Structures (Deitel chapter 4,5)

Control Structures (Deitel chapter 4,5) Control Structures (Deitel chapter 4,5) 1 2 Plan Control Structures ifsingle-selection Statement if else Selection Statement while Repetition Statement for Repetition Statement do while Repetition Statement

More information

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 9/e Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Copyright 1992-2012 by Pearson Copyright 1992-2012 by Pearson Before writing a program to solve a problem, have

More information

Computational Physics - Fortran February 1997

Computational Physics - Fortran February 1997 Fortran 90 Decision Structures IF commands 3 main possibilities IF (logical expression) IF (logical expression) THEN IF (logical expression) THEN IF (logical expression) THEN expression TRUE expression

More information

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

Flow of Control. Flow of control The order in which statements are executed. Transfer of control 1 Programming in C Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control

More information

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed Programming in C 1 Flow of Control Flow of control The order in which statements are executed Transfer of control When the next statement executed is not the next one in sequence 2 Flow of Control Control

More information

Add Subtract Multiply Divide

Add Subtract Multiply Divide ARITHMETIC OPERATORS if AND if/else AND while LOOP Order of Operation (Precedence Part 1) Copyright 2014 Dan McElroy Add Subtract Multiply Divide + Add - Subtract * Multiply / Divide = gives the quotient

More information

SECTION II: LANGUAGE BASICS

SECTION II: LANGUAGE BASICS Chapter 5 SECTION II: LANGUAGE BASICS Operators Chapter 04: Basic Fundamentals demonstrated declaring and initializing variables. This chapter depicts how to do something with them, using operators. Operators

More information

Darshan Institute of Engineering & Technology for Diploma Studies

Darshan Institute of Engineering & Technology for Diploma Studies Overview of Microsoft.Net Framework: The Dot Net or.net is a technology that is an outcome of Microsoft s new strategy to develop window based robust applications and rich web applications and to keep

More information

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved. Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

BRANCHING if-else statements

BRANCHING if-else statements BRANCHING if-else statements Conditional Statements A conditional statement lets us choose which statement t t will be executed next Therefore they are sometimes called selection statements Conditional

More information

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators Expressions 1 Expressions n Variables and constants linked with operators Arithmetic expressions n Uses arithmetic operators n Can evaluate to any value Logical expressions n Uses relational and logical

More information

4. Inputting data or messages to a function is called passing data to the function.

4. Inputting data or messages to a function is called passing data to the function. Test Bank for A First Book of ANSI C 4th Edition by Bronson Link full download test bank: http://testbankcollection.com/download/test-bank-for-a-first-book-of-ansi-c-4th-edition -by-bronson/ Link full

More information

Chapter 3. Selections

Chapter 3. Selections Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

More information