Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT5: Array (1D and 2D) CS2311 Computer Programming.

Slides:



Advertisements
Similar presentations
The simple built-in data types of the C language such as int, float, - are not sufficient to represent complex data such as lists, tables, vectors, and.
Advertisements

One Dimensional Arrays
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Lecture 4 Sept 4 Goals: chapter 1 (completion) 1-d array examples Selection sorting Insertion sorting Max subsequence sum Algorithm analysis (Chapter 2)
CS107 Introduction to Computer Science Lecture 5, 6 An Introduction to Algorithms: List variables.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Chapter 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Simple Arrays Programming COMP104 Lecture 12 / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g., a collection.
Data Structures/ Algorithms and Generic Programming Sorting Algorithms.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Scott Marino MSMIS Kean University MSAS5104 Programming with Data Structures and Algorithms Week 10 Scott Marino.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR
C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Chapter 8 Arrays and Strings
1 DATA STRUCTURES: LISTS. 2 LISTS ARE USED TO WORK WITH A GROUP OF VALUES IN AN ORGANIZED MANNER. A SERIES OF MEMORY LOCATIONS CAN BE DIRECTLY REFERENCED.
Examples using Arrays. Summing Squares Problem: To compute the sum of the squares of N numbers N is given N values are also given These should be read.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Min Chen School of Computer Science and Engineering Seoul National University Data Structure: Chapter 2.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
1 Arrays and Vectors Chapter 7 Arrays and Vectors Chapter 7.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
LAB#6. 2 Overview Before we go to our lesson we must know about : 1. data structure. 2.Algorithms. data structure is an arrangement of data in a computer.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Review Sorting algorithms Selection Sort Insertion Sort Bubble Sort Merge Sort Quick Sort.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT9: Pointer I CS2311 Computer Programming.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Multi-dimensional Array 1 Multi-dimensional array refers to an array with more than one index. It is a logical representation. On physical storage, the.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Arrays. C++ Style Data Structures: Arrays(1) An ordered set (sequence) with a fixed number of elements, all of the same type, where the basic operation.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Introduction to Programming Lecture 12. Today’s Lecture Includes Strings ( character arrays ) Strings ( character arrays ) Algorithms using arrays Algorithms.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Objectives You should be able to describe: One-Dimensional Arrays
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
1-d Arrays.
Basic Array Definition
Arrays Kingdom of Saudi Arabia
Arrays Prepared By Paritosh Srivastava PGT (CS) KV NHPC Banbasa.
Presentation transcript:

Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT5: Array (1D and 2D) CS2311 Computer Programming

Syntax Summary 2 Punctuators […]

Example 1 3 Input the marks for 10 students Store the marks in variables Compute the average marks Print the marks of the students and the average The mark of the students are: 100, 30, 44, 66, 50, 60, 80, 75, 80, 100 Average mark=68

The program 4 /*define variables for storing 10 students' mark*/ int mark1, mark2, mark3, mark4, mark5, mark6, mark7, mark8, mark9, mark10, average; /*input marks of student*/ cin >> mark1 >> mark2 >> mark3 >> mark4 >> \\ mark5 >> mark6 >> mark7 >> mark8 >> mark9 >> mark10; /*print the marks*/ cout << “The mark of the students are: “ << mark1 \\ << mark2 << mark3 << mark4 << mark5 << mark6 \\ << mark7 << mark8 << mark9 << mark10 << endl; average=(mark1+mark2+mark3+mark4+mark5 +mark6+mark7+mark8+mark9+mark10)/10; cout << "Average mark"<< average << endl; Is it easy to extend the program to handle more students?

What is an Array? 5 Sequence of data items of the same type Stored contiguously Can be accessed by index, or subscript

Outcomes 6 Array definition Array initialization Updating array elements Printing the content of arrays

Array definition 7 There are ten elements in this array mark[0], mark[1], ……, mark[9] The i th array element is mark[i-1]. The range of the subscript i ranges from 0 to array_size-1 The location mark[10] is invalid. Array out of bound! int mark[10]; Data type of the array element Size of the array Name of the array

Storing values to array elements 8 Suppose the mark for the first student is 30. We can use the notation mark[0] = 30 Reading the marks of the second student cin >> mark[1]; Reading the marks for 10 students for (i=0;i<10;i++) cin >> mark[i];

Retrieving the values of an array element 9 Print the mark of the second student cout << mark[1]; Print and Sum the marks of all the students for (i=0;i<10;i++) { cout << mark[i]; sum += mark[i]; }

Summary of Array Declaration and Access 10 TypeVariableArrayVariable AccessArray Access intint x;int x[20];x=1;x[0]=1 floatfloat x;float x[10];x=3.4;x[0]=3.4; x[9]=1.2; doubledouble x;double x[20];x=0.7;x[0]=0.7; x[3]=3.4; charchar x;char x[5];x='a';x[0]=‘c’; X[1]=‘s’; char x[] = “hello”; Array declaration and initialization

Example 1 (using an integer array with 10 elements) 11 /*define variables for storing10 students' mark*/ int marks[10], sum=0, average; int i; /*input marks of student*/ for (i=0;i<10;i++) cin >> mark[i]; /*print the marks*/ cout << "The mark of the students are:"; for (i=0;i<10;i++) { cout << mark[i]; sum=sum + mark[i]; } /*compute and print the average*/ average=sum/10; cout << "Average mark=“ << average << endl;

Example 2: counting digits 12 Input a sequence of digits {0, 1, 2, …, 9}, which is terminated by -1 Count the occurrence of each digit Use an integer array count of 10 elements count[i] stores the number of occurrence of digit i 9

The program: buggy version 13 #include using namespace std; void main(){ int count[10]; //number of occurrence of digits int digit; //input digit int i; //loop index //read the digits do { cin >> digit; if (digit>=0 && digit<=9)//necessary to avoid out-of-bound count[digit]++; } while(digit != -1); //stop if the input number is -1 //print the occurances for (i=0; i<10;i++){ cout << "Frequency of " << i << " is " << count[i] << endl; }

The actual output (incorrect!) Frequency of 0 is Frequency of 1 is Frequency of 2 is Frequency of 3 is 3 Frequency of 4 is Frequency of 5 is Frequency of 6 is Frequency of 7 is Frequency of 8 is 0 Frequency of 9 is

It's a good practice to initialize arrays 15 Otherwise, the values of the elements in the array is unpredictable. A common way to initialize an array is to set all the elements to zero for (i=0; i<10; i++) count[i]=0;

Array initializer 16 int mark[10]={100, 90}; Define an array of 10 elements, set the 1 st element to 100 and the 2 nd element to 90. We list fewer values than the array size (10). The remaining elements are set to 0 by default To initialize all elements to 0, int mark[10]={0};

Correct program for example 2 17 #include using namespace std; void main(){ int count[10]={0}; //number of occurrence of digits, and initialization int digit; //input digit int i; //loop index //read the digits do { cin >> digit; if (digit>=0 && digit<=9) count[digit]++; } while(digit != -1); //stop if the input number is -1 //print the frequency for (i=0; i<10;i++){ cout << "Frequency of " << i << " is " << count[i] << endl; }

Array Initialization Summary 18 Only fixed-length arrays can be initialized when they are defined. Variable length arrays must be initialized by inputting or assigning the values.

Example 3: Comparing 2 arrays 19 We have two integers arrays, each with 5 elements int array1[5]={10, 5, 3, 5, 1}; int array2[5]; The user inputs the values of array2 Compare whether all of the elements in array1 and array2 are the same

Array equality 20 Note that you have to compare array element 1 by 1. The following code generates incorrect results if (array1 == array2) cout << "The arrays are equal "; else cout << "The arrays are not equal ";

The Program 21 void main(){ int array1[5]={10, 5, 3, 5, 1}; int array2[5]; int i; bool arrayEqual=true; cout << "Input 5 numbers\n"; for (i=0;i<5;i++) cin >> array2[i]; for (i=0; i<5 && arrayEqual; i++){ if (array1[i]!=array2[i]){ arrayEqual=false; } if (arrayEqual) cout << "The arrays are equal"; else cout << "The arrays are not equal"; } Input 5 numbers The arrays are equal Input 5 numbers The arrays are not equal

Example 4: Searching 22 Read 10 numbers from the user and store them in an array User input another number x. The program checks if x is an element of the array If yes, output the index of the element If no, output -1

23 Searching for the rabbit (Case I) Search sequentially If found, skip the rest

24 Searching for the rabbit (Case II)

Searching for x=15 (Case 1) 25 Output i=2 break out of the loop Suppose N=6

Searching for x=8 (Case 2) 26 Output -1

The program 27 void main() { const int N = 6; int a[N], i, x, position = -1; for (i=0; i<N; i++) cin >> a[i]; cout << "Input your target: "; cin >>x; for (i=0; i<N; i++) if (a[i] == x) { position=i; break; } if (position == -1) cout << "Target not found!\n"); else cout << "Target found at position“ << position << endl; }

Example 5: Sorting One of the most common applications in CS is sorting arranging data by their values: {1, 5, 3, 2}  {1, 2, 3, 5} There are many algorithms for sorting Selection Sort Bubble Sort Insertion Sort Quick Sort Quicker Sort Merge Sort Heap Sort Based on iteratively swapping two elements in the array so that eventually the array is ordered. The algorithms differ in how they choose the two elements. 28 "Classic" sorting algorithms Faster, more complex sorting algorithms

Bubble Sort In each pass, start at the end, and swap neighboring elements if they are out of sequence ("bubbling up"). After i passes, the first i elements are sorted. 29 Sorted Bubbling Outer Loop (Pass) Inner Loop (Bubbling) Original After Pass 1

Bubble Sort 30 bubble-sort dance: insert-sort dance:

CS2363 A 31 void main() { const int n = 10; int a[n], j, k, tmp; cout <<"Input" << n <<" numbers: "; for (j=0; j<n; j++) cin >> a[j]; for(j=0; j<n-1; j++) // outer loop for(k=n-1; k>j; k--) // bubbling if (a[k]<a[k-1]) { tmp = a[k]; // swap neighbors a[k] = a[k-1]; a[k-1] = tmp; } cout << "Sorted: "; for(j=0; j<n; j++) cout << a[j]; } a[j] Bubble Sort

Multi-dimensional Array 32 Multi-dimensional array refers to an array with more than one index. It is a logical representation. On physical storage, the multi-dimensional array is same as single dimensional array (stored contiguously in memory space) To define a two-dimensional array, we specify the size of each dimension as follows int page [30][100];//[row][column] In C++, the array will be stored in the “row-major” order, i.e. first block of memory will be used to store page [0][0] to page [0][99], the next block for page [1][0] to page [1][99]

33

Multi-dimensional Array 34 To access an element of the array, we specify an index for each dimension: cin >> page [i][j];//[row][column] The above statement will input an integer into row-i and column –j of the array. When passing a multi-dimensional array into a function, the size of all dimensions except the first must be specified. The function below can take any two-dimensional integer array with size 100 in the second dimension (size of first dimension is specified in parameter size1 void display (int a[][100], int size1)

BMI Program 35 void main() { const int N=10; float data[N][2];// N records, each record holds weight and height int i, position; for (i=0; i<N; i++){ cout << "Weigth(kg) Height(m):"; cin >> data[i][0]; cin >> data[i][1]; } for (i=0; i<count; i++){ cout << "BMI for " << i+1 << “is :”; cout << data[i][0]/(data[i][1]*data[i][1]) << endl; }

Summary 36 Array is a sequence of variables of the same data type Array elements are indexed and can be accessed by the use of subscripts, e.g. array_name[1], array_name[4] Array elements are stored contiguously in memory space Array Declaration, Initialization, Searching and Sorting Array can be Multi-dimensional, i.e. 1D, 2D