Recursion Examples. Factorial Recursive: Factorial Iterative: #include <iostream> using namespace std; long fact(long n) { if (n == 1) return 1;

Size: px
Start display at page:

Download "Recursion Examples. Factorial Recursive: Factorial Iterative: #include <iostream> using namespace std; long fact(long n) { if (n == 1) return 1;"

Transcription

1 Recursion Examples Factorial Recursive: long fact(long n) if (n == 1) return 1; return n*fact(n-1); int main() long n; cout << "Input n: "; cin >> n; cout << n << "! = " << fact(n) << endl; return 0; Factorial Iterative: long fact(long n) long num = 1; for (int i = 1; i <= n; i++) num = num*i; return num; int main() long n; cout << "Input n: "; cin >> n; cout << n << "! = " << fact(n) << endl; return 0; 1

2 Fibonacci Sequence Recursive: int fib(int n) if ((n == 1) (n == 2)) return 1; return fib(n-1)+fib(n-2); int main() long n; cout << "Input n: "; cin >> n; cout << "Fibonacci Number " << n << " is " << fib(n) << endl << endl; cout << "The first " << n << " Fibonacci Numbers are " << endl; for (int j = 1; j <= n; j++) cout << fib(j) << " "; return 0; Fibonacci Sequence Iterative: long fib(long n) long backone = 1; long backtwo = 1; long num = 1; for (int i = 3; i <= n; i++) num = backone + backtwo; backtwo = backone; backone = num; return num; int main() SAME AS ABOVE 2

3 Divisibility by 9: int add_digits(int n) int sum = 0; while (n > 0) sum += (n % 10); n = n/10; return sum; bool isdiv9(int num) if (num == 9) return true; else if (num > 9) return isdiv9(add_digits(num)); return false; int main() long n; cout << "Input n: "; cin >> n; if (isdiv9(n)) cout << n << " is divisible by 9." << endl; else cout << n << " is not divisible by 9." << endl; return 0; 3

4 Towers of Hanoi Example: /* * Hanoi_Ex01.cpp * Simple Towers of Hanoi example. * Author: Don Spickler * Created: January 17, 2011 * Current: January 17, 2011 */ #include <string> void hanoi(int n, const std::string& initneedle, const std::string& endneedle, const std::string& tempneedle) if (n == 1) std::cout << "move " << initneedle << " to " << endneedle << std::endl; else hanoi(n-1, initneedle, tempneedle, endneedle); std::cout << "move " << initneedle << " to " << endneedle << std::endl; hanoi(n-1, tempneedle, endneedle, initneedle); int main() int n; string beginneedle = "A", middleneedle = "B", endneedle = "C"; cout << "Enter the number of disks: "; cin >> n; cout << "The solution for n = " << n << endl; hanoi(n, beginneedle, endneedle, middleneedle); return 0; 4

5 Advanced Recursion Applications: Backtracking Support file for EightQueens and Maze: #ifndef EXCEPTION_CLASSES #define EXCEPTION_CLASSES #include <strstream> #include <string> class baseexception baseexception(const string& str = ""): msgstring(str) if (msgstring == "") msgstring = "Unspecified exception"; string what() const return msgstring; // protected allows a derived class to access msgstring. // chapter 13 discusses protected in detail protected: string msgstring; ; // failure to allocate memory (new() returns NULL) class memoryallocationerror: public baseexception memoryallocationerror(const string& msg = ""): ; // function argument out of proper range class rangeerror: public baseexception rangeerror(const string& msg = ""): ; // index out of range class indexrangeerror: public baseexception indexrangeerror(const string& msg, int i, int size): 5

6 ; baseexception() char indexstring[80]; ostrstream indexerr(indexstring, 80); indexerr << msg << " index " << i << " size = " << size << ends; // indexrangeerror can modify msgstring, since it is in // the protected section of baseexception msgstring = indexstring; // attempt to erase from an empty container class underflowerror: public baseexception underflowerror(const string& msg = ""): ; // attempt to insert into a full container class overflowerror: public baseexception overflowerror(const string& msg = ""): ; // error in expression evaluation class expressionerror: public baseexception expressionerror(const string& msg = ""): ; // bad object reference class referenceerror: public baseexception referenceerror(const string& msg = ""): ; // feature not implemented class notimplementederror: public baseexception notimplementederror(const string& msg = ""): ; 6

7 // date errors class dateerror: public baseexception dateerror(const string& first, int v, const string& last): baseexception() char datestr[80]; ostrstream dateerr(datestr, 80); ; dateerr << first << ' ' << v << ' ' << last << ends; // dateerror can modify msgstring, since it is in // the protected section of baseexception msgstring = datestr; // error in graph class class grapherror: public baseexception grapherror(const string& msg = ""): ; // file open error class fileopenerror: public baseexception fileopenerror(const string& fname): baseexception() char errorstr[80]; ostrstream fileerr(errorstr, 80); ; fileerr << "Cannot open \"" << fname << "\"" << ends; // fileopenerror can modify msgstring, since it is in // the protected section of baseexception msgstring = errorstr; // error in graph class class fileerror: public baseexception fileerror(const string& msg = ""): ; #endif // EXCEPTION_CLASSES 7

8 Support file for EightQueens and Maze: #ifndef MATRIX_CLASS #define MATRIX_CLASS #include <vector> #include "d_except.h" template <typename T> class matrix matrix(int numrows = 1, int numcols = 1, const T& initval = T()); // constructor. // Postcondition: create array having numrows x numcols elements // all of whose elements have value initval vector<t>& operator[] (int i); // index operator. // Precondition: 0 <= i < nrows. a violation of this // precondition throws the indexrangeerror exception. // Postcondition: if the operator is used on the left-hand // side of an assignment statement, an element of row i // is changed const vector<t>& operator[](int i) const; // version for constant objects int rows() const; // return number of rows int cols() const; // return number of columns void resize(int numrows, int numcols); // modify the matrix size. // Postcondition: the matrix has size numrows x numcols. // any new elements are filled with the default value of type T private: int nrows, ncols; // number of rows and columns ; vector<vector<t> > mat; // matrix is implemented as nrows vectors (rows), // each having ncols elements (columns) template <typename T> matrix<t>::matrix(int numrows, int numcols, const T& initval): nrows(numrows), ncols(numcols), mat(numrows, vector<t>(numcols,initval)) // non-constant version. provides general access to matrix 8

9 // elements template <typename T> vector<t>& matrix<t>::operator[] (int i) if (i < 0 i >= nrows) throw indexrangeerror( "matrix: invalid row index", i, nrows); return mat[i]; // constant version. can be used with a constant object. // does not allow modification of a matrix element template <typename T> const vector<t>& matrix<t>::operator[] (int i) const if (i < 0 i >= nrows) throw indexrangeerror( "matrix: invalid row index", i, nrows); return mat[i]; template <typename T> int matrix<t>::rows() const return nrows; template <typename T> int matrix<t>::cols() const return ncols; template <typename T> void matrix<t>::resize(int numrows, int numcols) int i; // handle case of no size change with a return if (numrows == nrows && numcols == ncols) return; // assign the new matrix size nrows = numrows; ncols = numcols; // resize to nrows rows mat.resize(nrows); // resize each row to have ncols columns for (i=0; i < nrows; i++) mat[i].resize(ncols); #endif // MATRIX_CLASS 9

10 Eight Queens Header File: #ifndef EIGHT_QUEENS_PROBLEM #define EIGHT_QUEENS_PROBLEM #include <vector> #include "d_matrix.h" // can a queen at (row,col) be attacked by any of the // non-attacking queens in columns 0 to col-1? bool safelocation(int row, int col, const vector<int>& queenlist) int qrow, qcol; for (qcol = 0; qcol < col; qcol++) // check previous columns only qrow = queenlist[qcol]; if (qrow == row) // same row return false; else if (qcol == col) // same col return false; // can they attack on a diagonal? else if(qcol-qrow == col-row qcol+qrow == col+row) return false; return true; // place a queen in columns col through 7 bool placequeens(vector<int>& queenlist, int col) int row; bool foundlocation; if (col == 8) // stopping condition foundlocation = true; else foundlocation = false; // start with row 0 row = 0; while (row < 8 &&!foundlocation) // check whether cell (row, col) is safe; if so, // assign row to queenlist and call placequeens() // for next column; otherwise, go to the next row if (safelocation(row,col,queenlist) == true) // found good location queenlist[col] = row; // recursive step. try to place queens in columns col+1 // through 7 foundlocation = placequeens(queenlist,col+1); 10

11 if (!foundlocation) // use next row since current one does not lead // to a solution row++; else // current row fails. go to the next row row++; // end while // pass success or failure back to previous col return foundlocation; // try to find a solution to the 8-Queens problem starting // with a queen at (row,0) bool queens(vector<int>& queenlist, int row) // place first queen at (row,0) queenlist[0] = row; // locate remaining queens in columns 1 through 7 if (placequeens(queenlist, 1)) return true; else return false; class chessboard chessboard(); // default constructor void setqueens(const vector<int>& queenlist); // set queens on board at cells (queenlist[col], col) // 0 <= col < 8 void clearboard(); // clear the board void drawboard() const; // draw the board using symbols 'Q' or '-' private: // simulates chess board matrix<bool> board; ; // constructor. initialize board to blanks chessboard::chessboard(): board(8,8) clearboard(); 11

12 // assign queens at locations (queenlist[col],col), // 0 <= col < 8 void chessboard::setqueens(const vector<int>& queenlist) clearboard(); for (int col = 0; col < 8; col++) board[queenlist[col]][col] = true; void chessboard::clearboard() int i,j; for(i=0; i < 8; i++) for(j=0; j < 8; j++) board[i][j] = false; // draw the chess board void chessboard::drawboard() const int i,j; cout <<" " << endl; for (i = 0; i < 8; i++) cout << i << " "; // draw the squares in current row for (j = 0; j < 8; j++) if (board[i][j] == true) cout << " Q"; else cout << " -"; cout << endl; #endif // EIGHT_QUEENS_PROBLEM 12

13 Eight Queens Main: // the program solves the 8-Queens problem. it prompts the user for // the starting row for the queen in column 0 and calls the recursive // backtracking function queens() to determine if there is a solution. // if there is a solution, the position of the queens is passed to // the chessboard object, board, and a call to its drawboard() function // shows the placement of the queens #include "d_queens.h" int main () int row; vector<int> queenlist(8); chessboard board; // enter a starting row for queen in column 0 cout << "Enter row for queen in column 0: "; cin >> row; cout << endl; // see if there is a solution if (queens(queenlist, row)) board.setqueens(queenlist); // display the solution board.drawboard(); else cout << "No solution" << endl; return 0; Run: Enter row for queen in column 0: Q Q Q Q Q Q Q Q

14 Maze Program: #include <fstream> #include <string> #include <cstdlib> #include "matrix.h" void solvemaze(matrix<char> maze, matrix<char>& solmaze, int x, int y) if (maze[x][y] == 'F') maze[x][y] = '-'; solmaze = maze; else maze[x][y] = '-'; if ((x-1 >= 0) && ((maze[x-1][y] == ' ') (maze[x-1][y] == 'F'))) solvemaze(maze, solmaze, x-1, y); if ((y-1 >= 0) && ((maze[x][y-1] == ' ') (maze[x][y-1] == 'F'))) solvemaze(maze, solmaze, x, y-1); 'F'))) 'F'))) if ((x+1 < maze.rows()) && ((maze[x+1][y] == ' ') (maze[x+1][y] == solvemaze(maze, solmaze, x+1, y); if ((y+1 < maze.cols()) && ((maze[x][y+1] == ' ') (maze[x][y+1] == solvemaze(maze, solmaze, x, y+1); int main () string filename; cout << "Enter the maze filename: "; cin >> filename; fstream mazefile; mazefile.open(filename.c_str()); if (!mazefile) cerr << "Cannot open " << filename << endl; exit(1); char c; int rows = 0; int cols = 0; while(mazefile) mazefile.get(c); if (c == '\n') rows++; 14

15 if ((c!= '\n') && (rows == 0)) cols++; if (!mazefile) break; rows++; // Add 1 since the last return is not counted. cols++; // Add 1 so we can store the end line character in the maze. mazefile.close(); matrix<char> maze(rows, cols); // Load maze into matrix. mazefile.open(filename.c_str()); for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) mazefile.get(c); if (mazefile) maze[i][j] = c; mazefile.close(); // Find the S int sposx = 0; int sposy = 0; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) if (maze[i][j] == 'S') sposx = i; sposy = j; // Solve the maze. matrix<char> solmaze; solvemaze(maze, solmaze, sposx, sposy); // Write Result to Solution File string solfile = "Solution_" + filename; mazefile.open(solfile.c_str(), ios::out ios::trunc); if (!mazefile) cerr << "Cannot open " << solfile << endl; exit(1); for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) mazefile.put(solmaze[i][j]); mazefile.close(); return 0; 15

16 Run: Input File XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXX XXXXXXXXX XXXXXXXXXXXXX XXXX XXXXX XXX XXX XX XXXXXXX XXXXXXXXXXXXXXXX XXXXX XX XXXXXXXXXXXXXXXXXXXXXXX X X XXX XX X XXXXXXX XXXXXXXXXXXXXXXX XXXXX XXXX XX XXX XXXXXXXX XXXXX XXXXXXXXXX XXXXXXXXX XX XXXXX XXXX XX XXX XXXXXXXXXX XX XXX XXX XXXX XX XXXXXXXXXXXXXXXXXXX XXXX XX XXX XXXX XXXXX XX X XXX XXX XX XXXXXXXXXXXXXXXXXXX XX XXXXXXXXXXX XXXX XX XXX XXXX XXXXX X XXX XXX XX X X XXXX XXXXXXXXXX XXXX XXXXXX XXXX XX XXX XXXX XXXXXXXXXX XXX XXX XX X X XXXXXXXXXX XXXX XXX XXXX XXXXXX XXXX XX XXX XXXX XXXXXXXXXX XXX XXX XX X X XXXX XXXX XXX XXXXXXXXXXX XXXXXX XXXX XX XXX XXXX XXXXXXXXXX F XXX XX X X XXXXX XXXX XX XXX XXXXXXXXXXX XXXXXX XXXX XX XXX XX XXXXX XXX XX X X XX XX XXXX XXXX XXX XXXXXXXXXXX XXXXXX XXXX XX XXX XX XXXXXXXXXX XXXXX XXX XX X X XX XX XXXX XXXX XXX XXXX XX XXX XX X X XXXXX XXX XX X XX XXXX XXXX XXXXXXXXXX XXXXXXXXXXXXXXXX XX XXX XX X XXXXXX X XXXXX XXX XX X XXXX XX XXXX X XXXX XXXXX XX XXXXXX XX XXX XX X X XX X XXXXX XXX XX XXXXXXXXX XXXX XXXX XXXX XXXXX XXXXXXXXX XXXXXX XX XXX XX X X X XX X XXXXX XXX XX XXXX XXXX XXXX XXXXX XXXXXXXXX XXXXXX XX XXX XX X X X XX X XXXXX XXX XXXXXXXXXXXXXXXXX XXXX XX XXXXXX XX XXX XX X X X XX X XXXXX XXX XXXXXXXXXXXXXXXXX XXXX XX XXXXXXXXXXXXXXXXXXXXXXXX XX XXX XX X X X XX X XXXXX XXX XXX XXXX XX XXXXXXXXXXXXXXXXXXXXXXXX XX XXX XX X X X XX X XXXXX XXX XXX XXXXXXXXXXXXXXXXXX XX XXX XX XXX XX X X X X X XXXXX XXX XXX XXXXX XX XXX XXXXXXXXXXXXXXXXXXXXXXX XXX XX X X XXXX X XXXXX XXX XXXXXXXXXXXXXXXX XXXXX XX XXX XXXXX XXX XXXXXX XXXXX XXX XX X X X XXXXX XXX XXXXXXX XXXXX XX XXX XXXXX XXX XXXXXX XXXXX XXXX XX X XXXXXXXX XXXXX XXX XXXXXXX XXXX XXXXXXXXX XX XXX XX X XXXXX XXX XX X XX XXXX XXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX S XX XXXX X XXXX XX XXXXXXX XXXXXX XXXX XXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Output File XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXX XXXXXXXXX XXXXXXXXXXXXX XXXX XXXXX XXX XXX XX XXXXXXX-XXXXXXXXXXXXXXXX-XXXXX------XX XXXXXXXXXXXXXXXXXXXXXXX X X XXX XX X XXXXXXX-XXXXXXXXXXXXXXXX-XXXXX-XXXX-XX XXX XXXXXXXX XXXXX XXXXXXXXXX XXXXXXXXX-XX XXXXX-XXXX-XX XXX-XXXXXXXXXX-XX---XXX XXX---- XXXX-XX-XXXXXXXXXXXXXXXXXXX-XXXX-XX XXX-XXXX XXXXX-XX-X-XXX XXX-XX-XXXXXXXXXXXXXXXXXXX-XX XXXXXXXXXXX-XXXX-XX XXX-XXXX XXXXX----X-XXX XXX-XX-X X XXXX-XXXXXXXXXX-XXXX XXXXXX-XXXX-XX XXX-XXXX XXXXXXXXXX-XXX XXX-XX-X X-XXXXXXXXXX-XXXX-XXX XXXX XXXXXX-XXXX-XX XXX-XXXX XXXXXXXXXX-XXX XXX-XX-X X XXXX-XXXX-XXX-XXXXXXXXXXX XXXXXX-XXXX-XX XXX-XXXX XXXXXXXXXX---- XXX-XX-X X XXXXX-XXXX-XX -XXX-XXXXXXXXXXX XXXXXX-XXXX-XX XXX-XX XXXXX XXX-XX-X X XX XX-XXXX-XXXX-XXX-XXXXXXXXXXX XXXXXX-XXXX-XX XXX-XX XXXXXXXXXX XXXXX XXX-XX-X X XX XX-XXXX-XXXX-XXX XXXX-XX XXX-XX X X XXXXX XXX-XX-X XX-XXXX-XXXX-XXXXXXXXXX XXXXXXXXXXXXXXXX-XX XXX-XX X XXXXXX X XXXXX XXX-XX-X XXXX XX-XXXX-X -XXXX XXXXX XX XXXXXX-XX XXX-XX X X XX X XXXXX XXX-XX-XXXXXXXXX-XXXX-XXXX-XXXX XXXXX XXXXXXXXX XXXXXX-XX XXX-XX X X X XX X XXXXX XXX-XX XXXX-XXXX-XXXX XXXXX XXXXXXXXX XXXXXX-XX XXX-XX X X X XX X XXXXX XXX-XXXXXXXXXXXXXXXXX-XXXX-XX XXXXXX-XX XXX-XX X X X XX X XXXXX XXX-XXXXXXXXXXXXXXXXX-XXXX-XX XXXXXXXXXXXXXXXXXXXXXXXX-XX XXX-XX X X X XX X XXXXX XXX-XXX XXXX-XX XXXXXXXXXXXXXXXXXXXXXXXX-XX XXX-XX X X X XX X XXXXX XXX-XXX-XXXXXXXXXXXXXXXXXX-XX XXX XX XXX-XX X X X X X XXXXX XXX-XXX XXXXX-XX XXX-XXXXXXXXXXXXXXXXXXXXXXX XXX-XX X X XXXX X XXXXX XXX-XXXXXXXXXXXXXXXX-XXXXX-XX XXX-XXXXX XXX XXXXXX XXXXX XXX-XX X X X XXXXX XXX-XXXXXXX XXXXX-XX XXX-XXXXX XXX XXXXXX XXXXX XXXX-XX X XXXXXXXX XXXXX XXX-XXXXXXX-XXXX XXXXXXXXX-XX XXX XX X XXXXX XXX- XX-X XX XXXX XXXX-XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX ----XX XXXX-X XXXX-XX XXXXXXX XXXXXX XXXX-XXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 16

Chapter 6 Recursion. The Concept of Recursion

Chapter 6 Recursion. The Concept of Recursion Data Structures for Java William H. Ford William R. Topp Chapter 6 Recursion Bret Ford 2005, Prentice Hall The Concept of Recursion An algorithm is recursive if it can be broken into smaller problems of

More information

Functions. Functions in C++ Calling a function? What you should know? Function return types. Parameter Type-Checking. Defining a function

Functions. Functions in C++ Calling a function? What you should know? Function return types. Parameter Type-Checking. Defining a function Functions in C++ Functions For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Declarations vs Definitions Inline Functions Class Member functions Overloaded

More information

Solving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10;

Solving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10; Solving a 2D Maze Let s use a 2D array to represent a maze. Let s start with a 10x10 array of char. The array of char can hold either X for a wall, for a blank, and E for the exit. Initially we can hard-code

More information

Recursion. Recursion is: Recursion splits a problem:

Recursion. Recursion is: Recursion splits a problem: Recursion Recursion Recursion is: A problem solving approach, that can... Generate simple solutions to... Certain kinds of problems that... Would be difficult to solve in other ways Recursion splits a

More information

CS200: Recursion and induction (recap from cs161)

CS200: Recursion and induction (recap from cs161) CS200: Recursion and induction (recap from cs161) Prichard Ch. 6.1 & 6.3 1 2 Backtracking n Problem solving technique that involves moves: guesses at a solution. n Depth First Search: in case of failure

More information

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

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points) Name Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Relational Expression Iteration Counter Count-controlled loop Loop Flow

More information

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Reading for this lecture: Carrano, Chapter 2 Copy constructor, destructor, operator=

More information

Come and join us at WebLyceum

Come and join us at WebLyceum Come and join us at WebLyceum For Past Papers, Quiz, Assignments, GDBs, Video Lectures etc Go to http://www.weblyceum.com and click Register In Case of any Problem Contact Administrators Rana Muhammad

More information

Table II-1 Challenges in China s seeds, crops and grains in the next five years

Table II-1 Challenges in China s seeds, crops and grains in the next five years II Seeds, crops and grains situation in China Table II-1 Challenges in China s seeds, crops and grains in the next five years N Challenges Reason o. 1 xxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

More information

Lecture 6: Recursion RECURSION

Lecture 6: Recursion RECURSION Lecture 6: Recursion RECURSION You are now Java experts! 2 This was almost all the Java that we will teach you in this course Will see a few last things in the remainder of class Now will begin focusing

More information

Topics. bool and string types input/output library functions comments memory allocation templates classes

Topics. bool and string types input/output library functions comments memory allocation templates classes C++ Primer C++ is a major extension of c. It is similar to Java. The lectures in this course use pseudo-code (not C++). The textbook contains C++. The labs involve C++ programming. This lecture covers

More information

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

Bit level Binaries and Generalized Comprehensions in Erlang. Per Gustafsson and Kostis Sagonas Dept of Information Technology Uppsala University

Bit level Binaries and Generalized Comprehensions in Erlang. Per Gustafsson and Kostis Sagonas Dept of Information Technology Uppsala University Bit level Binaries and Generalized Comprehensions in Erlang Per Gustafsson and Kostis Sagonas Dept of Information Technology Uppsala University Binaries as we know them Introduced in 1992 as a container

More information

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

CPE Summer 2015 Exam I (150 pts) June 18, 2015 Name Closed notes and book. If you have any questions ask them. Write clearly and make sure the case of a letter is clear (where applicable) since C++ is case sensitive. You can assume that there is one

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017

More information

the pointer range [first, last) into the tree

the pointer range [first, last) into the tree 1 #ifndef BINARY_SEARCH_TREE_CLASS 2 #define BINARY_SEARCH_TREE_CLASS 3 4 #ifndef NULL 5 #include 6 #endif // NULL 7 8 #include // for setw() 9 #include // for format conversion

More information

EE 368. Weeks 4 (Notes)

EE 368. Weeks 4 (Notes) EE 368 Weeks 4 (Notes) 1 Read Chapter 3 Recursion and Backtracking Recursion - Recursive Definition - Some Examples - Pros and Cons A Class of Recursive Algorithms (steps or mechanics about performing

More information

Packaging and labelling

Packaging and labelling QRDvet template, opportunities for reduced label text and multi-lingual labels, recent examples EMA/IFAH-Europe Info Day 2014 Presented by: Jóhann M. Lenharðsson CVMP member (IS) An agency of the European

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

SOLUTIONS TO EXERCISES PART ONE: Problem-Solving Techniques

SOLUTIONS TO EXERCISES PART ONE: Problem-Solving Techniques SOLUTIONS TO EXERCISES PART ONE: Problem-Solving Techniques 1 Principles of Programming and Software Engineering 1 const CENTS_PER_DOLLAR = 100; void computechange(int dollarcost, int centscost, int& d,

More information

CSCI 101L - Data Structures. Practice problems for Final Exam. Instructor: Prof Tejada

CSCI 101L - Data Structures. Practice problems for Final Exam. Instructor: Prof Tejada CSCI 101L - Data Structures Practice problems for Final Exam Instructor: Prof Tejada 1 Problem 1. Debug this code Given the following code to increase the value of a variable: void Increment(int x) { x

More information

CS 7B - Spring Final Exam

CS 7B - Spring Final Exam CS 7B - Spring 2018 - Final Exam Write your responses to following questions on this paper, or attach extra, as needed. sentences where appropriate and write out code using proper style and syntax. 1.

More information

13.4 Case Study: vector<t>-based Matrices

13.4 Case Study: vector<t>-based Matrices 13.4 Case Study: vector-based Matrices 1 13.4 Case Study: vector-based Matrices A two-dimensional numeric array having m rows and n columns is called an m n matrix. There are many important applications

More information

Graphs. directed and undirected graphs weighted graphs adjacency matrices. abstract data type adjacency list adjacency matrix

Graphs. directed and undirected graphs weighted graphs adjacency matrices. abstract data type adjacency list adjacency matrix Graphs 1 Graphs directed and undirected graphs weighted graphs adjacency matrices 2 Graph Representations abstract data type adjacency list adjacency matrix 3 Graph Implementations adjacency matrix adjacency

More information

Data Structures And Algorithms

Data Structures And Algorithms Data Structures And Algorithms Recursion Eng. Anis Nazer First Semester 2016-2017 Recursion Recursion: to define something in terms of itself Example: factorial n!={ 1 n=0 n (n 1)! n>0 Recursion Example:

More information

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology 8/23/2014. Arrays Hold Multiple Values

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology 8/23/2014. Arrays Hold Multiple Values Chapter 7: Arrays 7.1 Arrays Hold Multiple Values Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations Declared using

More information

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Question No: 1 ( Marks: 2 ) Write a declaration statement for an array of 10

More information

C++ Exception Handling 1

C++ Exception Handling 1 C++ Exception Handling 1 An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such

More information

Chapter 7: Arrays Copyrig opy ht rig 2012 Pea e rson a Educa Educ ti a on, Inc I. nc

Chapter 7: Arrays Copyrig opy ht rig 2012 Pea e rson a Educa Educ ti a on, Inc I. nc Chapter 7: Arrays 7.1 Arrays Hold Multiple Values Arrays Hold Multiple Values Array variable that can store multiple values of the same type (aggregate type) Values are stored in adjacent memory locations

More information

Due Date: See Blackboard

Due Date: See Blackboard Source File: ~/2315/45/lab45.(C CPP cpp c++ cc cxx cp) Input: under control of main function Output: under control of main function Value: 4 Integer data is usually represented in a single word on a computer.

More information

CmpSci 187: Programming with Data Structures Spring 2015

CmpSci 187: Programming with Data Structures Spring 2015 CmpSci 187: Programming with Data Structures Spring 2015 Lecture #9 John Ridgway February 26, 2015 1 Recursive Definitions, Algorithms, and Programs Recursion in General In mathematics and computer science

More information

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. C++ TEMPLATES http://www.tutorialspoint.com/cplusplus/cpp_templates.htm Copyright tutorialspoint.com Templates are the foundation of generic programming, which involves writing code in a way that is independent

More information

CSCI 135 Software Design and Analysis, C++ Homework 8 Solution

CSCI 135 Software Design and Analysis, C++ Homework 8 Solution CSCI 135 Software Design and Analysis, C++ Homework 8 Solution Saad Mneimneh Computer Science Hunter College of CUNY Problem 1: Two-dimensional arrays and the 15 puzzle The 15 puzzle consist of 15 pieces

More information

UEE1303(1070) S12: Object-Oriented Programming Constant Pointer and Class

UEE1303(1070) S12: Object-Oriented Programming Constant Pointer and Class UEE1303(1070) S12: Object-Oriented Programming Constant Pointer and Class What you will learn from Lab 4 In this laboratory, you will learn how to use const to identify constant pointer and the basic of

More information

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT

Containers: Stack. The Stack ADT. The Stack ADT. The Stack ADT Containers: Stack The Stack ADT A stack is a list of objects in which insertions and deletions can only be performed at the top of the list. Also known as LIFO Last In, First Out) push insert an element

More information

Practice Final Examination #2

Practice Final Examination #2 Eric Roberts Handout #54 CS106B March 11, 2013 Practice Final Examination #2 Review session: Sunday, March 17, 3:00 5:00 P.M. (Hewlett 200) Scheduled finals: Tuesday, March 19, 12:15 3:15 P.M. (Hewlett

More information

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science Containers: Stack Jordi Cortadella and Jordi Petit Department of Computer Science The Stack ADT A stack is a list of objects in which insertions and deletions can only be performed at the top of the list.

More information

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. A single variable can only hold one value. Declared using [] operator:

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. A single variable can only hold one value. Declared using [] operator: Chapter 7: 7.1 Arrays Arrays Hold Multiple Values Arrays Hold Multiple Values Array - Memory Layout A single variable can only hold one value int test; 95 Enough memory for 1 int What if we need to store

More information

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

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition) Structures Programming in C++ Sequential Branching Repeating Loops (Repetition) 2 1 Loops Repetition is referred to the ability of repeating a statement or a set of statements as many times this is necessary.

More information

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park

CMSC 132: Object-Oriented Programming II. Recursive Algorithms. Department of Computer Science University of Maryland, College Park CMSC 132: Object-Oriented Programming II Recursive Algorithms Department of Computer Science University of Maryland, College Park Recursion Recursion is a strategy for solving problems A procedure that

More information

APCS-AB: Java. Recursion in Java December 12, week14 1

APCS-AB: Java. Recursion in Java December 12, week14 1 APCS-AB: Java Recursion in Java December 12, 2005 week14 1 Check point Double Linked List - extra project grade Must turn in today MBCS - Chapter 1 Installation Exercises Analysis Questions week14 2 Scheme

More information

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology Chapter 7: Arrays 7.1 Arrays Hold Multiple Values Copyright 2009 Pearson Education, Inc. Copyright Publishing as Pearson 2009 Addison-Wesley Pearson Education, Inc. Publishing as Pearson Addison-Wesley

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

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

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

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

Spare Matrix Formats, and The Standard Template Library

Spare Matrix Formats, and The Standard Template Library Annotated slides CS319: Scientific Computing (with C++) Spare Matrix Formats, and The Standard Template Library Week 10: 9am and 4pm, 20 March 2019 1 Sparse Matrices 2 3 Compressed Column Storage 4 (Not)

More information

Linked List using a Sentinel

Linked List using a Sentinel Linked List using a Sentinel Linked List.h / Linked List.h Using a sentinel for search Created by Enoch Hwang on 2/1/10. Copyright 2010 La Sierra University. All rights reserved. / #include

More information

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

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1 Chapter 5: Loops and Files The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; ++ can be used before (prefix) or after (postfix)

More information

Unified Modeling Language a case study

Unified Modeling Language a case study Unified Modeling Language a case study 1 an online phone book use case diagram encapsulating a file 2 Command Line Arguments arguments of main arrays of strings 3 Class Definition the filesphonebook.h

More information

CS302 - Data Structures using C++

CS302 - Data Structures using C++ CS302 - Data Structures using C++ Pre-Course: Variables, Basic Types, Control Structures Kostas Alexis Slides inspired by the course Modern C++, Uni Bonn: http://www.ipb.uni-bonn.de/teaching/modern-cpp/

More information

UEE1303(1070) S12: Object-Oriented Programming Constructors and Destructors

UEE1303(1070) S12: Object-Oriented Programming Constructors and Destructors UEE1303(1070) S12: Object-Oriented Programming Constructors and Destructors What you will learn from Lab 5 In this laboratory, you will learn how to use constructor and copy constructor to create an object

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

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

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table

More information

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15 C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of dynamic memory allocation of variables and objects in a C++ program.

More information

To explain growth rates and why constants and nondominating terms can be ignored in the estimation

To explain growth rates and why constants and nondominating terms can be ignored in the estimation CHAPTER 18 Developing Efficient Algorithms Objectives To estimate algorithm efficiency using the Big O notation ( 18.2). To explain growth rates and why constants and nondominating terms can be ignored

More information

For Teacher's Use Only Q No Total Q No Q No

For Teacher's Use Only Q No Total Q No Q No Student Info Student ID: Center: Exam Date: FINALTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Time: 90 min Marks: 58 For Teacher's Use Only Q No. 1 2 3 4 5 6 7 8 Total Marks Q No. 9

More information

www.thestudycampus.com Recursion Recursion is a process for solving problems by subdividing a larger problem into smaller cases of the problem itself and then solving the smaller, more trivial parts. Recursion

More information

Recursion (Rosen, 6 th edition, Section 4.3, 4.4)

Recursion (Rosen, 6 th edition, Section 4.3, 4.4) Recursion (Rosen, 6 th edition, Section 4.3, 4.4) Carol Zander For recursion, the focus is mostly on recursive algorithms. While recursive definitions will sometimes be used in definitions (you already

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

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

Operator Overloading in C++ Systems Programming

Operator Overloading in C++ Systems Programming Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading

More information

Object Oriented Programming using C++

Object Oriented Programming using C++ Object Oriented Programming using C++ Overview Problem Solving Features of an OOL Basic Syntax Programming Paradigms Solving a Programming Problem Analysis Design Coding Management Programming paradigms

More information

CS 115 Exam 3, Spring 2010

CS 115 Exam 3, Spring 2010 Your name: Rules You must briefly explain your answers to receive partial credit. When a snippet of code is given to you, you can assume o that the code is enclosed within some function, even if no function

More information

Lists. linking nodes. constructors. chasing pointers. MCS 360 Lecture 11 Introduction to Data Structures Jan Verschelde, 17 September 2010.

Lists. linking nodes. constructors. chasing pointers. MCS 360 Lecture 11 Introduction to Data Structures Jan Verschelde, 17 September 2010. 1 2 3 MCS 360 Lecture 11 Introduction to Data Structures Jan Verschelde, 17 September 2010 1 2 3 efficient updates with lists At http://www.sgi.com/tech/stl/ is the Standard Template Library Programmer

More information

Object oriented programming

Object oriented programming Exercises 12 Version 1.0, 9 May, 2017 Table of Contents 1. Virtual destructor and example problems...................................... 1 1.1. Virtual destructor.......................................................

More information

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures Lecture 10 Class string Exception Handling To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures Class template auto_ptr Lec 10 Programming in C++ 1 Class

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

Computer Science II Lecture 2 Strings, Vectors and Recursion

Computer Science II Lecture 2 Strings, Vectors and Recursion 1 Overview of Lecture 2 Computer Science II Lecture 2 Strings, Vectors and Recursion The following topics will be covered quickly strings vectors as smart arrays Basic recursion Mostly, these are assumed

More information

More Group HW. #ifndef Stackh #define Stackh. #include <cstdlib> using namespace std;

More Group HW. #ifndef Stackh #define Stackh. #include <cstdlib> using namespace std; More Group HW The following code is contained in the file ex1stck.h. Fill in the blanks with the C++ statement(s) that will correctly finish the method. Each blank may be filled in with more than one statement.

More information

Recursion Solution. Counting Things. Searching an Array. Organizing Data. Backtracking. Defining Languages

Recursion Solution. Counting Things. Searching an Array. Organizing Data. Backtracking. Defining Languages Recursion Solution Counting Things Searching an Array Organizing Data Backtracking Defining Languages 1 Recursion Solution 3 RECURSION SOLUTION Recursion An extremely powerful problem-solving technique

More information

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

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type. CS 7A - Fall 2016 - Midterm 1 10/20/16 Write responses to questions 1 and 2 on this paper or attach additional sheets, as necessary For all subsequent problems, use separate paper Do not use a computer

More information

selectors, methodsinsert() andto_string() the depth of a tree and a membership function

selectors, methodsinsert() andto_string() the depth of a tree and a membership function Binary Search Trees 1 Sorting Numbers using a Tree a sorting algorithm using a tree of integer numbers 2 Header Files defining a node struct defining a tree class 3 Definition of Methods selectors, methodsinsert()

More information

Chapter 5: Loops and Files

Chapter 5: Loops and Files Chapter 5: Loops and Files 5.1 The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1;

More information

In either case, remember to delete each array that you allocate.

In either case, remember to delete each array that you allocate. CS 103 Path-so-logical 1 Introduction In this programming assignment you will write a program to read a given maze (provided as an ASCII text file) and find the shortest path from start to finish. 2 Techniques

More information

Fundamentals of Programming Session 25

Fundamentals of Programming Session 25 Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Programming C++ Lecture 2. Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor

Programming C++ Lecture 2. Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor Programming C++ Lecture 2 Howest, Fall 2014 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Arrays and Pointers void myprint(const char *); int main() { char *phrasey = C++Fun ; myprint(phrasey);

More information

Lecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.)

Lecture 10. Command line arguments Character handling library void* String manipulation (copying, searching, etc.) Lecture 10 Class string Namespaces Preprocessor directives Macros Conditional compilation Command line arguments Character handling library void* TNCG18(C++): Lec 10 1 Class string Template class

More information

Templates and Vectors

Templates and Vectors Templates and Vectors 1 Generic Programming function templates class templates 2 the STL vector class a vector of strings enumerating elements with an iterator inserting and erasing 3 Writing our own vector

More information

BITG 1113: Array (Part 1) LECTURE 8

BITG 1113: Array (Part 1) LECTURE 8 BITG 1113: Array (Part 1) LECTURE 8 1 1 LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional (1 D)

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

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

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()

More information

Matrices. Jordi Cortadella Department of Computer Science

Matrices. Jordi Cortadella Department of Computer Science Matrices Jordi Cortadella Department of Computer Science Matrices A matrix can be considered a two-dimensional vector, i.e. a vector of vectors. my_matrix: 3 8 1 0 5 0 6 3 7 2 9 4 // Declaration of a matrix

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

COMP 2355 Introduction to Systems Programming

COMP 2355 Introduction to Systems Programming COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Today Templates Operator Overloading 2 Templates Syntactically similar to Java generics

More information

EE 355 Unit 10. C++ STL - Vectors and Deques. Mark Redekopp

EE 355 Unit 10. C++ STL - Vectors and Deques. Mark Redekopp 1 EE 355 Unit 10 C++ STL - Vectors and Deques Mark Redekopp 2 Templates We ve built a list to store integers But what if we want a list of double s or char s or other objects We would have to define the

More information

! Errors can be dealt with at place error occurs

! Errors can be dealt with at place error occurs UCLA Stat 1D Statistical Computing and Visualization in C++ Instructor: Ivo Dinov, Asst. Prof. in Statistics / Neurology University of California, Los Angeles, Winter 200 http://www.stat.ucla.edu/~dinov/courses_students.html

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

10/23/02 21:20:33 IO_Examples

10/23/02 21:20:33 IO_Examples 1 Oct 22 22:07 2000 extractor1.c Page 1 istream &operator>>( istream &in, Point &p ){ char junk; in >> junk >> p.x >> junk >> p.y >> junk; return in; 2 Oct 22 22:07 2000 extractor2.c Page 1 istream &operator>>(

More information

Programming in C++: Assignment Week 8

Programming in C++: Assignment Week 8 Programming in C++: Assignment Week 8 Total Marks : 20 Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology Kharagpur 721302 partha.p.das@gmail.com April 12,

More information

Recursion. Contents. Steven Zeil. November 25, Recursion 2. 2 Example: Compressing a Picture 4. 3 Example: Calculator 5

Recursion. Contents. Steven Zeil. November 25, Recursion 2. 2 Example: Compressing a Picture 4. 3 Example: Calculator 5 Steven Zeil November 25, 2013 Contents 1 Recursion 2 2 Example: Compressing a Picture 4 3 Example: Calculator 5 1 1 Recursion Recursion A function is recursive if it calls itself or calls some other function

More information

Arrays. Arizona State University 1

Arrays. Arizona State University 1 Arrays CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 8 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Recursion. Example R1

Recursion. Example R1 Recursion Certain computer problems are solved by repeating the execution of one or more statements a certain number of times. So far, we have implemented the repetition of one or more statements by using

More information

Recursion. Jordi Cortadella Department of Computer Science

Recursion. Jordi Cortadella Department of Computer Science Recursion Jordi Cortadella Department of Computer Science Recursion Introduction to Programming Dept. CS, UPC 2 Principle: Reduce a complex problem into a simpler instance of the same problem Recursion

More information

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak! //Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information