Unit 14. Passing Arrays & C++ Strings

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

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

pointers + memory double x; string a; int x; main overhead int y; main overhead

Lab Instructor : Jean Lai

Functions Overview. Functions (aka procedures, subroutines, or methods) are the unit of code decomposition and abstraction

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

What is recursion? Recursion. How can a function call itself? Recursive message() modified. contains a reference to itself. Week 7. Gaddis:

CS 103 Lab 6 - Party Like A Char Star

Ch 6. Functions. Example: function calls function

CMPS 221 Sample Final

Discussion 1H Notes (Week 4, April 22) TA: Brian Choi Section Webpage:

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 9. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

Functions, Arrays & Structs

EE 355 Lab 4 - Party Like A Char Star

Programming in C++: Assignment Week 1

Engineering Problem Solving with C++, Etter

CSE 303: Concepts and Tools for Software Development

Scientific Computing

Exercise 1.1 Hello world

CMSC 202 Midterm Exam 1 Fall 2015

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself.

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

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

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

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

Homework Assignment #2 (revised)

EE 109 Lab 8a Conversion Experience

CS 103 Lab - Party Like A Char Star

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

A SHORT COURSE ON C++

C++ For Science and Engineering Lecture 12

Lecture 12. We have already used strings. Strings. Hello Class is a string.

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

Definition Matching (10 Points)

Agenda / Learning Objectives: 1. Map out a plan to study for mid-term Review the C++ operators up to logical operators. 3. Read about the tips

Overloading Functions & Command Line Use in C++ CS 16: Solving Problems with Computers I Lecture #6

W3101: Programming Languages C++ Ramana Isukapalli

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

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.

Name. CPTR246 Spring '17 (100 total points) Exam 2

what are strings today: strings strings: output strings: declaring and initializing what are strings and why to use them reading: textbook chapter 8

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

Name SECTION: 12:45 2:20. True or False (12 Points)

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 (!

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

CS106X Handout 04 Autumn 2009 September 25 th, 2009 C++ Strings

Use the dot operator to access a member of a specific object.

Objectives. In this chapter, you will:

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

String Objects: The string class library

CS31 Discussion 1E. Jie(Jay) Wang Week5 Oct.27

CSCI 104 Memory Allocation. Mark Redekopp David Kempe

What is recursion? Recursion. Recursive message() modified. How can a function call itself? contains a reference to itself. Week 10. Gaddis:

Getting started with C++ (Part 2)

EECS402 Lecture 02. Functions. Function Prototype

CS242 COMPUTER PROGRAMMING

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

The string Class. Lecture 21 Sections 2.9, 3.9, Robb T. Koether. Wed, Oct 17, Hampden-Sydney College

More Examples Using Functions and Command-Line Arguments in C++ CS 16: Solving Problems with Computers I Lecture #6

CS2255 HOMEWORK #1 Fall 2012

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:

Lesson 2 Variables and I/O

CS103L SPRING 2018 UNIT 7: FILE I/O

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

1 Unit 8 'for' Loops

Review of Important Topics in CS1600. Functions Arrays C-strings

In this chapter, you will learn about: An Array Type for Strings. The Standard string Class. Vectors. Introduction Computer Science 1 CS 23021

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

CS 103 Unit 11. Linked Lists. Mark Redekopp

Exercise: Inventing Language

19.1 The Standard Template Library

STRUCTURED DATA TYPE ARRAYS IN C++ ONE-DIMENSIONAL ARRAY TWO-DIMENSIONAL ARRAY

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis

Functions, Arrays & Structs

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

Computer Programming

Chapter 1 INTRODUCTION

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

The University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters.

Introduction to C++ Introduction to C++ 1

C++ Programming Lecture 2 Software Engineering Group

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

CPSC 427: Object-Oriented Programming

LAB: INTRODUCTION TO FUNCTIONS IN C++

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

Chapter 2: Basic Elements of C++

BITG 1113: Array (Part 2) LECTURE 9

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:

Separate Compilation Model

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Object Reference and Memory Allocation. Questions:

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

C/C++ Functions. Mark Redekopp

CS31 Discussion. Jie(Jay) Wang Week6 Nov.4

Chapter 7: User-Defined Simple Data Types, Namespaces, and the string Type

Chapter 5. Section 5.4 The Common String Library Functions. CS 50 Hathairat Rattanasook

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself. Gaddis:

Transcription:

1 Unit 14 Passing Arrays & C++ Strings

PASSING ARRAYS 2

3 Passing Arrays As Arguments Can we pass an array to another function? YES!! Syntax: Step 1: In the prototype/signature: Put empty square brackets after the parameter name if it is an array (e.g. int data[]) Step 2: When you call the function, just provide the name of the array // Function that takes an array int sum(int data[], int size); 1 int sum(int data[], int size) int total = 0; for(int i=0; i < size; i++) total += data[i]; return total; int vals[100]; /* some code to initialize vals */ 2 int mysum = sum(vals, 100); cout << mysum << endl; // prints sum of all numbers return 0;

4 Pass-by-Value & Pass-by-Reference What are the pros and cons of emailing a document by: Attaching it to the email Sending a link (URL) to the document on some cloud service (etc. Google Docs) Pass-by-value is like emailing an attachment A copy is made and sent Pass-by-reference means emailing a link to the original No copy is made and any modifications by the other party are seen by the originator

5 Arrays And Pass-by-Reference Single (scalar) variables are passed-by-value in C/C++ Copies are passed Arrays are passed-byreference Links are passed This means any change to the array by the function is visible upon return to the caller void dec(int); int y = 3; dec(y); cout << y << endl; return 0; void dec(int y) y--; Single variables (aka scalars) are passed-by-value but arrays are passed-by-reference void init(int x[], int size); int data[10]; init(data, 10); cout << data[9] << endl; // prints 0 return 0; void init(int x[], int size) // x is really a link to data for(int i=0; i < size; i++) x[i] = 0; // changing data[i]

6 But Why? If we used pass-by-value then we'd have to make a copy of a potentially HUGE amount of data (what if the array had a million elements) To avoid copying vast amounts of data, we pass a link // Function that takes an array int sum(int data[], int size); int sum(int data[], int size) int total = 0; for(int i=0; i < size; i++) total += data[i]; return total; 520 [0] vals 916 [99]?? main() data 520 [0] 916 [99]?? int vals[100]; /* some code to initialize vals */ int mysum = sum(vals, 100); cout << mysum << endl; // prints sum of all numbers return 0; sum() return val

7 So What Is Actually Passed? The "link" that is passed is just the starting address (e.g. 520) of the array in memory The called function can now use 520 to access the original array (read it or write new values to it) 520 [0] vals 916 [99]?? main() data 520 // Function that takes an array int sum(int data[], int size); int sum(int data[], int size) int total = 0; for(int i=0; i < size; i++) total += data[i]; return total; int vals[100]; /* some code to initialize vals */ int mysum = sum(vals, 100); cout << mysum << endl; // prints sum of all numbers return 0; sum() return val

8 Analogy The first house on the 3600 block of Catalina Ave. has the address 3600. How many houses are on that block? There is no way to know!! We would have to count that separately.

9 Arrays in C/C++ vs. Other Languages Notice that if sum() only has the start address it would not know how big the array is Unlike Java or other languages where you can call some function to give the size of an array, C/C++ require you to track the size yourself in a separate variable and pass it as a secondary argument 520 [0] vals 916 [99]?? main() 100 520 data 100 size // Function that takes an array int sum(int data[], int size); int sum(int data[], int size) int total = 0; for(int i=0; i < size; i++) total += data[i]; return total; int vals[100]; /* some code to initialize vals */ int mysum = sum(vals, 100); cout << mysum << endl; // prints sum of all numbers return 0; sum() return val

10 Summary Syntax: In the prototype/signature: Put empty square brackets after the parameter name if it is an array (e.g. void f1(int data[]) ) When you call the function, just provide the name of the array (e.g. f1(data); ) Functions only know what you pass them You must pass the size of the array as an additional parameter in addition to the link to the array Arrays are passed-by-reference meaning no copy is made and changes by a function are actually being made to the original The C++ std:: library provides some alternatives to "plain-old arrays", but you will learn about these in CS 103/104

STRINGS 11

12 Character Arrays Recall that in C/C++ string constants (the text in between " ") are just character arrays Each character consumes 1 element in the array Ends with the null character (e.g. 0 decimal or '\0' ASCII) This approach of using an array of char's to store a string is referred to as a C-String char str1[7] = "CS 102" /* Initializes the array to "CS 102"*/ str1[5] = '3'; // now "CS 103" cout << str1 << endl; // prints "CS 103" cin >> str1; // get a new string from // the user (suppose user // types "hello" cout << str1; Program Output: CS 103 hello Addr: Index: 520 [0] 521 [1] 522 [2] 523 [3] 524 [4] 525 [5] 526 [6] str1: 'C' 'S' ' ' '1' '0' '2' '\0' Computer Memory

13 C++ Strings In C++, the library adds a new object type named string and provides an easier alternative to working with plain-old character arrays Do's and Don'ts Do #include <string> Don't need to declare the size (i.e. [7]), just assign Do still use it like an array by using [index] to get individual characters Do still use cin/cout with strings Don't worry about how many characters the user types when inputting to a C++ string #include <iostream> #include <string> using namespace std; char str1[7] = "CS 102"; /* Initializes the array to "CS 102"*/ string str2 = "CS 102"; /* Initializes str2 to "CS 102"*/ str1[5] = '3'; // now str1 = "CS 103" str2[5] = '4'; // now str2 = "CS 104" cout << str1 << endl; // prints "CS 103" cout << str2 << endl; // prints "CS 104" cin >> str1; // If the user types more // than 6 chars..uh oh! cin >> str2; // str2 will adjust to // hold whatever the user // types

14 What Do Strings Do Strings simply abstract character arrays Behind the scenes strings are just creating and manipulating character arrays but giving you a simplified set of operators and functions Can concatenate (append) to a string with the + operator #include <iostream> #include <string> using namespace std; string str2 = "CS 102"; // str2 stores 6 chars. = "CS 102" str2 = "Computer Science"; // now str2 stores 16 characters // Can append using '+' or '+=' operator str2 = str2 + " is cool"; // now str2 stores 24 characters str2 616 24 CS 102 Plain-old character array Computer Science Plain-old character array Computer Science is cool Plain-old character array

15 String Size Strings track how big they are Call the.size() function on a string to get the number of characters stored in the string #include <iostream> #include <string> using namespace std; string str2 = "CS 102"; cout << str2.size() << endl; // 6 str2 = "Computer Science"; cout << str2.size() << endl; // 16 str2 = str2 + " is cool"; cout << str2.size() << endl; // 24

16 String Comparison C++ strings will perform lexicographic (alphabetical) comparison when comparison operators (<, >, ==, etc.) are applied Comparison operators do not work with plain old character arrays #include <iostream> #include <string> using namespace std; char str1[4] = "abc"; string str2 = "abc"; if( str1 == "abc" ) // doesn't work... if( str2 == "abc" ) // works..true... if( str1 < "aac" ) // doesn't work... if( str2 < "aac" ) // works..false... string str3 = "acb"; if( str3 > str2 )... // works..true

17 Substrings C++ strings allow you to produce a new string from a substring Call either of the 2 versions:.substr(start_index) or.substr(start_index, length) function on the string 1 st version generates substring from starting index location all the way to the end of the string 2 nd version generates substring from the starting index and includes the next 'length' characters Note: when a function has the same name but different options for parameters we say the function is overloaded Returns a new string Even if length is 1 (i.e. if length is 1 you might think you just get a char, but you still get a string) #include <iostream> #include <string> using namespace std; string str1 = "CS102"; string str2 = str1.substr(2); // str2 = "102" str1 = "Hello World"; str2 = str1.substr(6,5); // str2 = "World" str2 = str1.substr(0,1); // str2 = "H"