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:

Similar documents
Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

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

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

Introduction to C ++

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

Lab Instructor : Jean Lai

CSCE 206: Structured Programming in C++

Introduction to Programming Using Java (98-388)

a data type is Types

Absolute C++ Walter Savitch

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

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

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

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Note 11/13/2014. They are like those i s, j s, and temp s that appear and disappear when the function starts and finishes...

A SHORT COURSE ON C++

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

Understanding main() function Input/Output Streams

Programming Language. Functions. Eng. Anis Nazer First Semester

Scientific Computing

Computer Science II Lecture 1 Introduction and Background

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

CSCE 110 PROGRAMMING FUNDAMENTALS

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

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

G52CPP C++ Programming Lecture 17

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

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

CIS 190: C/C++ Programming. Classes in C++

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

Bruce Merry. IOI Training Dec 2013

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

CSI33 Data Structures

C++ Quick Guide. Advertisements

Chapter 14 Sequential Access Files

Chapter 3 - Functions

Short Notes of CS201

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Introduction to C++ General Rules, Conventions and Styles CS 16: Solving Problems with Computers I Lecture #2

CS201 - Introduction to Programming Glossary By

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Introduction to C++ Systems Programming

Types, Values, Variables & Assignment. EECS 211 Winter 2018

Variables. Data Types.

CS3157: Advanced Programming. Outline

Summary of basic C++-commands

Chapter 2. Procedural Programming

CS2141 Software Development using C/C++ C++ Basics

Computer Programming : C++

COMP322 - Introduction to C++ Lecture 01 - Introduction

CS2255 HOMEWORK #1 Fall 2012

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

Motivation was to facilitate development of systems software, especially OS development.

CPSC 427: Object-Oriented Programming

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

AN OVERVIEW OF C++ 1

CSCI 1061U Programming Workshop 2. C++ Basics

PIC 10A Objects/Classes

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

C++ basics Getting started with, and Data Types.

COP 3014: Fall Final Study Guide. December 5, You will have an opportunity to earn 15 extra credit points.

Lecture 2, September 4

Chapter 2 C++ Fundamentals

CS 231 Data Structures and Algorithms, Fall 2016

Unit 7. 'while' Loops

Introduction to Programming using C++

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

C++ Support Classes (Data and Variables)

Intro. Scheme Basics. scm> 5 5. scm>

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

CSCI-1200 Computer Science II Fall 2008 Lecture 15 Associative Containers (Maps), Part 2

UNIT- 3 Introduction to C++

Outline. 1 About the course

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

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

FORM 2 (Please put your name and form # on the scantron!!!!)

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

11. Arrays. For example, an array containing 5 integer values of type int called foo could be represented as:

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

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

PIC 10A. Final Review

Motivation was to facilitate development of systems software, especially OS development.

Polymorphism Part 1 1

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Starting to Program in C++ (Basics & I/O)

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

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

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

Control Structures. A program can proceed: Sequentially Selectively (branch) - making a choice Repetitively (iteratively) - looping

Fundamentals of Programming CS-110. Lecture 2

EECS402 Lecture 24. Something New (Sort Of) Intro To Function Pointers

Superior University. Department of Electrical Engineering CS-115. Computing Fundamentals. Experiment No.7. User Defined Functions II

Cpt S 122 Data Structures. Introduction to C++ Part II

Fast Introduction to Object Oriented Programming and C++

Exam 2. CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson. Question Points Score Total: 80

Function Overloading

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Transcription:

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 Vectors Strings You remember all of this, right? 2 Hello, Let s Review Here s a simple C++ program: #include <iostream> using namespace std; int () { string hello = "Hello, world!"; cout << hello << endl; 3 A function, specifically the required function Return type Hello, Let s Review #include <iostream> using namespace std; Function name (Empty) parameter list Assignment operator int () { Variable Literal string hello = "Hello, world!"; cout << hello << endl; Type Return Operator value This tells the compiler that it should include symbols and types from the standard library iostream. This is boilerplate that lets you use standard library symbols without extra ugly syntax. Don t worry about it for now, just put it in whenever you #include something. 4 How to Review Reing slides: Some new material e.g., function overloading Mostly review Your responsibility: Go through all the slides that follow Note any questions on old or new concepts Try to learn concept from textbook Ask instructor if you still have questions! Starts with fun! FUNDAMENTALS 5 6 1

Declaration: int x; Use in expressions: x + 10 Set via assignment operator: x = 4; Declare and initialize: int x = 42; Variables Types Basic types Integer types: int : 42, -99, 103482039 unsigned: like int, but no negative values char : 'k' Floating point types: double : 3.14159, 4.5e3, -0.0001 Boolean type: bool : true, false Pointers Arrays Class/struct types 7 8 Expressions & Operators Working definition: anything with a value is an expression: Variables x Indexed array variables arr[10] Literals 42 "Hello" True Function calls returning a value sqrt(17) Arithmetic/logical expressions using operators: 4 + 7 / 3.0 Mixed type expressions allowed due to numeric type conversions (x * sqrt(2) + 1) % y count == 0 a b &&!c Which operators act first? Use parentheses or know precedence rules. Loops What if we want to print Hello, world! three times? Initial value for i for (int i = 1; i <= 3; i++) { cout << i << " Hello, world!" << endl; Output: 1 Hello, world! 2 Hello, world! 3 Hello, world! Loop condition Loop update 9 10 int i = 3; Another Loop while (i > 0) { cout << i << " Hello, world!" << endl; i--; Output: 3 Hello, world! 2 Hello, world! 1 Hello, world! Also should know use of: break continue Conditionals if (true-false-expression) { true-block else { false-block 11 12 2

Hello, if? Arrays Let s modify Hello to respond to an input: char answer; cout << "Say (H)ello or (G)oodbye?" << endl; cin >> answer; if (answer == 'H') { cout << "Hello, world!" << endl; else { cout << "Goodbye, world!" << endl; What happens if the user enters h instead of H? int numbers[3]; numbers[1] = 14; numbers[2] = -3; numbers[3] = 7093; Oops! What s wrong here? 13 14 Arrays Loops on Arrays int numbers[3]; numbers[0] = 14; numbers[1] = -3; numbers[2] = 7093; Let s print out the numbers in the array. What about in reverse order? int numbers[] = {14, -3, 7093; for (int i = 0; i < 3; i++) { cout << numbers[i] << endl; for (int i = 2; i >= 0; i--) { cout << numbers[i] << endl; Array initialization only when array is declared! 15 16 Functions We ve seen one function: int () { Even more fun! FUNCTIONS Here s another: int print_it(string msg) { cout << msg << endl; return msg.length(); A member function or method of the string class. 17 18 3

A silly program. #include <iostream> #include <string> #include <cmath> using namespace std; int print_it(string msg) { cout << msg << endl; return msg.length(); int () { int n; double nroot; Hello Functions! Note, we have to declare a function before we use it. (Could also use a prototype.) n = print_it("hello, world!"); nroot = sqrt(n); cout << "The square root of the number of characters printed is "; cout << nroot << endl; Recursion Functions can call themselves. void print_n_times(string s, int n) { if (n == 0) return; cout << s << endl; print_n_times(s, n 1); Base case. Very important! Recursive call. Note that the parameter n moves towards the base case condition. 19 20 Function Overloading C++ allows multiple functions of the same name: void print_it(int x) { cout << "an integer: " << x << endl; void print_it(string s) { cout << "a string: " << s << endl; What to call based on the parameter list So parameter lists must be different for each overload Can get confusing when mixed with type promotion: print_it(3.1415); // what does this do? Default Parameters Alternative when one overload is just a specialized version of another: // prints n times, or just once if n omitted void print_n_times(string s, int n = 1) { for (int j = 0; j < n; j++) { cout << s << endl; With the above, we can do: print_n_times("hello", 10); or print_n_times("goodbye"); // prints Hello 10 times // prints Goodbye once Rules: Cannot omit earlier parameters, supply later ones Cannot overload if parameter list is interpretable as call to function with default params omitted, e.g., cannot also define void print_n_times(string s) { 21 22 Parameter by Value or Reference Passing Parameters by Reference What does this program print? void set_to_zero(int x) { x = 0; int () { int n = 42; set_to_zero(n); cout << n << endl; Answer: 42 Parameter passed by value void set_to_zero(int &x) { x = 0; int () { int n = 42; set_to_zero(n); cout << n << endl; This prints: 0 4

The Holds stack frames aka activation records Each function call results in a new stack frame Each stack frame contains memory for: Local variables declared in the function Arguments passed into function Return address for function When the function is exited, all of this memory is returned to the stack automatically. Function Call void (int x, int y) { quotient(x, y); quotient(y, x); int () { int a, b; cout << "Please enter 2 non-zero integers: "; cin >> a >> b; (a, b); At start of () After getting input: One stack frame int a =? int b =? Top of Top of int () { int a, b; cout << "Please enter 2 non-zero integers: "; cin >> a >> b; (a, b); By custom, the function call stack is visualized as growing down. int () { int a, b; cout << "Please enter 2 non-zero integers: "; cin >> a >> b; (a, b); At beginning of call to : void (int x, int y) { quotient(x, y); quotient(y, x); Top of At beginning of first call to quotient: quotient double num = 7 double den = 2 double q =? Top of 5

At end of call to quotient: quotient double num = 7 double den = 2 double q = 3.5 After return from call to quotient: void (int x, int y) { quotient(x, y); quotient(y, x); Top of Top of At beginning of second call to quotient: At end of second call to quotient: > 2/7 is 0.285714 quotient double num = 2 double den = 7 double q =? quotient double num = 2 double den = 7 double q = 0.285714 Top of Top of After return from second call to quotient: After call to : > 2/7 is 0.285714 > 2/7 is 0.285714 Top of Top of void (int x, int y) { quotient(x, y); quotient(y, x); 6

Objects C++ is an object-oriented (OO) language. What s an object? CLASSES AND OBJECTS A working definition: An object is a package of data with associated behavior. More specifically, we say that an object has properties (fields, attributes, data, state), and that it has associated methods (functions). 37 38 Classes Objects also have type. Objects of the same type: Have a common set of properties and methods Used in a similar manner to primitive types. Types are (usually) modeled by classes. Classes formally define the properties and methods. Essentially, defining classes is a way to add new types to C++. (Classes do some other neat things, too, but we ll get to that later.) Classes in C++ Classes are created via a class declaration: visibility modifier class student { public: string name; string year; double gpa; bool is_hungry; ; class name student(); void eat(); void sleep(); void program(int); member variable declarations (properties) (C++98 didn t allow initializers here, but C++11 does.) A constructor function. member function declarations (methods) Don t forget this semi-colon! Defining Member Functions The declaration only gave the member function signatures (prototypes); we still have to write the functions themselves: Etc. void student::eat() { is_hungry = false; void student::program(int assignment) { if (grade(this, assignment) == 'A') gpa++; this is a special keyword that references the object itself. More on this later. Scope resolution operator defines what class the method belongs to. Using Objects in C++ Objects can be created just like chars, ints, etc.: student s; Properties are referenced by the. operator: s.name = "April"; s.gpa = 4.0; double d = s.gpa; Methods are invoked on objects also using. : s.sleep(); 7

Some Notes on Visibility Many philosophies around visibility All data should be private Partly a matter of style Rule of thumb: If it is specific to the implementation, it is private Else, it is public Not all OO languages have visibility modifiers. (But they all have commenting systems!) Input/Output STREAMS 44 Streams Console I/O: #include <iostream> cin >> some_var; cout << expression << endl; string s; getline(cin, s); // must #include <string> File I/O: #include <fstream> ifstream fin("words.txt"); fin >> some_var; getline(fin, s); ofstream fout("output.txt"); fout << expression << endl; VECTORS We ll also learn about stringstream objects (later). 45 46 Arrays and Vectors Arrays: int foo[10]; for (int j = 0; j < 10; j++) foo[j] = j; Vectors: #include <vector> Declares that this vector will hold int values. Gives an initial size to the Vector. vector<int> foo(10); for (int j = 0; j < 10; j++) foo[j] = j; // foo.at(j) = j Do More with Vectors E.g. you can append to a vector it automatically resizes: vector<int> foo; for (int j = 0; j < 10; j++) { foo.push_back(j); foo contains: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Initially size 0 without optional argument. And so much more: see Help page of course website for C++ documentation websites. 47 48 8

Something New-ish C++ 11 added a new type of for loop: Note vector initializer list can be used almost like a literal in certain contexts. vector<int> numbers = {14, -3, 7093; for (int x: numbers) { cout << x << endl; This denotes that x is a variable of type int which will take on each value in numbers in turn. STRINGS 49 50 About Strings More About Strings In C/C++, the literal "Hello" is called a string. It is of type char[] (a char array). Confusingly, C++ defines a new type, string. A string is mostly interchangeable with a string (which in C++ is called a C-string ). But, you can do more with string objects: #include <string> string foo = "Hello"; // note assignment of string to string string bar = "World"; // actually implicit constructor call string hello = foo + ", " + bar + "!"; if (foo == bar) { // test for equality works with string Know/learn the string interface! See Help page of course website for C++ documentation websites Some string methods you should know: length operator[] size operator+ find operator+= substr relational operators 51 52 Up Next Please continue to review chapters 1 10 in your textbook Friday, January 12 Lab 1 - Compile APT 1 assigned Monday, January 15: MLK, Jr. Day NO CLASS Wednesday, January 17 Abstraction Lab 1 due 53 9