CS31 Discussion 1H Fall18: week 6

Slides:



Advertisements
Similar presentations
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Advertisements

Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Chapter 10.
CS31: Introduction to Computer Science I Discussion 1A 5/7/2010 Sungwon Yang
1 C-strings String = null-terminated array of characters The null character ('\0') specifies where the string terminates in memory. Example: The string.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Lesson 7 Arrays CS 1 Lesson 7 -- John Cole1. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2013 CMPE-013/L Arrays and Strings Gabriel Hugh Elkaim Spring 2013.
CS 31 Discussion, Week 6 Faisal Alquaddoomi, Office Hours: BH 2432, W 4:30-6:30pm, F 12:30-1:30pm.
Introduction to C programming
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
Chapter 8 Arrays and Strings
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
COIT29222-Structured Programming Lecture Week 08  Reading: Textbook (4 th Ed.), Chapter 4 Textbook (6 th Ed.), Chapter 7 Study Guide Book 2, Module 11.
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 7 Arrays.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Review Pointer Pointer Variables Dynamic Memory Allocation Functions.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
CS113 Introduction to C Instructor: Ioannis A. Vetsikas Lecture 5 : September 4.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Strings C supports strings using one-dimensional character arrays. A string is defined as a null-terminated character array. In C, a null is 0. You must.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Introduction Programs which manipulate character data don’t usually just deal with single characters, but instead with collections of them (e.g. words,
Pointers and Dynamic Arrays
Computer Organization and Design Pointers, Arrays and Strings in C
CS31 Discussion Jie(Jay) Wang Week6 Nov.4.
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
New Structure Recall “average.cpp” program
Strings A string is a sequence of characters treated as a group
Arrays in C.
7 Arrays.
INC 161 , CPE 100 Computer Programming
Pointers, Dynamic Data, and Reference Types
Arrays Kingdom of Saudi Arabia
Beginning C for Engineers
String What it is Why it’s useful
Standard Version of Starting Out with C++, 4th Edition
Chapter 8 Character Arrays and Strings
CPS120: Introduction to Computer Science
Engineering Problem Solving with C++, Etter
7 Arrays.
Arrays Arrays A few types Structures of related data items
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
CS31 Discussion 1D Winter19: week 3
CS-161 Computer Programming Lecture 15 & 16: Arrays II
Lecture 2 Arrays & Pointers September 7, 2004
CS31 Discussion 1D Winter19: week 4
CS31 Discussion 1H Fall18: week 7
EECE.2160 ECE Application Programming
CS31 Discussion 1H Fall18: week 3
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
Dr. Khizar Hayat Associate Prof. of Computer Science
Presentation transcript:

CS31 Discussion 1H Fall18: week 6 TA: Behnam Shahbazi bshahbazi@cs.ucla.edu Credit to former TAs: Chelsea Ju and Bo-Jhang Ho, Ricky Lee, Sepideh Mazrouee

Overview Review: Multi-dimensional Arrays C-Strings Pseudocode & Test Cases Project 5 Multi-dimensional Arrays C-Strings Midterm 2 - Practice Problems

Pass a 2D array to a function Can we pass a 2-dimensional array to a function? Yes, but with restriction Have to provide the size of the array int fillInArray(int params[3][5]) { for (int i = 0; i < 3; i++) for (int j = 0; j < 5; j++) params[i][j] = i * 10 + j; } int main() { int arr[3][5]; fillInArray(arr); ... return 0; } Cannot omit the two numbers like one-dimensional array Have to match the caller

Pass an array to a function – Option 2 Can we pass a 2-dimensional array to a function? Yes, but with restriction int fillInArray(int params[][5], int row_num) { for (int i = 0; i < row_num; i++) for (int j = 0; j < 5; j++) params[i][j] = i * 10 + j; } int main() { int arr[3][5]; fillInArray(arr); ... return 0; } You can leave off the first bound, but you must supply the  second bound as a compile-time constant expression

Pass a 2D array to a function main() { const int NUM_SECTIONS = 4; const int MAX_STUDENTS = 5; int scores[NUM_SECTIONS][MAX_STUDENTS];   scores[0][0] = 97; scores[1][3] = 83; scores[3][4] = 69; } 1 2 3 0 1 2 3 4 97 83 69

2D Arrays void main(void) { int table[5][5]; int r,c;   for (r=0;r<5;r++) for (c=0;c<5;c++) table[r][c] = (r+1) * (c+1); cout << table[4][3] << endl; cout << table[2][1] << endl; } When you use two nested loops as above, the outer loop iterates over the rows, and the inner loop iterates over the columns. 1 2 3 4 0 1 2 3 4 1 2 3 4 5 2 4 6 8 10 6 3 12 20 4 20

Why learn C Strings? If you ever need to program in C Ex: embedded firmware Many legacy libraries are written in C, so there is no #include <string> library. Better performance.

What makes C strings different than C++ strings? C strings can be viewed as an array of chars. C strings have a null-terminating character at the end.

Null-terminated character \0 Allows us to know when the end of the string is.

Declaring a C string Template: char <name>[size]; char myString[10] = {‘h’,’e’,’l’,’l’,’o’,’\0’}; char myString[10] = “hello”; //does same as above char myString[10]; // same as char myString[10] = { '\0' } char myString[] = “hhheeellllooooooo”;

Example use of utilizing the null character While I is not \0, enter loop

Will this compile? No, no room for the null character that compiler will automatically put in

Will it compile? What if we try to put a null character at the end? No, with double quotes, compiler will put in a null character, making it too big.

Undefined, need the null character if you wont put the number in the braces

Now the compiler knows when the end is

Will this compile? If so what is the output? -first print will read until null terminating char -second print will access 3rd char directly

Will it compile? -cant reassign C strings like this after initializing it as empty.

One element at a time

Does this program not compile or have undefined behavior Does this program not compile or have undefined behavior? If not, what does this program output? i = 0, j = 0 Do{ print s2[0], increment 1 } while j < 5 && s2[j] isnt null && s2[j] == s1[j]

C String Library #include <cstring> strlen “string length” returns the number of characters before the null character. strcpy “string copy” copies the second argument into the first argument strcat “string concatenate” adds the second argument to the first argument strcmp “string compare” compares two strings.

strlen -syntax is a little different instead of the .length() in c++

Write the strlen() function Const means you wont modify it in this function

Would this program compile? They don’t work on c++ strings

strcpy -copies all characters including null character -when source array is larger than destination, undefined behavior. It tries copying past the allocated memory of the destination.

strcat -appends source to destination -destination’s null character is replaced by the first character of source -The behavior is undefined if the destination array is not large enough for the contents of both src and dest and the terminating null character. Output: C strings are C strings are

strcmp -the # is determined by the difference of the values of the stopping point <0 the first character that does not match has a lower value in ptr1 than in ptr2 0 the contents of both strings are equal >0 the first character that does not match has a greater value in ptr1 than in ptr2

strcmp Prints 0

Will it compile? If so, what is the output? 3

Will it compile? If so, what is the output? No, cant do line 7

Will it compile? If so, what is the output? lol LOL

Will it compile? If so, what is the output? 1234512345 10

What is the output? 10 01234! 6 012! 4 01! 3 0! 2

Summary Are stored in standard char arrays. C strings: Are stored in standard char arrays. An array of size n may hold n-1 characters. Must contain an ASCII 0 character at the end of the string to be valid. You may have an empty string too. It has an ASCII 0 in the first slot. Void main(void) { char name[5]; // holds up to a 4 char name[0] = ‘H’; name[1] = ‘i’; name[2] = 0; // or ‘\0’ }

Summary (Cont’d) C strings: 5. Always make sure when you copy one C string into another that there’s enough room! 6. It’s a good idea to initialize each string immediately before using it! 7. Remember, an uninitialized array contains a random, possibly invalid string! void main(void) { char name[5]; strcpy ( name , ”Adele” ); name[0] = ‘\0’; strcat(name,”Hi”); }

In class exercise Please write two versions of a function that replaces the existing all chars in a C string with the char ‘X'. 1. Uses the strlen function 2. Can’t use strlen void fillX(char s[]) { for (int i = 0; i < strlen(s); i++) s[i] = 'X'; //2nd version: replace for loop with // for (int i = 0; s[i] != '\0'; i++) }

- s and t represent strings. Don't use C++ functions on C strings! - s and t represent strings.

Array of char arrays Row 1 (a[0]) Row 2 (a[1]) Row m (a[m]) A matrix That means, an array of char arrays! Row 1 (a[0]) Row 2 (a[1]) Row m (a[m]) A matrix

Array of char arrays char a[10][20]; Expression with only one subscript, like a[k], can be treated like a C string. (assuming that row has a zero byte marking the end) -- strlen(a[k]) is  fine, for example. Strlen(a[k]) strcpy(a[0],"hello”) strcmp(a[0],a[1]) …