Study recommendations for the Mid-Term Exam - Chapters 1-5

Similar documents
Study recommendations for Quiz 5 - Chapter 5

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Increment and the While. Class 15

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

BITG 1233: Introduction to C++

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

Chapter 2 Basic Elements of C++

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.

Computer Programming : C++

UNIT- 3 Introduction to C++

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

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

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

Chapter 2. C++ Basics

Chapter 5: Loops and Files

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

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

Chapter 4 - Notes Control Structures I (Selection)

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

Objectives. In this chapter, you will:

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

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

Chapter 2: Basic Elements of C++

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

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

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

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

The C++ Language. Arizona State University 1

VARIABLES & ASSIGNMENTS

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

CPE Summer 2015 Exam I (150 pts) June 18, 2015

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

Fundamentals of Programming CS-110. Lecture 2

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

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

I/O Streams and Standard I/O Devices (cont d.)

Chapter 2: Introduction to C++

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

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Full file at

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

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

Expressions, Input, Output and Data Type Conversions

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

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

Chapter 2 - Control Structures

CSc 10200! Introduction to Computing. Lecture 4-5 Edgardo Molina Fall 2013 City College of New York

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Chapter 3 Problem Solving and the Computer

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

Chapter 3 - Notes Input/Output

CS242 COMPUTER PROGRAMMING

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Full file at C How to Program, 6/e Multiple Choice Test Bank

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

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

2 nd Week Lecture Notes

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

Chapter 2 - Control Structures

A First Program - Greeting.cpp

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

Engineering Problem Solving with C++, Etter/Ingber

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

5. Control Statements

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

Software Design & Programming I

Chapter 2: Overview of C++

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

Week 3: File I/O and Formatting 3.7 Formatting Output

CSCI 1061U Programming Workshop 2. C++ Basics

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

Loops and Files. of do-while loop

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

LECTURE 02 INTRODUCTION TO C++

Introduction to Programming EC-105. Lecture 2

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

Introduction to Programming using C++

Getting started with C++ (Part 2)

Programming. C++ Basics

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Definition Matching (10 Points)

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.

Chapter 2 - I know what I want to do NOW WHAT? Student Learning Outcomes (SLOs)

Program Organization and Comments

DEPARTMENT OF MATHS, MJ COLLEGE

Add Subtract Multiply Divide

Chapter 1 INTRODUCTION

UNIT-2 Introduction to C++

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

Introduction to the C++ Programming Language

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

Chapter 2 - Control Structures

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

REPETITION CONTROL STRUCTURE LOGO

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Looping. Arizona State University 1

COP 2000 Note Framework Chapter 5 - Repetition Page 1

BASIC ELEMENTS OF A COMPUTER PROGRAM

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

Transcription:

Study recommendations for the Mid-erm Exam - Chapters 1-5 Review Chapters 1-5 in your textbook, the Example Pages, and in the Glossary on the website Standard problem solving steps used in program development (in order): ANALYSIS: LOGICAL DESK WORK 1. Define the ask or Objectives 2. Define the Output 3. Define the Input 4. Define the Algorithm 5. Check the Algorithm PROGRAMMING: PHYSICAL CODING 6. Code the Program in a high-level language such as C++ 7. Debug the Program he three types of errors common in programming are: 1. Logic errors: mistakes made in the design of an algorithm - minimized by doing desk checks. 2. Syntax errors: mistakes in use of the programming language when writing source code - detected by the compiler during each attempted compilation. 3. Run-time errors: mistakes occurring during an execution of a program, usually resulting from the entry of unexpected data or some hardware problem. he rules of syntax for defining valid identifiers in the C++ Language: Identifiers can contain only letters (either case), numerals, or the underscore character ( _ ), although identifiers starting with an underscore had special restrictions and an identifier consisting of only a lone underscore is forbidden. No blank spaces or special characters are allowed; nor should you use double underscores. Identifiers cannot start with a digit. A C++ reserved word cannot be used as an identifier. Identifiers are case sensitive. he maximum length of an identifiers depends on the compiler being used, but most allow at least 1024 characters (although such lengths would be extremely impractical). Quiz preparation exercise: Circle the labels that are NO valid variable names under the rules of syntax for C++. cout xyz2 int Sue's 4th abc$ my2nd Note that cout is a standard identifier in C++ but not a reserved word, like int. Rev. 2012-10-18 Page 1 of 13

Order of Precedence able (including arithmetic, relational and Boolean operators): () Highest / irst postfix ++ postfix -- ^! prefix ++ prefix -- unary + unary - unary & casts * / % + - < > <= >= ==!= && Lowest / Last Quiz preparation exercise: In each of the four separate expressions below, circle the operator of the arithmetic operation that will be performed first. X / Y / Z ( X * ( M - N ) ) / Y Quiz preparation exercise: X - Y * Z Z / ( X - Y ) Circle any (and all) SYNAX errors in the following C++ statements and describe them briefly on the line provided. Do NO mention logical errors. If a line is valid, answer "OK". Each line is a separate question, independent of the others. #include <iostream>; #define ACOR = 9 const int MAX ; float = AM; Compiler directives are not terminated by a semi-colon Assignment is not used with a symbolic constant Named constants must be initialized when defined Equal sign can be used only after an identifier to initialize X = X * 2; OK (this statement simply doubles X) cout << Hello; // Display Hello loat AM,PAY,AX=10.0; String constants should be enclosed in double quotes he keyword float is all lowercase / his is a comment / Comments must be inside /* and */ pairs or preceded by // NUM = 100 / ( AM + 5 ) cin << AM; // Read keyboard cout >> Hello; cout << precision(4) << 12345; he statement terminating semi-colon is missing cin should use the >> stream extraction operator he << (stream insertion) operator belongs with the cout object he precision manipulator is named setprecision Rev. 2012-10-18 Page 2 of 13

cout << left(2) << 12.345; C = static-cast<float>(a) / B; cout << "Hello"\n; he left manipulator uses no arguments he keyword static_cast contains an underscore rather than a hyphen he \n escape sequence should be inside the quotes Quiz preparation exercise: or each of the following logical statements, write one C++ statement to perform the specified task. Assume that these tasks are all a part of a restaurant-bill-calculating program using identifiers as shown below: LABEL DESCRIPION SOURCE USAGE DESINAION PUR Amount of the purchase Assigned for AX & PAY --- AX Calculated sales tax Calculation for PAY --- PAY otal amount to pay after tax Calculation - Displayed 1. Allocate (set aside) storage for the three variables that may have decimal points. double PUR,AX,PAY; // Note: the float data type would also be OK for small values 2. Display the program title "AX PROGRAM" on a line of its own. cout << " AX PROGRAM\n "; // or cout << " AX PROGRAM" << endl; 3. Assign the value 123.45 into the variable that holds the purchase. PUR = 123.45; 4. Calculate and store the tax as 6% of the purchase amount. AX = 0.06 * PUR; 5. Display the string "Please pay $" followed by the total amount to pay rounded to cents, followed by a carriage return. cout << "Please pay $" << setprecision(2) << fixed << PAY << endl; Rev. 2012-10-18 Page 3 of 13

Output ormatting Examples Review the following examples of formatted output statements paying close attention to the format of the resulting output beside them. Each box indicates one character position on the screen. All output starts in the leftmost box, although some output might be "padded" with blank spaces to align it to the right edge of the field. "X"'s indicated unused positions. C++ command using cout with various stream manipulators (assuming default values for any missing manipulators) cout << setw(3) << 'A'; Output Produced on Screen Position: 1 1 1 1 1 1 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 A X X X X X X X X X X X X cout << setw(3) << left << 'A'; A X X X X X X X X X X X X cout << setw(8) << "ABCD"; cout << 52; cout << setw(8) << 52; A B C D X X X X X X X 5 2 X X X X X X X X X X X X X 5 2 X X X X X X X cout << setw(8) << left << 52; 5 2 X X X X X X X cout << 123.456; cout << setw(10) << setprecision(2) << fixed << 123.456; cout << setw(10) << setprecision(6) << fixed << showpoint << 123.456; cout << setw(10) << setprecision(2) << fixed << left << 123.456; cout << setprecision(2) << fixed << 123.456; cout << setw(10) << setprecision(3) << fixed << -45.8; cout << setw(10) << 0.00085; 1 2 3. 4 5 6 X X X X X X X X 1 2 3. 4 6 X X X X X 1 2 3. 4 5 6 0 0 0 X X X X X 1 2 3. 4 6 X X X X X 1 2 3. 4 6 X X X X X X X X X - 4 5. 8 0 0 X X X X X 0. 0 0 0 8 5 0 X X X X X Rev. 2012-10-18 Page 4 of 13

SELECION SRUCURES: Structures such as the one on the left are coded in C++ using the reserved word if. Set X to 1 Set A to 0 A > 0 and A < 9 Replace X with triple its original value. he diamond shape encloses the condition that is being tested (in this example, a Boolean expression). Remember that the C++ if statement can only execute one statement on each leg ( or ), so the pair of steps on the alse leg must be coded inside of a and pair to make them a single compound statement. hus the C++ code would be: if (A>0 && A<9) X=X*3; else X=1; A=0; Note the use of the parentheses around the condition in the code above. Additional parentheses are often necessary because of the order of precedence of operators in C++ (see the table on the previous page). Remember also that the alse leg may be empty, but not the rue leg. If your flowchart shows the opposite, then reverse the labeling of the rue and alse legs and reverse the logic of the condition inside the diamond. If you can't determine what the logical opposite of the condition would be, simply use the NO operator like this:! ( A>0 && A<9 ) ruth ables for Boolean Operators: (Op = Operand, a relational expression or Boolean value) Op.A Op.B Op.A && Op.B Op.A Op.B Op.A Op.B Op.A! ( Op.A ) Rev. 2012-10-18 Page 5 of 13

CASE Selection C++'s switch statement can be used in the special situation that you are testing for many possible values in a single ordinal storage location. In the example below, five possible paths might be followed depending on the value stored in the character storage location X. Each path (leg) is selected based on the individual value(s) that might be stored in X. he C++ code would be: A 1 X "A" "B" "C" "D","E" else A 2 Y 1 A 3 A 4 A 0 switch (X) case 'A': A=1; break; case 'B': A=2; Y=1; break; case 'C': A=3; break; case 'D': case 'E': A=4; break; default: A=0; break; Notice: (1) the parentheses around the character expression (X) (2) the inclusion of "break;" after each option serving to brace any multiple statements on each leg (3) the braces used to enclose the full list of options. he use of indentation and the positions of the carriage returns in the code are irrelevant. ( Continued on next page ) Rev. 2012-10-18 Page 6 of 13

SAMPLE QUESIONS: (AND ANSWERS) Draw a flowchart that matches the following code. Answer: Start X N = 30 if (N == 0); cout << "Yes"; End Yes Notice that the semicolon which follows the condition N==0 terminates the if statement, making it pointless. he cout statement will be executed regardless of the condition's value. Draw a flowchart that matches the following code. if (X == 3) Y = 4; Z = 5; Answer: Start End X = 3 Z 5 Y 4 Notice that the Z = 5 step follows the selection. It is not part of the true leg because it was not included inside of a pair of braces. he semicolon following the Y = 4 statement terminated the if statement. Circle any SYNAX (not run-time) ERRORS (there may be more than one) in each of the following C++ code segments. If a segment is valid answer "OK". Assume all variables already have been correctly declared. cin >> A; if ( A<10 && >20 ) cout << "ok"; >20 is not a complete relational expression X=1; cin >> Y; if X > Y cout << "OK" else cout << "NO"; missing parentheses around condition and missing semi-colon after if statement Rev. 2012-10-18 Page 7 of 13

Indicate the Boolean results (RUE or ALSE) for each of the following expressions, given: #define S "123" /* a string of numerals */ int A=0, B=2, C=-3; A==0 B<2 && C<0!(A>C) && A<C A!=0 B<2 S>"8" rue alse alse alse S>100 Logically invalid (data type mismatch) Given the following declarations for employee data within a program: int A; /* Age */ char D; /* Highest Degree Earned (only possible values are uppercase: 'N' = None, 'B' = Bachelor's, 'M' = Master's, or 'D' = Ph.D.) */ char G; /* Gender (only uppercase 'M' or '' are possible) */ Write a compound If statement in C++ that will display the message "OK" only when the employee is a female, between the ages of 20 and 30 (inclusive) and holds a college degree (Bachelor's, Master's or Ph.D.). Do NO check for case. Assume that previous statements have guaranteed uppercase values only, so that you need only check for uppercase values. Answer: if ( G== && A>=20 && A<=30 && ( D== B D== M D== D ) ) cout << "OK"; REPEIION SRUCURES: Structure: We studied two repetition structures (loops); one known as leading decision (a.k.a. pretest) and another known as trailing decision (a.k.a. posttest). he primary difference between them is in where the test that controls the loop is performed. Leading decision loops test before each pass and are coded in C++ using while (condition) body_statements; railing decision loops test after each pass and are coded in C++ using do body_statements; while (condition); We can design a loop that test somewhere in the middle, but that is consider very poor programming practice. Control: We studied two methods of controlling loop passage and exit. Counting control is based on the testing of values that have been set and altered by the programmer. Programmers know in advance how many times any counting loop will pass (execute its body) because all values of its control variable are predictable. Sentinel Rev. 2012-10-18 Page 8 of 13

control is based on the testing of external values that have been read into the program. Programmers do not know in advance how many times a sentinel loop will pass (execute its body) because the values of its control variable are unpredictable. Boundary Values: he values of variables just prior to the entry into a loop and just after the exit from a loop are called boundary values. Steps inside a loop can be organized so that the value of a variable is changed after it is displayed, so don't expect that variables will always contain the last value that you saw displayed. Counting Loops: All counting loops have at least four parts: initialization - prior to the loop entry, a first value of the control variable is set body - where the step(s) to be repeated belong increment (or decrement) - where the control variable is increased (or decreased) test - where the control variable is tested to determine whether the loop should pass or exit. he bottom three steps are not always in the order listed above. he order of the steps will affect the boundary values of the control variable. he two examples below show loops that will count from 1 to 9 and display the value of the control variable (also called a counter in a counting loop). Notice the exit value on N will be 10. N 1 N=1; N 1 N=1; while (N<=9) do N<=9 N cout <<N<<endl; N cout <<N<<endl; N = N+1; N N+1 N = N+1; N N+1 N <= 9 while (N<=9); If a loop: (1) uses the Leading Decision structure, (2) uses counting control, and (3) increments as the last step of its pass, C++ offers a special "automatic loop" statement combining the statements above (on the left) into the single statement: for (N=1; N<=9; N=N+1) cout << N << endl; Note: if the body of the loop has more than one statement to repeat, block it inside of braces. Most common coding errors when writing source code for loops: Closing the loop statement too soon with a misplaced semicolon ailing to block a body with multiple statements inside of braces orgetting the difference between the operators = (assignment) and == (equality) Rev. 2012-10-18 Page 9 of 13

SAMPLE QUESIONS: (AND ANSWERS) Circle any SYNAX (not run-time) ERRORS (there may be more than one) in each of the following C++ code segments. If a segment is valid answer "OK". Assume all variables have been correctly declared. for (I=1, I<=79, I++) cout << "-"; the commas (,) should be semi-colons (;) X=1; while X < 5 cout << X++; missing parentheses around condition Use the following for Statement to answer the next 3 questions (A-C). for (Count=Start; Count<=inish; Count++) cout << Count; (A) Which variable is the "control variable"? Count (B) What does Count++ mean? _Increment Count by 1 after a pass is complete (C) If Start contains a value of -4 and inish contains the value 0, how many times will the loop execute? Answer: 5 lowchart a program with a loop that accumulates whole numbers entered by the user until a -1 is entered and then identifies and displays the sum. hen write the C++ code to the right of it. Start ot 0 N is not -1 Sum is: ot Number (-1 to stop)? N N is not -1 ot ot + N End /* accumulate.cpp */ #include <iostream> using namespace std; int main () int N, ot=0; do cout << "Number (-1 to stop)? "); cin >> N; if (N!= -1) ot = ot + N; while (N!= -1); cout << "Sum is: " << ot << endl; return 0; Rev. 2012-10-18 Page 10 of 13

or each question below, circle any and all loop control methods for which the claims are true: (A) his control method is based on values assigned by the programmer, not given by the user. counting sentinel (B) his control method is based on values entered by the user. counting sentinel (C) he number of passes that the loop will perform can always be predetermined when the loop starts. counting sentinel or each question below, circle any and all loop structures for which the claims are true: (A) he test for each repetition is performed after the pass through the loop body. leading decision trailing decision (B) he body will always be executed at least once. leading decision trailing decision (C) his structure is appropriate for sentinel controlled loops that use a "prime read". leading decision trailing decision (D) Sentinel controlled loops using this structure need an extra test to guard the body from the sentinel value. leading decision trailing decision DISK ILE INPU AND OUPU: Review the last part of Chapter 5 in your textbook that discuss reading and writing of sequential text files on disks. hen study the practice exercise on the following page. It involves a file with a simple name that is located in the same folder as the program. Be aware that special consideration must be given when providing filenames or paths that contain whitespaces or characters that C++ interprets as having special meaning, such as backwards slashes. or example, to open a file named "My ile.txt" entered at the keyboard, you would need to input the string using the getline() function to prevent the whitespace from truncating the portion of the filename starting at the whitespace before assigning it to a string variable, as in: getline (cin, StringVar); // read a string containing whitespaces Rev. 2012-10-18 Page 11 of 13

o associate a file accessible from the disk location "C:\User\JStudent\Data.txt" with a file input stream object named "inile", you would have to escape the backwards slashes (\) as follows: inile.open("c:\\user\\jstudent\\data.txt "); Examine the following C++ source code: /************************************************************ * Program: diskio.cpp - Practice Exercise * * Opens a file in the same folder as the program based on a * * user supplied name (without whitespaces). hen writes ten * * lines of text, closes the file, then reopens the file and * * reads and displays each of the ten lines from the file. * ************************************************************/ #include <iostream> #include <fstream> using namespace std; int main () string ILENAME; // String object to hold a filename system ("cls"); /* Clear the Screen */ cout << "Disk I/O Program\n\n"; cout << "What is the filename (w/o path)? "; cin >> ILENAME; ofstream fileout; fileout.open(ilename.c_str()); // open requires a C-String if (fileout) // Verify successful open cout << ILENAME << " opened successfully for writing.\n\n"; for (int C=1; C<=10; C++) fileout << "Line " << C << endl; fileout.close(); else cout << ILENAME << "\a failed to open.\n"; string OSR; ifstream filein; filein.open(ilename.c_str()); if (filein) cout << ILENAME << " opened successfully for reading.\ncontents:\n"; for (int C=1; C<=10; C++) getline(filein,osr); // read a line of text with whitespaces cout << OSR << endl; Rev. 2012-10-18 Page 12 of 13

filein.close(); else cout << ILENAME << "\a failed to open.\n"; system ("pause"); return 0; Rev. 2012-10-18 Page 13 of 13