Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Size: px
Start display at page:

Download "Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons"

Transcription

1 Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

2 Objectives To learn about the three types of loops: while for do To avoid infinite loops and off-by-one errors To understand nested loops and sentinel. 2

3 What Is the Purpose of a Loop? A loop is a statement that is used to: execute one or more statements repeatedly until a goal is reached. Sometimes these one-or-more statements will not be executed at all if that s the way to reach the goal 3

4 The Three Loops in C++ C++ has these three looping statements: while for do 4

5 The while Loop while (condition) statements The condition is some kind of test (the same as it was in the if statement in Chap. 3) 5

6 The while Loop while (condition) statements The statements are repeatedly executed until the condition is false 6

7 The while Loop 1.0 START 2.0 Read input from user, countdown. 3.0 IF the countdown is more than 0 THEN 3.1 Display * 3.2 Decrement countdown by Repeat step 3.0. ELSE 3.4 Go to Step END. 7

8 The while Loop cin >> countdown; while( countdown > 0) cout << "* " ; countdown--; 8

9 The while Loop When doing something repetitive, we want to know when we are done. Example: I want to get at least $20,000 So we set balance >= TARGET But the while loop thinks the opposite: How long I am allowed to keep going? So the correct condition : while (balance < TARGET) 9

10 The while Loop 10

11 Using a Loop to Solve the Investment Problem. The algorithm for an investment problem: 1. Start with a year value of 0 and a balance of $10, Repeat the following steps while the balance is less than $20,000: Add 1 to the year value. Multiply the balance value by 1.05 (a 5 percent increase). 3. Report the final year value as the answer. Repeat.. while in the problem indicates a loop is needed. To reach the goal of being able to report the final year value, adding and multiplying must be repeated some unknown number of times. 11

12 Using a Loop to Solve the Investment Problem. The statements to be controlled are: Incrementing the year variable Updating the balance variable using a const for the RATE year++; balance = balance * (1 + RATE / 100); 12

13 Using a Loop to Solve the Investment Problem. The condition, which indicates when to stop executing the statements, is this test: (balance < TARGET) 13

14 Using a Loop to Solve the Investment Problem. Here is the complete while statement: while (balance < TARGET) year++; balance = balance * (1 + RATE / 100); 14

15 Flowchart of the Investment Calculation s while Loop 15

16 The Complete Investment Program #include <iostream> using namespace std; int main() const double RATE = 5; const double INITIAL_BALANCE = 10000; const double TARGET = 2 * INITIAL_BALANCE; double balance = INITIAL_BALANCE; int year = 0; while (balance < TARGET) year++; balance = balance * (1 + RATE / 100); cout << "The investment doubled after " << year << " years." << endl; return 0; 16

17 Program Run 1. Check the loop condition balance = year = 0 while (balance < TARGET) year++; balance = balance * (1 + rate / 100 ); 17

18 Program Run 1. Check the loop condition balance = year = 0 while (balance < TARGET) year++; The condition is true balance = balance * (1 + rate / 100 ); 18

19 Program Run 1. Check the loop condition balance = year = 0 while (balance < TARGET) year++; The condition is true balance = balance * (1 + rate / 100 ); 2. Execute the statements in the loop balance = year = 1 while (balance < TARGET) year++; balance = balance * (1 + rate / 100 ); 19

20 Program Run 3. Check the loop condition again balance = year = 1 while (balance < TARGET) year++; The condition is still true balance = balance * (1 + rate / 100 ); 20

21 Program Run 3. Check the loop condition again balance = year = 1 while (balance < TARGET) year++; The condition is still true balance = balance * (1 + rate / 100 ); 4. Execute the statements in the loop balance = year = 2 while (balance < TARGET) year++; balance = balance * (1 + rate / 100 ); 21

22 Program Run 3. Check the loop condition again balance = year = 2 while (balance < TARGET) year++; The condition is still true balance = balance * (1 + rate / 100 ); 4. Execute the statements in the loop balance = year = 3 while (balance < TARGET) year++; balance = balance * (1 + rate / 100 ); 22

23 Program Run This process continues for 15 iterations 23

24 Program Run The final output indicates that the investment doubled in 15 years. 24

25 Program Run 25

26 Program Run 26

27 More while Examples Skip the examples? NO YES 27

28 More while Examples For each of the following, do a hand-trace 28

29 Example of Normal Execution while loop to hand-trace What is the output? i = 5; while (i > 0) cout << i << " "; i--; 29

30 When i Is 0, the Loop Condition Is false, and the Loop Ends while loop The output i = 5; while (i > 0) cout << i << " "; i--; correct? OR

31 Example of a Problem An Infinite Loop while loop to hand-trace What is the output? i = 5; while (i > 0) cout << i << " "; i++; 31

32 Example of a Problem An Infinite Loop i is set to 5 The i++; statement makes i get bigger and bigger the condition will never become false an infinite loop while loop The output never ends i = 5; while (i > 0) cout << i << " "; i++;

33 Another Normal Execution No Errors while loop to hand-trace i = 5; while (i > 5) cout << i << " "; i--; What is the output? 33

34 Another Normal Execution No Errors while loop i = 5; while (i > 5) cout << i << " "; i--; There is (correctly) no output The expression i > 5 is initially false, so the statements are never executed. 34

35 Another Normal Execution No Errors while loop i = 5; while (i > 5) cout << i << " "; i--; There is (correctly) no output This is not a error. Sometimes we do not want to execute the statements unless the test is true. 35

36 Normal Execution with Another Programmer s Error while loop to hand-trace What is the output? i = 5; while (i < 0) cout << i << " "; i--; 36

37 Normal Execution with Another Programmer s Error The programmer probably thought: Stop when i is less than 0. However, the loop condition controls when the loop is executed - not when it ends. while loop i = 5; while (i < 0) cout << i << " "; i--; Again, there is no output 37

38 A Very Difficult Error to Find (especially after looking for it for hours and hours!) while loop to hand-trace What is the output? i = 5; while (i > 0); cout << i << " "; i--; 38

39 A Very Difficult Error to Find (especially after looking for it for hours and hours!) Another infinite loop caused by a single character: That semicolon causes the while loop to have an empty body which is executed forever. The i in (i > 0) is never changed. while loop There is no output! i = 5; while (i > 0); cout << i << " "; i--; ; 39

40 Common Error Infinite Loops Forgetting to update the variable used in the condition is common. In the investment program, it might look like this. year = 1; while (year <= 20) balance = balance * (1 + RATE / 100); The variable year is not updated in the body 40

41 Common Error Infinite Loops Another way to cause an infinite loop: Typing on autopilot Typing ++ when you meant to type -- is a real problem, especially when it s 3:30 am! year = 20; while (year > 0) balance = balance * (1 + RATE / 100); year++; 41

42 A Not Really Infinite Infinite Loop Due to what is called wrap around, the previous loop will end. At some point the value stored in the int variable gets to the largest representable positive integer. When it is incremented, the value stored wraps around to be a negative number. That definitely stops the loop! 42

43 Common Error Are We There Yet? When doing something repetitive, most of us want to know when we are done. For example, you may think, I want to get at least $20,000, and set the loop condition to while (balance >= TARGET) wrong test 43

44 Common Error Are We There Yet? But the while loop thinks the opposite: How long am I allowed to keep going? What is the correct loop condition? while ( ) 44

45 Common Error Are We There Yet? But the while loop thinks the opposite: How long am I allowed to keep going? What is the correct loop condition? while (balance < TARGET) In other words: Keep at it while the balance is less than the target. 45

46 Common Error Off-by-One Errors In the code to find when we have doubled our investment: Do we start the variable for the years at 0 or 1 years? Do we test for < TARGET or for <= TARGET? 46

47 Common Error Off-by-One Errors Maybe if you start trying some numbers and add +1 or -1 until you get the right answer you can figure these things out. It will most likely take a very long time to try ALL the possibilities. No, just try a couple of test cases (while thinking). 47

48 Use Thinking to Decide! Consider starting with $100 and a RATE of 50%. We want $200 (or more). At the end of the first year, the balance is $150 not done yet At the end of the second year, the balance is $225 definitely over TARGET and we are done. We made two increments. What must the original value be so that we end up with 2? Zero, of course. 48

49 Use Thinking to Decide! Another way to think about the initial value is: Before we even enter the loop, what is the correct value? Most often it s zero. 49

50 < vs. <= (More Thinking) Figure out what you want: we want to keep going until we have doubled the balance So you might have used: (balance < TARGET) 50

51 < vs. <= (More Thinking) But consider, did you really mean: to have at least doubled Exactly twice as much would happen with a RATE of 100% - the loop should top then So the test must be (balance <= TARGET) 51

52 The for Loop 52

53 The for Loop for (initialization; check; update) statements The check is some kind of test (the same as the condition in the while loop) It is usually used to cause the statements to happen a certain number of times. 53

54 The for Loop for (initialization; check; update) statements The statements are repeatedly executed until the check is false. 54

55 The for Loop for (initialization; check; update) statements The initialization is code that happens once, before the check is made, in order to set up for counting how many times the statements will happen. 55

56 The for Loop for (initialization; check; update) statements The update is code that causes the check to eventually become false. Usually it s incrementing or decrementing the loop variable. 56

57 The for Loop Is Better than while for Doing Certain Things Consider this code which write the values 1 through 10 on the screen: int count = 1; // Initialize the counter while (count <= 10) // Check the counter cout << count << endl; count++; // Update the counter initialization check statements update 57

58 The for Loop Is Better than while for Doing Certain Things Doing something a certain number of times or causing a variable to take on a sequence of values is so common, C++ has a statement just for that: for (int count = 1; count <= 10; count++) cout << count << endl; initialization check statements update 58

59 Execution of a for Statement Consider this for statement: int count; for (counter = 1; count <= 10; counter++) cout << counter << endl; 59

60 60

61 Scope of the Loop Variable Part of the for or Not? The loop variable when defined as part of the for statement cannot be used before or after the for statement it only exists as part of the for statement and should not need to be used anywhere else in a program. 61

62 Solving a Problem with a for Statement Earlier we determined the number of years it would take to (at least) double our balance. Now let s see the interest in action: We want to print the balance of our savings account over a five-year period. The over a five-year period indicates that a for loop should be used. Because we know how many times the statements must be executed we choose a for loop. 62

63 Solving a Problem with a for Statement The output should look something like this: 63

64 The for Loop Flowchart of the investment calculation s while loop Easily written using a for loop 64

65 Solving a Problem with a for Statement Two statements should happen five times. So use a for statement. They are: update balance print year and balance for (int year = 1; year <= nyears; year++) // update balance // print year and balance 65

66 The Modified Investment Program Using a for Loop #include <iostream> #include <iomanip> using namespace std; int main() const double RATE = 5; const double INITIAL_BALANCE = 10000; double balance = INITIAL_BALANCE; int nyears; cout << "Enter number of years: "; cin >> nyears; cout << fixed << setprecision(2); for (int year = 1; year <= nyears; year++) balance = balance * (1 + RATE / 100); cout << setw(4) << year << setw(10) << balance << endl; return 0; 66

67 The Modified Investment Program Using a for Loop A run of the program: Enter number of years:

68 More for Examples For each of the following, do a hand-trace. 68

69 Example of Normal Execution for loop to hand-trace for (int i = 0;i <= 5;i++) cout << i << " "; What is the output? 69

70 Example of Normal Execution for loop for (int i = 0;i <= 5;i++) cout << i << " "; The output Note that the output statement is executed six times, not five 70

71 Example of Normal Execution Going in the Other Direction for loop to hand-trace What is the output? for (int i = 5;i >= 0;i--) cout << i << " "; 71

72 Example of Normal Execution Going in the Other Direction Again six executions of the output statement occur. for loop for (int i = 5;i >= 0;i--) cout << i << " "; The output

73 Example of Normal Execution Taking Bigger Steps for loop to hand-trace for (int i = 0; i < 9; i += 2) cout << i << " "; What is the output?

74 Example of Normal Execution Taking Bigger Steps for loop for (int i = 0; i < 9; i += 2) cout << i << " "; The output The step value can be added to or subtracted from the loop variable. Here the value 2 is added. There are only 5 iterations, though. 74

75 Infinite Loops Can Occur in for Statements The danger of using == for loop to hand-trace for (int i = 0; i!= 9; i += 2) cout << i << " "; and/or!= What is the output? 75

76 Infinite Loops Can Occur in for Statements = = and!= are best avoided in the check of a for statement for loop for (int i = 0; i!= 9; i += 2) cout << i << " "; The output never ends

77 Example of Normal Execution Taking Even Bigger Steps for loop to hand-trace for (int i = 1; i <= 20; i *= 2) cout << i << " "; What is the output? The update can be any expression 77

78 Example of Normal Execution Taking Even Bigger Steps for loop for (int i = 1; i <= 20; i *= 2) cout << i << " "; The output The step can be multiplicative or any valid expression 78

79 The do Loop The while loop s condition test is the first thing that occurs in its execution. The do loop (or do-while loop) has its condition tested only after at least one execution of the statements. 79

80 The do Loop This means that the do loop should be used only when the statements must be executed before there is any knowledge of the condition. This also means that the do loop is the least used loop. 80

81 The do Loop What problems require something to have happened before the testing in a loop? Getting valid user input is often cited. Here is the flowchart for the problem in which the user is supposed to enter a value less than 100 and processing must not continue until they do. 81

82 The do Loop Here is the code: int value; do cout << "Enter a value < 100"; cin >> value; while (value >= 100); In this form, the user sees the same prompt each time until the enter valid input. 82

83 The do Loop In order to have a different, error prompt that the user sees only on invalid input, the initial prompt and input would be before a while loop: int value; cout << "Enter a value < 100"; cin >> value; while (value >= 100); cout << "Sorry, that is larger than 100\n" << "Try again: "; cin >> value; Notice what happens when the user gives valid input on the first attempt: nothing good. 83

84 Nested Loops For each hour, 60 minutes are processed a nested loop. 84

85 Nested Loops Nested loops are used mostly for data in tables as rows and columns. The processing across the columns is a loop, as you have seen before, nested inside a loop for going down the rows. Each row is processed similarly so design begins at that level. After writing a loop to process a generalized row, that loop, called the inner loop, is placed inside an outer loop. 85

86 Nested Loops Write a program to produce a table of powers. The output should be something like this: 86

87 Nested Loops The first step is to solve the nested loop. There are four columns and in each column we display the power. Using x to be the number of the row we are processing, we have (in pseudo-code): You would test that this works in your code before continuing. If you can t correctly print one row, why try printing lots of them? 87

88 Nested Loops Now, putting the inner loop into the whole process we have: (don t forget to indent, nestedly) 88

89 The Complete Program for Table of Powers #include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() const int NMAX = 4; const double XMAX = 10; // Print table header for (int n = 1; n <= NMAX; n++) cout << setw(10) << n; cout << endl; for (int n = 1; n <= NMAX; n++) cout << setw(10) << "x "; // print x cout << endl << endl; 89

90 The Complete Program for Table of Powers // Print table body for (double x = 1; x <= XMAX; x++) // Print table row for (int n = 1; n <= NMAX; n++) cout << setw(10) << pow(x, n); cout << endl; return 0; The program run would be: 90

91 More Nested Loop Examples The loop variables can have a value relationship. In this example the inner loop depends on the value of the outer loop. for (i = 1; i <= 4; i++) for (j = 1; j <= i; j++) cout << "*"; cout << endl; The output will be: * ** *** **** 91

92 More Nested Loop Examples for (i = 1; i <= 4; i++) for (j = 1; j <= i; j++) cout << "*"; cout << endl; j is the number of columns (or the line s length), which depends on the line number, i j stops at: i i i i line num. i 1 * i 2 * * i 3 * * * i 4 * * * * i represents the row number or the line number 92

93 More Nested Loop Examples In this example, the loop variables are still related, but the processing is a bit more complicated. for (i = 1; i <= 3; i++) for (j = 1; j <= 5; j++) if (i + j % 2 == 0) cout << "*"; else cout << " "; cout << endl; The output will be: * * * * * * * * 93

94 Processing Input When and/or How to Stop? or be stopped! 94

95 Processing Input When and/or How to Stop? We need to know, when getting input from a user, when they are done. One method is to hire a sentinel (as shown) or more correctly choose a value whose meaning is STOP! As long as there is a known range of valid data points, we can use a value not in it. 95

96 Processing Input When and/or How to Stop? We will write code to calculate the average of some salary values input by the user. How many will there be? That is the problem. We can t know. But we can use a sentinel value, as long as we tell the user to use it, to tell us when they are done. Since salaries are never negative, we can safely choose -1 as our sentinel value. 96

97 Processing Input When and/or How to Stop? In order to have a value to test, we will need to get the first input before the loop. The loop statements will process each non-sentinel value, and then get the next input. Suppose the user entered the sentinel value as the first input. Because averages involve division by the count of the inputs, we need to protect against dividing by zero. Using an if-else statement from Lecture 3 will do. 97

98 The Complete Salary Average Program #include <iostream> using namespace std; int main() double sum = 0; int count = 0; double salary = 0; // get all the inputs cout << "Enter salaries, -1 to finish: "; cin >> salary; while (salary!= -1) // process input sum = sum + salary; count++; // get next input cin >> salary; 98

99 The Complete Salary Average Program // process and display the average if (count > 0) double average = sum / count; cout << "Average salary: " << average << endl; else cout << "No data" << endl; return 0; A program run: Enter salaries, -1 to finish: Average salary: 20 99

100 Using Failed Input for Processing Sometimes is it easier and a bit more intuitive to ask the user to Hit Q to Quit instead or requiring the input of a sentinel value. Sometimes picking a sentinel value is simply impossible if any valid number is allowed, which number could be chosen? 100

101 Using Failed Input for Processing In the previous chapter we used cin.fail() to test if the most recent input failed. Note that if you intend to take more input from the keyboard after using failed input to end a loop, you must reset the keyboard with cin.clear(). 101

102 Using Failed Input for Processing If we introduce a bool variable to be used to test for a failed input, we can use cin.fail() to test for the input of a Q when we were expecting a number: 102

103 Using Failed Input for Processing cout << "Enter values, Q to quit: "; bool more = true; while (more) cin >> value; if (cin.fail()) more = false; else // process value here cin.clear() // reset if more input is to be taken 103

104 Using Failed Input for Processing Using a bool variable in this way is disliked by many programmers. Why? cin.fail is set when >> fails. This allows the use of an input itself to be used as the test for failure. Again note that if you intend to take more input from the keyboard, you must reset the keyboard with cin.clear. 104

105 Using Failed Input for Processing Using the input attempt directly we have: cout << "Enter values, Q to quit: "; while (cin >> value) // process value here cin.clear(); 105

106 Chapter Summary Loops execute a block of code repeatedly while a condition remains true. The for loop is used when the loop body must be executed at least once. Nested loops are commonly used for processing tabular structures. A sentinel value denotes the end of data set, but it is not part of the data. We can use a Boolean variable to control a loop. Set the variable to true before entering the loop, then set it to false to leave the loop. 106

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved Chapter Four: Loops Slides by Evan Gallagher The Three Loops in C++ C++ has these three looping statements: while for do The while Loop while (condition) { statements } The condition is some kind of test

More information

Chapter Four: Loops II

Chapter Four: Loops II Chapter Four: Loops II Slides by Evan Gallagher & Nikolay Kirov Chapter Goals To understand nested loops To implement programs that read and process data sets To use a computer for simulations Processing

More information

do { statements } while (condition);

do { statements } while (condition); Topic 4 1. The while loop 2. Problem solving: hand-tracing 3. The for loop 4. The do loop 5. Processing input 6. Problem solving: storyboards 7. Common loop algorithms 8. Nested loops 9. Problem solving:

More information

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A. Islamic University of Gaza Computer Engineering Dept. C++ Programming For Industrial And Electrical Engineering By Instructor: Ruba A. Salamh Chapter Four: Loops 2 Chapter Goals To implement while, for

More information

Problem Solving: Storyboards for User Interaction

Problem Solving: Storyboards for User Interaction Topic 6 1. The while loop 2. Problem solving: hand-tracing 3. The for loop 4. The do loop 5. Processing input 6. Problem solving: storyboards 7. Common loop algorithms 8. Nested loops 9. Problem solving:

More information

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators Chapter 5: 5.1 Looping The Increment and Decrement Operators The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++;

More information

Chapter Goals. Contents LOOPS

Chapter Goals. Contents LOOPS CHAPTER 4 LOOPS Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30, 2011 Chapter Goals To implement while, for, and do loops To hand-trace the execution of a program To become familiar with common

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York CSc 10200 Introduc/on to Compu/ng Lecture 8 Edgardo Molina Fall 2011 City College of New York 18 The Null Statement Null statement Semicolon with nothing preceding it ; Do-nothing statement required for

More information

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

More information

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator. Chapter 5: Looping 5.1 The Increment and Decrement Operators Copyright 2009 Pearson Education, Inc. Copyright Publishing as Pearson 2009 Addison-Wesley Pearson Education, Inc. Publishing as Pearson Addison-Wesley

More information

Looping. Arizona State University 1

Looping. Arizona State University 1 Looping CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 5 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

C/C++ Programming Lecture 7 Name:

C/C++ Programming Lecture 7 Name: 1. The increment (++) and decrement (--) operators increase or decrease a variable s value by one, respectively. They are great if all you want to do is increment (or decrement) a variable: i++;. HOWEVER,

More information

Computer Programming. Basic Control Flow - Decisions. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Decisions. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Decisions Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To be able to implement decisions using if statements To learn

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

Unit 7. 'while' Loops

Unit 7. 'while' Loops 1 Unit 7 'while' Loops 2 Control Structures We need ways of making decisions in our program To repeat code until we want it to stop To only execute certain code if a condition is true To execute one segment

More information

Java Coding 3. Over & over again!

Java Coding 3. Over & over again! Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

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

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

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester Programming Language Control Structures: Repetition (while) Eng. Anis Nazer Second Semester 2017-2018 Repetition statements Control statements change the order which statements are executed Selection :

More information

Increment and the While. Class 15

Increment and the While. Class 15 Increment and the While Class 15 Increment and Decrement Operators Increment and Decrement Increase or decrease a value by one, respectively. the most common operation in all of programming is to increment

More information

Chapter 5: Loops and Files

Chapter 5: Loops and Files Chapter 5: Loops and Files 5.1 The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1;

More information

Ch 6. Functions. Example: function calls function

Ch 6. Functions. Example: function calls function Ch 6. Functions Part 2 CS 1428 Fall 2011 Jill Seaman Lecture 21 1 Example: function calls function void deeper() { cout

More information

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab. University of Technology Laser & Optoelectronics Engineering Department C++ Lab. Fifth week Control Structures A program is usually not limited to a linear sequence of instructions. During its process

More information

Why Is Repetition Needed?

Why Is Repetition Needed? Why Is Repetition Needed? Repetition allows efficient use of variables. It lets you process many values using a small number of variables. For example, to add five numbers: Inefficient way: Declare a variable

More information

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points) Name Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Relational Expression Iteration Counter Count-controlled loop Loop Flow

More information

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1 ELEC 330 1 Structured Programming Control Structures ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne Algorithm Development Conditional Expressions Selection Statements Loops 206_C3

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

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1 Chapter 5: Loops and Files The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; ++ can be used before (prefix) or after (postfix)

More information

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;

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

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1 Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1 Chapter 6 : (Control Structure- Repetition) Using Decrement or Increment While Loop Do-While Loop FOR Loop Nested Loop

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

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh C++ PROGRAMMING For Industrial And Electrical Engineering Instructor: Ruba A. Salamh CHAPTER TWO: Fundamental Data Types Chapter Goals In this chapter, you will learn how to work with numbers and text,

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

(Refer Slide Time: 00:26)

(Refer Slide Time: 00:26) Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute Technology, Madras Module 07 Lecture 07 Contents Repetitive statements

More information

LAB: WHILE LOOPS IN C++

LAB: WHILE LOOPS IN C++ LAB: WHILE LOOPS IN C++ MODULE 2 JEFFREY A. STONE and TRICIA K. CLARK COPYRIGHT 2014 VERSION 4.0 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 2 Introduction This lab will provide students with an introduction

More information

Score score < score < score < 65 Score < 50

Score score < score < score < 65 Score < 50 What if we need to write a code segment to assign letter grades based on exam scores according to the following rules. Write this using if-only. How to use if-else correctly in this example? score Score

More information

The American University in Cairo Computer Science & Engineering Department CSCE Dr. KHALIL Exam II Spring 2010

The American University in Cairo Computer Science & Engineering Department CSCE Dr. KHALIL Exam II Spring 2010 The American University in Cairo Computer Science & Engineering Department CSCE 106-08 Dr. KHALIL Exam II Spring 2010 Last Name :... ID:... First Name:... Form - I EXAMINATION INSTRUCTIONS * Do not turn

More information

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture 18 Switch Statement (Contd.) And Introduction to

More information

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011 The American University in Cairo Department of Computer Science & Engineering CSCI 106-07&09 Dr. KHALIL Exam-I Fall 2011 Last Name :... ID:... First Name:... Form I Section No.: EXAMINATION INSTRUCTIONS

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering Lecture 3 Winter 2011/12 Oct 25 Visual C++: Problems and Solutions New section on web page (scroll down)

More information

Loops and Files. of do-while loop

Loops and Files. of do-while loop L E S S O N S E T 5 Loops and Files PURPOSE PROCEDURE 1. To introduce counter and event controlled loops 2. To work with the while loop 3. To introduce the do-while loop 4. To work with the for loop 5.

More information

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping). 1 causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping). Before considering specifics we define some general terms that

More information

Loops / Repetition Statements

Loops / Repetition Statements Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for

More information

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. 1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format

More information

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3 Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3 Ziad Matni Dept. of Computer Science, UCSB A Word About Registration for CS16 FOR THOSE OF YOU NOT YET REGISTERED:

More information

Chapter 3 Problem Solving and the Computer

Chapter 3 Problem Solving and the Computer Chapter 3 Problem Solving and the Computer An algorithm is a step-by-step operations that the CPU must execute in order to solve a problem, or to perform that task. A program is the specification of an

More information

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017 Loops! Loops! Loops! Lecture 5 COP 3014 Fall 2017 September 25, 2017 Repetition Statements Repetition statements are called loops, and are used to repeat the same code mulitple times in succession. The

More information

cs1114 REVIEW of details test closed laptop period

cs1114 REVIEW of details test closed laptop period python details DOES NOT COVER FUNCTIONS!!! This is a sample of some of the things that you are responsible for do not believe that if you know only the things on this test that they will get an A on any

More information

LOOPS. Repetition using the while statement

LOOPS. Repetition using the while statement 1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

More information

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6 Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6 Ziad Matni Dept. of Computer Science, UCSB Announcements Homework #5 due today Lab #3

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

To become familiar with array manipulation, searching, and sorting.

To become familiar with array manipulation, searching, and sorting. ELECTRICAL AND COMPUTER ENGINEERING 06-88-211: COMPUTER AIDED ANALYSIS LABORATORY EXPERIMENT #2: INTRODUCTION TO ARRAYS SID: OBJECTIVE: SECTIONS: Total Mark (out of 20): To become familiar with array manipulation,

More information

Lab 10: Alternate Controls

Lab 10: Alternate Controls _ Unit 2: Programming in C++, pages 1 of 8 Department of Computer and Mathematical Sciences CS 1410 Intro to Computer Science with C++ 9 Objectives: Lab 10: Alternate Controls The objective of this lab

More information

The while Loop 4/6/16 4

The while Loop 4/6/16 4 Chapter 4: Loops Chapter Goals To implement while and for loops To hand-trace the execution of a program To become familiar with common loop algorithms To understand nested loops To implement programs

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

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

Chapter 17 - Notes Recursion

Chapter 17 - Notes Recursion Chapter 17 - Notes Recursion I. Recursive Definitions A. Recursion: The process of solving a problem by reducing it to smaller versions of itself. B. Recursive Function: A function that calls itself. C.

More information

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed? Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct and use countercontrolled, sentinel-controlled,

More information

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure Learning Objectives At the end of this chapter, student should be able to: Understand the requirement of a loop Understand the Loop Control Variable () Use increment (++) and decrement ( ) operators Program

More information

Lecture 7 Tao Wang 1

Lecture 7 Tao Wang 1 Lecture 7 Tao Wang 1 Objectives In this chapter, you will learn about: Interactive loop break and continue do-while for loop Common programming errors Scientists, Third Edition 2 while Loops while statement

More information

Controls Structure for Repetition

Controls Structure for Repetition Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power

More information

IST 297D Introduction to Application Programming Chapter 4 Problem Set. Name:

IST 297D Introduction to Application Programming Chapter 4 Problem Set. Name: IST 297D Introduction to Application Programming Chapter 4 Problem Set Name: 1. Write a Java program to compute the value of an investment over a number of years. Prompt the user to enter the amount of

More information

In this chapter you will learn:

In this chapter you will learn: 1 In this chapter you will learn: Essentials of counter-controlled repetition. Use for, while and do while to execute statements in program repeatedly. Use nested control statements in your program. 2

More information

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop

Topics. Introduction to Repetition Structures Often have to write code that performs the same task multiple times. Controlled Loop Topics C H A P T E R 4 Repetition Structures Introduction to Repetition Structures The for Loop: a Count- Sentinels Nested Loops Introduction to Repetition Structures Often have to write code that performs

More information

Today in CS161. Lecture #7. Learn about. Rewrite our First Program. Create new Graphics Demos. If and else statements. Using if and else statements

Today in CS161. Lecture #7. Learn about. Rewrite our First Program. Create new Graphics Demos. If and else statements. Using if and else statements Today in CS161 Lecture #7 Learn about If and else statements Rewrite our First Program Using if and else statements Create new Graphics Demos Using if and else statements CS161 Lecture #7 1 Selective Execution

More information

BITG 1233: Introduction to C++

BITG 1233: Introduction to C++ BITG 1233: Introduction to C++ 1 Learning Outcomes At the end of this lecture, you should be able to: Identify basic structure of C++ program (pg 3) Describe the concepts of : Character set. (pg 11) Token

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

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition) C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures

More information

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << The sum of the integers 1 to 10 is  << sum << endl; Debugging Some have said that any monkey can write a program the hard part is debugging it. While this is somewhat oversimplifying the difficult process of writing a program, it is sometimes more time

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

Chapter 3. More Flow of Control

Chapter 3. More Flow of Control 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-2 Flow Of Control Flow of control refers to the

More information

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 14) 28 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

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

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 14) 28 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

LECTURE 5 Control Structures Part 2

LECTURE 5 Control Structures Part 2 LECTURE 5 Control Structures Part 2 REPETITION STATEMENTS Repetition statements are called loops, and are used to repeat the same code multiple times in succession. The number of repetitions is based on

More information

Getting started with C++ (Part 2)

Getting started with C++ (Part 2) Getting started with C++ (Part 2) CS427: Elements of Software Engineering Lecture 2.2 11am, 16 Jan 2012 CS427 Getting started with C++ (Part 2) 1/22 Outline 1 Recall from last week... 2 Recall: Output

More information

Introduction to Programming

Introduction to Programming Introduction to Programming Summer Term 2015 Dr. Adrian Kacso, Univ. Siegen adriana.dkacsoa@duni-siegena.de Tel.: 0271/740-3966, Office: H-B 8406 State: May 6, 2015 Betriebssysteme / verteilte Systeme

More information

EP241 Computing Programming

EP241 Computing Programming EP241 Computing Programming Topic 4 Loops Department of Engineering Physics University of Gaziantep Course web page www.gantep.edu.tr/~bingul/ep241 Sep 2013 Sayfa 1 Introduction Loops are control structures

More information

Name Section: M/W T/TH Number Definition Matching (8 Points)

Name Section: M/W T/TH Number Definition Matching (8 Points) Name Section: M/W T/TH Number Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Iteration Counter Event Counter Loop Abstract Step

More information

Repetition, Looping. While Loop

Repetition, Looping. While Loop Repetition, Looping Last time we looked at how to use if-then statements to control the flow of a program. In this section we will look at different ways to repeat blocks of statements. Such repetitions

More information

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x ); Chapter 4 Loops Sections Pages Review Questions Programming Exercises 4.1 4.7, 4.9 4.10 104 117, 122 128 2 9, 11 13,15 16,18 19,21 2,4,6,8,10,12,14,18,20,24,26,28,30,38 Loops Loops are used to make a program

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 5: Control Structures II (Repetition) Why Is Repetition Needed? Repetition allows you to efficiently use variables Can input,

More information

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration) Week 7: Advanced Loops while Loops in C++ (review) while (expression) may be a compound (a block: {s) Gaddis: 5.7-12 CS 1428 Fall 2015 Jill Seaman 1 for if expression is true, is executed, repeat equivalent

More information

3 The L oop Control Structure

3 The L oop Control Structure 3 The L oop Control Structure Loops The while Loop Tips and Traps More Operators The for Loop Nesting of Loops Multiple Initialisations in the for Loop The Odd Loop The break Statement The continue Statement

More information

Notes on the 2008 Exam

Notes on the 2008 Exam Notes on the 2008 Exam A hastily compiled review of this year s exam. Apologies if there are errors. Please also read notes on previous years exams especially the first set of notes. Question 1 Question

More information

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

PIC 10A Flow control. Ernest Ryu UCLA Mathematics PIC 10A Flow control Ernest Ryu UCLA Mathematics If statement An if statement conditionally executes a block of code. # include < iostream > using namespace std ; int main () { double d1; cin >> d1; if

More information

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

Review. Modules. CS 151 Review #6. Sample Program 6.1a: Review Modules A key element of structured (well organized and documented) programs is their modularity: the breaking of code into small units. These units, or modules, that do not return a value are called

More information

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

1) What of the following sets of values for A, B, C, and D would cause the string one to be printed? Instructions: This homework assignment focuses primarily on some of the basic syntax and semantics of C++. The answers to the following questions can be determined from Chapters 6 and 7 of the lecture

More information

CS112 Lecture: Repetition Statements

CS112 Lecture: Repetition Statements CS112 Lecture: Repetition Statements Objectives: Last revised 2/18/05 1. To explain the general form of the java while loop 2. To introduce and motivate the java do.. while loop 3. To explain the general

More information

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions.

6 Functions. 6.1 Focus on Software Engineering: Modular Programming TOPICS. CONCEPT: A program may be broken up into manageable functions. 6 Functions TOPICS 6.1 Focus on Software Engineering: Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5 Passing Data by Value 6.6 Focus

More information

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3 Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3 Ziad Matni Dept. of Computer Science, UCSB Compiling Programs in C++ Input and Output Streams Simple Flow

More information

Lecture Transcript While and Do While Statements in C++

Lecture Transcript While and Do While Statements in C++ Lecture Transcript While and Do While Statements in C++ Hello and welcome back. In this lecture we are going to look at the while and do...while iteration statements in C++. Here is a quick recap of some

More information

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Outline 13.1 Test-Driving the Salary Survey Application 13.2 Introducing Arrays 13.3 Declaring and Initializing Arrays 13.4 Constructing

More information

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5. Week 2: Console I/O and Operators Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.1) CS 1428 Fall 2014 Jill Seaman 1 2.14 Arithmetic Operators An operator is a symbol that tells the computer to perform specific

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

Looping and Counting. Lecture 3 Hartmut Kaiser hkaiser/fall_2012/csc1254.html

Looping and Counting. Lecture 3 Hartmut Kaiser  hkaiser/fall_2012/csc1254.html Looping and Counting Lecture 3 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html Abstract First we ll discuss types and type safety. Then we will modify the program

More information