C++ Quick Reference. switch Statements

Similar documents
Introduction to Algorithms and Data Structures. Lecture 6 - Stringing Along - Character and String Manipulation

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

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

Introduction. What is function? Multiple functions form a larger program Modular programming

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

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

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

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

Why Is Repetition Needed?

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

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

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

do { statements } while (condition);

REPETITION CONTROL STRUCTURE LOGO

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

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

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

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

Other operators. Some times a simple comparison is not enough to determine if our criteria has been met.

Chapter Four: Loops II

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

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Discussion 1H Notes (Week 4, April 22) TA: Brian Choi Section Webpage:

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

Fundamentals of Programming CS-110. Lecture 2

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

Total 100. The American University in Cairo Computer Science & Engineering Department CSCE 106. Dr. Khalil Exam II Fall 2011

Introduction to Programming EC-105. Lecture 2

Increment and the While. Class 15

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

Module Contact: Dr Pierre Chardaire, CMP Copyright of the University of East Anglia Version 1

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

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Chapter 3 Problem Solving and the Computer

University of Dublin

Getting started with C++ (Part 2)

CS31 Discussion 1E. Jie(Jay) Wang Week5 Oct.27

Elements of C in C++ data types if else statement for loops. random numbers rolling a die

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.

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

Programming. C++ Basics

The following list represents the written codes in order:

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

Course organization. Course introduction ( Week 1)

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

C-LANGUAGE CURRICULAM

Chapter 2 - Control Structures

System Design and Programming II

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

Chapter 2 - Control Structures

Exam 1 Practice CSE 232 Summer 2018 (1) DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

Looping. Arizona State University 1

Lecture 7: General Loops (Chapter 7)

Introduction to Programming

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Problem Solving: Storyboards for User Interaction

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

switch-case Statements

Lab Instructor : Jean Lai

VARIABLES & ASSIGNMENTS

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

CS 117 Programming II, Spring 2018 Dr. Ghriga. Midterm Exam Estimated Time: 2 hours. March 21, DUE DATE: March 28, 2018 at 12:00 PM

Loops / Repetition Statements

REVIEW. The C++ Programming Language. CS 151 Review #2

Introduction to Programming

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.

Lecture 7 Tao Wang 1

Loops and Files. of do-while loop

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

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

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

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

Strings. Daily Puzzle

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

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

BITG 1233: Introduction to C++

In this chapter you will learn:

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

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

LESSON 4. The DATA TYPE char

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

case control statement (switch case)

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

Number System. Introduction. Natural Numbers (N) Whole Numbers (W) Integers (Z) Prime Numbers (P) Face Value. Place Value

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Chapter 3 - Functions

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

Chapter 2 - Control Structures

Unit 7. 'while' Loops

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Strings and Library Functions

CSCE 206: Structured Programming in C++

Computer Programming I - Unit 5 Lecture page 1 of 14

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

LAB: WHILE LOOPS IN C++

Engineering Problem Solving with C++, Etter/Ingber

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

Transcription:

C++ Quick Reference if Statements switch Statements Array/Initializer if (condition) if (condition) else if (condition1) else if (condition2) else Loop Statements while (condition) do while (condition); for (init; condition; adjustment) switch (intexpression) case value1: break; case valuen: break; default: Frequently Used functions int list[10]; int list[] = 1, 2, 3, 4; Multidimensional Array/Initializer int list[10][15]; int list[2][2] = 1, 2, 3, 4; Dynamic Memory Creation/Deletion int* p1 = new int; int* p2 = new int[10]; delete p1; delete [] p2; time(0) returns current time srand(seed) sets a new seed for generating random numbers rand() returns a random integer pow(a, b) returns a b Character Functions isdigit(c) returns true if c is a digit. isalpha(c) returns true if c is a letter. isalnum(c) returns true if c is a letter or a digit. islower(c) returns true if c is a lowercase letter. isupper(c) returns true if c is an uppercase letter. tolower(c) returns a lowercase for c. toupper(c) returns an uppercase for c. C-String Functions strlen strcpy strcat strcmp atol itoa returns string length copies a string concatenate two strings compares two strings converts a string to a long value converts a an integer a string The string Class Member Functions append appends new contents to the string insert inserts new contents to the string at retrieves character from the string [] string subscript operator length returns the length of the string. substr returns a substring from the string Companion Website: www.cs.armstrong.edu/liang/cpp3e

210 Chapter 5 Loops two characters differ (line 23). In this case, the break statement is used to exit the while loop (line 24). If the loop terminates when low >= high, ispalindrome is true, which indicates that the string is a palindrome. Key Point 5.11 Case Study: Displaying Prime Numbers This section presents a program that displays the first 50 prime numbers in 5 lines, each containing 10 numbers. An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. The program can be broken into the following tasks: n Determine whether a given number is prime. n For number = 2, 3, 4, 5, 6,..., test whether it is prime. n Count the prime numbers. n Display each prime number, and display ten numbers per line. Obviously, you need to write a loop and repeatedly test whether a new number is prime. If the number is prime, increase the count by 1. The count is 0 initially. When it reaches 50, the loop terminates. Here is the algorithm: Set the number of prime numbers to be printed as a constant NUMBER_OF_PRIMES; Use count to track the number of prime numbers and set an initial count to 0; Set an initial number to 2; while (count < NUMBER_OF_PRIMES) Test whether number is prime; if number is prime Display the prime number and increase the count; Increment number by 1; To test whether a number is prime, check whether it is divisible by 2, 3, 4, up to number/2. If a divisor is found, the number is not a prime. The algorithm can be described as follows: Use a bool variable isprime to denote whether the number is prime; Set isprime to true initially; for (int divisor = 2; divisor <= number / 2; divisor++) if (number % divisor == 0) Set isprime to false Exit the loop; The complete program is given in Listing 5.17.

5.11 Case Study: Displaying Prime Numbers 211 Listing 5.17 PrimeNumber.cpp 1 #include <iostream> 2 #include <iomanip> 3 using namespace std; 4 5 int main() 6 7 const int NUMBER_OF_PRIMES = 50; // Number of primes to display 8 const int NUMBER_OF_PRIMES_PER_LINE = 10; // Display 10 per line 9 int count = 0; // Count the number of prime numbers 10 int number = 2; // A number to be tested for primeness 11 12 cout << "The first 50 prime numbers are \n"; 13 14 // Repeatedly find prime numbers 15 while (count < NUMBER_OF_PRIMES) 16 17 // Assume the number is prime 18 bool isprime = true; // Is the current number prime? 19 20 // Test if number is prime 21 for (int divisor = 2; divisor <= number / 2; divisor++) 22 23 if (number % divisor == 0) 24 25 // If true, the number is not prime 26 isprime = false; // Set isprime to false 27 break; // Exit the for loop 28 29 30 31 // Display the prime number and increase the count 32 if (isprime) 33 34 count++; // Increase the count 35 36 if (count % NUMBER_OF_PRIMES_PER_LINE == 0) 37 // Display the number and advance to the new line 38 cout << setw(4) << number << endl; 39 else 40 cout << setw(4) << number; 41 42 43 // Check if the next number is prime 44 number++; 45 46 47 return 0; 48 count prime numbers check primeness exit loop display if prime The first 50 prime numbers are 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229

212 Chapter 5 Loops subproblem This is a complex program for novice programmers. The key to developing a programmatic solution for this problem, and for many other problems, is to break it into subproblems and develop solutions for each of them in turn. Do not attempt to develop a complete solution in the first trial. Instead, begin by writing the code to determine whether a given number is prime, then expand the program to test whether other numbers are prime in a loop. To determine whether a number is prime, check whether it is divisible by a number between 2 and number/2 inclusive. If so, it is not a prime number; otherwise, it is a prime number. For a prime number, display it. If the count is divisible by 10, advance to a new line. The program ends when the count reaches 50. The program uses the break statement in line 27 to exit the for loop as soon as the number is found to be a nonprime. You can rewrite the loop (lines 21 29) without using the break statement, as follows: for (int divisor = 2; divisor <= number / 2 && isprime; divisor++) // If true, the number is not prime if (number % divisor == 0) // Set isprime to false, if the number is not prime isprime = false; However, using the break statement makes the program simpler and easier to read in this case. Key Terms break statement 205 continue statement 206 do-while loop 188 for loop 191 infinite loop 178 input redirection 186 iteration 176 loop 176 loop body 176 loop-continuation-condition 176 nested loop 196 off-by-one error 178 output redirection 186 posttest loop 194 pretest loop 194 sentinel value 184 while loop 176 Chapter Summary 1. There are three types of repetition statements: the while loop, the do-while loop, and the for loop. 2. The part of the loop that contains the statements to be repeated is called the loop body. 3. A one-time execution of a loop body is referred to as an iteration of the loop. 4. An infinite loop is a loop statement that executes infinitely. 5. In designing loops, you need to consider both the loop control structure and the loop body.

6. The while loop checks the loop-continuation-condition first. If the condition is true, the loop body is executed; if it is false, the loop terminates. 7. The do-while loop is similar to the while loop, except that the do-while loop executes the loop body first and then checks the loop-continuation-condition to decide whether to continue or to terminate. 8. The while loop and the do-while loop often are used when the number of repetitions is not predetermined. 9. A sentinel value is a special value that signifies the end of the loop. 10. The for loop generally is used to execute a loop body a fixed number of times. 11. The for loop control has three parts. The first part is an initial action that often initializes a control variable. The second part, the loop-continuation-condition, determines whether the loop body is to be executed. The third part is executed after each iteration and is often used to adjust the control variable. Usually, the loop control variables are initialized and changed in the control structure. 12. The while loop and for loop are called pretest loops because the continuation condition is checked before the loop body is executed. 13. The do-while loop is called a posttest loop because the condition is checked after the loop body is executed. 14. Two keywords, break and continue, can be used in a loop. 15. The break keyword immediately ends the innermost loop, which contains the break. 16. The continue keyword only ends the current iteration. Programming Exercises 213 Quiz Answer the quiz for this chapter online at www.cs.armstrong.edu/liang/cpp3e/quiz.html. Programming Exercises Pedagogical Note Read each problem several times until you understand it. Think how to solve the problem before starting to write code. Translate your logic into a program. A problem often can be solved in many different ways. Students are encouraged to explore various solutions. read and think before coding explore solutions Sections 5.2 5.7 *5.1 (Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number. Here is a sample run:

214 Chapter 5 Loops Enter an integer, the input ends if it is 0: 1 2-1 3 0 The number of positives is 3 The number of negatives is 1 The total is 5 The average is 1.25 Enter an integer, the input ends if it is 0: 0 No numbers are entered except 0 5.2 (Repeat multiplications) Listing 5.4, SubtractionQuizLoop.cpp, generates five random subtraction questions. Revise the program to generate nine random multiplication questions for three integers between 1 and 5. Display the correct count and test time. 5.3 (Conversion from millimeters to inches) Write a program that displays the following table (note that 1 millimeter is 0.039 inches): Millimeters Inches 2 0.078 4 0.156 96 3.744 98 3.822 5.4 (Conversion from meters to feet) Write a program that displays the following table (note that 1 meter is 3.280 feet): Meters Feet 1 3.280 2 6.560 14 45.920 15 49.200 5.5 (Conversion from millimeters to inches and inches to millimeters) Write a program that displays the following tables side by side (note that 1 millimeter is 0.039 inches): Millimeters Inches Inches Millimeters 2 0.078 1 25.641 4 0.156 2 51.282 98 3.822 49 1256.410 100 3.900 50 1282.051 5.6 (Conversion from meters to feet) Write a program that displays the following tables side by side (note that 1 meter is 3.280 feet): Meters Feet Feet Meters 1 3.280 3 0.915 2 6.560 6 1.829 14 45.920 42 12.805 15 49.200 45 13.720 5.7 (Use trigonometric functions) Print the following table to display the tan and cot values of degrees from 0 to 60 with increments of 10 degrees. Round the value to keep four digits after the decimal point.