LAB: FOR LOOPS IN C++

Size: px
Start display at page:

Download "LAB: FOR LOOPS IN C++"

Transcription

1 LAB: FOR LOOPS IN C++ MODULE 2 JEFFREY A. STONE and TRICIA K. CLARK COPYRIGHT 2014 VERSION 4.0

2 PALMS MODULE 2 LAB: FOR LOOPS IN C++ 2 Introduction This lab will provide students with an introduction to the fundamentals of conditional repetition in the C++ programming language. The focus of this lab is on how to solve complex problems using the C++ for statement. At the end of this module, students will Be able to solve simple problems using C++ for statement Understand the structure of C++ for statement These exercises have two different types of answers. Some questions ask for answers to specific questions; you should collect these answers in a Microsoft Word document. Other exercises ask you to write code; for these exercises, structure your storage drive in the following manner. There should be a palms folder, and within that folder there should be a LabFor folder. All coding exercises (and related folders) for this lesson should be placed in the LabFor folder. As always, be sure to properly document your code. Consult the C++ Coding Guidelines document for proper coding standards. Use good design principles and design the solution before attempting to write code. All programs should make use of multiple functions besides main() (use the input/process/output cycle as your guide). Think about how each problem actually involves more than one subproblem. At a minimum, you must construct functions aligned with the input-process-output steps. Let s begin! Part #1: Counter-Driven Repetition in C++ The idea of repetition, repeating a set of statements until a condition becomes false, has many applications in computer programming. As a result, C++ provides us with several constructs we can use to do repetitive programming. We have see one such construct in (the while statement) and we will now focus on the for construct. The for construct allows us to do something called counter-driven repetition in a more compact manner. While loops provide for conditional repetition within a program, allowing you to specify a statement or sequence of statements that you want executed as long as some condition holds. Since a while loop is controlled by a condition, it is usually the case that the number of repetitions cannot be predicted ahead of time. In contrast, there are many problems involving repetition where the number of repetitions is known ahead of time. In these cases, some action must be carried out a certain number of times in order to complete a task. For example, suppose you wanted to sum the numbers from one to ten. You could do this by using a counter variable. A counter is a variable that keeps track of the number of occurrences

3 PALMS MODULE 2 LAB: FOR LOOPS IN C++ 3 of some event. A common use of counters is to keep track of the number of times a loop has executed, and so control the number of repetitions. For example, in the code below, we use a counter to ensure we only add the numbers from one to ten, inclusive. int count = 1, sum = 0; while (count <= 10) sum = sum + count; count = count + 1 The variable count is initialized to 1, signifying that no summation has been made yet. During each pass through the loop, the current value of the count variable is added to the value of sum. Afterwards, the value of count is incremented accordingly. When the count finally reaches 11, the loop test will fail and the loop will terminate. For Loops The above code is an example of a counter-driven loop, one whose number of repetitions is controlled by a counter. Counter driven loops always involve three components: 1. Initialization of the counter variable to a starting value. 2. Testing the counter variable for a terminating condition. 3. Modifying the value of the counter variable to ensure an eventual end to the loop. Since counter-driven loops of this form are common, C++ provides a variant of while loops that captures this pattern more succinctly. The general form of a for loop is: for ( /*initialize counter*/ ; /*test counter*/ ; /*modify counter*/) // statements to execute... As this general form shows, a for loop combines all of the components of a counter-driven loop, making the loop more compact and easier to read. In particular, the steps involving the loop counter: initialization, testing, and modification, are all isolated on one line, separated by semicolons. Since these statements control the behavior of the loop, listing them together makes it easier to grasp the overall behavior of the loop. Separating the loop control statements from the actual code to be executed in the body of the loop also makes it easier to focus on the actions performed by the loop.

4 PALMS MODULE 2 LAB: FOR LOOPS IN C++ 4 In all other respects, a for loop behaves precisely the same as its while loop counterpart. In particular, the initialization of the loop counter (the first component of the for loop header) is executed first. Then, the loop test (the second component) is evaluated, and if the test succeeds then the body of the loop is executed. After the loop body is executed, the loop counter is incremented (the third component) and the loop test is reevaluated, possibly re-executing the loop body as before. As an example, the code below that uses a for loop to sum the numbers from one to ten: int sum = 0; for (int count = 1; count <= 10; count = count + 1) sum = sum + count; Notice in the above example the use of int count = 1 as the initialization component. When we want to only use a variable within a for loop, we can create the variable in this manner. The variable is created when the loop begins and is destroyed when the loop ends; i.e. the variable count would not be accessible in code following the loop. Watch and listen to the For Loops in C++ podcast below:

5 PALMS MODULE 2 LAB: FOR LOOPS IN C++ 5 Part #2: Applications of For Loops We previously examined the the while statement as a general-purpose loop structure. These loops can be used for any type of conditional repetition needed by our programs. However, alternative repetition constructs are available for specific purposes. Recall that the purpose of the for construct is to allow us to perform counter-driven repetition in a more compact manner. In the While Loops in C++ lab, the program CompoundInterest was one of the examples used to illustrate the use of a while statement. This program involves the use of counter-driven repetition. If we swap out the while statement for a for statement, the code in main would look like the following: int main() double interest_rate = 0.0; double balance = 0.0; // stores the interest rate // stores the user balance // prompt the user and input two values cout << "Enter a starting balance and interest rate, " << "separated by a space: "; cin >> balance >> interest_rate; // set up the output for two digits of precision... cout.setf(ios::fixed); cout.precision(2); for (int year = 1; year <= 10; year++) // compute the new balance for this year... balance = balance + (balance * interest_rate); // show the balance each year... cout << setw(4) << year << setw(15) << balance << endl; // return "success" to the operating system... return 0; Ultimately the code in this version is more compact. Since we have separated the loop control statements from the actual code to be executed in the loop body, the purpose of the loop can be made more apparent to the casual reader: to compute a new balance and to output that new value.

6 PALMS MODULE 2 LAB: FOR LOOPS IN C++ 6 For Loops and Grade Calculators Suppose we wanted to write a C++ program to compute student grades. Our program would take one input at the beginning: Inputs Data Type Description Student ID string Exactly four characters Next, our program would input exactly 11 of the following values: Inputs Data Type Description Exam Score int An exam score [0-100] Once the input was finished, our program would calculate the total score by throwing out the lowest score and computing the students grade as a percentage. One possible dialog between the program and the user would look like the following: Enter the student ID: 11AB Enter Exam Score #0: 80 Enter Exam Score #1: 82 Enter Exam Score #2: 87 Enter Exam Score #3: 74 Enter Exam Score #4: 68 Enter Exam Score #5: 89 Enter Exam Score #6: 80 Enter Exam Score #7: 92 Enter Exam Score #8: 83 Enter Exam Score #9: 81 Enter Exam Score #10: 84 The lowest score was removed (68). Student 11AB has a total score of 832 (83.20 percent, B). This problem is well-suited to the use of for loops. The problem involves a repeated set of instructions (the instructions to provide input) which differ only in terms of the prompt: each user prompt includes a number (#0, #1, etc) which increases by 1 each time. The repeated prompting of the user has a defined starting point (Exam Score #0) and a defined ending point (Exam Score #10). The succession of prompts is an example of counter-driven repetition. Exercise 1: Create a new C++ Project called GradeCalculator. Add a new C++ code file called GradeCalculator.cpp to the project, and construct the program described above. A few notes as you construct the program:

7 PALMS MODULE 2 LAB: FOR LOOPS IN C++ 7 The percentage score must be output with two digits of precision. Letter grades should follow the following scale: [ )% = F, [ )% = D, [ )% = C, [ )% = B, and [ ]% = A. Be sure to validate all input. Repetition and conditional constructs must be used where appropriate. Compile and Build your program to verify it works as expected. Enter in several different tests cases to verify your program s logic. For Loops and Population Growth Two major factors that affect population growth are birth rates and death rates. These rates can be measured and can be used to predict how the population s size will change over time. To find a change in population size over a fixed time interval, use the formula: Where ΔN Δt = (B D) Variable ΔN Δt B D Meaning The change ( ) in population size The change ( ) in time (fixed interval) The number of births The number of deaths This equation can be modified to represent the average number of births and deaths per individual during the time interval. The variable b represents the per capita birth rate (the number of offspring per unit of time for an average individual), where similarly, d is the per capita death rate. Using N to represent population size, the equation becomes ΔN Δt = (bn dn) To identify the difference in per capita birth and death rates this equation becomes: r = (b d) When r = 0, the birth rates and death rates are equal, and this is defined as Zero Population growth (ZPG). Combining the previous two equations gives the overall equation:

8 ΔN Δt = rn PALMS MODULE 2 LAB: FOR LOOPS IN C++ 8 If population growth is experienced under ideal conditions, the growth is referred to as exponential population growth because the curve of population size vs. time is a j-shaped curve that corresponds to the graph of an exponential function. Exponential growth appears in populations that have been drastically reduced and are now rebuilding their population. In the next exercise, we will use a modified form of this logic to simulate population growth. Exercise 2: Create a new C++ Project called PopulationGrowth. Add a new C++ code file called PopulationGrowth.cpp to the project. In this exercise you will write a program to compute the growth rates of a population of Lycans over time. Your program should take the following inputs from the user: Variable Meaning Range/Valid Values P Initial population size [1-1000] b Per capita birth rate [ ) d Per capita death rate [ ) All input values should be validated according to the rules above. Once the input is finished, perform your calculations for the next 50 years and display them to the screen. Your output report should have two columns of information: Year and Population Size. Remember that the first year is considered Year 0, not Year 1. Be aware that it is possible for the population to go extinct (i.e. have a population 0.005); at that point you must stop processing, close the report, and inform the user. The population in any year is a function of two things: the current population (i.e. last year s population) and the difference in per capita birth and death rates (r). The following equations may be handy: Difference in per capita birth and death rates: r = b d Calculating the new population for years 1-49: This Year s Population = (Last Year s Population) + (r (Last Year s Population)) Remember that the population at year 0 is the initial population. Your numerical output should be precise to two decimal places on the right of the decimal for all real-number data.

9 PALMS MODULE 2 LAB: FOR LOOPS IN C++ 9 Compile and Build your program to verify it works as expected. Two sample output dialogs are provided. The first involves a continuously growing population and is provided below: Enter the initial population size (1-1000): 100 Enter the Birth Rate [ ): 0.5 Enter the Death Rate [ ): 0.4 YEAR POPULATION

10 PALMS MODULE 2 LAB: FOR LOOPS IN C++ 10 The second case involves extinction and is shown below: Enter the initial population size (1-1000): 10 Enter the Birth Rate [ ): 0.4 Enter the Death Rate [ ): 0.6 YEAR POPULATION The population has gone extinct Part 3: The Game of Roulette The idea of Monte Carlo Methods involves processes whereby we can predict the behavior (on average) of a random event. The end result of the application of this methodology is a numerical probability (likelihood) that a given event will occur. For example, suppose we have an American roulette wheel. This version of a roulette wheel has 38 numbers on it (1-36, 0, and 00). The "slots" for each number are each colored according to the following chart:

11 PALMS MODULE 2 LAB: FOR LOOPS IN C++ 11 Even or Odd Numbers......In Range......Has Color Odd 1-9 Red Odd Red Even Red Even Red N/A 0 Green N/A 00 Green All slots falling outside of these values are colored Black. Exercise 3: Create a C++ program which simulates "spins" of the roulette wheel. Allow the user to specify how many spins to perform, and print out a summary of how many times the colors Red, Green, and Black are "winners", i.e. the spin lands on these colors. Perform some tests of your own and watch the results. Your output should consist of three things: The total number of spins; The number of times each of Red, Green, and Black "win"; The winning percentage for each color. To simulate a die roll you can use the spin() function, as shown below. Note that we are using the value 37 to represent 00. You will need to write this function into your code:

12 PALMS MODULE 2 LAB: FOR LOOPS IN C++ 12 ///////////////////////////////////////////////////////////////////////////// // // FUNCTION NAME: spin // PARAMETERS: None // RETURN TYPE: int // PURPOSE: Returns a random integer in the range // //////////////////////////////////////////////////////////////////////////// int spin() static bool initialized = false; if (!initialized) // Set the seed value for generating random numbers. srand((unsigned)time(0)); // set the flag initialized = true; // This computes a random integer between 0 and 37 using the // Standard C++ rand() function. // Get the random number. int rand_num = rand(); // Convert the number to a number in the range [0 37]... rand_num = (rand_num % 38); return rand_num; Part 4: Vocabulary Words You will be assessed on your knowledge of the following terms and concepts as well as the C++ concepts discussed in this document. As a result, you are encouraged to review these terms in the preceding document. Boolean true or false. Conditions/Conditional Expressions expressions which evaluate to one of two possible values: true or false. Conditional Repetition the repeated execution of a statement or a sequence of statements.

13 PALMS MODULE 2 LAB: FOR LOOPS IN C++ 13 Counter-Driven Repetition (Loop) a loop whose number of repetitions is controlled by a counter. These loops always involve three components: initialization of the counter variable to a starting value; testing the counter variable for a terminating condition; and modifying the value of the counter variable to ensure an eventual end to the loop. Counter Variable A variable (usually an integer) which keeps track of the number of loop iterations. Infinite Loop Occurs when a conditional expression never becomes false, causing a loop to repeat forever. It appears to the user as a non-responsive or hanging program.. Iterations the cycles of a loop; in other words, the number of times the loop body is repeated. Loop In C++, a construct that repeats a series of statements. Loop Body the portion of a loop inside.

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

LAB: INTRODUCTION TO FUNCTIONS IN C++

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

More information

LAB: STRUCTURES, ARRAYS,

LAB: STRUCTURES, ARRAYS, LAB: STRUCTURES, ARRAYS, AND FILES IN C++ MODULE 2 JEFFREY A. STONE and TRICIA K. CLARK COPYRIGHT 2008-2016 VERSION 3.3 PALMS MODULE 2 LAB: STRUCTURES, ARRAYS, AND FILES IN C++ 2 Introduction This lab

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

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

LAB: SWITCH STATEMENTS

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

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

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

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

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

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 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

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

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

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

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

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

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

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips Lab6 Array I Objectivities 1. Using rand to generate random numbers and using srand to seed the random-number generator. 2. Declaring, initializing and referencing arrays. 3. The follow-up questions and

More information

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently. The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without

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

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

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

Distributions of Continuous Data

Distributions of Continuous Data C H A P T ER Distributions of Continuous Data New cars and trucks sold in the United States average about 28 highway miles per gallon (mpg) in 2010, up from about 24 mpg in 2004. Some of the improvement

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

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

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode STUDENT OUTLINE Lesson 8: Structured Programming, Control Structures, if- Statements, Pseudocode INTRODUCTION: This lesson is the first of four covering the standard control structures of a high-level

More information

Information Science 1

Information Science 1 Topics covered Information Science 1 Fundamental Programming Constructs (1) Week 11 Terms and concepts from Week 10 Flow of control and conditional statements Selection structures if statement switch statement

More information

More About WHILE Loops

More About WHILE Loops More About WHILE Loops http://people.sc.fsu.edu/ jburkardt/isc/week04 lecture 07.pdf... ISC3313: Introduction to Scientific Computing with C++ Summer Semester 2011... John Burkardt Department of Scientific

More information

Information Science 1

Information Science 1 Information Science 1 Fundamental Programming Constructs (1) Week 11 College of Information Science and Engineering Ritsumeikan University Topics covered l Terms and concepts from Week 10 l Flow of control

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

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

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

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

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

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science Instructor: Dr. Howaida Ismail Final Exam Spring 2013 Last Name :... ID:... First Name:...

More information

Control Statements: Part 1

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

More information

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No.

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Instructor: Final Exam Fall Section No. The American University in Cairo Computer Science & Engineering Department CSCE 106 Instructor: Final Exam Fall 2010 Last Name :... ID:... First Name:... Section No.: EXAMINATION INSTRUCTIONS * Do not

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

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++.

Concepts Review. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++. Concepts Review 1. An algorithm is a sequence of steps to solve a problem. 2. A program is the implementation of an algorithm in a particular computer language, like C and C++. 3. A flowchart is the graphical

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

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

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 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

AP Calculus. Slide 1 / 213 Slide 2 / 213. Slide 3 / 213. Slide 4 / 213. Slide 4 (Answer) / 213 Slide 5 / 213. Derivatives. Derivatives Exploration

AP Calculus. Slide 1 / 213 Slide 2 / 213. Slide 3 / 213. Slide 4 / 213. Slide 4 (Answer) / 213 Slide 5 / 213. Derivatives. Derivatives Exploration Slide 1 / 213 Slide 2 / 213 AP Calculus Derivatives 2015-11-03 www.njctl.org Slide 3 / 213 Table of Contents Slide 4 / 213 Rate of Change Slope of a Curve (Instantaneous ROC) Derivative Rules: Power, Constant,

More information

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

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

More information

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition) Structures Programming in C++ Sequential Branching Repeating Loops (Repetition) 2 1 Loops Repetition is referred to the ability of repeating a statement or a set of statements as many times this is necessary.

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

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

Math 205 Test 3 Grading Guidelines Problem 1 Part a: 1 point for figuring out r, 2 points for setting up the equation P = ln 2 P and 1 point for the initial condition. Part b: All or nothing. This is really

More information

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science Instructor: Dr. Khalil Final Exam Fall 2013 Last Name :... ID:... First Name:... Form

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

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

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

CS 142 Style Guide Grading and Details

CS 142 Style Guide Grading and Details CS 142 Style Guide Grading and Details In the English language, there are many different ways to convey a message or idea: some ways are acceptable, whereas others are not. Similarly, there are acceptable

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

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

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

C++ Quick Reference. switch Statements

C++ Quick Reference. switch Statements C++ Quick Reference if Statements switch Statements Array/Initializer if (condition) if (condition) else if (condition1) else if (condition2) else Loop Statements while (condition) do while (condition);

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

Common Loop Algorithms 9/21/16 42

Common Loop Algorithms 9/21/16 42 Common Loop Algorithms 9/21/16 42 Common Loop Algorithms 1. Sum and Average Value 2. Coun4ng Matches 3. Promp4ng un4l a Match Is Found 4. Maximum and Minimum 5. Comparing Adjacent Values 9/21/16 43 Sum

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

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

CSC 1351: Quiz 6: Sort and Search

CSC 1351: Quiz 6: Sort and Search CSC 1351: Quiz 6: Sort and Search Name: 0.1 You want to implement combat within a role playing game on a computer. Specifically, the game rules for damage inflicted by a hit are: In order to figure out

More information

Measures of Dispersion

Measures of Dispersion Lesson 7.6 Objectives Find the variance of a set of data. Calculate standard deviation for a set of data. Read data from a normal curve. Estimate the area under a curve. Variance Measures of Dispersion

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

Repetition, Looping CS101

Repetition, Looping CS101 Repetition, Looping CS101 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

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

15-110: Principles of Computing, Spring 2018

15-110: Principles of Computing, Spring 2018 5-: Principles of Computing, Spring 28 Problem Set 8 (PS8) Due: Friday, March 3 by 2:3PM via Gradescope Hand-in HANDIN INSTRUCTIONS Download a copy of this PDF file. You have two ways to fill in your answers:.

More information

CIS 130 Exam #2 Review Suggestions

CIS 130 Exam #2 Review Suggestions CIS 130 - Exam #2 Review Suggestions p. 1 * last modified: 11-11-05, 12:32 am CIS 130 Exam #2 Review Suggestions * remember: YOU ARE RESPONSIBLE for course reading, lectures/labs, and especially anything

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

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

4. Use a loop to print the first 25 Fibonacci numbers. Do you need to store these values in a data structure such as an array or list?

4. Use a loop to print the first 25 Fibonacci numbers. Do you need to store these values in a data structure such as an array or list? 1 Practice problems Here is a collection of some relatively straightforward problems that let you practice simple nuts and bolts of programming. Each problem is intended to be a separate program. 1. Write

More information

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014 Lesson 6A Loops By John B. Owen All rights reserved 2011, revised 2014 Topic List Objectives Loop structure 4 parts Three loop styles Example of a while loop Example of a do while loop Comparison while

More information

Math Modeling in Java: An S-I Compartment Model

Math Modeling in Java: An S-I Compartment Model 1 Math Modeling in Java: An S-I Compartment Model Basic Concepts What is a compartment model? A compartment model is one in which a population is modeled by treating its members as if they are separated

More information

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency Introduction Fundamentals Declaring arrays Indexing arrays Initializing arrays Arrays and functions Multidimensional arrays Sorting and algorithm efficiency An array is a sequence of values of the same

More information

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science

The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science The American University in Cairo Computer Science & Engineering Department CSCE 106 Fundamentals of Computer Science Instructor: Dr. Khalil Final Exam Fall 2012 Last Name :... ID:... First Name:... Form

More information

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control Chapter 2 Control, Quick Overview Control Selection Selection Selection is how programs make choices, and it is the process of making choices that provides a lot of the power of computing 1 Python if statement

More information

In this lesson, students build fractals and track the growth of fractal measurements using tables and equations. Enduring Understanding

In this lesson, students build fractals and track the growth of fractal measurements using tables and equations. Enduring Understanding LessonTitle: Fractal Functions Alg 5.8 Utah State Core Standard and Indicators Algebra Standards 2, 4 Process Standards 1-5 Summary In this lesson, students build fractals and track the growth of fractal

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

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

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements Chapter 5 Looping Building on the foundation Now that we know a little about cout cin math operators boolean operators making decisions using if statements Advantages of Computers Computers are really

More information

Programming Assignment #4 Arrays and Pointers

Programming Assignment #4 Arrays and Pointers CS-2301, System Programming for Non-majors, B-term 2013 Project 4 (30 points) Assigned: Tuesday, November 19, 2013 Due: Tuesday, November 26, Noon Abstract Programming Assignment #4 Arrays and Pointers

More information

Lesson 7A Arrays. By John B. Owen All rights reserved 2011, revised 2014

Lesson 7A Arrays. By John B. Owen All rights reserved 2011, revised 2014 Lesson 7A Arrays By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives What is an array? Initializing an array of integers Array processing For Each loop Other data type arrays

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

Lecture 5. Review from last week. Selection Statements. cin and cout directives escape sequences

Lecture 5. Review from last week. Selection Statements. cin and cout directives escape sequences Lecture 5 Selection Statements Review from last week cin and cout directives escape sequences member functions formatting flags manipulators cout.width(20); cout.setf(ios::fixed); setwidth(20); 1 What

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

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable Basic C++ Overview C++ is a version of the older C programming language. This is a language that is used for a wide variety of applications and which has a mature base of compilers and libraries. C++ is

More information

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

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

More information

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved. Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create

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

LESSON 3 CONTROL STRUCTURES

LESSON 3 CONTROL STRUCTURES LESSON CONTROL STRUCTURES PROF. JOHN P. BAUGH PROFJPBAUGH@GMAIL.COM PROFJPBAUGH.COM CONTENTS INTRODUCTION... Assumptions.... Logic, Logical Operators, AND Relational Operators..... - Logical AND (&&) Truth

More information

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps Overview By the end of the lab, you will be able to: use fscanf() to accept inputs from the user and use fprint() for print statements to the

More information

Lab ACN : C++ Programming Exercises

Lab ACN : C++ Programming Exercises Lab ACN : C++ Programming Exercises ------------------------------------------------------------------------------------------------------------------- Exercise 1 Write a temperature conversion program

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

Subprime Fibonacci sequences

Subprime Fibonacci sequences CS 7A - Spring 2015 - Richard Guy s Sub-Fibonacci Sequence. Due 5/21/15 Subprime Fibonacci sequences 0.1 Background Theory Start like the Fibonacci sequence 0, 1, 1, 2, 3, 5,..., but before you write down

More information

[Page 177 (continued)] a. if ( age >= 65 ); cout << "Age is greater than or equal to 65" << endl; else cout << "Age is less than 65 << endl";

[Page 177 (continued)] a. if ( age >= 65 ); cout << Age is greater than or equal to 65 << endl; else cout << Age is less than 65 << endl; Page 1 of 10 [Page 177 (continued)] Exercises 4.11 Identify and correct the error(s) in each of the following: a. if ( age >= 65 ); cout

More information

Loops (while and for)

Loops (while and for) Loops (while and for) CSE 1310 Introduction to Computers and Programming Alexandra Stefan 1 Motivation Was there any program we did (class or hw) where you wanted to repeat an action? 2 Motivation Name

More information

CS 007A Midterm 1 Practice Chapters 1 5

CS 007A Midterm 1 Practice Chapters 1 5 CS 007A Midterm 1 Practice Chapters 1 5 1. Consider the 4 bytes stored in contiguous memory, as shown to the right. a. Determine the decimal representation of these 4 one-byte integers: b. Determine the

More information