CS 007A Midterm 1 Practice Chapters 1 5

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

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

REPETITION CONTROL STRUCTURE LOGO

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

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

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

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

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

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

Chapter 2 - Control Structures

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

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.

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

C++ PROGRAMMING. For Industrial And Electrical Engineering Instructor: Ruba A. Salamh

CHAPTER 3 Expressions, Functions, Output

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

Write a program that displays all the even integers between 1 and 100, inclusive

BITG 1233: Introduction to C++

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

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

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

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

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

Looping. Arizona State University 1

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

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

3 The L oop Control Structure

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

Add Subtract Multiply Divide

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

UNIT- 3 Introduction to C++

Unit 3. Operators. School of Science and Technology INTRODUCTION

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

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

Chapter 2 - Control Structures

Chapter 2 - Control Structures

C/C++ Programming Lecture 7 Name:

Chapter 5: Loops and Files

Chapter Four: Loops II

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

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Operators & Expressions

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Chapter 3 - Functions

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Lab 10: Alternate Controls

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

CS 7B - Spring Final Exam

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

Arithmetic Operators. Binary Arithmetic Operators. Arithmetic Operators. A Closer Look at the / Operator. A Closer Look at the % Operator

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

Homework #3 CS2255 Fall 2012

Expressions, Input, Output and Data Type Conversions

Objectives. In this chapter, you will:

CS 1428 Review. CS 2308 :: Spring 2016 Molly O Neil

Chapter 3. Numeric Types, Expressions, and Output

CSCE Practice Midterm. Data Types

Chapter 3. More Flow of Control

C++ Final Exam 2017/2018

Lecture 4 Tao Wang 1

CSCE Practice Midterm. Data Types

Engineering Problem Solving with C++, Etter/Ingber

Introduction to C++ Lecture Set 2. Introduction to C++ Week 2 Dr Alex Martin 2013 Slide 1

CS007A Fall 12 Second Midterm

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

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

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

Getting started with C++ (Part 2)

TEST 1 CS 1410 Intro. To Computer Science Name KEY. October 13, 2010 Fall 2010

WARM UP LESSONS BARE BASICS

Loops and Files. of do-while loop

Other Loop Options EXAMPLE

1. Variables 2. Arithmetic 3. Input and output 4. Problem solving: first do it by hand 5. Strings 6. Chapter summary

CSC 126 FINAL EXAMINATION Spring Total Possible TOTAL 100

Introduction. C provides two styles of flow control:

Control Statements: Part Pearson Education, Inc. All rights reserved.

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

Introduction to C ++

Programming Language. Functions. Eng. Anis Nazer First Semester

Introduction to C ++

Chapter 3 Problem Solving and the Computer

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

Flow Control in C++ Condi&onals & Loops CS 16: Solving Problems with Computers I Lecture #4

C++ Programming Lecture 1 Software Engineering Group

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

CSCE 121 ENGR 112 List of Topics for Exam 1

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Practice test for midterm 1

Lecture 3 Tao Wang 1

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

2.11 Assignment Operators. Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator

Starting Out With C++: Early Objects, Fifth Edition Solutions to Review Questions. Chapter 1

Window s Visual Studio Output

Computer Department. Question (1): State whether each of the following is true or false. Question (2): Select the correct answer from the following:

Transcription:

CS 007A Midterm 1 Practice Chapters 1 5 1. Consider the 4 bytes stored in contiguous memory, as shown to the right. a. Determine the decimal representation of these 4 one-byte integers: b. Determine the decimal form of these, interpreting the data as 2 two-byte integers are stored in these 4 bytes. c. Interpret the 4 bytes as 4 ASCII characters. Note that the ASCII value of A is 65. 2. Write 125 in binary form. 01000001 01010011 01001011 01011001 3. Write 125 in Hex form. 4. Convert the hex number abba to decimal form. 5. Find as many errors in the following code as you can. Classify each error as a syntax error or a logic error and describe how to fix it so it works properly. //This program uses a loop to raise a number to a power. int num, bignum, power, count; cout << "Enter an integer: "; cin >> num; cout << "\nwhat power do you want it raised to? "; cin >> power; bignum = num; while (count++ < power); bignum *= num; cout << "\nthe result is " << bignum << endl; return 0; 6. Consider the following C++ program. Is there an error? If so what kind of error? What will be the result of attempting to compile and execute the program? for(int i = 0; i < 2; ++i) for(int j = 0; j < 2; ++ j) cout << "i = " << i << " "; --i; cin.get(); return 0; 7. Evaluate the following expressions, step by step, assuming integer variables a = 52, b = 13, c = 4, d = 5 and float e = 2.71828 If the expression doesn t parse, explain why. a. a / d % b * c b. a % c == b

c.!(b + d!= c * c) d. d % b * c > 5 c % b * d < 7 e. (((a + 1)*b + 2) % c + 3)/d + e 8. What is the output of the following code fragment? for (int ct = 1; ct <= 3; ct++) cout << ct; for (int i = 3; i <= 4; i++) cout << ct << " " << i; cout << "do re mi"; 9. What is the output produced by the following program if the user enters 4? #include <iomanip> setiosflags(ios::right); int n; cout << "How many columns? (1-16): "; cin >> n; for (int x=1; x <= n; x++) for (int y=1; y <= n; y++) cout << setw(5) << x*y; cout << endl; 10. Write code to implement the following flow chart. The user will enter 10 numbers between 0 and 100 and the program will count how many are 90, how many are in the interval [80, 90) and how many are less than 80 and then report the results.

11. Write a program to a. Find the square root of the sum of the first 100 even numbers, correct to 10 significant digits. You may use not the cmath library. b. Find the reciprocal of the product of the first 10 odd numbers correct to 10 significant digits. c. Fill up an array of 3 elements with 3 random numbers between 1 and 10 and then compute the cube root of their product. Do not use the cmath library. d. Compute the value of the zeta function, for any positive integer s > 1. 12. Consider the following program fragment. int accumulator = 0, sam, pam; cout << "\nenter integers for sam and pam: "; cin >> sam >> pam; while (true ) if (pam == 0) break ; accumulator += ((pam % 2 == 1)? sam : 0); pam /= 2; sam *= 2; cout << accumulator << "\n"; a. Complete the following tables until the program completes, or indicate that it s an infinite loop: sam pam accumulator sam pam accumulator 5 4 0 6 17 0 b. In a few words, describe the output of this program in terms of the input values of sam and pam, and how it works. 13. Suppose that p = 0x0012FF50, &a = 0x0012FF44, &p = 0x0012FF38. What will be output by the following code? int a[] = 22, 33, 44, 55, 66, 77, 88, 99 ; int* p = &a[3]; // p points to a[3] cout << "p = " << p << ", *p = " << *p; cout << "\n&a = " << &a; // ok: a is an lvalue cout << "\n&p = " << &p; // ok: p is an lvalue cout << "\n&(a[5]) = " << &(a[5]); // ok: a[5] is an lvalue cout << "\n&(*(a+5)) = " << &(*(a+5));// ok: *(a+5) is an lvalue cout << "\n&(*(p+2)) = " << &(*(p+2));// ok: *(p+2) is an lvalue cout << "\n&(p+2) = " << p+2; //&(p+2); // ERROR: p+2 is not an lvalue cout << endl;

14. Write a C++ program to implement the flow chart below.

CS 007A Midterm 1 Practice Problems Solutions Chapters 1 5 1. Consider the 4 bytes stored in contiguous memory, as shown to the right. a. Determine the decimal representation of these 4 one-byte integers: SOLN: 01000001 2 = 2 6 +2 0 = 64 + 1 = 65 01010011 2 = 2 6 +2 4 + 2 1 + 2 0 = 64 + 16 + 2 + 1 = 83 01001011 2 = 2 6 +2 3 + 2 1 + 2 0 = 64 + 8 + 2 + 1 = 75 01011001 2 = 2 6 +2 4 + 2 3 + 2 0 = 64 + 16 + 8 + 1 = 89 b. Determine the decimal form of these, interpreting the data as 2 two-byte integers are stored in these 4 bytes. SOLN: Of course there are two ways to do this: either the most significant byte is first, or the least significant byte is first. That is, either 0101001101000001 2 = 83*2 8 + 65 = 21313 Or 0100000101010011 2 = 65*2 8 + 83 = 16723 Similarly for the second pair: it s either 0100101101011001 2 = 75* 2 8 + 89 = 19289 or 0101100101001011 2 = 89* 2 8 + 75 = 22859 c. Interpret the 4 bytes as 4 ASCII characters. Note that the ASCII value of A is 65. SOLN: ASKY 2. Write 125 in binary form. SOLN: 125 = 64 + 32 + 16 + 8 + 4 + 1 = 2 6 + 2 5 + 2 4 + 2 3 + 2 2 + 2 0 = 1111101 3. Write 125 in Hex SOLN: 125 = 16*7 + 13 = 7D 4. Convert the hex number abba to decimal form. SOLN: abba = 10*16 3 + 11*16 2 + 11*16 + 10 = 40960 + 2816 + 176 +10 = 43962 01000001 01010011 01001011 01011001 5. Find as many errors in the following code as you can. Classify each error as a syntax error or a logic error and describe how to fix it so it works properly. //This program uses a loop to raise a number to a power. int num, bignum, power, count; cout << "Enter an integer: "; cin >> num; cout << "\nwhat power do you want it raised to? "; cin >> power; bignum = num; while (count++ < power); bignum *= num; cout << "\nthe result is " << bignum << endl; return 0; SOLN: ANS: There is a logic error that looks like a syntax error: the semicolon after while (count++ < power); and another logic error: count is never initialized. If the semicolon is deleted and count is initialized to 0, then the algorithm should successfully raise the user supplied int to the user supplied positive int.

6. Consider the following C++ program. Is there an error? If so what kind of error? What will be the result of attempting to compile and execute the program? for(int i = 0; i < 2; ++i) for(int j = 0; j < 2; ++ j) cout << "i = " << i << " "; --i; cin.get(); return 0; ANS: There is a logic error. The output of the program will proceed in an infinite loop like so: i = 0 i = -1 i = -1 i = -2 i = -2 i = -3 i = -3 To see this, note that initially, i = j = 0 and i = 0 is printed. Then i is decremented by 1, so i = -1, and the program waits for a keystroke, say, Enter. Then j = 1 and i = -1 is printed and i is decremented again so i = -2, but then we arrive at the update for the outer for loop, which increments i again to i = -1, so i = -1 is printed again. Now i is decremented to -2 again and j counts to 1, i = -2 is printed and i decremented to i = -3. After pressing Enter again, control passes back to the outer for loop, which increments i again so i = -2 and the inner for loop prints i = -2, decrements i again (so i = -3) and waits for a keystroke. Everytime the user presses a key (in the above example, simply the Enter key) the pattern repeats with i steadily decreasing by one every time the outer for loop repeats, printing two instances of the same value of i and since the sentinel for the outer for loop is i < 2, it s an infinite loop. 7. Evaluate the following expressions, step by step, assuming integer variables a = 52, b = 13, c = 4, d = 5 and float e = 2.71828 If the expression doesn t parse, explain why. a. a / d % b * c SOLN: According the precedence of operators in C++ (described, for instance, at http://en.cppreference.com/w/cpp/language/operator_precedence ) the operators and all have the same precedence and are associated left to right. a / d % b * c = 10 % b * c = 10 * 4 = 40 b. a % c == b The comparison operator has lower precedence than the modulus operator, so this is equivalent to 0==13, which is false, or 0. c.!(b + d!= c * c) The negation operator has high precedence, but the parentheses have higher precedence, so we look inside the parentheses first. The addition and multiplication operators have higher precedence than the comparison operator, so this is simplified to!(18!= 16). Now the comparison inside the parentheses is true, which is negated to false or, = 0 d. d % b * c > 5 c % b * d < 7 Here the logical or has low precedence and we simplify the expressions on the left and right of it first, and since the comparison operators have lower precedence than the arithmetic operators, this goes like so: 5 * 4 > 5 4 * 5 < 7 and then

20 > 5 20 < 7 and then true false which is true or 1. = 20 > 5 20 < 7 e. (((a + 1)*b + 2) % c + 3)/d + e = 3.71828 This is largely driven by the parentheses: ((53*13 + 2) % 4 + 3)/5 + 2.71828 ((689 + 2) % 4 + 3)/5 + 2.71828 (691 % 4 + 3)/5 + 2.71828 (3 + 3)/5 + 2.71828 6/5 + 2.71828 1 + 2.71828 = 3.71828 Note the promotion of the int on the left to the float type on the last step. 8. What is the output of the following code fragment? for (int ct = 1; ct <= 3; ct++) cout << ct; for (int i = 3; i <= 4; i++) cout << ct << " " << i; cout << "do re mi"; SOLN: 11 31 4do re mi22 32 4do re mi33 33 4do re mi 9. What is the output produced by the following program if the user enters 4? #include <iomanip> setiosflags(ios::right); int n; cout << "How many columns? (1-16): "; cin >> n; for (int x=1; x <= n; x++) for (int y=1; y <= n; y++) cout << setw(5) << x*y; cout << endl; SOLN: 1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16 Write code to implement the following flow chart. The user will enter 10 numbers between 0 and 100 and the program will count how many are 90, how many are in the interval [80, 90) and how many are less than 80 and then report the results.

SOLN: int a = 0, b = 0, lower = 0; for(int i = 0; i < 10; ++i) cin >> k; if(k >= 90) ++a; else if(k >= 80) ++b; else ++lower; cout << \nthere are << a << 90 or more.\n << b << in [80,90) and \n << lower << less than 80. ; 10. Write a program to a. Find the square root of the sum of the first 100 even numbers, correct to 10 significant digits. You may use not the cmath library. SOLN: #include <iomanip> double root(double); double sum = 0; cout << setprecision(10); for (double n = 2; n < 100; n += 2) sum += n; cout << "\nsqrt(0 + 2 +... + 98) = " << root(sum) << endl; double root(double A) // Use the babylonian algorithm to compute the square root double x1 = A, x2 = x1/2; const double tolerance = 1e-14; while(x2 - x1 > tolerance x1 - x2 > tolerance)

x1 = x2; x2 = (x1 + A/x1)/2; return x2; Output: sqrt(0 + 2 +... + 98) = 49.49747468 b. Find the reciprocal of the product of the first 10 odd numbers correct to 10 significant digits. SOLN: double product = 1; cout << setprecision(10); for (double n = 1; n < 20; n += 2) product *= n; cout << "\nthe reciprocal of 1*3*5*... * 19 = " << 1/product << endl; Output: The reciprocal of 1*3*5*... * 19 = 1.527349309e 009 c. Fill up an array of 3 elements with 3 random numbers between 1 and 10 and then compute the cube root of their product. Do not use the cmath library. srand(time(null)); double randdoubles[3], product = 1; for(int i = 0; i < 3; ++i) randdoubles[i] = (double)(1+rand()%10); cout << setprecision(10); for (int n = 0; n < 3; n++) product *= randdoubles[n]; cout << "\nthe cube root of the random product " << product << " is " << croot(product) << endl; double croot(double A) // Use the babylonian algorithm to compute the square root double x1 = A, x2 = x1/2; const double tolerance = 1e-14; while(x2 - x1 > tolerance x1 - x2 > tolerance) x1 = x2; x2 = (2*x1 + A/(x1*x1))/3; return x2; Output: The cube root of the random product 40 is 3.419951893 d. Compute the value of the zeta function, for any positive integer s > 1. double input;

cout << setprecision(10); cout << "\nzeta(2) = " << zeta(2) << " = " << PI*PI/6. << endl; cout << "\nenter another input: "; cin >> input; cout << "\nzeta(" << input << ") = " << zeta(input) << endl; double zeta(double s) double zetaval = 1, term = 1., n = 1.; while(term > 1.e-15) ++n; term = 1.; for(double pow = 1;pow <= s; ++pow) term *= 1/n; zetaval += term; return zetaval; Output: zeta(2) = 1.644934035 = 1.644934067 Enter another input: 5 zeta(5) = 1.036927755 11. Consider the following program fragment. int accumulator = 0, sam, pam; cout << "\nenter integers for sam and pam: "; cin >> sam >> pam; while (true ) if (pam == 0) break ; accumulator += ((pam % 2 == 1)? sam : 0); pam /= 2; sam *= 2; cout << accumulator << "\n"; a. Complete the following tables until the program completes, or indicate that it s an infinite loop: sam pam accumulator sam pam accumulator 5 4 0 6 17 0 10 2 0 12 8 6 20 1 0 24 4 6 40 0 20 48 2 6 96 1 6 192 0 102 b. In a few words, describe the output of this program in terms of the input values of sam and pam, and how it works. ANS: This is a multiplication algorithm that uses the binary form of the second factor like so: 5 4 5 2 20 so just double 5 twice. This is recognized by dividing by writing 2 100 and proceding thus: 5 100 10 10 20 1 20. Similarly, 6 17 6 10001 6 12 1000 6 24 100 6 48 10 6 96 1 102

or 3 21 3 10101 3 6 1010 3 12 101 15 24 10 15 48 63. 12. Suppose that p = 0x0012FF50, &a = 0x0012FF44, &p = 0x0012FF38. What will be output by the following code? int a[] = 22, 33, 44, 55, 66, 77, 88, 99 ; int* p = &a[3]; // p points to a[3] cout << "p = " << p << ", *p = " << *p; cout << "\n&a = " << &a; // ok: a is an lvalue cout << "\n&p = " << &p; // ok: p is an lvalue cout << "\n&(a[5]) = " << &(a[5]); // ok: a[5] is an lvalue cout << "\n&(*(a+5)) = " << &(*(a+5));// ok: *(a+5) is an lvalue cout << "\n&(*(p+2)) = " << &(*(p+2));// ok: *(p+2) is an lvalue cout << "\n&(p+2) = " << p+2; //&(p+2); // ERROR: p+2 is not an lvalue cout << endl; SOLN: (note this is not really fair game for the exam) p = 0012FF50, *p = 55 &a = 0023FF44 &p = 0012FF38 &(a[5]) = 0023FF58 &(*(a+5)) = 0023FF58 &(*(p+2)) = 0023FF58 &(p+2) = 0023FF58 13. Write a C++ program to implement the flow chart below. // implementation of flow chart int b,n,z = 1; cout << "\ninput b and n and we'll compute << something with them: "; cin >> b >> n; cout << "\nb = " << b << "\nn = " << n; while(n!=0) if(n%2==0) // n is even --n; z *= b; else b *= b; n /= 2; cout << "\nthe result is " << b << endl;