Arrays. Week 4. Assylbek Jumagaliyev

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

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

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

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

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

C++ PROGRAMMING SKILLS Part 4: Arrays

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

C Arrays Pearson Education, Inc. All rights reserved.

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

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

Pointers and Strings Prentice Hall, Inc. All rights reserved.

Pointers and Strings. Adhi Harmoko S, M.Komp

Computer Programming Lecture 14 Arrays (Part 2)

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.

Chapter 10 - Notes Applications of Arrays

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

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

Sorting Algorithms. Array Data is being arranged in ascending order using the bubble sort algorithm. #1 #2 #3 #4 #5 #6 #7

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

C: How to Program. Week /Apr/23

IS 0020 Program Design and Software Tools

Lecture 04 FUNCTIONS AND ARRAYS

Operator Overloading in C++ Systems Programming

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

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

C/C++ Programming Lecture 18 Name:

Introduction to Computer Science Midterm 3 Fall, Points

CS242 COMPUTER PROGRAMMING

Chapter 5 - Pointers and Strings

Chapter 5 - Pointers and Strings

Pointers and Strings Prentice Hall, Inc. All rights reserved.

Functions and Recursion

Week 3: Pointers (Part 2)

Exercise 1.1 Hello world

Chapter 18 - C++ Operator Overloading

CSE101-Lec#17. Arrays. (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

BITG 1113: Array (Part 1) LECTURE 8

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

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

Fast Introduction to Object Oriented Programming and C++

CMPS 221 Sample Final

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

by Pearson Education, Inc. All Rights Reserved.

CSC 330 Object Oriented Programming. Operator Overloading Friend Functions & Forms

CMSC 202 Midterm Exam 1 Fall 2015

Getting started with C++ (Part 2)

C: How to Program. Week /Apr/16

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

CSE101-lec#19. Array searching and sorting techniques. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

Introduction to C++ Introduction to C++ 1

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

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

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Principles of Programming. Chapter 6: Arrays

Chapter 3 - Functions

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Computer Science II Lecture 2 Strings, Vectors and Recursion

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Introduction to C++ (Extensions to C)

Introduction to C++ Systems Programming

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

Chapter 2 - Control Structures

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Pointers, Dynamic Data, and Reference Types

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

C Pointers. 7.2 Pointer Variable Definitions and Initialization

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

CSC 211 Intermediate Programming. Arrays & Pointers

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Lecture 6 Sorting and Searching

Programming for Engineers Arrays

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

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

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

Ch 5-2. Arrays Part 2

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays

Introduction to C Final Review Chapters 1-6 & 13

To become familiar with array manipulation, searching, and sorting.

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

Here, type declares the base type of the array, which is the type of each element in the array size defines how many elements the array will hold

Working with Batches of Data

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

Chapter 2 - Control Structures

Procedural Programming

W8.2 Operator Overloading

Introduction to Programming

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

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

Introduction to Arrays

Arrays and Applications

Search Algorithms. Linear Search Binary Search

Transcription:

Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz

Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays as objects (C++) 2

Arrays Array Consecutive group of memory locations Same name and type (int, char, etc.) To refer to an element Specify array name and position number (index) Format: arrayname[ position number ] First element at position 0 N-element array c c[ 0 ], c[ 1 ] c[ n - 1 ] Nth element as position N-1 3

Arrays Array elements like other variables Assignment, printing for an integer array c c[ 0 ] = 3; cout << c[ 0 ]; Can perform operations inside subscript c[ 5 2 ] same as c[3] 4

Arrays Note that all elements of this array have the same name, c 5

Declaring Arrays When declaring arrays, specify Name Type of array Any data type(int, char, double, etc.) Number of elements type arrayname[ arraysize ]; int c[ 10 ]; // array of 10 integers float d[ 3284 ]; // array of 3284 floats Declaring multiple arrays of same type Use comma separated list, like regular variables int b[ 100 ], x[ 27 ]; 6

Initializing arrays For loop Set each element Initializer list Specify each element when array declared int n[ 5 ] = { 1, 2, 3, 4, 5 }; If not enough initializers, rightmost elements 0 If too many syntax error To set every element to same value int n[ 5 ] = { 0 }; If array size omitted, initializers determine size int n[] = { 1, 2, 3, 4, 5 }; 5 initializers, therefore 5 element array 7

Declare a 5-element array of integers. Initialize array to 0 using a for loop. Note that the array has elements n[0] to n[4]. Element Value 0 0 1 0 2 0 3 0 4 08

Note the use of the initializer list. Element Value 0 32 1 27 2 64 3 18 4 95 5 14 6 90 7 70 8 60 9 37 9

Array size Array size Can be specif ied with constant variable (const) const int size = 20; Constants cannot be changed Constants must be initialized when declared Also called named constants or read-only variables 10

Note use of const keyword. Only const variables can specify array sizes. Element Value 0 2 1 4 The program 2 becomes 6 more scalable 3 when 8we set the array 4 size using 10a const 5 variable. We 12 can change 6 arraysize, 14 and all the 7 loops will still 16 work (otherwise, 8 we d have 18 to update 9 every loop 20 in the program). 11

Total of array element values is 55 12

12 3 5-9 8 4 10 0 7 11 Total of array elements values is 51 13

Strings as Arrays Strings Arrays of characters All strings end with null ('\0') Examples char string1[] = "hello"; Null character implicitly added string1 has 6 elements char string1[] = { 'h', 'e', 'l', 'l', 'o', '\0 }; Subscripting is the same String1[ 0 ] is 'h' string1[ 2 ] is 'l' 14

Strings as Arrays Input from keyboard char string2[ 10 ]; cin >> string2; Puts user input in string Stops at f irst whitespace character Adds null character If too much text entered, data written beyond array We want to avoid this Printing strings cout << string2 << endl; Does not work for other array types Characters printed until null found 15

Enter the string Two different "hello ways there": to hello there string1 is: declare hellostrings. string2 string2 is: is string initialized, literal and its size string1 with determined spaces automatically between characters. is: h e l l o string1 is: there Examples of reading strings from the keyboard and printing them out. Can access the characters in a string using array notation. The loop ends when the null character is found. 16

Sorting Arrays Sorting data Important computing application Virtually every organization must sort some data Massive amounts must be sorted Bubble sort (sinking sort) Several passes through the array Successive pairs of elements are compared If increasing order (or identical), no change If decreasing order, elements exchanged Repeat these steps for every element 17

Bubble sort Starting from the beginning of the list, compare every adjacent pair, swap their position if they are not in the right order (the latter one is smaller than the former one).

Sorting Arrays Example: Go left to right, and exchange elements as necessary One pass for each element Original: 3 4 2 7 6 Pass 1: 3 2 4 6 7 (elements exchanged) Pass 2: 2 3 4 6 7 Pass 3: 2 3 4 6 7 (no changes needed) Pass 4: 2 3 4 6 7 Pass 5: 2 3 4 6 7 Small elements "bubble" to the top (like 2 in this example) 19

Sorting Arrays Swapping variables int x = 3, y = 4; y = x; x = y; What happened? Both x and y are 3! Need a temporary variable Solution int x = 3, y = 4, temp = 0; temp = x; // temp gets 3 x = y; // x gets 4 y = temp; // y gets 3 20

Do a pass for each element in the array. If the element on the left (index j) is larger than the element on the right (index j + 1), then we swap them. Remember the need of a temp variable. 21

Date items in ascending order 2 4 6 8 10 12 37 45 68 89 22

Searching Arrays: Linear Search Search array for a key value Linear search Compare each element of array with key value Start at one end, go to other Useful for small and unsorted arrays Ineff icient If search key not present, examines every element 23

Searching Arrays: Binary Search Binary search Only used with sorted arrays Compare middle element with key If equal, match found If key < middle Repeat search on f irst half of array If key > middle Repeat search on last half Very fast At most N steps, where 2 N > # of elements 30 element array takes at most 5 steps 2 > 30 5 24

Takes array, search key, and array size. Enter integer search key: 36 Found value in element 18 Enter integer search key: 37 Value not found 25

1 // Fig. 3.20: f ig04_20.cpp 2 // Binary search of an array. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 #include <iomanip> 10 11 using std::setw; 12 13 // function prototypes 14 int binarysearch( const int [], int, int, int, int ); 15 void printheader( int ); 16 void printrow( const int [], int, int, int, int ); 17 18 int main() 19 { 20 const int arraysize = 15; // size of array a 21 int a[ arraysize ]; // create array a 22 int key; // value to locate in a 23 24 for ( int i = 0; i < arraysize; i++ ) // create some data 25 a[ i ] = 2 * i; 26 26

27 cout << "Enter a number between 0 and 28: "; 28 cin >> key; 29 30 printheader( arraysize ); 31 32 // search for key in array a 33 int result = 34 binarysearch( a, key, 0, arraysize - 1, arraysize ); 35 36 // display results 37 if ( result!= -1 ) 38 cout << '\n' << key << " found in array element " 39 << result << endl; 40 else 41 cout << '\n' << key << " not found" << endl; 42 43 return 0; // indicates successful termination 44 45 } // end main 46 27

47 // function to perform binary search of an array 48 int binarysearch( const int b[], int searchkey, int low, 49 int high, int size ) 50 { 51 int middle; 52 53 // loop until low subscript is greater than high subscript 54 while ( low <= high ) { 55 56 // determine middle element of subarray being searched 57 middle = ( low + high ) / 2; 58 Determine middle element 59 // display subarray used in this loop iteration 60 printrow( b, low, middle, high, size ); 61 28

62 // if searchkey matches middle element, return middle 63 if ( searchkey == b[ middle ] ) // match 64 return middle; 65 66 else 67 68 // if searchkey less than middle element, 69 // set new high element 70 if ( searchkey < b[ middle ] ) 71 high = middle - 1; // search low end of array 72 73 // if searchkey greater than middle element, 74 // set new low element 75 else 76 low = middle + 1; // search high end of array 77 } 78 79 return -1; // searchkey not found 80 81 } // end function binarysearch Use the rule of binary search: If key equals middle, match If less, search low end If greater, search high end Loop sets low, middle and high dynamically. If searching the high end, the new low is the element above the middle. 29

82 83 // print header for output 84 void printheader( int size ) 85 { 86 cout << "\nsubscripts:\n"; 87 88 // output column heads 89 for ( int j = 0; j < size; j++ ) 90 cout << setw( 3 ) << j << ' '; 91 92 cout << '\n'; // start new line of output 93 94 // output line of - characters 95 for ( int k = 1; k <= 4 * size; k++ ) 96 cout << '-'; 97 98 cout << endl; // start new line of output 99 100 } // end function printheader 101 30

102 // print one row of output showing the current 103 // part of the array being processed 104 void printrow( const int b[], int low, int mid, 105 int high, int size ) 106 { 107 // loop through entire array 108 for ( int m = 0; m < size; m++ ) 109 110 // display spaces if outside current subarray range 111 if ( m < low m > high ) 112 cout << " "; 113 114 // display middle element marked with a * 115 else 116 117 if ( m == mid ) // mark middle value 118 cout << setw( 3 ) << b[ m ] << '*'; 119 120 // display other elements in subarray 121 else 122 cout << setw( 3 ) << b[ m ] << ' '; 123 124 cout << endl; // start new line of output 125 126 } // end function printrow 31

Enter a number between 0 and 28: 6 Subscripts: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ------------------------------------------------------------ 0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28 0 2 4 6* 8 10 12 6 found in array element 3 Enter a number between 0 and 28: 25 Subscripts: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ------------------------------------------------------------ 0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28 16 18 20 22* 24 26 28 24 26* 28 24* 25 not found 32

Enter a number between 0 and 28: 8 Subscripts: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ------------------------------------------------------------ 0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28 0 2 4 6* 8 10 12 8 10* 12 8* 8 found in array element 4 33

Readings: C++ How to Program, By H. M. Deitel Chapter 7. Arrays and Vectors

Thanks for your attention! 35