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

Size: px
Start display at page:

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

Transcription

1 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 The while Control Structure Count-Controlled while Loops Event-Controlled while Loops Sentinel-Controlled while Loops 1.6 Infinite Loops 1.7 of the for Control Structure Example for Control Structure Headers Declarations in the for Header 1.8 Equivalence of for and while Loops 1.9 Floating-Point Counter Variables 1.10 Nested Loops This lab will illustrate looping and the use of the C++ while and for control structures. Topics Covered in this Lab: count-controlled looping event-controlled looping sentinels while control structure for control structure declaring variables in for control structures problems with using double-type looping variables Questions Answered in this Lab: How are floating point variables used in stopping conditions? How is an input sentinel chosen? Why do programs sometimes fail to halt? What are the parts of a for control structure header? What is the connection between the for control structure and the while control structure? What are some common errors in constructing for loops? Demonstrable Skills Acquired in this Lab: understand stopping conditions for both count- and event-controlled loops ability to construct while loops ability to construct appropriate for loops understanding of when to use for loops Three Types of Program Control There are three programming constructs sufficient for the solution of any programming problem: sequence, selection, and repetition. The hello, world type of program illustrates the sequence construct; one statement executes after another in the order written. The previous lab examined selections with the if and if-else control structures. This lab introduces repetition, which is what allows the speed of a computer to be exploited by performing the same task many times. Two Types of Repetition From a logical standpoint, there are two types of repetition: event-controlled and count-controlled. Event-controlled repetition continues until some specific event occurs. When a telephone number is looked up in a directory, the search stops when the corresponding name is either found or determined not to be in the directory; the specific quantity of names and numbers to be examined will not be known beforehand. A program may be designed to execute until the user indicates finished with a y (yes) or n (no). (Incidentally, the indication in this case is a sentinel value and this type of event-controlled loop is often referred to as a sentinel-controlled loop.) Count-controlled loops execute a specific number of times which is known in advance of the loop's start. Many mathematical formulae involve summations or products of a known number of values; for example, Horner's method for evaluating a polynomial of degree requires one multiplication and one addition for each of the degrees. Other more mundane count-controlled loops may be based on seven days in a week, twelve items in a dozen, or a known number of students enrolled in a course. Three Structures for Looping in C++ With respect to C++ syntax, there are three looping structures: while, for, and do-while. Each of these looping structures has a purpose depending on the context where repetition occurs in a program; each of these structures can be used for either event- or count-controlled repetition. The three C++ loops are categorized as pre-test and post-test based on whether they perform their test before or after the body of the loop. The while control structure is a pre-test loop and the do-while control structure is a post-test loop; these two structures are typically associated with event-controlled iteration. The for control structure is another pre-test loop, but it is typically used for count-controlled iteration. In this lab the while and for control structures will be examined; the do-while control structure will be considered in a subsequent lab. The while Control Structure The basic syntax of the while control structure is as follows:

2 while (CONDITION) STATEMENT; // body The condition given by CONDITION may utilize any combination of relational, logical, arithmetic, and/or other operators in C++. The while control structure will repeat the body of the loop (the STATEMENT) as long as the condition is true (non-zero). If the condition ever becomes false (zero), the repetition ends and execution continues at the statement following the while loop. In the example above, the loop body is only one statement. Generally, it is desired to repeat more than one statement; to do so, use a compound statement, or block of code, for the loop body. Recall that a compound statement uses the curly braces and to enclose any number of statements. Count-controlled and event-controlled examples will be given in subsequent sections. Count-Controlled while Loops When it is known in advance how many times a task is to be performed, a count-controlled loop is used. Much as a child might count on its fingers to keep track of something, a computer uses a counter variable. Count-controlled loops have three parts, each of which involves the counter: initialization of the counter, testing of the counter, and update of the counter. The extended syntax for the while control structure shown below incorporates the three parts of the count-controlled loop. while (CONDITION) Consider the following example. int factorial = 1; int i = 1; // c-c loop pt1: initialize while (i <= 4) // c-c loop pt2: test factorial = factorial * i; i++; // c-c loop pt3: update (increment) cout << factorial << endl; Here, the while control structure will continue repeating the body of the loop as long as the value of i is less than four. The loop body is the compound statement including the statements factorial = factorial * i and i++. If the above statements are executed, what is the value of factorial when the execution ends? Carefully step through this loop to discover what happens. step execution i factorial 1 factorial = i = Is (i <= 4)? Yes factorial = factorial * i i Is (i <= 4)? Yes factorial = factorial * i i Is (i <= 4)? Yes factorial = factorial * i i Is (i <= 4)? Yes factorial = factorial * i i Is (i <= 4)? No 5 24 Notice that the loop body was executed three times and the condition was tested four times for this repetition. In general, the condition is tested exactly one more time than the body of the loop is executed. If the test condition is changed to i <= n, what is a general formula for the value of factorial? Begin a C++ program in file sp05t.cpp. Construct a function main that will get input from the user to replace the constant value 4 used in the loop condition above and then display the value of factorial. Execute the program for different small input values: 5, 6, 7, etc.; this will help in working out the formula. Event-Controlled while Loops When it is not known in advance how many times a task is to be performed, an event-controlled loop is used. As an example, consider finding the next perfect square following a given number. For example, the next perfect square after 7 is 9, the next after 11 is 16, and the next after 24 is 25. Notice in each case that the distance from the given number to the perfect square is different; it is this characteristic that suggests the use of an event-controlled

3 loop. In order to find the next perfect square, one might start simplistically at one and count upwards, squaring numbers until a square is found bigger than the given value. Add the following code segment to function main and verify that it behaves as expected. cout << "Enter a number for which to find the next largest perfect square: "; int n; cin >> n; int sqroot = 1; // where would be another place to start? while (sqroot*sqroot < n) // sqroot is too small sqroot++; // get ready to try the next number cout << sqroot*sqroot << endl; Pay particular attention to the fact that a variable in the while's test (sqroot) is modified in the body of the loop (sqroot++). This observation must hold true for every event-controlled loop (and count-controlled loops, too); otherwise, the loop will never terminate. (This problem will be considered in more detail shortly.) The next smallest perfect square is defined similarly. Examples would include a result of 4 for 7, a result of 9 for 15, and a result of 16 for 17. One could start at a large value and try successive smaller values until the desired result is found. Sentinel-Controlled while Loops An event-controlled loop which repeats until a particular value is encountered in the data being read is commonly referred to as a sentinel-controlled loop. The particular value is the sentinel value; the sentinel value should be a value that would not be considered a valid data value for the data being read. Consider the following syntax change from a count-controlled loop to a sentinel-controlled loop. PROMPT AND READ FIRST DATA VALUE; while (CONDITION) => while (DATA!= SENTINEL VALUE) PROMPT AND READ NEXT DATA VALUE; The initialization step for a sentinel-controlled loop is to prompt the user for data and get the keyboard input. (If the input was from a file, the prompt would not be needed, only the read.) The CONDITION is the verification that the data read was not the sentinel value. The UPDATE becomes the prompt and subsequent read of the next data value. Sentinel-controlled loops often have the following format. Pseudocode cout << "Enter data (sentinel value to end): "; cin >> data; while (data!= sentinel value) // process data cout << "Enter data (sentinel value to end): "; cin >> data; Note that a value is read prior to the initial test of the while loop; subsequent values are read at the bottom of the loop, immediately prior to the return to the top of the loop and another test. All data is tested prior to being used in any calculations. The last piece of data read is not processed; consequently, reads are required for meaningful pieces of data. Beginning students are often troubled by the repetition of the cout-cin pair, sometimes trying to replace them with logic which is inevitably more complicated. Suffice it to say that there simply is no more succinct manner in which to accomplish this task. As an example of a sentinel-controlled loop, add the following to function main to read a series of test scores and determine their average. int sum = 0; // total of all scores int numberofscores = 0; // quantity of scores int score; // individual exam cout << "Enter a test score (-1 to end): "; cin >> score; while (score!= -1) // test for sentinel sum += score; // running total numberofscores++; // count cout << "Enter a test score (-1 to end): "; cin >> score; double average = static_cast <double> (sum) / numberofscores; The sentinel value for this loop is -1, chosen because exam scores are generally non-negative. The variables sum and numberofscores are both naturally integers; simple division with them in C++ would result in an integer quotient as well. However, the average is by its nature a floating-point quantity. Consequently, the numerator is cast to become a floating-point dividend prior to what must then be a floating-point division and quotient. Execute the program with some values for which the results are easily predicable: 71, 72, 73 or 60, 70, 80, 90. The pre-test nature of the while loop allows for the possibility that the loop body may never be executed at all. In the example at hand, the first score entered could be -1. In this case, there will be no meaningful average; worse, numberofscores remains zero which will result in an undefined quotient. Any time division involves a variable as divisor, the division should be protected from a divisor of zero. Replace the last line of the preceding segment with the following. if (numberofscores > 0) double average = static_cast <double> (sum) / numberofscores; cout << "The average of the " << numberofscores << " scores is " << average << ".\n";

4 else cout << "No scores were entered!\n"; Execute the program again to test this addition. Modify the program to read the exam scores from a file. An example data file might contain the following Test your code with the following data: Or it might contain Test your code with the following data: Infinite Loops One problem with looping is the so-called infinite loop, a loop with a condition that is always true. The loop body must always act to alter one or more of the variables involved in the condition of the loop. If the condition never changes then the loop will continue executing. If your program enters an infinite loop then it will never exit. So, how do you get the command prompt back so that you can fix the error and recompile your program? The key combination ctrl-c (which means hold down the ctrl key and then hit the c key) will kill the current program that is running on the command line. This command works in Windows, Unix, and Mac OS X. /current/directory $./sp05 I've fallen and I can't get up!... Hit ctrl-c to kill the stuck program. An accidental infinite loop is illustrated in the following example. int i = 1; while (j < 10) cout << j; i++; In this case, the programmer inadvertently based the termination of the loop upon a condition which is unaffected by the loop. Said another way, condition variable j is not modified in the body of the loop. This problem appears in many forms, some as simple as a typographical error. Here is another example. i = 100; while (i > 10); i = i - 1; This is a problem that is common, even among more seasoned programmers. What problem causes the infinite loop? It would seem that the meaning of the loop is clear, but the semicolon at the end of the condition ends the loop; the loop body is thus empty. The code reformatted to illustrate the real meaning is as follows. i = 100; while (i > 10) ; // empty statement i = i - 1; // will execute once after loop ends Since variable i is never altered by the body of the loop it retains the value of 100, which is greater than 10, and so the loop continues indefinitely. The code can be fixed by removing the extra semicolon at the end of the while condition. The semicolon is not placed at the end of every line of code; it is meant to terminate statements, each of which may extend through multiple lines. of the for Control Structure The for construct is especially well-suited for count-controlled loops. In count-controlled loops, the number of executions of the loop body is known before the loop body is executed the first time. As will be seen, the very format of the for loop suggests count-controlled repetition. As a general rule, use while for event-controlled loops, such as sentinel-controlled loops, and for with count-controlled loops. Consistency in this will make programs that much more readable and maintainable. Here is an example of the syntax of the for control structure. for ( TEST; UPDATE) An example for loop that increments through pages one through six.

5 for (int page = 1; page <= 6; page++) // header: initialize, test & update cout << "page " << page << endl; // loop body The for control structure is comprised of two parts, the header and the body; this much is the same as for the while control structure. The for control structure header in turn has three parts, each a C++ statement, separated by semicolons: initialize, test, and update. 1. Initialize: Initialization occurs once, as the first (preliminary) step in executing the for loop, before the loop begins repeating. This statement should be used to initialize the loop variable used in the test part of the header. In general, this variable will count the number of times through the loop. As will be seen, this variable may or may not appear in the loop body. 2. Test: After initialization, the test expression is then evaluated repeatedly; each time it is determined to be true (nonzero), the loop body is executed. The for loop execution ends the first time the test expression is found to be false (zero). Note that the expression is evaluated before each execution of the loop, exactly as is done for the while loop. In counting loops, this test will compare the loop variable against some limit. In the above example, the loop continues as long as the loop variable page is less than seven. How many times does the above loop body execute? 3. Update: Immediately after each execution of the loop body (and thus just prior to the next evaluation of the test expression), the loop control update is performed. In most iterative or counting loops, the loop variable needs to be incremented. In the example above, the loop variable page is incremented by one before it is tested. It is also possible to count down by using a decrement here or count by more than one using the += operator. Add the for loop above and execute the program; observe that the numbers one through six are displayed, as one would expect. A common mistake when constructing for loops is to use a comma in place of a semicolon. Change the semicolon following the initialization in the program to a comma and recompile the program. Example for Control Structure Headers The for control structure header is very flexible; here are several different for loop headers, some good and some not so good. for (i = 1; i <= 100; i++) // count naturally through 100 This header is much like the first example, except that the loop variable (or counter) starts at one and ends at one hundred. for (i = 100; i > 0; i--) // count down This header counts from one hundred down to one by decrementing the count variable instead of incrementing. for (int i = 0; i < 10; ++i) // preincrement ++; any difference? This header illustrates the ability to declare the looping variables in the header. According to the defined standard for C++, the looping variable goes out of scope at the end of the for body; this means that a loop variable declared this way does not exist outside the body of the loop. This will be considered again in the next section. for (i=0,j=1; j <= 100; j=i+j,i=j-i) // asking for trouble This header uses commas to allow more than one statement in the initialization and increment parts. In fact, the increments are dependent on the previous values of the variables. Such dense loop headers should be avoided, as they lead to confusion and code that is difficult to maintain. (Try to determine what the values of these loop variables are.) for (j = -5; j <= 42; j+=2) // count by two This header sets different loop variable bounds and increments the loop variable by two instead of one. for (;;) The missing statements in this header are empty statements in C++; an empty condition is treated as being true, and since it can never become false, an infinite loop results. A more common intentional infinite loop uses the while loop with a header such as while(1) or while(true). Declarations in the for Header As mentioned above, variables can be declared inside the for loop header itself. Doing so can be useful when the only purpose of the variable is to count the number of iterations of the loop. Why clutter up the rest of the program with these variables when they serve no purpose outside the loop? Extend the program's function main to contain the following and execute it. for (int i = 1; i <= 3; i++) cout << "loop 1: i = " << i << endl; for (int i = 11; i < 13; i++) cout << "loop 2: i = " << i << endl; According to the C++ standard, which describes how C++ is supposed to behave, the for loops above result in a variable named i being declared within the scope of the for loop. Equivalence of for and while Loops It is interesting to note that since the for loop and the while loop are both pre-test loops, any for loop can be written as a while loop and vice versa. The following illustrates the conversion between a for and a while loop. for ( TEST; UPDATE) <==> while (TEST) Notice this follows the discussion earlier about the parts of the for loop header. The for control structure initializes only once before the loop, the condition is tested before each execution of the body of the loop, and the increment is done at the end of the loop prior to the next test. As suggested above, any while loop can also be written as a for loop, again due to the fact that both are pre-test loops.

6 while (TEST) <==> for ( ; TEST; ) Observe that the for loop's variable initialization and increment are omitted from the header. As noted earlier, C++ considers the missing statements to be empty statements and will still execute the for loop. Extend function main with a while loop corresponding to each one of the for loops of the section Example for Control Structure Headers. Let the body of each loop display the content of the tested variable; the last (infinite) loop should be omitted. Floating-Point Counter Variables A different kind of problem can occur when using float or double loop variables. Consider the following loop. for (double x = 0; x!= 1; x += 0.10) cout << x << endl; From inspection, one might expect the numbers to look like the following. 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 Add this loop to function main and run it. The computer goes into what appears to be an infinite loop. Why did this occur? The answer lies in the computer representation of decimal values. Decimal numbers are exactly what "decimal" advertises: base 10 (for which the digits are 0 through 9). Computers inherently work in base 2 (for which the digits are restricted to 0 and 1); computers are often able to hide base 2 by converting everything to base 10, but the conversions are not always perfect. To avoid this type of problem, use a less-demanding test (which the conversion will be able to pass). The previous program could be made to work by examining the absolute value of the difference between x and 1; when the difference becomes small, positive or negative, x can be considered close enough to 1. The absolute value function in C++ is fabs, and it requires that the cmath header file be included (like iostream, although no using is necessary). Use the multi-line comment delimiters /* and */ to comment out the infinite loop recently added to the program. Extend the program as follows. for (double x = 0; fabs (x - 1) > 0.001; x += 0.10) cout << x << endl; Devise another test to stop the loop when x gets close to one; this test should not use the fabs function. Nested Loops When loops are placed inside one another, they are said to be nested. To illustrate how for loops are nested, extend function main to ask the user for the number of students who made an 'A' on the last test. int numberofas; cout << "Enter the number of 'A's on the last test: "; cin >> numberofas; Next, write a count-controlled loop using for that will print a row of asterisks equal in length to the number of 'A's. for (int i = 1; i <= numberofas; i++) cout << "*"; When this sequence is working successfully, write another for loop around the sequence which will repeat the question and print rows of asterisks for each of the letter grades 'A' through 'F' (including 'E' for the moment). A for loop whose loop index is of type char can be used for this task; it would be initialized to 'A', tested against 'F', and incremented the same way an integer would be. for (char grade = 'A'; grade <= 'F'; grade++) int numberofgrade; cout << "Enter the number of '" << grade << "'s on the last test: "; cin >> numberofgrade; for (int i = 1; i <= numberofgrade; i++) cout << "*"; Note that an if control structure will be required to prevent the question from being asked for the non-existent grade 'E'. Add this if control structure now. Modify this program so that it asks for the quantity of all five grades before displaying any asterisks. Two separate loops will be required: one for reading quantities and the other for displaying asterisks. A if-else chain will be needed inside each for loop in order to access the correct counter. You will need to use a technique similar to the one you employed in the previous section to ignore the 'E' grade. Pseudocode int numberofas = 0; // etc. for // grade = 'A' to 'F'

7 cout << "Enter the number of '" << grade << "'s on the last test: "; if (grade == 'A') cin >> numberofas; else if // etc. // end for for // grade = 'A' to 'F' cout << grade << ": "; if (grade == 'A') for // i = 1 to numberofas cout << "*"; else if // etc. // end for Note: Additional refinements will be made to this task in a future tutorial.

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

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

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

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

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

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

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

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

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

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

*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

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

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

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

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 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

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

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept. EEE-117 COMPUTER PROGRAMMING Control Structures Conditional Statements Today s s Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical

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

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

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

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

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

CS112 Lecture: Loops

CS112 Lecture: Loops CS112 Lecture: Loops Objectives: Last revised 3/11/08 1. To introduce some while loop patterns 2. To introduce and motivate the java do.. while loop 3. To review the general form of the java for loop.

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

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

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

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

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

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

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

More information

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1 CSE123 LECTURE 3-1 Program Design and Control Structures Repetitions (Loops) 1-1 The Essentials of Repetition Loop Group of instructions computer executes repeatedly while some condition remains true Counter-controlled

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

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

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

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

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

Chapter 5: Control Structures II (Repetition)

Chapter 5: Control Structures II (Repetition) Chapter 5: Control Structures II (Repetition) 1 Objectives Learn about repetition (looping) control structures Explore how to construct and use count-controlled, sentinel-controlled, flag-controlled, and

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

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

L o o p s. for(initializing expression; control expression; step expression) { one or more statements } L o o p s Objective #1: Explain the importance of loops in programs. In order to write a non trivial computer program, you almost always need to use one or more loops. Loops allow your program to repeat

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

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

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

Fundamentals of Programming Session 7

Fundamentals of Programming Session 7 Fundamentals of Programming Session 7 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

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

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

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

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

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

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

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

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

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

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

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

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

A Look Back at Arithmetic Operators: the Increment and Decrement

A Look Back at Arithmetic Operators: the Increment and Decrement A Look Back at Arithmetic Operators: the Increment and Decrement Spring Semester 2016 Programming and Data Structure 27 Increment (++) and Decrement (--) Both of these are unary operators; they operate

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

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

Lab # 02. Basic Elements of C++ _ Part1

Lab # 02. Basic Elements of C++ _ Part1 Lab # 02 Basic Elements of C++ _ Part1 Lab Objectives: After performing this lab, the students should be able to: Become familiar with the basic components of a C++ program, including functions, special

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

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

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1

ADARSH VIDYA KENDRA NAGERCOIL COMPUTER SCIENCE. Grade: IX C++ PROGRAMMING. Department of Computer Science 1 NAGERCOIL COMPUTER SCIENCE Grade: IX C++ PROGRAMMING 1 C++ 1. Object Oriented Programming OOP is Object Oriented Programming. It was developed to overcome the flaws of the procedural approach to programming.

More information

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

More information

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection) C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection) Objectives In this chapter, you will: Learn about control structures Examine relational

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

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

Chapter 5: Control Structures

Chapter 5: Control Structures Chapter 5: Control Structures In this chapter you will learn about: Sequential structure Selection structure if if else switch Repetition Structure while do while for Continue and break statements S1 2017/18

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

Binomial pricer (1.1)

Binomial pricer (1.1) 1 Binomial pricer 1.1 Program shell 1.2 Entering data 1.3 Functions 1.4 Separate compilation 1.5 CRR pricer 1.6 Pointers 1.7 Function pointers 1.8 Taking stock In the binomial model the prices of assets

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

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

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

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2018 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Expressions and Operator Precedence

More information

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

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma. REVIEW cout Statement The cout statement invokes an output stream, which is a sequence of characters to be displayed to the screen. cout

More information

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva All copyrights reserved - KV NAD, Aluva Dinesh Kumar Ram PGT(CS) KV NAD Aluva Overview Looping Introduction While loops Syntax Examples Points to Observe Infinite Loops Examples using while loops do..

More information

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started Handout written by Julie Zelenski, Mehran Sahami, Robert Plummer, and Jerry Cain. After today s lecture, you should run home and read

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

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

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

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition Learn about repetition (looping) control structures Explore how to construct and use: o Counter-controlled

More information

The following expression causes a divide by zero error:

The following expression causes a divide by zero error: Chapter 2 - Test Questions These test questions are true-false, fill in the blank, multiple choice, and free form questions that may require code. The multiple choice questions may have more than one correct

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

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

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 4: Control Structures I (Selection) Control Structures A computer can proceed: In sequence Selectively (branch) - making

More information

Lecture 3 Tao Wang 1

Lecture 3 Tao Wang 1 Lecture 3 Tao Wang 1 Objectives In this chapter, you will learn about: Arithmetic operations Variables and declaration statements Program input using the cin object Common programming errors C++ for Engineers

More information

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl? Exercises with solutions. 1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl? #include b) What using statement do you always put at the top of

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

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski) Class 2: Variables and Memory Variables A variable is a value that is stored in memory It can be numeric or a character C++ needs to be told what type it is before it can store it in memory It also needs

More information

COMP-202 Unit 4: Programming with Iterations

COMP-202 Unit 4: Programming with Iterations COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

More information

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

C++ Programming Lecture 7 Control Structure I (Repetition) Part I C++ Programming Lecture 7 Control Structure I (Repetition) Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department while Repetition Structure I Repetition structure Programmer

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

Name SECTION: 12:45 2:20. True or False (12 Points)

Name SECTION: 12:45 2:20. True or False (12 Points) Name SECION: 12:45 2:20 rue or False (12 Points) 1. (12 pts) Circle for true and F for false: F a) Local identifiers have name precedence over global identifiers of the same name. F b) Local variables

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

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information