BITG 1113: Array (Part 2) LECTURE 9

Similar documents
Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

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

Objectives. Chapter 8 Arrays and Strings. Objectives (cont d.) Introduction 12/14/2014. In this chapter, you will:

Strings in C++ Dr. Ferdin Joe John Joseph Kamnoetvidya Science Academy

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

C++ Arrays. Arrays: The Basics. Areas for Discussion. Arrays: The Basics Strings and Arrays of Characters Array Parameters

Introduction to string

Lecture 10 Arrays (2) and Strings. UniMAP SEM II - 11/12 DKT121 1

Copyright 2003 Pearson Education, Inc. Slide 1

String Class in C++ When the above code is compiled and executed, it produces result something as follows: cin and strings

3. Functions. Modular programming is the dividing of the entire problem into small sub problems that can be solved by writing separate programs.

Engineering Problem Solving with C++, Etter

Object oriented programming C++

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

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

System Design and Programming II

LECTURE 15. String I/O and cstring library

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

C-String Library Functions

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

C Style Strings. Lecture 11 COP 3014 Spring March 19, 2018

LOGO BASIC ELEMENTS OF A COMPUTER PROGRAM

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting

Chapter 10 Characters, Strings, and the string class

Introduction to Algorithms and Data Structures. Lecture 6 - Stringing Along - Character and String Manipulation

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

Introduction to C/C++ Lecture 5 - String & its Manipulation

ONE DIMENSIONAL ARRAYS

Object Oriented Programming COP3330 / CGS5409

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings

Computers Programming Course 11. Iulian Năstac

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Objectives. In this chapter, you will:

Fundamentals of Programming CS-110. Lecture 2

Chapter 8 - Characters and Strings

BITG 1113: Function (Part 2) LECTURE 5

Introduction to Programming EC-105. Lecture 2

C++ For Science and Engineering Lecture 12

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Chapter 8: Character & String. In this chapter, you ll learn about;

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

Chapter 10: Character Testing. From Program Character Case Conversion 8/23/2014. Character Testing. Character Case Conversion

Chapter 10: Characters, C- Strings, and More About the string Class

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 6: One Dimensional Array

Unit 2: The string class

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

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

2 nd Week Lecture Notes

Chapter 10: Characters, C- Strings, and More About the string Class Character Testing

Exercise 1.1 Hello world

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS

Chapter 7 Array. Array. C++, How to Program

CSC 126 FINAL EXAMINATION Spring Total Possible TOTAL 100

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

LECTURE 02 INTRODUCTION TO C++

CSc Introduction to Computing

CCE1111 Programming for Engineers [C Programming Language]

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

CSI33 Data Structures

1 Pointer Concepts. 1.1 Pointer Examples

Arrays. Lecture 9 COP 3014 Fall October 16, 2017

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

Chapter 9 Strings. With this array declaration: char s[10];

Functions: call by reference vs. call by value

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Built-in Functions for NTCAs.

C: How to Program. Week /May/28

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

EECS402 Lecture 08. Intro To The Standard string Class. Some string Functionality

Computers Programming Course 10. Iulian Năstac

Intermediate Programming, Spring 2017*

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Converting a Lowercase Letter Character to Uppercase (Or Vice Versa)

Using Character Arrays. What is a String? Using Character Arrays. Using Strings Life is simpler with strings. #include <stdio.

Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters,

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

CS 103 Lab 6 - Party Like A Char Star

String can be represented as a single-dimensional character type array. Declaration of strings

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

BITG 1113: Array (Part 1) LECTURE 8

Create a Program in C (Last Class)

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

Scientific Programming in C V. Strings

CSc Introduc/on to Compu/ng. Lecture 17 Edgardo Molina Fall 2011 City College of New York

CS 103 Lab - Party Like A Char Star

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

Computer Programming

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

Getting started with C++ (Part 2)

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

String Variables and Output/Input. Adding Strings and Literals to Your Programming Skills and output/input formatting

Arrays. Week 4. Assylbek Jumagaliyev

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

ARRAYS(II Unit Part II)

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Transcription:

BITG 1113: Array (Part 2) LECTURE 9 1

LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of C-strings (character arrays) 2. Use C-string functions 3. Use array as function parameter. 4. Manipulate data in arrays using function. 2

THE CONCEPT OF STRINGS Strings are used often in programming. You have used string literals before. String literal : a sequence of characters enclosed in a set of double quotes ( ) Example : Hello There are two ways to process strings in C++. One way is to treat strings as arrays of characters. This is known as C-strings. The other way is to process strings using the string class. However this lecture introduces C-strings only. 3

The Concept of C-strings C-string: a sequence of characters stored in adjacent memory locations and terminated by a NULL character ( \0 ). A NULL character ( \0 ) specifies the end of the C-string. C-string Declaration and Initialization Array of characters is used to declare a C-string. The size of the C-string must be large enough to store the string literal and a NULL character ( \0 ). Example : char name[8]; name is a C-string and it could consists of 8 characters. The largest string literal that it can store has 7 characters. If you store a string literal of a shorter length, say 6 in name, then the first 7 elements of name are used and the last one is left unused. name Example : char name[8]= Aisyah ; [0] [1] [2] [3] [4] [5] [6] [7] A i s y a h \0 Unused element 4

More on C-string Declaration and Initialization We could also declare with initializing a C-string with values (without giving the size) by either of these two ways: char mystring[] = { H, e, l, l, o, \0 }; char mystring [] = Hello ; H e l l o \0 Either statements would allocate the same amount of memory. mystring is declared with a size of 6 characters (its size is determined by the length of its string literal plus a NULL character). In the second case, when using double quotes, NULL character is automatically appended. 5

Characters and C-strings To store a single character, we have two options: Character literal use single quote marks : a String literal use double quote marks : a Example: A is the character A. A is the C-string A, where A represents two characters, A and \0. 6

Summary of C-string declaration and initialization. The statement char name[16] = "John"; declares an array name of length 16 and stores "John" and a \0 in it. The statement char name[] = "John"; declares an array name of length 5 and stores "John" and a \0 in it. 7

C-string Initialization vs. Assignment A C-string can be initialized at the time of its creation. char month[10] = May ; //correct However, a C-string cannot later be assigned a value using the = operator; you must use the strcpy() function. char month[10]; month = May ; // wrong! strcpy(month, May ); //correct 8

C-string input cin operator shows that the compiler expects the user to type a one-word string from the keyboard. char name[31]; cin >> name; // Reads in characters until a // space,tab or new line is // encountered. cout << name; //Will print the string name If you want the user to type text that includes space, use cin.getline() or cin.get() function. Example : cin.getline(name, 31); //Stores the first 30 //characters from the text entered into name. //The last character in name is reserved for the null //character ('\0'). 9

String Functions strcat() strlwr() strupr() 10

String Functions There are many useful functions for manipulating string data such as comparing string, searching string, and determining the length of string. These functions are provided by the string handling library from the standard library. You must include the <cstring> header file when using functions from the string handling library. 11

String Function : strcpy() An array cannot be assigned to another using the = operator. strcpy() function - used to copy one string into another string. The syntax of the strcpy() function is: strcpy (s1, s2); This function takes two arguments: - s1: the destination string that you are trying to replace. - s2: the source (origin) of the string that you want to copy. 12

String Function : strcpy() Can be used : to replace an existing string or to initialize a string. Example : char carname1[20]; char carname2[20]= Honda City ; 1) strcpy(carname1, "Toyota Camry"); cout << "Car Name: " << carname1 ; Output : Car Name: Toyota Camry 2) strcpy(carname1, carname2); cout << "Car Name: " << carname1 ; Output : Car Name: Honda City 13

String Function : strncpy() strncpy() function works like the strcpy() Allows you to specify the number of characters that the compiler would copy from the source string. syntax: strncpy(s1, s2, intnumber); //s1:destination, s2:source The intnumber argument specifies the number of characters that will be copied from the source string. 14

String Function : strncpy() Example : char carname1[20]; char carname2[20]= Honda City ; 1)strncpy(carName1, Toyota Camry, 6); cout << carname1: << carname1 ; Output : carname1: Toyota 2)strncpy(carName1, carname2, 5); cout << carname1: << carname1 ; Output : carname2: Honda 15

String Comparison C-strings are compared character by character using the collating sequence of the system If we are using the ASCII character set "Air" < "Boat" "Air" < "An" "Bill" < "Billy" "Hello" < "hello" 16

String Function : strcmp() The strcmp() function compares two strings and returns an integer as a result of its comparison. The syntax is: strcmp(s1, s2); This function takes two strings, s1 and s2 and compares them. It returns a negative value : if s1 is less than s2 0 : if s1 and s2 are equal a positive value : if s1 is greater than s2 17

String Function : strcmp() Example : char faculty[10] = FTMK "; char input[10]; int i; cout<< Enter your faculty: ; cin>>input; i = strcmp(faculty, input); if(i == 0) { cout<< You are from FTMK ; } 18

String Function : strlen() strlen() function is used to find the number of characters of a string. Its syntax is: strlen(s1); The strlen() function takes one argument, which is the string you are considering. The function returns the number of characters of the string. 19

String Function : strlen() Example : char CarName [20]= Honda City ; int length; length = strlen(carname); cout << "Car Name: " << length; Output : Car Name: 10 20

21

String Function : strcat() If you have two strings, to append one to another, use the strcat() function. Its syntax is: strcat(s1, s2); The strcat() function takes two arguments : - The first string is referred to as the destination - The second argument, called the source string, is the string you want to add to the first string. 22

String Function : strcat() Example : char faculty[20] = FTMK ; char university[13] = UTeM, MELAKA ; strcat(faculty, university); cout << \n\nafter concatenating: << faculty << endl; Output: After concatenating: FTMK UTeM, MELAKA 23

String Function : strncat() strcat() function and considers all characters of the source string. The syntax is: strncat(s1, s2, intnumber); strncat() function allows you to specify the number of characters from the source string that you want to append to the destination string. This means that, if the source string has 12 characters, you can decide to append only a set number of its characters. 24

String Function : strncat() Example : char faculty[20] = FTMK ; char university[13] = UTeM, MELAKA ; strncat(faculty, university,4); cout << "\n\nafter concatenating: << faculty << endl; Output : After concatenating: FTMK UTeM 25

String Function : strlwr() strlwr() function is used to convert a string to lowercase. Its syntax is: strlwr(s); This function takes, as argument, the string that needs to be converted. During conversion, if a Latin character were in uppercase, it would be converted to lowercase. 26

String Function : strlwr() Example : char faculty1[10] = FTMK "; char faculty2[10]; strcpy(faculty2,strlwr(faculty1)); cout << faculty2; Output : ftmk 27

String Function : strupr() strupr() function is used to convert a string to uppercase. Its syntax is: strupr(s); Each lowercase character in the function s argument, S, would be converted to uppercase. Any character or symbol that is not in lowercase would not be changed. 28

String Function : strupr() Example : char faculty1[10] = ftmk "; strcpy(faculty2,strupr(faculty1)); cout << faculty2; Output : FTMK 29

Converting strings to other types The cstdlib (stdlib) library provides three useful functions for this purpose: atoi: converts string to int type. atol: converts string to long type. atof: converts string to float type. All of these functions admit one parameter and return a value of the requested type (int, long or float). Example: int x = atoi( 1234 ); double y = atof( 456.98 ); 30

ARRAYS AND FUNCTIONS Using function to process arrays in large program : 1) Passing a one-dimensional array to function By passing individual elements Same as passing any ordinary variable to a function By passing the whole array When we need the function to operate on the whole array 31

1- D array : Passing individual elements Passing individual element Array element must matches the function parameter type When as a value parameter, function cannot change the value of the element in the calling function E.g : a function, print_square receives an integer and prints its square, using an array, we can loop through the array and pass each element in turn to print_square 32

Passing individual element - Example 33

1- D array : Passing the whole array Passing the whole array When we use large arrays in functions, by passing each value we need an extra memory to do so E.g : if an array containing 20k elements were passed by value to a function, another 20k elements would have to be allocated in the function and each element would have to be copied from one array to another Instead of passing the whole array, C++ passes the address of the array 34

An array name is the address of the first element in the array Because of the name of array is in fact its address, passing an array name allows the called function to refer to the array back in the calling function Two rules associated with passing the whole array: The function must be called by passing only the name of the array In the function definition, the formal parameter must be an array type, the size of the array doesn t need to be specified. If provided, it is ignored by the compiler. A function can change the elements in array by passing the array name without the constant modifier 35

Passing the whole arrays for updating - Example 1 Array used in a function is a reference parameter The symbol & is not used when declaring an array as a formal parameter C++ does not allow functions to return a value of the type array 36

Passing the whole arrays for updating Example 2 #include <iostream> using namespace std; #define SIZE 7 void reverseorder(int [], int); // function prototype int main() { int numbers[size]={1,2,3,4,5,6,7}; reverseorder(numbers, SIZE); return 0; } // end main void reverseorder(int list[], int arraysize) { for (int i = arraysize-1; i >= 0; i--) cout << list[i] << "\t"; } // end reverseorder 37

Passing the whole array as constants : Example const : This means array x CANNOT change the content of array base 38

2 ) Passing a two-dimensional array to function Passing an individual element - Pass the individual element by indexing the array name with the row number and the column number Passing a row Pass the whole row by indexing the array name with only the row number Passing the whole array Use the array name as the actual parameter 39

2 D Array: Passing an individual element - Example #include <iostream> using namespace std; void print(int a); int main() { int i,j,ary1[4][3]={{1,2,3},{2,4,6},{3,6,9},{3,2,1}}; for(int i=0; i<4; i++) { for(int j=0; j<3; j++) print(ary1[i][j]); cout<<endl; } return 0; } void print(int a) { cout<<a<< \t ; } 40

2 D Array : Passing a row - Example 41

2 D Array : Passing the whole array Example 1 42

2 D Array : Passing the whole array - Example 2 #define NUMBER_OF_STUDENTS 5 // const int NUMBER_OF_STUDENTS=5; #define NUMBER_OF_QUESTIONS 10 // const int NUMBER_OF_QUESTIONS=10; void checkanswer(char[], char[][number_of_questions], int, int, int[]); // function prototype int main() { char key[number_of_questions] = {'C','C','B','A','D','B','A','B','C','D' }; char answer[number_of_students][number_of_questions]= { {'C','D','C','C','B','B','A','B','C','B'}, {'C','C','B','C','D','B','A','B','A','B'}, {'D','D','C','A','D','B','A','B','A','D'}, {'B','C','C','C','B','B','B','B','C','C'}, {'C','C','C','A','D','B','C','B','C','D'} }; int checked[number_of_students]; checkanswer(key, answer, NUMBER_OF_STUDENTS, NUMBER_OF_QUESTIONS, checked); // passing array numbers return 0; } // end main 43

cont. eg. 2 D Array : Passing the whole array void checkanswer(char key[], char answer[][number_of_questions], int numstud, int numques, int checked[]) { int i, j; // declaring index for (i = 0; i < numstud; i++) // initializing checked (zeros) checked [i] = 0; for (i = 0; i < numstud; i++) { for (j = 0; j < numques; j++) { if (answer[i][j] == key[j]) checked[i] += 1; } // inner for cout << "Student " << i << "'s marks : " << checked[i] << "/" << NUMBER_OF_QUESTIONS << "." << endl; } // end for } // end checkanswer - END - 44