Practice question Answers

Similar documents
COMP322 - Introduction to C++

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

At the end of this module, the student should be able to:

Ch. 12: Operator Overloading

Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable

When we program, we have to deal with errors. Our most basic aim is correctness, but we must

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

Consider the above code. This code compiles and runs, but has an error. Can you tell what the error is?

CSCE 121 ENGR 112 List of Topics for Exam 1

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

Functions and Methods. Questions:

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

9.2 Pointer Variables. Pointer Variables CS Pointer Variables. Pointer Variables. 9.1 Getting the Address of a. Variable

C++ for Java Programmers

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

Functions, Pointers, and the Basics of C++ Classes

UEE1302(1066) F12: Introduction to Computers and Programming Function (II) - Parameter

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

Fast Introduction to Object Oriented Programming and C++

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Exceptions, Templates, and the STL

Lab Instructor : Jean Lai

Pointers, Dynamic Data, and Reference Types

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

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

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

ECE264 Spring 2013 Final Exam, April 30, 2013

Language comparison. C has pointers. Java has references. C++ has pointers and references

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

CS11 Advanced C++ Spring 2018 Lecture 2

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators

Variables, Memory and Pointers

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Intermediate Programming, Spring 2017*

6. Pointers, Structs, and Arrays. 1. Juli 2011

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators

Review Problems for Final Exam. 1. What is the output of the following program? #include <iostream> #include <string> using namespace std;

a data type is Types

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

G52CPP C++ Programming Lecture 18

CSCE Practice Midterm. Data Types

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

Singly linked lists in C.

CS 103 Unit 11. Linked Lists. Mark Redekopp

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

CS 240 Data Structure Spring 2018 Exam I 03/01/2018

CSCI-1200 Data Structures Spring 2016 Lecture 7 Iterators, STL Lists & Order Notation

Programming in C. Pointers and Arrays

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

Section 05: Solutions

Pointers and Strings Chapters 10, Pointers and Arrays (10.3) 3.2 Pointers and Arrays (10.3) An array of ints can be declared as

SYSC 2006 C Winter 2012

Computer Science II CSci 1200 Lecture 18 Operators and Friends

CS201 Some Important Definitions

7 TEMPLATES AND STL. 7.1 Function Templates

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage:

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

Manual Allocation. CS 1622: Garbage Collection. Example 1. Memory Leaks. Example 3. Example 2 11/26/2012. Jonathan Misurda

Data Structures in C. C Programming and Software Tools. N.C. State Department of Computer Science

We do not teach programming

Pointers Pointer Variables. Pointer Variables Getting the Address of a Variable. Each variable in program is stored at a

Templates. Giuseppe Lipari Scuola Superiore Sant Anna Pisa. June 8, 2009

CS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

CSE 303: Concepts and Tools for Software Development

Computer Programming

CS 376b Computer Vision

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Pointers in C/C++ 1 Memory Addresses 2

struct Buffer { Buffer(int s) { buf = new char[s]; } ~Buffer() { delete [] buf; } char *buf; };

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Item 3: Predicates, Part 2: Matters of State

CISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts)

G52CPP C++ Programming Lecture 20

for (i=1; i<=100000; i++) { x = sqrt (y); // square root function cout << x+i << endl; }

Array. Array Declaration:

CS 103 Unit 13 Slides

CA31-1K DIS. Pointers. TA: You Lu

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

CSCI-1200 Data Structures Fall 2018 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

CS11 Advanced C++ Fall Lecture 1

CSE 333 Midterm Exam 7/25/16 Sample Solution. Question 1. (10 points) Preprocessor. Suppose we have the following two files:

2 is type double 3 auto i = 1 + 2; // evaluates to an 4 integer, so it is int. 1 auto d = 5.0; // 5.0 is a double literal, so it

Pointers. 10/5/07 Pointers 1

Bruce Merry. IOI Training Dec 2013


Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library

Introduction to C++ Introduction to C++ 1

CSE 333 Midterm Exam 7/25/16. Name UW ID#

Transcription:

Practice question Answers COMP-322, Winter 2012, All Sections These questions are not necessarily the same as a final as they aren t necessarily exactly representative of the degree of difficulty, length, or material of the exam. That is, you should not assume that the questions on the quiz will be exactly like these. List of important topics Here is a rough list of the topics we ve covered so far that would be examinable. 1. Pointers, pointers to struct, * and & operators, pointer arithmetic on arrays 2. Linked lists 3. References 4. Memory management, memory leaks. new/delete 5. Basics of iterators: how to iterate over a list, vector, etc. How to write a function to take as input iterators. 6. Basics of streams Part 1 (0 points): Warm-up Warm-up Question 1 (0 points) Suppose I have the following functions: void swap(int& a, int&b) int temp = a; a = b; b = temp; int main() int x = 3; int y = 4;????? What would I write in place of the????? if I wanted to call the function to properly swap x and y? Rewrite swap() so that it took as input two int* instead of int&. How would that affect the way you call the method? 1

//Since swap takes as input 2 reference types, we can simply call it normally" //instead of??????? write swap(x,y); //To rewrite using pointers one would put: void swap(int* p, int *q) int temp = *p; *p = *q; *q = temp; //the function call would then be: swap(&x, &y); Warm-up Question 2 (0 points) What is the problem with the following code? struct Point2d int x; int y; ; Point2d* makepoint(int x, int y) Point2d point; point.x = x; point.y = y; return &point; How could one solve this problem and still return a Point2d? The issue here is that we are returning the address of automatically assigned data. That is, since the address returned is the address of the variable point, and the variable point is a local variable, it will be erased once the function completes. This means that the address will have no meaning. One should fix this using the new operator and pointers the whole time: Point2d* makepoint(int x, int y) Point2d* point = new Point2d; point->x = x; point->y = y; return point; Warm-up Question 3 (0 points) Suppose I have the following struct: struct IntNode int data; IntNode* next; Page 2

Write a function that takes as input a pointer to an IntNode that represents a linked list. Assume that it is sorted in increasing order by the int data. Insert the new node in the correct location. You should obey proper memory management. IntNode* insert(intnode* root, int newvalue) IntNode* newnode = new IntNode; newnode->data = newvalue; if (root == NULL) return newnode; if (newnode < root->data) newnode->next = root; return newnode; IntNode* current = root; //use a while loop because we want access to current after the loop while (current->next!= NULL) if (newvalue > current->next->data) newnode->next = current->next; current->next = newnode; return root; current = current->next; //if we reach here then we must be adding to the very end. newnode->next = NULL; current->next = newnode; return root; Warm-up Question 4 (0 points) Suppose there exists a function IntNode* fun(intnode* x). Which of the following are valid? For those that are invalid, correct them. In cases that something prints, output what will print. 1. IntNode* bar = fun(null); //this is good 2. IntNode* bar; bar = &(*(fun(null))); //fun() returns a pointer, pointers can be deferenced with * and then //one can get the address of it using & 3. IntNode b = *(fun(null)); //good 4. IntNode b; IntNode* c = *b; Page 3

//the above line is no good. //*b doesn t make sense since b isn t a pointer (*c) = b; 5. int x = 3; int&y = &x; //the above line isn t good since y is a reference //change to int*y = &x; or int&y = x; cout << x; 6. int x = 3; int&y = x; //this is good y = 10; cout << x; 7. int x = 2; int* y = &x; y = new int; (*y) = 3; cout << x; //This prints 2. If we removed y = new int, it would print 3 //because *y = 3 would have changed x as well. //However, y = new int means that y should store a different //address than the address of x, meaning y and x are no longer //linked in any way. 8. int x[10]; for (int j = 0; j < 10; j++) x[j] = 0; int* p = (x[3]); //the above doesn t compile, should be &x[3] *(p + 3) = 4; //if we fixed the prior mistake then this would //be the same as writing x[6] = 4 cout << x[3] << " " << x[6] << endl; After answering the normal question, how would you rewrite the above using a reference instead of a pointer? This question doesn t make sense...i think I was sleepy when I wrote this... You can t do the equivalent of *(p+3) with references Warm-up Question 5 (0 points) Write a function that takes as input a const list<int>& (from the stl library) and iterates over the entire list, summing all of the values. int sumlist(const list<int>\& list) int total = 0; for (list<int>::const_iterator start = list.begin(); start!= list.end(); start++ ) total = total + *start; Page 4

return total; Warm-up Question 6 (0 points) Write a function that takes as input a start iterator for a container of int and an end (one past the finish) of a forward iterator and sums all the values in the container. template<class InputIterator> int sum(inputiterator start, InputIterator finish) int total = 0; for (InputIterator current = start; current!= finish; current++) total = total + *current; return total; Now write how you would call this function to take the sum of all the values in the vector<int> v sum(v.begin(), v.end()); Warm-up Question 7 (0 points) What is the advantage of using references? Why are they better than pointers in some cases? How does this relate to the notion of l-value (something you can put on the left side of an equation) The main advantage is that you are associating a variable with another variable. This allows you to call a function and pass BY REFERENCE a variable which is usually much faster than passing something by value which requires an expression to be evaluated and then copied into a new variable. Additionally, references are often syntactically cleaner since if we pass something by reference, we just add an & in the function header and then can change the variables normally without having to use * or & or anything. A reference variable has to be assigned to an l-value, which is anything you can assign to. It doesn t make sense to assign a reference to a const for example, since then one couldn t change it. Warm-up Question 8 (0 points) What is the difference between the * operator and the & operator? They are the inverse operators. * operator dereferences a pointer. The & operator gets the address of an l-value. So * turns an address into "data" and & turns "data" into an address. (Of course an address is still data, so hence the quotes) Warm-up Question 9 (0 points) What is wrong with the following code? //adds an element to a list at the front if it isn t already in the linked list, //returns the element (linked to original list) or original list depending //on if it was found or not IntNode* insertunique(intnode* root, int value) Page 5

IntNode* newnode = new IntNode; newnode->value = value; newnode->next = NULL; for (IntNode* current = root; current!= NULL; current = current->next) if (current->value == value) return root; //insert at the beginning now newnode->next = root; return newnode; There is a memory leak. When we right return root inside the if statement, we lose all links to the newnode. We need to add delete newnode before return root or alternatively shift the creation of the new node to be later on after the loop finishes (before newnode->next = root) Warm-up Question 10 (0 points) Explain the difference between how the computer evaluates cout in C++ vs a more standard method call such as printf() in C or System.out.println() in Java. In other words, what is the difference between writing: System.out.println("hi" + "bye"); OR printf("hibye"); vs cout << "hi" << "bye"; In Java or C, we are calling a function or method that prints whatever is passed to the function as input. However when using cout or cin we are using an operator << or >>. This operator is evaluated as part of an expression and has the side effect of printing or reading something. Page 6