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

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

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

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

6. User Defined Functions I

Objectives. In this chapter, you will:

BITG 1113: Array (Part 2) LECTURE 9

CSC 307 DATA STRUCTURES AND ALGORITHM ANALYSIS IN C++ SPRING 2011

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

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

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

BITG 1113: Array (Part 1) LECTURE 8

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

ONE DIMENSIONAL ARRAYS

Computers Programming Course 11. Iulian Năstac

Computers Programming Course 10. Iulian Năstac

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

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

Computer Programming: C++

Arrays. Defining arrays, declaration and initialization of arrays. Designed by Parul Khurana, LIECA.

Programming for Engineers Arrays

C++ PROGRAMMING SKILLS Part 4: Arrays

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

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

V2 3/5/2012. Programming in C. Introduction to Arrays. 111 Ch 07 A 1. Introduction to Arrays

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

type arrayname [ size type arrayname [ size ] = { item ,, item size size

Computer Science & Engineering 150A Problem Solving Using Computers

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays

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

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

How to declare an array in C?

13 4 Understanding Character Strings

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

Chapter 2: Basic Elements of C++

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

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

Engineering Problem Solving with C++, Etter

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Arrays. Week 4. Assylbek Jumagaliyev

Learning Objectives. Introduction to Arrays. Arrays in Functions. Programming with Arrays. Multidimensional Arrays

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

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

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

Lecture 3 The character, string data Types Files

Recognize the correct ordering of decisions in multiple branches Program simple and complex decision

Abstract Data Type (ADT) & ARRAYS ALGORITHMS & DATA STRUCTURES I COMP 221

Module 6: Array in C

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

Principles of Programming. Chapter 6: Arrays

Arrays. Chapter 7 (Done right after 4 arrays and loops go together, especially for loops)

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

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

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Object oriented programming C++

Chapter 10. Arrays and Strings

by Pearson Education, Inc. All Rights Reserved. 2

Maltepe University Computer Engineering Department. BİL 133 Algoritma ve Programlama. Chapter 8: Arrays and pointers

Chapter 4 - Notes Control Structures I (Selection)

Week 5. Muhao Chen.

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

ARRAYS(II Unit Part II)

C-LANGUAGE CURRICULAM

Objectives. Order (sort) the elements of an array Search an array for a particular item Define, use multidimensional array

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

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

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

Chapter 12 Two-Dimensional Arrays

Chapter 2 Basic Elements of C++

Array. Prepared By - Rifat Shahriyar

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Review of the C Programming Language for Principles of Operating Systems

Chapter 9 Introduction to Arrays. Fundamentals of Java

Euclid s algorithm, 133

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

BTE2313. Chapter 2: Introduction to C++ Programming

Personal SE. Functions, Arrays, Strings & Command Line Arguments

Spring 2010 Java Programming

Chapter Nine Arrays. Sixth Edition

Data types. CISC 1600/1610 Computer Science I. Array syntax. Memory allocation. Zero-indexing 4/4/2016. Arrays

C-String Library Functions

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Arrays. Lecture 9 COP 3014 Fall October 16, 2017

CSI33 Data Structures

Write a C program using arrays and structure

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

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

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

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

Lesson 7. Reading and Writing a.k.a. Input and Output

For example, let s say we define an array of char of size six:

Lab Session # 5 Arrays. ALQUDS University Department of Computer Engineering

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

Chapter 6 Pointers and Arrays

CSCE 110 PROGRAMMING FUNDAMENTALS. Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

Transcription:

Chapter 8 Arrays and Strings Objectives In this chapter, you will: Learn about arrays Declare and manipulate data into arrays Learn about array index out of bounds Learn about the restrictions on array processing Pass an array as a parameter to a function Search and sort an array Objectives (cont d.) In this chapter, you will (cont d.): Learn about C-strings Use string functions to process C-strings Input data into and output data from a C-string Learn about parallel arrays Manipulate data in a two-dimensional array Learn about multidimensional arrays 3 4 Introduction Arrays Simple data type: variables of these types can store only one value at a time Structured data type: a data type in which each data item is a collection of other data items Array: a collection of a fixed number of components, all of the same data type One-dimensional array: components are arranged in a list form Syntax for declaring a one-dimensional array: intexp: any constant expression that evaluates to a positive integer 5 6 1

Accessing Array Components General syntax: Accessing Array Components (cont d.) indexexp: called the index An expression with a nonnegative integer value Value of the index is the position of the item in the array []: array subscripting operator Array index always starts at 0 7 8 Accessing Array Components (cont d.) Processing One-Dimensional Arrays Basic operations on a one-dimensional array: Initializing Inputting data Outputting data stored in an array Finding the largest and/or smallest element Each operation requires ability to step through elements of the array Easily accomplished by a loop 9 10 Processing One-Dimensional Arrays (cont d.) Array Index Out of Bounds Given the declaration: int list[100]; //array of size 100 int i; Use a for loop to access array elements: for (i = 0; i < 100; i++) //Line 1 cin >> list[i]; //Line 2 Index of an array is in bounds if the index is >=0 and <= ARRAY_SIZE-1 Otherwise, the index is out of bounds In C++, there is no guard against indices that are out of bounds 11 12 2

Array Initialization During Declaration Arrays can be initialized during declaration Values are placed between curly braces Size determined by the number of initial values in the braces double sales[] = {12.25, 32.50, 16.90, 23, 45.68}; Partial Initialization of Arrays During Declaration The statement: int list[10] = {0}; Declares an array of 10 components and initializes all of them to zero The statement: int list[10] = {8, 5, 12}; Declares an array of 10 components and initializes list[0] to 8, list[1] to 5, list[2] to 12 All other components are initialized to 0 13 14 Some Restrictions on Array Processing Aggregate operation: any operation that manipulates the entire array as a single unit Not allowed on arrays in C++ Solution: 15 16 Arrays as Parameters to Functions Arrays are passed by reference only Do not use symbol & when declaring an array as a formal parameter Size of the array is usually omitted If provided, it is ignored by the compiler Constant Arrays as Formal Parameters Can prevent a function from changing the actual parameter when passed by reference Use const in the declaration of the formal parameter 17 18 3

Base Address of an Array and Array in Computer Memory Base address of an array: address (memory location) of the first array component If list is a one-dimensional array, its base address is the address of list[0] When an array is passed as a parameter, the base address of the actual array is passed to the formal parameter Functions Cannot Return a Value of the Type Array C++ does not allow functions to return a value of type array 19 20 Integral Data Type and Array Indices Other Ways to Declare Arrays C++ allows any integral type to be used as an array index Improves code readability Examples: 21 22 Searching an Array for a Specific Item Sequential search (or linear search): Searching a list for a given item, starting from the first array element Compare each element in the array with value being searched for Continue the search until item is found or no more data is left in the list Selection Sort Selection sort: rearrange the list by selecting an element and moving it to its proper position Steps: Find the smallest element in the unsorted portion of the list Move it to the top of the unsorted portion by swapping with the element currently there Start again with the rest of the list 23 24 4

Selection Sort (cont d.) C-Strings (Character Arrays) Character array: an array whose components are of type char C-strings are null-terminated ('\0 ) character arrays 'A' is the character A "A" is the C-string A "A" represents two characters, 'A' and '\0 25 26 C-Strings (Character Arrays) (cont d.) char name[16]; Since C-strings are null terminated and name has 16 components, the largest string it can store has 15 characters If you store a string whose length is less than the array size, the last components are unused C-Strings (Character Arrays) (cont d.) Size of an array can be omitted if the array is initialized during declaration char name[] = "John"; Declares an array of length 5 and stores the C- string "John" in it Useful string manipulation functions strcpy, strcmp, and strlen 27 28 String Comparison Reading and Writing Strings C-strings are compared character by character using the collating sequence of the system Use the function strcmp If using the ASCII character set: "Air" < "Boat" "Air" < "An" "Bill" < "Billy" "Hello" < "hello" Most rules for arrays also apply to C-strings (which are character arrays) Aggregate operations, such as assignment and comparison, are not allowed on arrays C++ does allow aggregate operations for the input and output of C-strings 29 30 5

cin >> name; String Input Stores the next input C-string into name To read strings with blanks, use get function: cin.get(str, m+1); Stores the next m characters into str but the newline character is not stored in str If input string has fewer than m characters, reading stops at the newline character cout << name; String Output Outputs the content of name on the screen << continues to write the contents of name until it finds the null character If name does not contain the null character, then strange output may occur << continues to output data from memory adjacent to name until a '\0' is found 31 32 Specifying Input/Output Files at Execution Time User can specify the name of an input and/or output file at execution time: string Type and Input/Output Files Argument to the open function must be a nullterminated string (a C-string) If using a string variable for the name of an I/O file, the value must first be converted to a C-string before calling open Use the c_str function to convert Syntax: strvar.c_str() Where strvar is a variable of type string 33 34 Parallel Arrays Two (or more) arrays are called parallel if their corresponding components hold related information int studentid[50]; char coursegrade[50]; Two- and Multidimensional Arrays Two-dimensional array: collection of a fixed number of components (of the same type) arranged in two dimensions Sometimes called matrices or tables Declaration syntax: intexp1 and intexp2 are expressions with positive integer values specifying the number of rows and columns in the array 35 36 6

Accessing Array Components Accessing components in a two-dimensional array: Accessing Array Components (cont d.) Where indexexp1 and indexexp2 are expressions with positive integer values, and specify the row and column position sales[5][3] = 25.75; 37 38 Two-Dimensional Array Initialization During Declaration Two-Dimensional Arrays and Enumeration Types Two-dimensional arrays can be initialized when they are declared: Elements of each row are enclosed within braces and separated by commas All rows are enclosed within braces For number arrays, unspecified elements are set to 0 Enumeration types can be used for array indices: 39 40 Processing Two-Dimensional Arrays Initialization Ways to process a two-dimensional array: Process entire array Row processing: process a single row at a time Column processing: process a single column at a time Each row and each column of a twodimensional array is a one-dimensional array To process, use algorithms similar to processing one-dimensional arrays Examples: To initialize row number 4 (fifth row) to 0: To initialize the entire matrix to 0: 41 42 7

Print Input Use a nested loop to output the components of a two dimensional array: Examples: To input into row number 4 (fifth row): To input data into each component of matrix: 43 44 Sum by Row Sum by Column To find the sum of row number 4: To find the sum of each individual column: 45 46 Largest Element in Each Row and Each Column Passing Two-Dimensional Arrays as Parameters to Functions To find the largest element in each row: Two-dimensional arrays are passed by reference as parameters to a function Base address is passed to formal parameter Two-dimensional arrays are stored in row order When declaring a two-dimensional array as a formal parameter, can omit size of first dimension, but not the second 47 48 8

Arrays of Strings Strings in C++ can be manipulated using either the data type string or character arrays (Cstrings) On some compilers, the data type string may not be available in Standard C++ (i.e., non-ansi/iso Standard C++) Arrays of Strings and the string Type To declare an array of 100 components of type string: string list[100]; Basic operations, such as assignment, comparison, and input/output, can be performed on values of the string type The data in list can be processed just like any one-dimensional array 49 50 Arrays of Strings and C-Strings (Character Arrays) Another Way to Declare a Two-Dimensional Array Can use typedef to define a two-dimensional array data type: To declare an array of 20 rows and 10 columns: 51 52 Multidimensional Arrays Summary n-dimensional array: collection of a fixed number of elements arranged in n dimensions (n >= 1) Declaration syntax: To access a component: Array: structured data type with a fixed number of components of the same type Components are accessed using their relative positions in the array Elements of a one-dimensional array are arranged in the form of a list An array index can be any expression that evaluates to a nonnegative integer Must always be less than the size of the array 53 54 9

Summary (cont d.) The base address of an array is the address of the first array component When passing an array as an actual parameter, use only its name Passed by reference only A function cannot return an array type value In C++, C-strings are null terminated and are stored in character arrays Summary (cont d.) Commonly used C-string manipulation functions include: strcpy, strcmp, and strlen Parallel arrays are used to hold related information In a two-dimensional array, the elements are arranged in a table form 55 56 Summary (cont d.) To access an element of a two-dimensional array, you need a pair of indices: One for row position, one for column position In row processing, a two-dimensional array is processed one row at a time In column processing, a two-dimensional array is processed one column at a time 57 10