LAB: WHILE LOOPS IN C++

Size: px
Start display at page:

Download "LAB: WHILE LOOPS IN C++"

Transcription

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

2 PALMS MODULE 2 LAB: WHILE 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++ while statement. At the end of this module, students will Be able to solve simple problems using C++ while statement Understand the structure of C++ while 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 LabWhile folder. All coding exercises (and related folders) for this lesson should be placed in the LabWhile 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: Conditional Repetition in C++ Many operations in computer programs (as in real life) involve repeating a sequence of events. Consider the simple act of buying groceries. When you bring groceries up to the grocery store clerk, he or she will scan each item and place it into a grocery bag. The act of scanning the item you wish to buy is repeated for each item in your shopping cart until your cart is empty. Similarly, the act of placing the item purchased into a grocery bag is repeated until there are no more items. In algorithms and computer programming, the process of repeatedly performing the same set of operation until a specific condition is false is known as conditional repetition. Conditional repetition is the repeated execution of a statement or a sequence of statements. This repetition of statements continues while a specified condition is true. Like conditional selection, conditional repetition involves making a decision. In the grocery store example, the decision is whether to scan the next item. This decision is made by checking the shopping cart: if the cart is not empty, continue; if the cart is empty, stop.

3 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 3 Once again, conditional expressions are used to determine the next step. However, unlike with conditional selection, the decision process may be repeated multiple times. If the conditional expression is true, a set of nested statements are executed. At the end of this execution, flow of control returns back to the original condition, and the process repeats. Only when the conditional expression is false does this loop end. The process of conditional repetition is often represented in algorithms and programs with the use of while statements, sometimes called while loops. These compound statements execute a statement or a series of statements as long as a specified condition is true. C++ provides a while statement to implement conditional repetition. The general form for a while loop is as follows: while ( /* conditional expression */ ) one or more statements to execute if the condition is true The loop behavior is controlled by the conditional expression enclosed in parentheses. Similar to an if statement, the conditional expression is evaluated first. If the expression evaluates to true, then the statements inside the loop body ( i.e., inside ) are executed in order. After making a pass through the loop body, the whole process is repeated control loops back around to the conditional expression. The conditional expression is evaluated again, and if it succeeds, then the statements inside the loop body are executed again. This process repeats until the conditional expression evaluates to false. For example, consider the while loop in the C++ code below: cout << "Please enter a number between 0 and 100: "; cin >> user_input; while ((user_input < 0) (user_input > 100)) cout << "Invalid input please try again." << endl; cout << "Please enter a number between 0 and 100: "; cin >> user_input; The user is prompted for a number between 0 and 100. If the user enters a valid number, then the while loop condition will fail (be false) and the code inside the loop body will not execute. However, if the user entered a number outside the requested range, the while loop condition will fail and he/she will be told of his/her mistake and will be prompted for a new number. This cycle will repeat until the user enters a valid number. It is important to note if a conditional expression never becomes false the loop will repeat forever. This loop behavior is called an infinite loop. It appears to the user as a non-responsive or hanging program.

4 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 4 Watch and listen to the While Loops in C++ podcast below: Exercise 1: Create a new C++ Project called CompoundInterest. Add a new C++ code file called CompoundInterest.cpp to the project, and type the following code into the new file: / Name: CompoundInterest.cpp Author: Jeffrey A. Stone Purpose: Displays the growth of a bank account, given a starting balance and an interest rate, if the interest is compounded. Interest rates are input as numbers less than zero (e.g. 5.9% is input as 0.059). / #include <iostream> #include <iomanip> using namespace std;

5 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 5 / FUNCTION NAME: main PARAMETERS: None RETURN TYPE: int PURPOSE: Entry point for the application. / int main() double interest_rate = 0.0; double balance = 0.0; int year = 0; stores the interest rate stores the user balance time counter (in years) 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); while (year <= 10) increment the time counter... 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; Compile and run the program. Remember that interest rates are numbers in the range 0-1: for example, 7.6% is really You should input the into this program. Exercise 2: Examine the CompoundInterest program. How many times does the loop repeat in other words, how many times do the statements in the loop body execute? How many times is the conditional expression evaluated? Note: The answers to these two questions are not the same. Exercise 3: Perform some research, either in your textbook or on the Web, to determine what the setw code statement does. What effect does it have in a program?

6 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 6 Sentinel Values The conditional expression used to control the number of loop iterations (cycles) often involves a special value which signals the loop to stop. These values are called sentinel values, because they act as a signal when these values are encountered the loop should stop. For example: while (factor!= 1000)... The sentinel value in this example is When the variable factor assumes the value 1000, the loop will end. Part 3: Counter-Based Loops Suppose you wanted to write a function to sum the integers from one (1) up to and including some higher integer (e.g. 10, 20, etc). You could do this by using a counter variable. A counter variable is a simply variable (usually an integer) which keeps track of the number of loop iterations. The counter variable is tested before each iteration for a sentinel value. When the sentinel value has been reached, the loop terminates. A counter-based while loop to compute a sum of integers is as follows: int sumofintegers( int terminal_int ) int count = 1; acts as the counter variable int sum = 0; stores the sum while (count <= terminal_int) add the value of the counter to our sum... sum = sum + count; add one to the counter... count = count + 1; return sum; return the summation... The Binomial Coefficient and Factorials In algebra, the binomial coefficient is symbolized as: ( n r )

7 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 7 And is defined by the following formula, given integer values of n and r (both > 0): n! r! (n r)! The exclamation mark (!) means factorial, which is a mathematical concept expressed as follows: The factorial of a given integer is the product of that integer and all the integers which precede, down to and including 1. For example: 5! = ( ) = 120 In the case of the binomial coefficient formula, we have three uses of factorial in conjunction with multiplication and division. Since we are repeating a similar iterative calculation (a factorial) three times, this problem lends itself to the use of a function. The use of a function allows us to write one set of code for the calculation that can be called three times with different arguments. The use of a while loop is warranted here, since the factorial s calculation is actually a repeated multiplication. Suppose we wanted to write a C++ program to compute the value of this coefficient. Our program would take two inputs at the beginning: Inputs Data Type Restrictions Value of n int [1 10] Value of r int [1 10] Our program would also need to aware of the following conditions: When r is equal to n, the value of the binomial coefficient is 1. Note: 0! = 1. When r is greater than n the formula does not apply and this situation should be considered an error condition (requiring a suitable message for the end user). Once the input is finished, our program would calculate the binomial coefficient and display it to the user. An example dialog between the program and the user would look like the following: Enter the value of n: 5 Enter the value of r: 3 The binomial coefficient for n=5, r=3 is 10.

8 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 8 Exercise 4: Create a new C++ Project called Binomial. Add a new C++ code file called Binomial.cpp to the project, and construct the program described above. Here is some test data you can use to assess your program: n r Binomial Coefficient <Your Error Message> Compile, Build, and Test your program to verify it works as expected. Part 4: The Game of Craps Suppose we wanted to simulate a game of craps, a game of chance involving dice. The rules of craps are as follows: Craps is played by a single player. The player rolls two die (each a fair die, containing faces 1, 2, 3, 4, 5, and 6). The sum of each roll is what's important. Rolling a 7 or an 11 on the first throw of the dice results in a "win" for the player. If the sum of the dice is 2, 3, or 12 on the first throw, the player "loses". If the player doesn t "win" or "lose" on the first throw, the player has the option to continue rolling the dice. o The sum of the dice from the first throw becomes the players' "point" value. The goal is to roll the dice until the "point" value is rolled again (a "win", i.e. "making your point"). o If a 7 is rolled before the "point" value is rolled again, the player "loses". Simulating this game would necessarily involve a conditional repetition structure, as the process of rolling the dice repeats some number of times. Exercise 5: Create a C++ program to simulate a game of craps and keep track of how long it takes a user to "win" or "lose". Your program should begin by rolling the dice; if the player wins, display an appropriate message to the user, something like: Congratulations, you win! If the player does not win, display an appropriate message indicating a loss. If the player neither wins nor loses, ask the user if he/she wishes to continue:

9 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 9 Continue (Y/N)? If the user elects to continue, roll the dice again. Repeat this process (rolling the dice, checking for a win/loss, and asking the user to continue) until the user wins or loses. Regardless of the outcome, display a count of the number of rolls that have occurred. To simulate a die roll you can use the rolldie() function, as shown below. You will need to write this function into your code: / FUNCTION NAME: rolldie PARAMETERS: None RETURN TYPE: int PURPOSE: Returns a random integer in the range [1 6]. int rolldie() 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 low and high using the Standard C++ rand() function. Get the random number. int rand_num = rand(); Convert the number to a number in the range [1..6]) rand_num = (rand_num % ( )) + 1; return the integer in the range [low high]... return rand_num;

10 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 10 Part 4: Amortization, Input Validation, and While Loops Suppose we wanted to construct a C++ program to display a payment schedule for a bank loan. Bank loans are commonly taken to provide for big-ticket purchases like a house or a car. Loan terms and payment amounts vary based on interest rates, bank promotions, and other factors. A payment schedule is used to show the distribution of payments over the life of a loan. Each payment has two components the amount applied to the principal, or the loan amount, and the amount paid for interest on the loan. Calculating a loan payment schedule involves a series of calculations over time; as a result, constructing a payment schedule involves the concept of conditional repetition. The program you will write will have four inputs: Input Data Type Range of Valid Values Principal double Must be greater than zero Annual Interest Rate double Must be in the range [1-100] Term of the Loan int Must be in the range [10-30] Payments per Year int Must be in the range [1-12] Each of these inputs requires the user to enter values which fall within a given range. Two methods are used in combination to restrict the input the user provides. First, the prompt given by the program should include a description of the valid range of acceptable input values. Second, we can use while loops to force the user to enter in an acceptable value. A while loop allows the program to check the user input for validity: if the input is invalid, the user can be informed of his or her error and be given an opportunity to re-enter the value. For example, the following function would be used to enforce the restrictions on the principal input described above:

11 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 11 FUNCTION NAME: inputprincipal PARAMETERS: None RETURN TYPE: double PURPOSE: Grabs the loan amount from the user. Restricts the input to be > 0. double inputprincipal() bool valid_input = false; double input_value = 0; flag value for the input's validity stores the actual input value while (!valid_input ) prompt the user... cout << "Enter the Beginning Principal (> 0): "; read in the value... cin >> input_value; check for validity... if ( input_value > 0 ) otherwise OK valid_input = true; else tell the user and set the flag... cout << "Invalid input. Please try again." << endl << endl; valid_input = false; return the validated value... return input_value; The prompt in this function informs the user of the input restrictions (> 0). Note also how a bool variable (valid_input) is used to control the execution of the while loop. This approach uses the bool variable as a so-called flag variable; if the user enters an invalid value, a red flag is raised and the user is forced to try again. The approach used in this function guarantees that the return value provide by the function is valid for the principal (i.e. not garbage). Exercise 6: Create a new C++ Project called Amortization. Add a new C++ code file called Amortization.cpp to the project. Construct four functions, one for each of the input values described above. Each function should use descriptive prompts and a while loop to force the user to enter valid values. Finally, add code to your main function which calls these four input

12 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 12 functions and records the return values. Compile and Build your program, and test it out. Try to enter invalid values and see what happens does it force you to enter in valid values? Exercise 7: Enhance your Amortization.cpp file by adding a function called computeamortizedpayment. The purpose of this function is to compute the individual payment amount for the loan (for example, a monthly payment). The formula to compute the amortized payment is as follows: p i (1 + i)n A = (1 + i) n 1 Where p is the principal, i is the [ (annual interest rate / 100.0) / payments per year ], and n is the total number of payments for the loan (i.e. term of the loan * payments per year). After constructing this function, add code to your main function which calls computeamortizedpayment with the four necessary arguments and records the return value. The function should have the following prototype and comment header: double computeamortizedpayment( double p, double ir, double ppy, int n); FUNCTION NAME: computeamortizedpayment PARAMETERS: double p -- the beginning principal double ir -- the annual interest rate int ppy -- the payments per year int n -- the total number of payments RETURN TYPE: double PURPOSE: Computes and returns the amortized payment amount. Exercise 8: Enhance your Amortization.cpp file by adding a function with the following function prototype and comment header: void printheaderinformation(double princ, double ir, double amort, int n); FUNCTION NAME: printheaderinformation PARAMETERS: double princ -- the beginning principal double ir -- the annual interest rate double amort -- the amortized payment int n -- the total number of payments RETURN TYPE: void PURPOSE: Prints the header information to the screen.

13 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 13 The purpose of this function is to display summary information at the top of your eventual payment schedule (a report header of sorts). The screen output should be formatted as follows: AMORTIZATION SCHEDULE Beginning Principal: NNNNNN.NN Annual Interest Rate: NN.NN% Total Payments: NNN Payment Amount: NNN.NN Payment# Interest Due Principal Balance Remaining The use of N indicates that, in the actual output, a number should appear in that position. The number of N s after a decimal point indicates the desired precision of the output. For example, there should be two digits to the right of the decimal for the principal amount, annual interest rate, and payment amount. Finally, add code to your main function which calls printheaderinformation with the four necessary arguments. Compile and Build your program and test it out. Hint: use cout.precision() and setw() to format your output. Exercise 9: Enhance your Amortization.cpp file by adding the following function to the end of your file (don t forget to add the function prototype!): / FUNCTION NAME: computeinterestportion PARAMETERS: double remaining_balance -- the loan balance double ir -- the annual interest rate int ppy -- the payments per year RETURN TYPE: double PURPOSE: Computes and returns the interest portion for the current payment. / double computeinterestportion(double remaining_balance, double ir, int ppy) compute the interest portion of the payment... return (remaining_balance * (ir / 100.0)) / ppy; The purpose of this function is to compute the interest portion of each individual payment. This amount fluctuates based on the remaining balance for the loan. The formula used as the basis of this function is as follows:

14 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 14 (current balance) [(annual interest rate / 100.0)] (payments per year) This formula computes the interest amount present in any payment. Compile your file to make sure there are no errors. You will not add code to your main function to test this function, but it will be used in the next exercise. Exercise 10: Enhance your Amortization.cpp file by adding a function called computeandprintrows. The purpose of this function is to compute (and display) the payment schedule for the loan. Recall that in Exercise 8 you produced a report header to the screen. The last line of this header was as follows: Payment# Interest Due Principal Balance Remaining These four items are column headings for the report which follows. Your computeandprintrows function must produce the rows which follow in other words, the lines of the report consisting of the four column values. There will be one row per payment. For example, if the loan was for 10 years, 12 payments per year, there would be 120 rows of data in your table (10 years * 12 payments per year). The computeandprintrows function should have the following prototype and comment header: void computeandprintrows(double p, double ir, double amort, int n, int ppy); / FUNCTION NAME: computeandprintrows PARAMETERS: double p -- the beginning principal double ir -- the annual interest rate double amort -- the amortized payment int n -- the total number of payments int ppy -- the payments per year RETURN TYPE: void PURPOSE: Computes the row values and prints them to the screen. / Each row will show the payments interest amount, principal amount, and the balance remaining on the loan. This will require a while loop which ends with the last payment. Each iteration of the while loop will compute the interest due (using the computeinterestportion function), the principal amount provided by the payment (i.e. the amortized payment amount minus the interest due) and the remaining balance (the prior balance minus the principal amount paid with this specific payment).

15 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 15 Here is an example of what a sample report would look like for a small loan: AMORTIZATION SCHEDULE Beginning Principal: Annual Interest Rate: 7.38% Total Payments: 30 Payment Amount: Payment# Interest Due Principal Balance Remaining Total Interest: Note that, at the end of the report, the total amount of interest paid is displayed. You will need to keep track of this in your while loop! Finally, add code to your main function which calls computeandprintrows with the five necessary arguments. Compile, Build, and test your program to make sure it works! Note: there are many online mortgage calculators you can use to test your results.

16 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 16 Part 5: Projectile Motion The motion of a projectile follows an arc trajectory, unless the starting velocity is large enough to be considered an escape velocity (a velocity that allows a projectile to defy gravity and leave the earth). For example, the path of a baseball once it leaves the bat follows an arc, beginning at the bat and ending when it hits the ground. On the other hand, NASA launches its space shuttles at a high enough velocity to outrun the pull of the earth s gravity. The height s of the projectile at time t with initial velocity v0 is calculated by the formula s = v 0 t 1 2 gt2 Where g is the gravitational constant (9.8 m/s 2 ). Exercise 11: Write a C++ program to create a table of height vs. time for a given projectile. Allow the user to enter an initial velocity in m/s (v0) and calculate the height of the projectile for time t = 0, 1, 2, 3,, n-1, n seconds. The last entry in your table (n seconds) should come when the height of the projectile reaches 0. Note that the final height may be less than 0; simply report this value as zero in your output. Remember to break your program down into functions and follow the C++ Coding Guidelines. Some other notes: Use four digits of precision for real-number output. Use the setw tool to properly format your output. Remember to validate the input (must be > 0). Create a constant for the gravitational constant (9.8 m/s 2 ). Four test cases are provided on the following pages.

17 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 17 Case #1: Please enter you initial velocity (in m/s): 5 Projectile Height Chart Initial Velocity: m/s Time Height Case #2: Please enter you initial velocity (in m/s): 0.0 Projectile Height Chart Initial Velocity: m/s Time Height Case #3: Please enter you initial velocity (in m/s): Projectile Height Chart Initial Velocity: m/s Time Height

18 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 18 Case #4: Please enter you initial velocity (in m/s): Projectile Height Chart Initial Velocity: m/s Time Height

19 PALMS MODULE 2 LAB: WHILE LOOPS IN C++ 19 Part 5: 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. 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. Sentinel A value which signals a loop to stop. While loops A basic C++ loop construct; compound statements which execute a statement or a series of statements as long as a specified condition is true.

LAB: FOR LOOPS IN C++

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

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

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

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

More information

Chapter Four: Loops II

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

More information

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

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

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

More about Loops and Decisions

More about Loops and Decisions More about Loops and Decisions 5 In this chapter, we continue to explore the topic of repetition structures. We will discuss how loops are used in conjunction with the other control structures sequence

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

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

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

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

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

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

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

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

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous Assignment 3 Methods Review CSC 123 Fall 2018 Notes: All homework must be submitted via e-mail. All parts of assignment must be submitted in a single e-mail with multiple attachments when required. Notes:

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

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

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme Chapter 4: 4.1 Making Decisions Relational Operators Simple Program Scheme Simple Program Scheme So far our programs follow a simple scheme Gather input from the user Perform one or more calculations Display

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

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

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

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

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 2 Monday, March 20, 2017 Total - 100 Points B Instructions: Total of 13 pages, including this cover and the last page. Before starting the exam,

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

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop Announcements Lab Friday, 1-2:30 and 3-4:30 in 26-152 Boot your laptop and start Forte, if you brought your laptop Create an empty file called Lecture4 and create an empty main() method in a class: 1.00

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

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

COMP 110 Programming Exercise: Simulation of the Game of Craps

COMP 110 Programming Exercise: Simulation of the Game of Craps COMP 110 Programming Exercise: Simulation of the Game of Craps Craps is a game of chance played by rolling two dice for a series of rolls and placing bets on the outcomes. The background on probability,

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

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

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

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

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

LOOPS. Repetition using the while statement

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

More information

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

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

Functions and Recursion

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

More information

Expressions, Input, Output and Data Type Conversions

Expressions, Input, Output and Data Type Conversions L E S S O N S E T 3 Expressions, Input, Output and Data Type Conversions PURPOSE 1. To learn input and formatted output statements 2. To learn data type conversions (coercion and casting) 3. To work with

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

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

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

Function Call Stack and Activation Records

Function Call Stack and Activation Records 71 Function Call Stack and Activation Records To understand how C performs function calls, we first need to consider a data structure (i.e., collection of related data items) known as a stack. Students

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

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

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module

More information

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

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

More information

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

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

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 06 / 04 / 2015 Instructor: Michael Eckmann Today s Topics Questions / comments? Calling methods (noting parameter(s) and their types, as well as the return type)

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

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.5. for loop and do-while loop

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.5. for loop and do-while loop Superior University Department of Electrical Engineering CS-115 Computing Fundamentals Experiment No.5 for loop and do-while loop Prepared for By: Name: ID: Section: Semester: Total Marks: Obtained Marks:

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

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

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

do { statements } while (condition);

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

More information

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

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

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

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Outline 12.1 Test-Driving the Craps Game Application 12.2 Random Number Generation 12.3 Using an enum in the Craps

More information

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

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

More information

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

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

More information

CSci 1113 Lab Exercise 5 (Week 6): Reference Parameters and Basic File I/O

CSci 1113 Lab Exercise 5 (Week 6): Reference Parameters and Basic File I/O CSci 1113 Lab Exercise 5 (Week 6): Reference Parameters and Basic File I/O So far, we've been getting our program input from the console keyboard using cin and displaying results on the terminal display

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

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

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

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

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

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

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

More information

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver) Introduction to C++ 1. General C++ is an Object oriented extension of C which was derived from B (BCPL) Developed by Bjarne Stroustrup (AT&T Bell Labs) in early 1980 s 2. A Simple C++ Program A C++ program

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

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

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision Lesson Outcomes At the end of this chapter, student should be able to: Use the relational operator (>, >=,

More information

Introduction to C++ (using Microsoft Visual C++)

Introduction to C++ (using Microsoft Visual C++) Introduction to C++ (using Microsoft Visual C++) By the end of this section, the students should be able to: Understand the basics of C++ programs and its development environment. Develop a simple C++

More information

Introduction to Programming using C++

Introduction to Programming using C++ Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse Course Prerequisites What you should already know

More information

Functions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92

Functions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92 L E S S O N S E T 6.2 Functions that Return a Value PURPOSE PROCEDURE 1. To introduce the concept of scope 2. To understand the difference between static, local and global variables 3. To introduce 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

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

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

More information

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

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

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

More information

Chapter 17 - Notes Recursion

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

More information

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

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

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

Lesson 2 Variables and I/O

Lesson 2 Variables and I/O Lesson 2 Variables and I/O Pic 10A Ricardo Salazar Free form layout C++ lets you use spaces and returns (enter key) wherever you see fit. cout

More information

CS 101 Computer Programming and utilization. Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay

CS 101 Computer Programming and utilization. Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay CS 101 Computer Programming and utilization Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building Bombay Lecture 4, Conditional execution of instructions Friday, August

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

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

WARM UP LESSONS BARE BASICS

WARM UP LESSONS BARE BASICS WARM UP LESSONS BARE BASICS CONTENTS Common primitive data types for variables... 2 About standard input / output... 2 More on standard output in C standard... 3 Practice Exercise... 6 About Math Expressions

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 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 3 2.1 Variables and Assignments Variables and

More information

Chapter 2. C++ Basics

Chapter 2. C++ Basics Chapter 2 C++ Basics 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-2 2.1 Variables and Assignments Variables

More information

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments Chapter 2 C++ Basics 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 Copyright 2011 Pearson Addison-Wesley. All rights

More information