Control Structures. Flowchart Symbols

Size: px
Start display at page:

Download "Control Structures. Flowchart Symbols"

Transcription

1 Control Structures The basic operations of a C/C++ programming language are specified using the following statements or structures: the input statement the output statement the assignment statements the single-way selection structure the two-way selection structure the multiple-way selection structure the counter-controlled iteration structure, and the logically-controlled iteration structure. The single-way selection, the two-way selection, the multiple-way selection, the counter-controlled iteration and the logically-controlled iteration are collectively called control structures. The specification of a controlled structure depends on a logical expression called condition. Controlled structures may also be specified using the following flowchart symbols: Flowchart Symbols SYMBOL NAME DESCRIPTION (a) Terminal Indicates the beginning or the end of an algorithm. (b) (c) Input/Output Process Indicates an input or an output operation. Indicates a computation or a data manipulation. (d) (e) Flow Lines Decision Used to connect the symbols and to indicate the logic flow. Indicates a decision point in an algorithm. (f) Connector Indicates an entry or an exit from another part of the flowchart Gilbert Ndjatou Page 57

2 Logical Expressions A logical expression (or condition) is an expression that evaluates to either true or false. There are two types of conditions: simple conditions and Compound conditions. Simple Conditions A simple condition has the following syntax: <arithmetic expression> <relational operator> <arithmetic expression> Relational Operators C/C++ Symbol Meaning < is less than > is greater than == is equal to <= is less than or equal to >= is greater than or equal to!= is not equal to Evaluations of simple conditions Assuming that the variables are defined and initialized as follows: int num1 = 5, num2 = 7, num3 = 2; float fnum = 11.75; char ch = K ; Evaluate the following conditions: a) num1 >= 5 d) num2 + 3 == num3 * 4 b) fnum + 7.2!= fnum / 2 e) 3 * num1 + 4 < num3 * 2 c) fnum * 2 > num f) A <= ch 2013 Gilbert Ndjatou Page 58

3 Solutions a) num1 >= 5 d) num2 + 3 == num3 * 4 5 >= == 2 * 4 10 == 8 b) fnum + 7.2!= fnum / 2 e) 3 * num1 + 4 < num3 * != / 2 3 * < 2 * != < 4 c) fnum * 2 > num1 +20 f) A <= ch *2 > A <= K > 25 Characters are ordered according to their ASCII code representations: 0' < 1' < 2' <... < 9' < A <... < Z < a... < z. Relational operators have a lower precedence than arithmetic operators: o In the absence of parentheses, arithmetic operations are evaluated before any relational operation is evaluated. However, it is a good programming practice to use parentheses to clarify the meaning of logical expressions. For example: (fnum * 2) > (num1 + 20) Compound Conditions A compound condition is built from simple conditions using logical operators. Logical Operators C++ Symbol Meaning Evaluation && AND OR <condition1> && <condition2> is true if and only if both conditions are true <condition1> <condition2> is true if and only if at least one of the two conditions is true! NOT!<condition> is true if and only if <condition> is false 2013 Gilbert Ndjatou Page 59

4 Evaluations of compound conditions && && && && There is a short-circuit evaluation of a compound condition when you do not have to evaluate the right-most condition in order to get the true value of the compound condition: and Therefore - Also, && and && Therefore && - Exercise CS1* Assuming that the variables are defined and initialized as follows: int num1 = 5, num2 = 7, num3 = 2; float fnum = 11.75; char ch = K ; Compute the true value of each of the following compound conditions: a) num1 >= 5 num2 + 3 == num3 d) num2 + 3 == num3 * 4 ch >= Z b) A <= ch && fnum + 7.2!= 2.5 e) num1 < 3 && num2 > num3 c)!(3 * num1 + 4 < num3 * 2) f)!(fnum * 2 < num1 + 20) 2013 Gilbert Ndjatou Page 60

5 Precedence of C/C++ Operators Operator Order of Evaluation Precedence! Unary right to left 7 * / left to right 6 % + - left to right 5 < <= > left to right 4 <= == left to right!= 3 && left to right 2 left to right 1 In the evaluation of an expression, operators with higher precedence are evaluated before those with lower precedence. Operators with the same precedence are evaluated in the order specified in the order of evaluation column. Exercise CS2 Assuming that the variables are defined and initialized as follows: int num1 = 9, num2 = 5, num3 = 10; float fnum = 12.50; char ch = P ; Evaluate the following conditions (using short circuit evaluation whenever possible): a) 2 * num1-5 >= 9 fnum / <= 6.5 b) num1 + num2 == num3 + 5 && 2 * num3 <= 4 * num2 c)! (num1 + 5 <= 13) d) num1 + 5 = = 24 num1 1 > num2 5 e) 2 * num1-5 >= 9 && fnum / <= 6.5 f) num1 - num2 <= num1 / 3 num1 * num2 > 100 g) num1-5 >= num3 num2 < 15 && num1 >= Gilbert Ndjatou Page 61

6 Accuracy of Floating-Point Values The fact that floating-point values are approximated inside a computer makes it difficult to test for the equality of floating-point values. For example, if the variable fnum is defined as follows: float fnum = 7.1; Then, the condition: fnum / 2 == 3.55 may not be true. The problem may be solved by assuming that two floating-point values are equal if their difference is relatively very small. This is done by testing if the absolute value of their difference is less than a certain value chosen by the programmer (for example ). Using the library function fabs() that takes as argument a floating-point value and returns its absolute value, the condition: value1 == value2 is replaced with the condition: fabs(value1 - value2) < which tests whether the difference between the two values is small enough so that we can make them equal. Evaluation of and In the C/C++ programming language, false is represented by the integer value 0, and any value other than 0 represents true. Therefore, the following two conditions are equivalent (have the same true value): o Conditions value!= 0 and value (value is not zero means that it is true) o Conditions value == 0 and! value (value is zero means that!value is true) bool Data Type A variable with data type bool can only hold the bool values true and false. Examples: bool flag = true; bool condvalue = false, HighTemperature, ExtremeTemperature; double temperature; HighTemperature = false cin >> temperature; HighTemperature = (temperature >= 120) ExtremeTemperature = (HighTemperature (temperature <= -20); 2013 Gilbert Ndjatou Page 62

7 Exercise CS3 1. Which of the following conditions are equivalent (that means have the same true value)? a) num!= 0 d)!num b) num == 0 e)!(num == 0) c) num 2. Suppose that a person s age is stored in the variable age, his number of children in the variable numchild, his salary in the variable salary, and his height in the variable height. Write the relational expressions to specify the following conditions: a. he is 45 year old. b. he is more than 5.7 feet tall. c. his salary is between 35,000 and 50,000. d. he does not have 3 children. e. he is either 6.0 feet tall, or he has less than 4 children. f. he is not older than 35 and he has 2 or 3 children 2013 Gilbert Ndjatou Page 63

8 Two-Way Selection using the if-else Structure The solutions of some problems require the CPU to test a condition and to select the action to be performed based on whether or not that condition is true. Example: Suppose that at a party, you serve alcohol drinks only to guests who are 21 or older, and a juice to guests who are less than 21. When a guest comes to get a drink, you first test his age: if he is 21 or older, you serve him an alcohol drink; otherwise you serve him a juice. The solutions of these types of problems are written using a two-way selection structure which is specified using a flowchart as follows: Condition F-Statement T-Statement Next-Statement It says to do the following: Test condition a. if it is true, perform the actions (T-Action) specified by T-Statement, b. otherwise, perform the actions (F-Action) specified by F-Statement. Next-Statement is the statement that says what to do after any of the actions (F-Action or T-Action) above has been executed. A two-way selection structure is specified in C++ using the if - else structure as follows: if (<condition>) <T-statement> else <F-statement> <Next-Statement> 2013 Gilbert Ndjatou Page 64

9 <T-statement> is a single statement that specifies the T-Action <F-statement> is a single statement that specifies the <F-Action>. Case Study CS1 Problem Statement Write a program to read the age of an individual, and to output the message serve alcohol drink if he is 21 or older, and the message serve juice otherwise. Your program will then output the message thank you for using this program. Program Logic output: Serve alcohol or Serve Juice, depending on the individual s age. Input: an individual s age. Variables: age (int) to hold an individual s age. Algorithm Specification (using a Flowchart) start Read age Write serve a juice age >= 21 Write serve alcohol drink Write Thank you for using this program Stop 2013 Gilbert Ndjatou Page 65

10 Figure CS1 Using the if-else Structure /************************************************************************* Program to read the age of an individual and to output the type of drink that he should be served *************************************************************************/ #include <iostream> using namespace std; #define DRINKAGE 21 int main() int age; // to hold an individual s age /* read the individual s age */ cout << \n\nenter the individual s age please:\t ; cin >> age; /* determine what type of drink he should be served */ if (age >= DRINKAGE) // he is over the drinking age cout << endl << Serve alcohol drink ; else // he can not drink alcohol cout << endl << Serve juice ; cout << endl << Thank you for using this program ; return (0); Case Study CS2 Problem Statement Write a program to read a positive integer value and to determine if it is even or odd. If it is even, print it with the message EVEN ; otherwise, print it with the message ODD. Program Logic Output: Input: Variable: the input value with the message EVEN or ODD, depending on whether the input value is even or odd. an integer value. num (int) to hold the input value. Note: An integer value is even if the remainder in its division by 2 is 0; otherwise, it is odd Gilbert Ndjatou Page 66

11 Algorithm Specification (using a Flowchart) Start Read num num % 2 = 0 Write num, odd Write num, even Stop Figure CS2 Using the if - else Structure /************************************************************************ Program to read an integer value and to determine if it is even or odd ************************************************************************/ #include <iostream> using namespace std; int main() int num; // to hold the value read /* read in an integer value */ cout << \n\nenter an integer value please:\t ; cin >> num; /* determine if it is even or odd */ if (num %2 == 0) // it is even cout << endl << num << \teven ; else // it is odd cout << endl << num << \todd ; return ( 0 ); Exercise CS4 Write a C++ code segment to read an integer value and to determine if it is a multiple of 5. If it is a multiple of 5, print it with the message MULTIPLE OF 5, otherwise, print it with the message NOT MULTIPLE OF Gilbert Ndjatou Page 67

12 Exercise CS5 Write a C++ code segment to read a character and to determine if it is a letter of the alphabet. If it is a letter of the alphabet, print it with the message, it is a letter otherwise, print it with the message, it is not a letter. Compound Statement A compound statement has the following syntax: (One or more statements to be executed as a block) Example num2 = num1 + 5; num1 = num1 +1; cout << endl << num1=\t << num1 << \n num2=\t << num2; The statements of a compound statement are executed one after another, starting with the first one in the sequence. A compound statement may appear anywhere in a C++ program where a single statement may appear. If you have to specify two or more statements as the T-statement or the F-statement of an if-else structure, these statements must be specified as a compound statement. Case study CS3 Problem Statement Write a program to read an integer value and to do the following: If the value read is zero, print it with the message INVALID DIVISOR. Otherwise read a second value and then compute and print the quotient and the remainder in the division of the second value by the first. At the end write the message Thank you for using this program Gilbert Ndjatou Page 68

13 Program Logic Output: Input: Variables: the quotient and the remainder in the division of the second value by the first or the message 0 is invalid divisor depending on the input. one or two integer values, depending on the value of the first. divisor (int) to hold the first value. dividend (int) to hold the second value. Note: The second value is input and the quotient and the remainder in the division of the second value by the first are computed only if the first value is not zero. Algorithm Specification (using a Flowchart) Start Read divisor divisor == 0 Read dividend Write dividend / divisor dividend % divisor Write divisor invalid divisor Write Thank you Stop 2013 Gilbert Ndjatou Page 69

14 Figure CS3 Using a Compound Statement in an if-else Structure /************************************************************************* Program to read two integer values and to compute the quotient and the remainder in the division of the second value by the first. *************************************************************************/ #include <iostream> using namespace std; int main() int divisor, dividend; // to hold the first value // to hold the second value /* read in the divisor */ cout << \n\nenter the divisor please:\t ; cin >> divisor; /*-----read the dividend and compute the quotient and the remainder--*/ if (divisor == 0) // it is invalid cout << endl << divisor << \tis INVALID DIVISOR ; else cout << \n\nenter the dividend please:\t ; cin >> dividend; cout << \nthe quotient in the division of:\t << dividend << by << divisor << \tis:\t << (dividend / divisor); cout << \nand the remainder is:\t << (dividend % divisor); cout << \n\nthank you for using this program ; return( 0 ); Exercise CS6* Assuming that all variables are properly defined and initialized, what are the error(s) in each of the following program segments? a. cin >> num; if (num = 5) sum = num + 4; else sum = num + 10; b. cin >> num; if (num > 5 && <= 10) cout << (num + 15); else cout << (num - 3); 2013 Gilbert Ndjatou Page 70

15 c. cin >> num; if (num < 15) result1 = 2 * num; result2 = num + 20; else result1 = 5 * num; result = result1 + result2; cout << \nthe result is:\t << result; Exercise CS7* Trace the execution of the following program segment and show its output for each of the following input values: a. input: 4 b. input: 20 Line # Statements 1 cin >> num; 2 if (num <10 ) 3 num = num + 6; 4 cout << endl << num =\t << num; else 5 cout << endl << num / 4 =\t << (num 4); 6 cout << endl << result =\t << (2 * num); Exercise CS8 Write a C++ code segment to read an integer value into variable num1and another integer value into variable num2 and to do the following: if the value in variable num1 is greater than the value in variable num2 do the following: add 1 to the value in num1 and 5 to the value in num2 and then print the result of the product of the new value in num1 and the new value in num2; otherwise, do the following: subtract 1from the value in num1 and 5 from the value in num2 and then print the result of the product of the new value in num1 and the new value in num2. Exercise CS9 A department store offers a rebate of 5% if the total amount of the purchase is at least 100 and a rebate of 2% otherwise. A sale tax of 8.25 % is also imposed on the price of each purchase (after the rebate). Write a C++ code segment to read the unit price and the number of items purchased, and to output the amount of the rebate and the price (including taxes) of the purchase Gilbert Ndjatou Page 71

16 Counter-Controlled Iteration using the while Structure The solutions of some problems require the CPU to repeat the execution of one or more statements a certain number of times. Example: Suppose that a candy bar costs 70 cents in a candy machine that only accepts dimes. To buy a candy bar from this machine, a user has to deposit a dime in the machine seven times. The solutions of these types of problems are written using a counter-controlled iteration (or loop) which is specified using a flowchart as follows: counter = initial-value Counter < final-value Body-of-the-Loop Next-Statement Body-of- the- Loop counter Next-Statement consists of the statements whose executions are repeated by the CPU. is called the loop counter it is a variable that is used to hold the number of repetitions is the first statement to be executed after the repetitions. Initial/Final Value If the initial value is 0 (no execution is done yet), then the final value must be the number of executions. If the initial value is 1 (one execution is about to be done), then the final value must be the number of execution plus 1. Loop Increment After each execution of the body-of-the-loop, the loop counter must be updated to reflect the number of executions. The statement that you use to update the loop counter is called the loop increment. The loop increment is a statement in the body-of-the-loop Gilbert Ndjatou Page 72

17 Algorithm of the Candy Bar Machine (using a flowchart) Start total = 0 count = 0 count < 7 Read coin total = total + coin Write Thank you count = count + 1 Stop Specification of a Counter-Controlled Iteration in C++ A counter-controlled iteration may be specified in C++ using the while structure as follows: counter = initial-value; while (counter < final-value) <Body-of-of the-loop (including the increment-statement)> <Next-statement> 2013 Gilbert Ndjatou Page 73

18 Algorithm for the Candy Bar Machine Problem (in C++) int total, coin, count; // to hold the total value of the coins // to hold the value of a coin // to hold the number of repetitions total = 0; count = 0; while ( count < 7 ) cin >> coin; total += coin; count ++; cout << endl << Thank You ; Case Study CS4 Problem Statement Write a program to read 30 weight measurements in pounds and to convert them into kilograms. Note that 1 Lb =.454 Kgs. Program Logic Input: Output: Variables: 30 weight measurements (in Lbs). 30 weight measurements (in Kgs). count (int) to count the weight measurements: Initial value is 0 - Final value is 30. pound (double) to hold a weight measurement in Lbs Gilbert Ndjatou Page 74

19 Algorithm Specification (using a flowchart) Start count = 0 count < 30 Read pound Write.454 * pound count = count + 1 Write Thank you Stop Figure CS4 Counter-Controlled Iteration using the while Structure Line Number 1 /************************************************************* 2 Program to read 30 weight measurements in pounds and convert 3 them into kilograms 4 *************************************************************/ 5 #include <iostream.h> 6 #include <iomanip.h> 7 #define MAXCOUNT 30 8 #define COEFICIENT int main() int count; // to count weight measurements 13 double pound, // the current weight measurement in Lbs Gilbert Ndjatou Page 75

20 15 cout << fixed << showpoint << setprecision(2); /*read all weight measurements (Lbs) and convert them to Kgs*/ 18 count = 0; // no weight measurement is read so far 19 while (count < MAXCOUNT) // repeat thirty times cout << \nenter a weight measurement please:\t ; 22 cin >> pound; 23 cout << \t = << (.454 * pound); 24 count ++; cout << endl << Thank you ; 28 return (0); 29 The body of the loop consists of the statements in line 21 to line 24. The loop-counter is initialized in line 18; and the loop-increment statement is in line 24. Exercise CS10* Assuming that all variables are properly defined, find the mistake(s) in the specification of each of the following while structures: a. b. c. while( count < 10 ) while(count < 10) count = 0; while(count < 10 ) cin >> num; count = 0; cout << 2 * num; cin >> num; cin >> num; count = count + 1; cout << 2 * num; cout << 2 * num; count = count + 1; Exercise CS11 Write a C++ code segment to read 50 temperature values in Fahrenheit and to convert them to Celsius. You convert a Fahrenheit temperature to Celsius by using the following formula: Celsius = 5.0 / 9 * (Fahrenheit - 32) Gilbert Ndjatou Page 76

21 Using a Running Total A running total is a variable that is used to compute the sum of the values processed at ach iteration of a loop: it is first initialized to 0 and each new value processed in the loop is added to the previous total. Case Study CS5 Problem Statement Write a program to read 20 integer values and to compute their sum. Program Logic Input: 20 integer values. Output: their sum. Variable: count (int) to count the values: Initial value is 0 (no value is read so far); Final value is 20. value (int) to hold the integer value read. totalvalue (int) to hold the sum of the integer values read so far: Initial value is 0. Algorithm Specification (using a Flowchart) Start totalvalue = 0 count = 0 count < 20 Read value totalvalue = totalvalue + value Write totalvalue count = count + 1 Stop 2013 Gilbert Ndjatou Page 77

22 Figure CS5 Counter-Controlled Iteration using the while Structure Line Number 1 /************************************************************* 2 Program to read twenty integer values and to compute their sum. 3 *************************************************************/ 4 #include <iostream> 5 using namespace std; 6 #define MAXCOUNT int main() 9 10 int count; // to count values 11 value, // to hold the value read 12 totalvalue; // the hold the sum of the values read so far /*------read all values and compute their sum */ 15 totalvalue = 0; 15 count = 0; // no value has been read so far 16 while (count < MAXCOUNT) // repeat twenty times cout << \nenter an integer value please:\t ; 19 cin >> value; 20 totalvalue += value; 21 count++; /*-----print the sum of all the values read */ 25 cout << \n\nthe sum of all the values read is:\t 26 << totalvalue; 27 return (0); 28 Exercise CS12* Each of the following code segments is supposed to read 10 integer values and to compute their sum. What is wrong in each of these code segments? a. b. count = 0; count = 0; while (count < 10 ) while (count < 10 ) sum = 0; cin>>num; cin >> num; sum = sum + num; sum = sum + num; count = count + 1; count = count + 1; cout << endl << sum; cout << endl << sum; 2013 Gilbert Ndjatou Page 78

23 Exercise CS13* Write a C++ code segment to read the test scores of twenty students and to compute and print their average. Exercise CS14 A client has purchased 20 products in a store. Write a C++ code segment to read the unit price and the number of items of each product and to compute and print the total price of all these products. Case Study CS6 Problem Statement Write a program to compute the sum of the first 20 positive even integer values (2, 4,...). Program Logic Input: none. Output: the sum of the first 20 positive integer values. Variable: count (int) to count the values: Initial value is 1; Final value is 21. totalvalue (int) to hold the sum of the integer values processed so far: Initial value is 0. Algorithm Specification (using a Flowchart) Start totalvalue = 0 count = 1 Write totalvalue Stop count < 21 totalvalue = totalvalue + 2 * count count = count Gilbert Ndjatou Page 79

24 Figure CS6 Counter-Controlled Iteration using the while Structure Line Number 1 /************************************************************* 2 Program to read twenty integer values and to compute their sum. 3 *************************************************************/ 4 #include <iostream> 5 using namespace std; 6 #define MAXCOUNT int main() 9 10 int count; // to count the values 11 totalvalue; // the hold the sum of the values so far totalvalue = 0; 14 count = 1; 15 while (count < MAXCOUNT) // repeat twenty times totalvalue += 2 * count; 18 count ++; /*-----print the sum of the first 20 positive even values */ 23 cout << \n\nthe sum of the first 20 positive even values is:\t 24 << totalvalue; 25 return (0); 26 Exercise CS15 Write a C++ code segment to add the first 20 positive multiples of 5 ( ) and to output the result. Using a Running Product and a Counter with the initial value Greater than the final Value A running product is a variable that is used to compute the product of values processed at each iteration of a loop: it is first initialized to 1 and each new value processed in the loop is multiplied to it. Case Study CS7 Problem Statement For a positive integer value n, n factorial (written n!) is the product of all the integer values from 1 to n (1 * 2 * 3 *... * n). Write a program to read a positive integer value n, and to compute and print n! 2013 Gilbert Ndjatou Page 80

25 Program Logic Input: a positive integer value. Output: the product of all positive integer values less than or equal to the value read. Variables: number (int) to hold the value read factorial (int) to hold the product of the integer values: initial value = 1 After Iteration Value of number value of factorial - n 1 1 n x n 2 n x n x (n - 1)... n x n x (n - 1) x... x 2 Algorithm Specification (using a Flowchart) Start Read number factorial = 1 number > 1 Factorial = factorial * number Write factorial number = number - 1 Stop 2013 Gilbert Ndjatou Page 81

26 Figure CS7 Counter-Controlled Iteration using the while Structure Line Number 1 /************************************************************* 2 Program to read a positive integer value and to compute and print its factorial. 3 *************************************************************/ 4 #include <iostream> 5 using namespace std; 6 int main() 7 8 int number, //integer value/loop counter 9 factorial = 1; // to hold the product /* read the integer value */ 12 cout << endl << enter a positive integer value:\t ; 13 cin >> number; /* compute the factorial of the number read */ 16 while (number > 1) factorial *= number; 19 number --; /* print the factorial */ 23 cout << endl << n factorial is:\t 24 << factorial; 25 return (0); 26 The body of the loop consists of the statements in lines 18 and 19. The loop-counter is initialized in line 13; and the loop-increment statement is in line 19. Exercise CS16 Write a C++ code segment to generate the squares (n*n) of the integer values 20, 18, 16, 14,..., 2, starting with 20. Exercise CS17 Write a C++ code segment to read ten integer values and to compute and print their product Gilbert Ndjatou Page 82

27 Logically-Controlled Iteration using the while Structure The solutions of a class of problems require the CPU to repeat the execution of one or more statements as long as a certain condition is true (that means, until a certain condition becomes false). Case Study CS8 Problem Statement A can of soda costs $ 1.00 in a soda machine, and a user buys a can of soda by depositing coins (nickels, dimes or quarters) in the machine until the total value of the coins deposited in the machine is greater than or equal to $ Write a program to read the value of each coin deposited in the soda machine (5, 10, or 25) until the total value of the coins deposited in the machine is greater than or equal to 100. The program will then output the message Thank you for using the soda machine and the amount of the change. Program Logic input: the value of a coin (5, 10 or 25). Output: Note: the message Thank you for using this soda machine and the amount of change. To read the value of each coin deposited in the machine and to compute their sum, we need the following: A variable coinvalue to hold the input value of a coin. A variable totalvalue to hold the sum of the values of the coins read so far. It is initialized to 0 before the body-of-the-loop. The loop condition is: totalvalue < 100. Variables: coinvalue ( int ) totalvalue ( int ) to hold the value of a coin. to hold the total value of the coins deposited so far Gilbert Ndjatou Page 83

28 Algorithm Specification (using a Flowchart) Start totalvalue = 0 totalvalue < 100 Read coinvalue totalvalue = totalvalue + coinvalue Write Thank you Write totalvalue Stop 2013 Gilbert Ndjatou Page 84

29 Figure CS8 Line Number Logically-Controlled Iteration using the while Structure 1 /***************************************************************** 2 Program to monitor the purchase of a can of soda in a soda machine 3 *****************************************************************/ 4 #include <iostream> 5 using namespace std; 6 int main() 7 8 const int SODAPRICE = 100; // the price of a can of soda 9 int coinvalue, // the value of a coin 10 totalvalue = 0; // the total value of the coins 11 while( totalvalue < SODAPRICE ) /* read the value of the next coin */ 14 cout << endl << enter the value of the next coin:\t ; 15 cin >> coinvalue; /* compute the total value of the coins deposited so far */ 18 totalvalue = totalvalue + coinvalue; /*--- say thank you and give the change back to the user */ 22 cout << \n\nthank you for using this soda machine 23 << \n\nyour change is:\t << (totalvalue - SODAPRICE); 24 return ( 0 ); 25 Exercise CS18* The manager of a store is required to make a deposit of $ 10,000 whenever the sum of the daily sales in that store is $ 10,000 or more. Write a C++ code segment to read the daily sales in that store, and to compute their sum until it becomes greater than or equal to $ 10,000. The sum of the daily sales and the message it is time to make a deposit are then printed. Exercise CS19 A store has 120 bags of coffee and every day, the amount of bags sold is deducted from the current stock until it becomes less than or equal to 30. The manager of the store must then place a new order. Write a C++ code segment to read the number of bags sold daily and to update the current stock until it becomes less than or equal to 30. The message place a new order and the amount of bags to purchase in order to have 120 bags are then printed Gilbert Ndjatou Page 85

30 while Structure with one Statement in the Body-of- the-loop When the body-of-the-loop consists of just one statement, the braces may be omitted from the while structure. Case Study CS9 Problem Statement Write a program to compute the smallest power of 5 greater than (1, 5, 25, 125,... ). Program Logic Input: none. Output: the smallest power of 5 greater than Note: To compute the smallest power of 5 greater than 10000, we need: A variable power to hold the powers of 5. It is initialized to 1 before the body-of-the-loop. The current value of variable power is multiplied by 5 in the body-of-the-loop until it becomes greater than The loop condition is therefore: power <= After Value of Iteration variable power x 5 = x 5 = x 5 = Variable: power (int) to hold the powers of Gilbert Ndjatou Page 86

31 Algorithm Specification (using a Flowchart) Start power = 1 power <= Power = power * 5 Stop Figure CS9 Line Number while Structure with a single statement in the body-of-the-loop 1 /*************************************************************** 2 Program to compute the smallest power of 5 greater than ****************************************************************/ 4 #include <iostream> 5 using namespace std; 6 int main() 7 8 int power; // to hold the current power of 5 9 power = 1; // first power of 5 10 while ( power <= 10000) 11 Power = power * 5; /* print the result */ 14 cout << endl << power 15 << is the smallest power of 5 greater than 10000"; 16 return (0); 17 Although the body-of-the-loop consists of just one statement, it could also be specified as a compound statement as follows: while (power <= 10000) power = power * 5; 2013 Gilbert Ndjatou Page 87

32 Sentinel-Controlled Iteration When you want to process a list of values and you do not know how many values are in the list, you can use a sentinel value (dummy value, flag value, or signal value) to mark the end of the list. A sentinel value is in general chosen in such a way that they can not possibly be one of the data items in the list. Example: For a program to read and process a list of test scores received by students in an exam, a sentinel value might be -1 or -99. With -99, the list could be: The data items in the list are accessed and processed one at a time until the sentinel value is accessed. However, the sentinel value must not be processed. The algorithm to perform this type of repetition is specified using a flowchart as follows: Read/Access the first data item data item!= sentinel Process a data item Next-Statement Read/Access the next data item 2013 Gilbert Ndjatou Page 88

33 It is specified using the while structure as follows: <statement-to read/access-the first-value> While(<value-read/access!= sentinel-value>) <processing-statements> <statement-to-read/access-the-next-value> <processing-statements> consists of one or more statements used to process a data item in the list. Case Study CS10 Problem Statement Write a program to read one or more weight measurements in pounds and to convert them into kilograms. The dummy value is entered to end the input of the weight measurements. Note that 1 Lb =.454 Kgs. Program Logic Input: one or more weight measurement (in Lbs) followed by the sentinel value Output: weight measurements in (Kgs). Variables: pound (double) to hold a weight measurement in Lbs Gilbert Ndjatou Page 89

34 Algorithm Specification (using a Flowchart) Start Read pound pound!= -99 Write.454 * pound Read pound Write Thank you Stop Figure CS10 Sentinel-Controlled Iteration using the while Structure Line Number 1 /************************************************************* 2 Program to read one or more weight measurements in pounds and 3 to convert them into kilograms. 4 *************************************************************/ 5 #include <iostream> 6 #include <iomanip> 7 using namespace std; 8 #define COEFICIENT #define DUMMYWEIGHT int main() double pound, // the current weight measurement in Lbs cout << fixed << showpoint) << setprecision(2); Gilbert Ndjatou Page 90

35 17 /*read the first weight measurement or the dummy value -99.0*/ 18 cout << endl << Enter a weight measurement or to terminate:\t ; 19 cin >> pound; 20 while (pound!= DUMMYWEIGHT) cout << \t = << (.454 * pound); 23 cout << endl << Enter a weight measurement or to terminate:\t ; 24 cin >> pound; cout << endl << Thank you ; 27 return (0); 28 Exercise CS20* The following program that should read a list of integer values and compute their sum until the sentinel value -99 is read, contains some error(s). Rewrite it with these errors corrected. #include <iostream> using namespace std; #definedummyvalue -99 int main( ) int total, value; cout << \nenter all values to add followed by << DUMMYVALUE << to stop\n ; while ( value!= DUMMYVALUE ) cin >> value; total = total + value; cout << endl << The total of these value is:\t <<total; return( 0 ); Exercise CS21* Write a C++ code segment to read one or more temperature values in Fahrenheit and to convert them to Celsius. The sentinel value -99 marks the end of the input temperatures. You convert a Fahrenheit temperature to Celsius by using the following formula: Celsius = 5.0 / 9 *(Fahrenheit - 32). Exercise CS22 Write a C++ code segment to read the pay rate and the number of hours of work of one or more employees and to compute each employee s gross pay: pay rate * number of hours. The dummy pay rate marks the end of the input values Gilbert Ndjatou Page 91

36 Exercise CS23 Write a C++ code segment to read the test scores of one or more students (until the sentinel value -99 is read) and to compute their average. One-Way Selection using the if Structure A one-way selection structure is used to specify that the execution of one or more actions be performed only if a test performed on a condition is true. It is specified using a flowchart as follows: condition C-Statement Next-Statement C-Statement is one or more statements that specify the operations to be performed when condition evaluates to true. It is specified in C++ language using the if structure as follows: if (<condition>) <Statement> <Next-Statement> where <Statement> is a single statement or a compound statement. Note that when <condition> evaluates to false, no action is performed. Instead, the execution of the program continues with the execution of <Next-Statement> Gilbert Ndjatou Page 92

37 Case Study CS11 Problem Statement A rebate of 5% is given in a store only if the price of the merchandise is at least $ Write a program to read the unit price and the number of quantity of the merchandise, and to compute the amount of the purchase after the rebate if applicable. Program Logic Input: Output: the unit price and the quantity of the merchandise. the total amount of purchase. Variables: unitprice ( double ) to hold the unit price. quantity ( int ) to hold the quantity. purchase ( double ) to hold the amount of purchase. Algorithm Specification (using a Flowchart) Start Read unitprice, quantity purchase = unitprice * quantity purchase >= purchase = purchase -.05 * purchase Write purchase Stop 2013 Gilbert Ndjatou Page 93

38 Figure CS11 Line Number One-Way Selection using the if Structure 1 /**************************************************************** 2 Program to compute the total amount of purchase in a store 3 ****************************************************************/ 4 #include <iostream> 5 using namespace std; 6 int main() 7 8 const double MINPURCHASE = ; //minimum purchase 9 const double RRATE = 0.05; // rebate rate 10 double unitprice, // unit price 11 Purchase // amount of purchase 12 int quantity; // number of quantity /* read in the unit price and the quantity */ 15 cout << \nenter the merchandise unit price:\t ; 16 cin >> unitprice; 17 cout << \nenter its quantity:\t ; 18 cin >> quantity; /* compute the amount of purchase */ 21 purchase = unitprice * quantity; 22 if(purchase >= MINPURCHASE) 23 purchase = purchase - RRATE * purchase; /* print the amount of purchase */ 26 cout << \nyour total amount of purchase is:\t 27 << purchase; 28 return( 0 ); 29 The Null Statement The null statement is a statement that consists of just the semicolon. It says to do nothing, but to continue with the next operation. You may also use the if-else structure and the null statement to specify a one-way selection as follows: if (<condition>) else; <Statement> <Next-Statement> 2013 Gilbert Ndjatou Page 94

39 Example The if structure in lines 22 and 23 of the program in Figure 3.19 could be written as follows: if (purchase >= ) else; purchase = purchase - RRATE * purchase; /* print the amount of purchase */ cout << \nyour total amount of purchase is:\t << purchase; Exercise CS24* What is the output of the following program segment for each of the following input values? a. input value: 4 b. input value: 20 cin >> num; if( num >= 5) pnum = num + 7; cout << endl << pnum=\t << pnum; cout << result=\t << (num - 1); Exercise CS25* greatt, smallt, and somet are integer variables with initial values. Write a C++ code segment to read an integer value and to do the following: add 1 to smallt if the value read is less than 5; then add 2 to greatt if the value read is greater than 20, otherwise subtract 3 from smallt. Then, regardless of the value read add 7 to somet. Exercise CS26 In a department store, a 10% rebate is given for every purchase of at least $ Write a C++ code segment to read the unit price of a product, the quantity purchased, and to compute the amount of the purchase after the rebate if applicable. Exercise CS27 sum, large_ct, middle_ct, and small_ct are integer variables with initial values. Write a C++ code segment to carry out the following tasks: read a value into the integer variable num. if the value read is greater than 100, add 1 to variable large_ct; if it is less than 50, add 2 to variable small_ct; otherwise, add 3 to variable middle_ct; regardless of the value read, add it to variable sum Gilbert Ndjatou Page 95

40 Multiple-Way Selection using if-else Structures A multiple-way selection structure is used to specify that the action to be performed be chosen from a list of three or more actions based on the true values of two or more conditions. A multiple-way selection with four actions and three conditions is specified as follows: condition1 Action-1 condition2 Action-2 condition3 Action-3 Action-4 Next-Action Condition1 is first tested, and if it is true, Action-1 is executed, followed by Next-Action; Otherwise, condition2 is tested, and if it is true, Action-2 is executed, followed by Next-Action; Otherwise, condition3 is tested, and if its true, Action-3 is executed, followed by Next-Action; Otherwise, Action-4 is executed, followed by Next-Action. Note that only one of the actions, Action-1, Action-2, Action-3, or Action-4 is executed. In some situations, Action-4 may also be the null action Gilbert Ndjatou Page 96

41 This behavior is specified in C/C++ using if-else structures as follows: if ( <condition1> ) <Statement-1> else if ( <condition2> ) <Statement-2> else if ( <condition3> ) <Statement-3> else <Statement-4> <Next-Statement> <Statement-1>, <Statement-2>, <Statement-3>, and <Statement-4> are single or compound statements that specify respectively, Action-1, Action-2, Action-3, and Action-4. <Next-Statement> is a statement that specifies the Next-Action. In the case that <Statement-4> is the null statement, this behavior may also be specified as follows: if ( <condition1> ) <Statement-1> else if ( <condition2> ) <Statement-2> else if ( <condition3> ) <Statement-3> <Next-Statement> Case Study CS12 Problem Statement Four letters M, S, D, and W are used to encode the marital status of an individual as follows: M (married), S (single), D (divorced), and W (widowed). Any other character is considered invalid. Write a program to read a marital code and to output the corresponding marital status. Program Logic Input: Output: Variables: mcode (char ) a marital code (capital M, S, D, or W). a marital status. Any other character is considered invalid. to hold the marital code Gilbert Ndjatou Page 97

42 Algorithm Specification (using a Flowchart) Start Read mcode mcode = M Write married mcode = S mcode = D Write single Write divorced Mcode = W Write Widowed Write invalid Stop Figure CS12 Multiple-Way Selection using if-else Structures Line Number 1 /**************************************************************** 2 Program to read a marital code and to output the corresponding 3 marital status. 4 ****************************************************************/ 5 #include <iostream> 6 using namespace std; 2013 Gilbert Ndjatou Page 98

43 7 int main() 8 9 char mcode; // to hold a marital code /* read in a marital code */ 12 cout << \nenter a marital code:\t ; 13 cin >> mcode; /*---determine and print the corresponding marital status --*/ 16 if (mcode == M ) 17 cout << \nthis individual is married ; 18 else if (mcode == S ) 19 cout << \nthis individual is single ; 20 else if (mcode == D ) 21 cout << \nthis individual is divorced ; 22 else if (mcode == W ) 23 cout << \nthis individual is a widow ; 24 else 25 cout << \nthe marital code is invalid ; 26 return( 0 ); 27 Exercise CS28* A florist who sells four different types of bouquets of flowers has numbered them 101, 202, 303, and 404 with their unit prices specified as follows: ITEM NUMBER UNIT PRICE 101 $ $ $ $ 6.50 Write a C++ code segment to read an item number and the number of bouquets of that type purchased, and to compute and print the price of those bouquets. Exercise CS29 A game consists of selecting a positive integer value and rewarding bonuses to the player according to the remainder in the division of that number by 5 as follows: REMAINDER BONUS Write a C++ code segment to read a positive integer value and to output the bonus received by the user Gilbert Ndjatou Page 99

44 Case Study CS13 Problem Statement Write a program to read a test score and to determine and print the corresponding letter grade as follows: A ( score >= 90.00) B (80.00 <= score < 90.00) C (70.00 <= score <80.00) D (60.00 <= score < 70.00), F (score < 60.00). It is assumed the input value is a valid test score. Program Logic Input: a test score (floating-point value in the range 0.00 to ). Output: the corresponding letter grade. Variables: score (double ) to hold a test score. Algorithm Specification Using a Flowchart Start Read score score >= Write A Write B score >= Score >= Write C score >= Write D Write F Stop 2013 Gilbert Ndjatou Page 100

45 Figure CS13 Line Number Multiple-Way Selection using if-else structures 1 /**************************************************************** 2 Program to read a test score and to determine and output the 3 corresponding letter grade. 4 ****************************************************************/ 5 #include <iostream.h> 6 using namespace std; 7 int main() 8 9 double score; // to hold a test score /* read in a test score */ 12 cout << \nenter a test score:\t ; 13 cin >> score; /*----determine and print the corresponding letter grade ---*/ 16 if ( score >= 90.00) 17 cout << \nthe letter grade is:\t << A ; 18 else if (score >= 80.00) 19 cout << \nthe letter grade is:\t << B ; 20 else if (score >= 70.00) 21 cout << \nthe letter grade is:\t << C ; 22 else if (score >= 60.00) 23 cout << \nthe letter grade is:\t << D ; 24 else 25 cout << \nthe letter grade is:\t << F ; 26 return ( 0 ); 26 The multiple-way selection specified in line 16 to line 25 could also be written as follows: if ( score < 60.00) cout << \nthe corresponding letter grade is:\t << F ; else if (score < 70.00) cout << \nthe corresponding letter grade is:\t << D ; else if (score < 80.00) cout << \nthe corresponding letter grade is:\t << C ; else if (score < 90.00) cout << \nthe corresponding letter grade is:\t << B ; else cout << \nthe corresponding letter grade is:\t << A ; 2013 Gilbert Ndjatou Page 101

46 Exercise CS30* What is the output of the following program segment for each of the following input values? a. input value: 3 b. input value: 7 c. input value: 12 cin >> num; if (num < 5) cout << "Red\n"; else if (num < 10) cout << "Yellow\n"; else cout << "Green\n"; cout << blue Exercise CS31* The decision table below shows fines imposed for speeding violations. Write a C++ code segment to read the speed of a car and to output the corresponding fine. Speed <= 50 mph Fine = $ < Speed <= 70 Fine = $ < Speed <= 80 Fine = $ Speed > 80 Fine = $ Exercise CS32 A department store offers rebates to customers according to the price of the items purchased as follows: Price >= $ Rebate = $ $ 50 <= Price < $ Rebate = $ 5.00 $ 20 <= price < $ Rebate = $ 2.00 price < $ No rebate A sale tax of 8.25% is also imposed on the price of each purchase (after the rebate, if any). Write a C++ code segment to read the price of a product and to output the rebate received by the customer, the price (including the rebate), and the amount due (including taxes) Gilbert Ndjatou Page 102

47 Iterations using the for Structure The for structure has the following general syntax: for(<init-expression-list> ; <loop-condition> ; <increment-expression-list>) <body-of-the-loop> It is executed in the same way that the following while structure is executed: <init-expression-statements> while ( <loop-condition> ) <body-of-the-loop> <increment-expression-statements> Example 1. The following counter-controlled iteration (specified using the while structure) may be specified using the for structure in any of the following ways in (a), (b), and ( c ): totalscore = 0; testcount = 0; // no test score has been read so far while (testcount < 20) // repeat twenty times cout << \nenter a test score please:\t ; cin >> score; totalscore + = score; testcount ++; 2013 Gilbert Ndjatou Page 103

48 ( a ) The <init-expression-list> consists of the expression, testcount = 0, The <loop-condition> is testcount < 20, and The <increment-expression-list> consists of the expression, testcount ++. totalscore = 0; for (tescount = 0 ; testcount < 20 ; testcount ++) cout << \nenter a test score please:\t ; cin >> score; totalscore + = score; // repeat twenty times ( b ) Any expression that is evaluated before the <loop condition> is tested for the first time may also be moved into the <init-expression-list>. So, we may also specify the expression totalscore = 0 in the <init-expression-list> as follows: for (totalscore = 0, tescount = 0 ; testcount < 20 ; testcount ++) // repeat twenty times cout << \nenter a test score please:\t ; cin >> score; totalscore + = score; ( c ) Expressions that are evaluated in the <body-of-the-loop> may be moved into the <incrementexpression-list>. However, keep in mind that expressions in an expression list are evaluated from left to right. So, we may move the expression totalscore + = score from the <body-of-the-loop> to the <increment-expression-list> before the loop increment expression as follows: 2013 Gilbert Ndjatou Page 104

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

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

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 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

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

More information

Chapter 1 INTRODUCTION

Chapter 1 INTRODUCTION Chapter 1 INTRODUCTION A digital computer system consists of hardware and software: The hardware consists of the physical components of the system. The software is the collection of programs that a computer

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

Chapter 4 - Notes Control Structures I (Selection)

Chapter 4 - Notes Control Structures I (Selection) Chapter 4 - Notes Control Structures I (Selection) I. Control Structures A. Three Ways to Process a Program 1. In Sequence: Starts at the beginning and follows the statements in order 2. Selectively (by

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

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

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

More information

Chapter 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

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

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

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

More information

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

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

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

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

More information

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

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

More information

Chapter 5. 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

BITG 1233: Introduction to C++

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

More information

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

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja

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

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

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program 1 By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program variables. Apply C++ syntax rules to declare variables, initialize

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

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

More information

VARIABLE, OPERATOR AND EXPRESSION [SET 1]

VARIABLE, OPERATOR AND EXPRESSION [SET 1] VARIABLE, OPERATOR AND EXPRESSION Question 1 Write a program to print HELLO WORLD on screen. Write a program to display the following output using a single cout statement. Subject Marks Mathematics 90

More information

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad

CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad Outline 1. C++ Iterative Constructs 2. The for Repetition Structure 3. Examples Using the for Structure 4. The while Repetition Structure

More information

Other Loop Options EXAMPLE

Other Loop Options EXAMPLE C++ 14 By EXAMPLE Other Loop Options Now that you have mastered the looping constructs, you should learn some loop-related statements. This chapter teaches the concepts of timing loops, which enable you

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

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

Objectives. In this chapter, you will:

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

More information

download instant at Introduction to C++

download instant at  Introduction to C++ Introduction to C++ 2 Programming: Solutions What s in a name? that which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would

More information

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char Week 1 Operators, Data Types & I/O Gaddis: Chapters 1, 2, 3 CS 5301 Fall 2016 Jill Seaman Programming A program is a set of instructions that the computer follows to perform a task It must be translated

More information

Chapter 5 : Repetition (pp )

Chapter 5 : Repetition (pp ) Page 1 of 41 Printer Friendly Version User Name: Stephen Castleberry email Id: scastleberry@rivercityscience.org Book: A First Book of C++ 2007 Cengage Learning Inc. All rights reserved. No part of this

More information

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II Superior University Department of Electrical Engineering CS-115 Computing Fundamentals Experiment No.7 User Defined Functions II Prepared for By: Name: ID: Section: Semester: Total Marks: Obtained Marks:

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

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions.

1. C++ Overview. C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions. 1. C++ Overview 1. C++ Overview C++ Program Structure. Data Types. Assignment Statements. Input/Output Operations. Arithmetic Expressions. Interactive Mode, Batch Mode and Data Files. Common Programming

More information

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

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

More information

Chapter 4 : Selection (pp )

Chapter 4 : Selection (pp ) Page 1 of 40 Printer Friendly Version User Name: Stephen Castleberry email Id: scastleberry@rivercityscience.org Book: A First Book of C++ 2007 Cengage Learning Inc. All rights reserved. No part of this

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

Programming. C++ Basics

Programming. C++ Basics Programming C++ Basics Introduction to C++ C is a programming language developed in the 1970s with the UNIX operating system C programs are efficient and portable across different hardware platforms C++

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

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

A Freshman C++ Programming Course

A Freshman C++ Programming Course A Freshman C++ Programming Course Dr. Ali H. Al-Saedi Al-Mustansiria University, Baghdad, Iraq January 2, 2018 1 Number Systems and Base Conversions Before studying any programming languages, students

More information

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

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

More information

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++ CHAPTER 9 C++ 1. WRITE ABOUT THE BINARY OPERATORS USED IN C++? ARITHMETIC OPERATORS: Arithmetic operators perform simple arithmetic operations like addition, subtraction, multiplication, division etc.,

More information

Chapter 7 Arithmetic

Chapter 7 Arithmetic Chapter 7 Arithmetic 7-1 Arithmetic in C++ Arithmetic expressions are made up of constants, variables, operators and parentheses. The arithmetic operators in C++ are as follows + (addition) - (subtraction)

More information

Chapter 6 Pointers and Arrays

Chapter 6 Pointers and Arrays Chapter 6 Pointers and Arrays This chapter addresses the following two issues: 1. How to access a variable (memory location) using its address. 2. How to process a collection of data as a list or a table.

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

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

Subject: Computer Science

Subject: Computer Science Subject: Computer Science Topic: Data Types, Variables & Operators 1 Write a program to print HELLO WORLD on screen. 2 Write a program to display output using a single cout statement. 3 Write a program

More information

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

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

More information

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++ DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++ Objective: To Learn Basic input, output, and procedural part of C++. C++ Object-orientated programming language

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

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

Review of Important Topics in CS1600. Functions Arrays C-strings

Review of Important Topics in CS1600. Functions Arrays C-strings Review of Important Topics in CS1600 Functions Arrays C-strings Array Basics Arrays An array is used to process a collection of data of the same type Examples: A list of names A list of temperatures Why

More information

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. Week 3 Functions & Arrays Gaddis: Chapters 6 and 7 CS 5301 Fall 2015 Jill Seaman 1 Function Definitions! Function definition pattern: datatype identifier (parameter1, parameter2,...) { statements... Where

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

CHAPTER 3 BASIC INSTRUCTION OF C++

CHAPTER 3 BASIC INSTRUCTION OF C++ CHAPTER 3 BASIC INSTRUCTION OF C++ MOHD HATTA BIN HJ MOHAMED ALI Computer programming (BFC 20802) Subtopics 2 Parts of a C++ Program Classes and Objects The #include Directive Variables and Literals Identifiers

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

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

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

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

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Copyright 2009 Publishing Pearson as Pearson Education, Addison-Wesley Inc. Publishing as Pearson Addison-Wesley

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

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

CS101 PLEDGED SPRING 2001

CS101 PLEDGED SPRING 2001 The following exam is pledged. All answers are to be given on the provided answer sheet. The test is closed book, closed note, and closed calculator. If you believe more than one answer is acceptable,

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

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

Reviewing all Topics this term

Reviewing all Topics this term Today in CS161 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for) Functions (pass by value, pass by reference) Arrays (specifically arrays of characters)

More information

Chapter 2: Basic Elements of C++

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

More information

C++ Final Exam 2017/2018

C++ Final Exam 2017/2018 1) All of the following are examples of integral data types EXCEPT. o A Double o B Char o C Short o D Int 2) After the execution of the following code, what will be the value of numb if the input value

More information

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

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

More information

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

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

More information

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING MULTIPLE SELECTION To solve a problem that has several selection, use either of the following method: Multiple selection nested

More information

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

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

More information

Lecture 3 Tao Wang 1

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

More information

VARIABLES & ASSIGNMENTS

VARIABLES & ASSIGNMENTS Fall 2018 CS150 - Intro to CS I 1 VARIABLES & ASSIGNMENTS Sections 2.1, 2.2, 2.3, 2.4 Fall 2018 CS150 - Intro to CS I 2 Variables Named storage location for holding data named piece of memory You need

More information

Control Structures. Repetition (Loop) Structure. Repetition (Loop) Structure. Repetition (Loop) Structure. CS225: Slide Set 8: C++ Loop Structure

Control Structures. Repetition (Loop) Structure. Repetition (Loop) Structure. Repetition (Loop) Structure. CS225: Slide Set 8: C++ Loop Structure Control Structures Flow of control Execution sequence of program statements Repetition (Loop) Structure Control structure used to repeat a sequence of instructions in a loop The simplest loop structure

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

Introduction to Programming

Introduction to Programming Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines

More information

CS2255 HOMEWORK #1 Fall 2012

CS2255 HOMEWORK #1 Fall 2012 CS55 HOMEWORK #1 Fall 01 1.What is assigned to the variable a given the statement below with the following assumptions: x = 10, y = 7, and z, a, and b are all int variables. a = x >= y; a. 10 b. 7 c. The

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

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

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++ 0.1 Introduction This is a session to familiarize working with the Visual Studio development environment. It

More information

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank 1. Match each of the following data types with literal constants of that data type. A data type can be used more than once. A. integer B 1.427E3 B. double D "Oct" C. character B -63.29 D. string F #Hashtag

More information

UNIT- 3 Introduction to C++

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

More information

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

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

More information

A First Program - Greeting.cpp

A First Program - Greeting.cpp C++ Basics A First Program - Greeting.cpp Preprocessor directives Function named main() indicates start of program // Program: Display greetings #include using namespace std; int main() { cout

More information

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points) Name 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 retain their value

More information

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

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

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

Fundamentals of Programming CS-110. Lecture 2

Fundamentals of Programming CS-110. Lecture 2 Fundamentals of Programming CS-110 Lecture 2 Last Lab // Example program #include using namespace std; int main() { cout

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

Starting Out With C++: Early Objects, Seventh Edition Solutions to End-of-Chapter Review Questions

Starting Out With C++: Early Objects, Seventh Edition Solutions to End-of-Chapter Review Questions Starting Out With C++: Early Objects, Seventh Edition Solutions to End-of-Chapter Review Questions Chapter 1 1. programmed 12. key 2. CPU 13. programmer-defined symbols 3. arithmetic logic unit (ALU) and

More information

The following expression causes a divide by zero error:

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

More information

Condition Controlled Loops. Introduction to Programming - Python

Condition Controlled Loops. Introduction to Programming - Python + Condition Controlled Loops Introduction to Programming - Python + Repetition Structures n Programmers commonly find that they need to write code that performs the same task over and over again + Example:

More information