C++ Review. COMPSCI 355 Fall 2016

Size: px
Start display at page:

Download "C++ Review. COMPSCI 355 Fall 2016"

Transcription

1 C++ Review COMPSCI 355 Fall 2016

2 C++ Review basic I/O command-line arguments dynamic memory allocation pointers and memory leaks random number generation

3 Balls and Bins How many people must be in a group before it is likely that at least two of them have the same birthday? Many problems in mathematics and computer science can be modeled as Balls and Bins problems. Hashing Load balancing How to distribute k processes among n CPUs. How to assign k visiting students to n professors.

4 Balls and Bins /* * Estimates probability that if k balls are randomly thrown * into n bins, at least one bin will receive multiple balls. * * Author: Drue Coles */ #include <cstdlib> #include <iostream> #include <ctime> using namespace std; // Simulates tossing k balls into n bins. Returns true if at // least one bin receives multiple balls. bool toss(int k, int n); int main(int argc, char** argv) { bool toss(int k, int n) {

5 Balls and Bins int main(int argc, char** argv) { if (argc!= 3) { cout << "Usage: " << argv[0] << " [balls] [bins]\n"; return 0; int balls = atoi(argv[1]); int bins = atoi(argv[2]); // Perform the simulation many times const int TRIALS = ; srand(time(0)); int success = 0; for (int i = 0; i < TRIALS; i++) { if (toss(balls, bins)) success++; // Estimate probability as fraction of successful trials. double prob = static_cast<double>(success) / TRIALS; cout << "Probability of a bin with at least 2 balls: " << prob << endl; return 0;

6 Balls and Bins bool toss(int k, int n) { // bins[i] = true if the i-th bin contains a ball bool* bins = new bool[n]; for (int i = 0; i < n; i++) { Is this necessary? bins[i] = false; // Throw each ball into a random bin. for (int i = 0; i < k; i++) { int j = rand() % n; if (bins[j]) { // j-th bin already contains a ball return true; bins[j] = true; return false; What is the problem here?

7 Balls and Bins bool toss(int k, int n) { // bins[i] = true if the i-th bin contains a ball bool* bins = new bool[n]; for (int i = 0; i < n; i++) { Is this necessary? bins[i] = false; // Throw each ball into a random bin. for (int i = 0; i < k; i++) { int j = rand() % n; if (bins[j]) { // j-th bin already contains a ball delete bins; return true; bins[j] = true; delete bins; return false; Now what is the problem?

8 C++ Review arguments vs parameters argument passing value semantics reference semantics

9 Swapper #include <iostream> using namespace std; void swap(int, int); int main (int argc, char* const argv[]) { int a = 3, b = 5; swap(a, b); cout << a << b << endl; What will happen? return 0; void swap(int x, int y) { int temp = x; x = y; y = temp;

10 Swapper #include <iostream> using namespace std; void swap(int*, int*); int main (int argc, char* const argv[]) { int a = 3, b = 5; swap(&a, &b); cout << a << b << endl; return 0; void swap(int* x, int* y) { int temp = *x; *x = *y; *y = temp;

11 Swapper #include <iostream> using namespace std; void swap(int&, int&); int main (int argc, char* const argv[]) { int a = 3, b = 5; swap(a, b); cout << a << b << endl; return 0; void swap(int& x, int& y) { int temp = x; x = y; y = temp;

12 Exercise void f(int, int&); int main() { int x = 3, y = 5; f(x, y); cout << x << " " << y << endl; // Also try: f(y, x), f(x+y, y), f(x, x + y). return 0; void f(int x, int& y) { x *= 2; y += x;

13 Fibonacci Numbers // Outputs the first 20 fibonacci numbers. // Author: Drue Coles #include <iostream> using namespace std; int main() { const int N = 25; int a[n] = {0, 1; for (int i = 2; i < n; i++) { a[i] = a[i - 1] + a[i - 2]; return 0;

14 Fibonacci Numbers // Outputs the first 20 fibonacci numbers. // Author: Drue Coles #include <iostream> using namespace std; void set_fib_numbers(int[], int n); void print(const int[], int n); int main() { const int N = 25; int a[n]; set_fib_numbers(a, N); print(a, N); return 0;

15 Fibonacci Numbers void set_fib_numbers(int a[], int n) { a[0] = 0; a[1] = 1; for (int i = 2; i < n; i++) { a[i] = a[i - 1] + a[i - 2]; void print(const int a[], int n) { for (int i = 0; i < n - 1; i++) { cout << a[i] << endl;

16 C++ Review implementing classes assert macro destructors const methods prefix vs. postfix increment

17 String Reverse with Stack /* * Prompts user for a string of alphabetic characters * and then prints it backwards. Non-alphabetic chars * are ignored, and each input character is converted * to uppercase. * * Author: Drue Coles */ #include <iostream> #include <cassert> #include <cctype> using namespace std; // A bounded stack of characters. class Stack {... int main() {...

18 String Reverse with Stack // A bounded stack of characters. class Stack { private: char* ptr; int top; int size; public: Stack(int); ~Stack(); void push(char); char pop(); bool isempty() const; bool isfull() const; ;

19 String Reverse with Stack Stack::Stack(int n) { size = n; ptr = new char[size]; top = 0; Stack::~Stack() { delete []ptr; No such thing in Java. Why not? void Stack::push(char c) { assert(!isfull()); ptr[top++] = c;

20 String Reverse with Stack int main() { const int STACK_SIZE = 100; Stack s(stack_size); cout << "Enter a string: "; char c; cin.get(c); while (c!= '\n') { s.push((char) toupper(c)); cin.get(c); cout << endl; while (!s.isempty()) { // print string backwards cout << s.pop(); cout << endl; return 0;

21 C++ Review separate compilation header files implementation files object files

22 Header File // A bounded stack of characters. // Author: Drue Coles class Stack { private: char* ptr; int top; // index into array at next position int size; // maximum size of stack public: // Constructs a stack with a given amount of space. Stack(int); // Releases the dynamically allocated stack space. ~Stack();

23 Implementation File #include <cassert> #include "stack.h" Stack::Stack(int n) { size = n; ptr = new char[size]; top = 0; g++ -c stack.cpp Stack::~Stack() { delete []ptr; void Stack::push(char c) { assert(!isfull()); ptr[top++] = c;

24 Client Program /* * Prompts user for string of alphabetic characters and * then prints it backwards. Non-alphabetic chars are * ignored, and each input character is converted to * uppercase. * * Author: Drue Coles */ #include <iostream> #include <cctype> #include "stack.h" using namespace std; int main() {... g++ main.cpp stack.o

25 C++ Review copy constructor default arguments overloaded assignment operator

26 Header File class Stack { private: char* ptr; int top; int size; public: Stack(int = 10); Stack(Stack&); Stack& operator=(const Stack&); ~Stack(); void push(char); char pop(); bool isempty() const; bool isfull() const; ;

27 Implementation File Stack::Stack(int n) { size = n; ptr = new char[size]; top = 0; Stack::Stack(Stack& s) { ptr = new char[s.size]; for (int i = 0; i < s.size; i++) ptr[i] = s.ptr[i]; size = s.size; top = s.top;

28 Implementation File Stack& Stack::operator=(const Stack& s) { if (this == &s) return *this; delete []ptr; ptr = new char[s.size]; for (int i = 0; i < s.size; i++) ptr[i] = s.ptr[i]; top = s.top; return *this;

29 Client Program int main() { Stack s(10); s.push('a'); s.push('b'); Stack t(s); t.push('c'); t.push('d'); Stack u; u = t; u.push('e'); u.push('f'); Why not demonstrate assignment operator with: Stack u = t; while (!u.isempty()) cout << u.pop() << endl; return 0;

30 C++ Review template functions template classes separate compilation

31 Template Function #include <iostream> int main() { int a = 3, b = 5; double u = 3.7, v = 9.1; swap(a, b); swap(u, v); std::cout << a << " " << b << std::endl; std::cout << u << " " << v << std::endl; return 0;

32 Template Function #include <iostream> template <typename T> void swap(t& x, T& y); int main() { template <typename T> void swap(t& x, T& y) { T temp = x; x = y; y = temp;

33 Template Function int main() { int a, b; double u, v; swap(a, b); swap(u, v); void swap(int& x, int& y) { int temp = x; x = y; y = temp; void swap(double& x, double& y) { double temp = x; x = y; y = temp;

34 Header File template <typename T> class Stack { private: T* ptr; int top; int size; public: Stack(int = 10); Stack(Stack&); Stack& operator=(const Stack&); ~Stack(); void push(t); T pop(); bool isempty() const; bool isfull() const; ;

35 Implementation File #include <cassert> #include "stack.h" template <typename T> Stack<T>::Stack(int n) { size = n; ptr = new T[size]; top = 0; template <typename T> Stack<T>::Stack(Stack<T>& s) { ptr = new T[s.size]; for (int i = 0; i < s.size; i++) ptr[i] = s.ptr[i]; size = s.size; top = s.top;

36 Implementation File template <typename T> Stack<T>& Stack<T>::operator=(const Stack<T>& s) { delete []ptr; ptr = new char[s.size]; for (int i = 0; i < s.size; i++) ptr[i] = s.ptr[i]; top = s.top; return *this; template <typename T> Stack<T>::~Stack() { delete []ptr;

37 Implementation File template <typename T> void Stack<T>::push(T c) { assert(!isfull()); ptr[top++] = c; template <typename T> T Stack<T>::pop() { assert(!isempty()); return ptr[--top]; template <typename T> bool Stack<T>::isEmpty() const { return top == 0;

38 Client Program Stack<int> s; cout << "Pushing: "; while (!s.isfull()) { int k = rand() % 1000; cout << k << " "; s.push(k); cout << "\n\npopping: "; while (!s.isempty()) cout << s.pop() << " "; cout << endl; Must include stack.cpp, not stack.h... Why? Pushing: Popping: Your powers are weak, old man. 2. You weren't on any mercy mission this time. 1. An elegant weapon, for a more civilized age. Stack<const char*> t; t.push("1. An elegant weapon, for a more civilized age."); t.push("2. You weren't on any mercy mission this time."); t.push("3. Your powers are weak, old man."); while (!t.isempty()) cout << t.pop() << endl; return 0;

39 Separate Compilation? stack.h template <typename T> class Stack { void push(t); stack.cpp template <typename T> class Stack { g++ -c stack.cpp stack.o? template <typename T> void Stack<T>::push(T c) { assert(!isfull()); ptr[top++] = c; main.c #include stack.h gcc main.c stack.o int main() { Stack<int> s; s.push(23);

40 C++ Review the Standard Template Library stack and vector iterators stream insertion operator operator overloading friend functions

41 STL Stack stack<int> s; for (int i = 0; i < 10; i++) s.push(i); while (!s.empty()) { cout << s.top() << " "; s.pop();

42 STL Vector vector<int> v(5); v[0] = 27; v.push_back(56); v.resize(10); v[8] = 355; for (int i = 0; i < v.size(); i++) cout << v[i] << " "; cout << endl; vector<int>::iterator iter; for (iter = v.begin(); iter!= v.end(); ++iter) cout << *iter << " ";

43 STL Vector vector<int> v(5); v[0] = 27; v.push_back(56); v.resize(10); v[8] = 355; v.operator[](0) = 27; v.operator[](8) = 355; for (int i = 0; i < v.size(); i++) cout << v[i] << " "; cout << endl; v.operator[](i) vector<int>::iterator iter; for (iter = v.begin(); iter!= v.end(); ++iter) cout << *iter << " ";

44 STL Vector class MyClass { private: int x; public: MyClass(int y) { x = y; MyClass() { x = 0; int main () { vector<myclass> w(5); w[0] = MyClass(17); w[3] = MyClass(23); w.resize(8); vector<myclass>::iterator iter; for (iter = w.begin(); iter!= w.end(); ++iter) cout << *iter << " "; cout << endl; return 0; ; friend ostream& operator<<(ostream& out, MyClass& m) { out << m.x; return out;

45 C++ Review operator overloading friend functions

46 Rational #include "rational.h" int main() { Rational r(3, 8); Enter rational number (num den): 5 12 Sum: 19/24 Product: 5/32 3/8 is smaller than 5/12. int x, y; cout << "Enter rational number (num den): "; cin >> x >> y; Rational s(x, y); cout << "Sum: " << r + s << endl; cout << "Product: " << r * s << endl; if (r < s) cout << r << " is smaller than " << s << ".\n"; else cout << s << " is smaller than " << r << ".\n"; return 0;

47 Header File class Rational { private: int num; int den; void reduce(); // reduces to lowest common terms public: Rational(int=0, int=1); ; // modified assignment operators Rational& operator+=(rational&); Rational& operator-=(rational&); Rational& operator*=(rational&); Rational& operator/=(rational&); // Displays number in standard format (e.g., 2/3, -23/17, 5). friend ostream& operator<<(ostream&, const Rational&); // friend functions for arithmetic operations friend Rational operator+(const Rational&, const Rational&); friend Rational operator-(const Rational&, const Rational&); friend Rational operator*(const Rational&, const Rational&); friend Rational operator/(const Rational&, const Rational&); // friend functions for relational operations friend bool operator==(const Rational&, const Rational&); friend bool operator!=(const Rational&, const Rational&); friend bool operator<(const Rational&, const Rational&); friend bool operator<=(const Rational&, const Rational&); friend bool operator>(const Rational&, const Rational&); friend bool operator>=(const Rational&, const Rational&);

48 Implementation File Rational::Rational(int a, int b) { assert (a >= 0 && b > 0); num = a; den = b; reduce(); Rational& Rational::operator+=(Rational& r) { *this = *this + r; return *this; Rational operator+(const Rational& r, const Rational& s) { Rational sum; sum.num = r.num * s.den + s.num * r.den; sum.den = r.den * s.den; sum.reduce(); return sum;

49 Stream Insertion Operator ostream& operator<<(ostream& out, const Rational& r) { if (r.num == 0) { out << r.den; else if (r.den == 1) { out << r.num; else out << r.num << "/" << r.den; return out;

An Incomplete C++ Primer. University of Wyoming MA 5310

An Incomplete C++ Primer. University of Wyoming MA 5310 An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages

More information

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

CHAPTER 4 ESSENTIAL DATA STRUCTRURES CHAPTER 4 ESSENTIAL DATA STRUCTURES 72 CHAPTER 4 ESSENTIAL DATA STRUCTRURES In every algorithm, there is a need to store data. Ranging from storing a single value in a single variable, to more complex

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 25, 2015 Outline Outline 1 Chapter 12: C++ Templates Outline Chapter 12: C++ Templates 1 Chapter 12: C++ Templates

More information

Cours de C++ Utilisations des conteneurs

Cours de C++ Utilisations des conteneurs Cours de C++ Utilisations des conteneurs Cécile Braunstein cecile.braunstein@lip6.fr 1 / 18 Introduction Containers - Why? Help to solve messy problems Provide useful function and data structure Consistency

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

Comp151. Definitions & Declarations

Comp151. Definitions & Declarations Comp151 Definitions & Declarations Example: Definition /* reverse_printcpp */ #include #include using namespace std; int global_var = 23; // global variable definition void reverse_print(const

More information

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing CpSc212 Goddard Notes Chapter 6 Yet More on Classes We discuss the problems of comparing, copying, passing, outputting, and destructing objects. 6.1 Object Storage, Allocation and Destructors Some objects

More information

Cpt S 223. School of EECS, WSU

Cpt S 223. School of EECS, WSU Abstract Data Types 1 Topics Abstract Data Types (ADTs) Some basic ADTs: Lists Stacks Queues 2 Primitive Data Type vs. Abstract Data Types Primitive DT: ADT: programmer progra ammer Interface (API) e.g.,

More information

Coding conventions and C++-style

Coding conventions and C++-style Chapter 1 Coding conventions and C++-style This document provides an overview of the general coding conventions that are used throughout oomph-lib. Knowledge of these conventions will greatly facilitate

More information

Pointers and Linked Lists

Pointers and Linked Lists 15 Pointers and Linked Lists 15.1 Nodes and Linked Lists 828 Nodes 828 Linked Lists 834 Inserting a Node at the Head of a List 835 Pitfall:Losing Nodes 839 Searching a Linked List 840 Pointers as Iterators

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

CORBA Programming with TAOX11. The C++11 CORBA Implementation

CORBA Programming with TAOX11. The C++11 CORBA Implementation CORBA Programming with TAOX11 The C++11 CORBA Implementation TAOX11: the CORBA Implementation by Remedy IT TAOX11 simplifies development of CORBA based applications IDL to C++11 language mapping is easy

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II C++ intro Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 26, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26,

More information

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1 Stacks (and Queues) 1 Stacks Stack: what is it? ADT Applications Implementation(s) 2 CSCU9A3 1 Stacks and ueues A stack is a very important data structure in computing science. A stack is a seuence of

More information

C++ Overloading, Constructors, Assignment operator

C++ Overloading, Constructors, Assignment operator C++ Overloading, Constructors, Assignment operator 1 Overloading Before looking at the initialization of objects in C++ with constructors, we need to understand what function overloading is In C, two functions

More information

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from

More information

Basics of I/O Streams and File I/O

Basics of I/O Streams and File I/O Basics of This is like a cheat sheet for file I/O in C++. It summarizes the steps you must take to do basic I/O to and from files, with only a tiny bit of explanation. It is not a replacement for reading

More information

C++ Crash Kurs. C++ Object-Oriented Programming

C++ Crash Kurs. C++ Object-Oriented Programming C++ Crash Kurs C++ Object-Oriented Programming Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck http://www.itm.uni-luebeck.de/people/pfisterer C++ classes A class is user-defined type

More information

El Dorado Union High School District Educational Services

El Dorado Union High School District Educational Services El Dorado Union High School District Course of Study Information Page Course Title: ACE Computer Programming II (#495) Rationale: A continuum of courses, including advanced classes in technology is needed.

More information

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1 QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For

More information

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS) KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

More information

vector vec double # in # cl in ude <s ude tdexcept> tdexcept> // std::ou std t_of ::ou _range t_of class class V Vector { ector {

vector vec double # in # cl in ude <s ude tdexcept> tdexcept> // std::ou std t_of ::ou _range t_of class class V Vector { ector { Software Design (C++) 3. Resource management and exception safety (idioms and technicalities) Juha Vihavainen University of Helsinki Preview More on error handling and exceptions checking array indices

More information

C++ Language Tutorial

C++ Language Tutorial cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain

More information

Subject Name: Object Oriented Programming in C++ Subject Code: 2140705

Subject Name: Object Oriented Programming in C++ Subject Code: 2140705 Faculties: L.J. Institute of Engineering & Technology Semester: IV (2016) Subject Name: Object Oriented Programming in C++ Subject Code: 21405 Sr No UNIT - 1 : CONCEPTS OF OOCP Topics -Introduction OOCP,

More information

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson Outline Computer Science 1 Stacks Mike Jacobson Department of Computer Science University of Calgary Lecture #12 1 2 Applications Array-Based Linked List-Based 4 Additional Information Mike Jacobson (University

More information

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics

More information

An API for Reading the MySQL Binary Log

An API for Reading the MySQL Binary Log An API for Reading the MySQL Binary Log Mats Kindahl Lead Software Engineer, MySQL Replication & Utilities Lars Thalmann Development Director, MySQL Replication, Backup & Connectors

More information

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points

More information

Passing 1D arrays to functions.

Passing 1D arrays to functions. Passing 1D arrays to functions. In C++ arrays can only be reference parameters. It is not possible to pass an array by value. Therefore, the ampersand (&) is omitted. What is actually passed to the function,

More information

Object-Oriented Desin and Prorammin C++ Container Classes Outline Introduction Container Class Objectives Class Library Architecture Parameterized Types Preprocessor Macros enclass void Pointer Method

More information

URI and UUID. Identifying things on the Web.

URI and UUID. Identifying things on the Web. URI and UUID Identifying things on the Web. Overview > Uniform Resource Identifiers (URIs) > URIStreamOpener > Universally Unique Identifiers (UUIDs) Uniform Resource Identifiers > Uniform Resource Identifiers

More information

A brief introduction to C++ and Interfacing with Excel

A brief introduction to C++ and Interfacing with Excel A brief introduction to C++ and Interfacing with Excel ANDREW L. HAZEL School of Mathematics, The University of Manchester Oxford Road, Manchester, M13 9PL, UK CONTENTS 1 Contents 1 Introduction 3 1.1

More information

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

C++ Outline. cout << Enter two integers: ; int x, y; cin >> x >> y; cout << The sum is:  << x + y << \n ; C++ Outline Notes taken from: - Drake, Caleb. EECS 370 Course Notes, University of Illinois Chicago, Spring 97. Chapters 9, 10, 11, 13.1 & 13.2 - Horstman, Cay S. Mastering Object-Oriented Design in C++.

More information

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure Short Notes on Dynamic Memory Allocation, Pointer and Data Structure 1 Dynamic Memory Allocation in C/C++ Motivation /* a[100] vs. *b or *c */ Func(int array_size) double k, a[100], *b, *c; b = (double

More information

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is preceded by an equal sign d. its name has undereline 2. Associations

More information

Curriculum Map. Discipline: Computer Science Course: C++

Curriculum Map. Discipline: Computer Science Course: C++ Curriculum Map Discipline: Computer Science Course: C++ August/September: How can computer programs make problem solving easier and more efficient? In what order does a computer execute the lines of code

More information

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) { Operators C and C++ 6. Operators Inheritance Virtual Alastair R. Beresford University of Cambridge Lent Term 2008 C++ allows the programmer to overload the built-in operators For example, a new test for

More information

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever! ECE 551 C++ Programming, Data structures, and Algorithms Abstract Data Type: Stack Last In First Out (LIFO) 1 2 2 1 4 3 1 3 4 Stacks in Programming Worst line ever! 5 3 1 5 Stacks are not useful for waiting

More information

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Data Structures Using C++ 2E. Chapter 5 Linked Lists Data Structures Using C++ 2E Chapter 5 Linked Lists Doubly Linked Lists Traversed in either direction Typical operations Initialize the list Destroy the list Determine if list empty Search list for a given

More information

An Overview of the C++ Programming Language

An Overview of the C++ Programming Language From The Handbook of Object Technology (Editor: Saba Zamir). CRC Press LLC, Boca Raton. 1999. ISBN 0-8493-3135-8. An Overview of the C++ Programming Language Bjarne Stroustrup AT&T Laboratories Florham

More information

Tutorial on C Language Programming

Tutorial on C Language Programming Tutorial on C Language Programming Teodor Rus rus@cs.uiowa.edu The University of Iowa, Department of Computer Science Introduction to System Software p.1/64 Tutorial on C programming C program structure:

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

Answers to Review Questions Chapter 7

Answers to Review Questions Chapter 7 Answers to Review Questions Chapter 7 1. The size declarator is used in a definition of an array to indicate the number of elements the array will have. A subscript is used to access a specific element

More information

Course notes Standard C++ programming

Course notes Standard C++ programming Department of Cybernetics The University of Reading SE2B2 Further Computer Systems Course notes Standard C++ programming by Dr Virginie F. Ruiz November, 03 CREATING AND USING A COPY CONSTRUCTOR... 27

More information

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference? Functions in C++ Let s take a look at an example declaration: Lecture 2 long factorial(int n) Functions The declaration above has the following meaning: The return type is long That means the function

More information

! " # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1

!  # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1 !" #$%&%'())*%%+,-..*/*%%+- 0 )12 1 *!" 34 5 6 * #& ) 7 8 5)# 97&)8 5)# 9 : & ; < 5 11 8 1 5)=19 7 19 : 0 5)=1 ) & & >) ) >) 1? 5)= 19 7 19 : # )! #"&@)1 # )? 1 1#& 5)=19719:# 1 5)=9 7 9 : 11 0 #) 5 A

More information

C++FA 5.1 PRACTICE MID-TERM EXAM

C++FA 5.1 PRACTICE MID-TERM EXAM C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer

More information

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER Course Outline (2015) Basic Programming With Procedural & Object Oriented Concepts (C, C++) Training Office# Road: 11, House: 1 A, Nikunja 2, Khilkhet,

More information

Variable Base Interface

Variable Base Interface Chapter 6 Variable Base Interface 6.1 Introduction Finite element codes has been changed a lot during the evolution of the Finite Element Method, In its early times, finite element applications were developed

More information

Syllabus OBJECT ORIENTED PROGRAMMING C++

Syllabus OBJECT ORIENTED PROGRAMMING C++ 1 Syllabus OBJECT ORIENTED PROGRAMMING C++ 1. Introduction : What is object oriented programming? Why do we need objectoriented. Programming characteristics of object-oriented languages. C and C++. 2.

More information

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction Class Overview CSE 326: Data Structures Introduction Introduction to many of the basic data structures used in computer software Understand the data structures Analyze the algorithms that use them Know

More information

10CS35: Data Structures Using C

10CS35: Data Structures Using C CS35: Data Structures Using C QUESTION BANK REVIEW OF STRUCTURES AND POINTERS, INTRODUCTION TO SPECIAL FEATURES OF C OBJECTIVE: Learn : Usage of structures, unions - a conventional tool for handling a

More information

The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002. True or False (2 points each)

The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002. True or False (2 points each) True or False (2 points each) The University of Alabama in Huntsville Electrical and Computer Engineering CPE 112 01 Test #4 November 20, 2002 1. Using global variables is better style than using local

More information

Ch 7-1. Object-Oriented Programming and Classes

Ch 7-1. Object-Oriented Programming and Classes 2014-1 Ch 7-1. Object-Oriented Programming and Classes May 10, 2014 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497;

More information

Logging. Working with the POCO logging framework.

Logging. Working with the POCO logging framework. Logging Working with the POCO logging framework. Overview > Messages, Loggers and Channels > Formatting > Performance Considerations Logging Architecture Message Logger Channel Log File Logging Architecture

More information

Bevezetés a C++ Standard Template Library-be

Bevezetés a C++ Standard Template Library-be C++, 1/ 33 Bevezetés a C++ Standard Template Library-be Pataki Norbert 2013. május 17. C++, 2/ 33 STL STL vs. STL implementáció Konténerek Funktorok Algoritmusok Iterátorok STL Konténerek C++, 3/ 33 Szekvenciális:

More information

Common Data Structures

Common Data Structures Data Structures 1 Common Data Structures Arrays (single and multiple dimensional) Linked Lists Stacks Queues Trees Graphs You should already be familiar with arrays, so they will not be discussed. Trees

More information

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c Lecture 3 Data structures arrays structs C strings: array of chars Arrays as parameters to functions Multiple subscripted arrays Structs as parameters to functions Default arguments Inline functions Redirection

More information

Grundlagen der Betriebssystemprogrammierung

Grundlagen der Betriebssystemprogrammierung Grundlagen der Betriebssystemprogrammierung Präsentation A3, A4, A5, A6 21. März 2013 IAIK Grundlagen der Betriebssystemprogrammierung 1 / 73 1 A3 - Function Pointers 2 A4 - C++: The good, the bad and

More information

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum James P. Kelsh James.Kelsh@cmich.edu Roger Y. Lee lee@cps.cmich.edu Department of Computer Science Central

More information

C++ Programming Language

C++ Programming Language C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

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 #12 John Ridgway March 10, 2015 1 Implementations of Queues 1.1 Linked Queues A Linked Queue Implementing a queue with a linked list is

More information

Object Oriented Programming With C++(10CS36) Question Bank. UNIT 1: Introduction to C++

Object Oriented Programming With C++(10CS36) Question Bank. UNIT 1: Introduction to C++ Question Bank UNIT 1: Introduction to C++ 1. What is Procedure-oriented Programming System? Dec 2005 2. What is Object-oriented Programming System? June 2006 3. Explain the console I/O functions supported

More information

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang 6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang Today s topics Why objects? Object-oriented programming (OOP) in C++ classes fields & methods objects representation

More information

Illustration 1: Diagram of program function and data flow

Illustration 1: Diagram of program function and data flow The contract called for creation of a random access database of plumbing shops within the near perimeter of FIU Engineering school. The database features a rating number from 1-10 to offer a guideline

More information

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= We already know that the compiler will supply a default (zero-argument) constructor if the programmer does not specify one.

More information

16 Collection Classes

16 Collection Classes 16 Collection Classes Collections are a key feature of the ROOT system. Many, if not most, of the applications you write will use collections. If you have used parameterized C++ collections or polymorphic

More information

N3458: Simple Database Integration in C++11

N3458: Simple Database Integration in C++11 N3458: Simple Database Integration in C++11 Thomas Neumann Technische Univeristät München neumann@in.tum.de 2012-10-22 Many applications make use of relational database to store and query their data. However,

More information

Abstract Data Types. Chapter 2

Abstract Data Types. Chapter 2 Chapter 2 Abstract Data Types The second idea at the core of computer science, along with algorithms, is data. In a modern computer, data consists fundamentally of binary bits, but meaningful data is organized

More information

Class 16: Function Parameters and Polymorphism

Class 16: Function Parameters and Polymorphism Class 16: Function Parameters and Polymorphism SI 413 - Programming Languages and Implementation Dr. Daniel S. Roche United States Naval Academy Fall 2011 Roche (USNA) SI413 - Class 16 Fall 2011 1 / 15

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

Fondamenti di C++ - Cay Horstmann 1

Fondamenti di C++ - Cay Horstmann 1 Fondamenti di C++ - Cay Horstmann 1 Review Exercises R10.1 Line 2: Can't assign int to int* Line 4: Can't assign Employee* to Employee Line 6: Can't apply -> to object Line 7: Can't delete object Line

More information

7.1 Our Current Model

7.1 Our Current Model Chapter 7 The Stack In this chapter we examine what is arguably the most important abstract data type in computer science, the stack. We will see that the stack ADT and its implementation are very simple.

More information

Binary storage of graphs and related data

Binary storage of graphs and related data EÖTVÖS LORÁND UNIVERSITY Faculty of Informatics Department of Algorithms and their Applications Binary storage of graphs and related data BSc thesis Author: Frantisek Csajka full-time student Informatics

More information

1 Abstract Data Types Information Hiding

1 Abstract Data Types Information Hiding 1 1 Abstract Data Types Information Hiding 1.1 Data Types Data types are an integral part of every programming language. ANSI-C has int, double and char to name just a few. Programmers are rarely content

More information

Why you shouldn't use set (and what you should use instead) Matt Austern

Why you shouldn't use set (and what you should use instead) Matt Austern Why you shouldn't use set (and what you should use instead) Matt Austern Everything in the standard C++ library is there for a reason, but it isn't always obvious what that reason is. The standard isn't

More information

Member Functions of the istream Class

Member Functions of the istream Class Member Functions of the istream Class The extraction operator is of limited use because it always uses whitespace to delimit its reads of the input stream. It cannot be used to read those whitespace characters,

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore

More information

7.7 Case Study: Calculating Depreciation

7.7 Case Study: Calculating Depreciation 7.7 Case Study: Calculating Depreciation 1 7.7 Case Study: Calculating Depreciation PROBLEM Depreciation is a decrease in the value over time of some asset due to wear and tear, decay, declining price,

More information

Simple C++ (Vol.1) Computer Science. simpler code through better C++11 usage. ESE Kongress 2012. slides: http://wiki.hsr.

Simple C++ (Vol.1) Computer Science. simpler code through better C++11 usage. ESE Kongress 2012. slides: http://wiki.hsr. Computer Science Simple C++ (Vol.1) simpler code through better C++11 usage ESE Kongress 2012 slides: http://wiki.hsr.ch/petersommerlad/ Prof. Peter Sommerlad Director IFS Institute for Software Sindelfingen

More information

BCS2B02: OOP Concepts and Data Structures Using C++

BCS2B02: OOP Concepts and Data Structures Using C++ SECOND SEMESTER BCS2B02: OOP Concepts and Data Structures Using C++ Course Number: 10 Contact Hours per Week: 4 (2T + 2P) Number of Credits: 2 Number of Contact Hours: 30 Hrs. Course Evaluation: Internal

More information

DATA STRUCTURE - STACK

DATA STRUCTURE - STACK DATA STRUCTURE - STACK http://www.tutorialspoint.com/data_structures_algorithms/stack_algorithm.htm Copyright tutorialspoint.com A stack is an abstract data type ADT, commonly used in most programming

More information

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following: In creating objects of the type, we have used statements similar to the following: f = new (); The parentheses in the expression () makes it look like a method, yet we never created such a method in our

More information

Development of a Campus Routing System Praxis der Software-Entwicklung

Development of a Campus Routing System Praxis der Software-Entwicklung Development of a Campus Routing System Praxis der Software-Entwicklung Introduction April 24, 2013 Thomas Bläsius, Tamara Mchedlidze INSTITUTE OF THEORETICAL INFORMATICS PROF. DR. DOROTHEA WAGNER KIT University

More information

Chao Chen 1 Michael Lang 2 Yong Chen 1. IEEE BigData, 2013. Department of Computer Science Texas Tech University

Chao Chen 1 Michael Lang 2 Yong Chen 1. IEEE BigData, 2013. Department of Computer Science Texas Tech University Chao Chen 1 Michael Lang 2 1 1 Data-Intensive Scalable Laboratory Department of Computer Science Texas Tech University 2 Los Alamos National Laboratory IEEE BigData, 2013 Outline 1 2 3 4 Outline 1 2 3

More information

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams: istream

More information

C++ for Safety-Critical Systems. DI Günter Obiltschnig Applied Informatics Software Engineering GmbH guenter.obiltschnig@appinf.

C++ for Safety-Critical Systems. DI Günter Obiltschnig Applied Informatics Software Engineering GmbH guenter.obiltschnig@appinf. C++ for Safety-Critical Systems DI Günter Obiltschnig Applied Informatics Software Engineering GmbH guenter.obiltschnig@appinf.com A life-critical system or safety-critical system is a system whose failure

More information

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1 Definition Course: Programming II - Abstract Data Types The ADT Stack The ADT Stack is a linear sequence of an arbitrary number of items, together with access procedures. The access procedures permit insertions

More information

PES Institute of Technology-BSC QUESTION BANK

PES Institute of Technology-BSC QUESTION BANK PES Institute of Technology-BSC Faculty: Mrs. R.Bharathi CS35: Data Structures Using C QUESTION BANK UNIT I -BASIC CONCEPTS 1. What is an ADT? Briefly explain the categories that classify the functions

More information

Parallel Programming with MPI on the Odyssey Cluster

Parallel Programming with MPI on the Odyssey Cluster Parallel Programming with MPI on the Odyssey Cluster Plamen Krastev Office: Oxford 38, Room 204 Email: plamenkrastev@fas.harvard.edu FAS Research Computing Harvard University Objectives: To introduce you

More information