BITG 1113: Array (Part 1) LECTURE 8

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

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

TWO DIMENSIONAL ARRAY OR MATRIX common name scores Defined as scores[10][5] IE 10 rows x 5 columns showing name of each position; some values below

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

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

Chapter 01 Arrays Prepared By: Dr. Murad Magableh 2013

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays

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

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

C++ PROGRAMMING SKILLS Part 4: Arrays

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Arrays. Week 4. Assylbek Jumagaliyev

The University Of Michigan. EECS402 Lecture 05. Andrew M. Morgan. Savitch Ch. 5 Arrays Multi-Dimensional Arrays. Consider This Program

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. A single variable can only hold one value. Declared using [] operator:

CS242 COMPUTER PROGRAMMING

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

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

1. In C++, reserved words are the same as predefined identifiers. a. True

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

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

CMPS 221 Sample Final

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

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

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

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

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

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

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Declaring a 2D Array

Week 3: Pointers (Part 2)

Problem Solving: Storyboards for User Interaction

Chapter 6 Pointers and Arrays

Pointers. Variable Declaration. Chapter 10

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Objectives. In this chapter, you will:

ARRAYS(II Unit Part II)

Computer Department. Question (1): State whether each of the following is true or false. Question (2): Select the correct answer from the following:

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

CSC 126 FINAL EXAMINATION Spring Total Possible TOTAL 100

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Lab #10 Multi-dimensional Arrays

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

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

Exam 3 Chapters 7 & 9

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 1 Basic Elements of C++

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

Lecture 3 Tao Wang 1

Computer Programming : C++

Why Is Repetition Needed?

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

Array Part dimensional arrays - 2-dimensional array operations - Arrays of Strings - N-dimensional arrays

Lab Instructor : Jean Lai

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

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

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

9.1 The Array Data Type. Data Structures Arrays and Structs. Arrays. Arrays. Array Declaration. Arrays. Array elements have a common name

Chapter 2 Basic Elements of C++

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

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

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

Chapter 4 - Notes Control Structures I (Selection)

Sample Code: OUTPUT Daily Highs & Lows

Practice Exercises #8

1. To introduce and allow students to work with arrays 2. To introduce the typedef statement 3. To work with and manipulate multidimensional arrays

Computer Science II Lecture 2 Strings, Vectors and Recursion

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

Functions, Arrays & Structs

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

BITG 1113: Function (Part 2) LECTURE 5

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

BITG 1233: Introduction to C++

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

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

Chapter 7 - Notes User-Defined Functions II

Fundamentals of Programming CS-110. Lecture 2

The C++ Language. Arizona State University 1

1 Unit 8 'for' Loops

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

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

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

Increment and the While. Class 15

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

BITG 1113: Array (Part 2) LECTURE 9

Arrays. Arizona State University 1

CS2255 HOMEWORK #1 Fall 2012

Getting started with C++ (Part 2)

EP241 Computing Programming

C++ Programming: From Problem Analysis to Program Design, Third Edition

Programming Language. Functions. Eng. Anis Nazer First Semester

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Principles of Programming. Chapter 6: Arrays

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

3/12/2018. Structures. Programming in C++ Sequential Branching Repeating. Loops (Repetition)

Lab # 02. Basic Elements of C++ _ Part1

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology

Transcription:

BITG 1113: Array (Part 1) LECTURE 8 1 1

LEARNING OUTCOMES At the end of this lecture, you should be able to: 1. Describe the fundamentals of arrays 2. Describe the types of array: One Dimensional (1 D) and Two Dimensional (2 D) 3. Write declaration, initialization and assignment 4. Manipulate data in arrays (operations on arrays) 5. Explore the applicability of arrays 2 2

WHAT IS AN ARRAY? 3 Array of bugs An array is a derived data type (derived from fundamental data type) It is a group of a fixed number of elements (values or variables) of the same data type, placed in consecutive memory locations that are acessed or referenced using the array name and a subscript (or also known as index). If the name of an array of 10 elements is ARY, then its elements will be referenced as : ARY[0], ARY[1], ARY[2],, ARY[9] WHY ARRAY? Array is used to store a large number of values of the same data type under a single variable. That means, for example, using an array we can store 5 different values of the same type (int for example) with ONE unique identifier without having to declare 5 different variables. E.g.: To store the Marks of 50 students. To record the Sales of 100 salesman.

BASIC OPERATIONS ON ARRAY Some basic operations performed on arrays are: Initializing elements of array Input data to an array Output data stored in an array Finding the largest and/or smallest element Computations Each operation requires ability to step through the elements of the array Easily accomplished by a for loop. 44

TYPES OF ARRAY : THE MEANING OF DIMENSION Types of array: One dimensional (1-D), Two dimensional (2-D), etc. The dimension of an array is the number of indices (subscripts) needed to select an element. Thus a one-dimensional array is a list of data, a twodimensional array a rectangle of data, a threedimensional array a block of data, etc. Like a regular variable, an array must be declared before it is used. Array is declared using [ ] operator. 5

THE DIMENSIONS OF ARRAY 1-D array: with 10 elements. 2-D array: with 20 elements (4 x 5) 3-D array with: 24 elements(2x3x4) 3-Dimensional 6

1-D ARRAY : DECLARATION AND MEMORY LAYOUT Declaration Syntax: data_type array_name[size]; (Note :number of elements in the array) Example: (Note: size declarator - is an integer constant > 0) int number[5]; allocates the following memory to the elements of array number: SUBSCRIPT number [0] [1] [2] [3] [4]????? first element second element third element fourth element fifth element 7 In C++ the subscript of the first element is always 0.

8 1-D ARRAY : DECLARATION AND MEMORY LAYOUT

1 D ARRAY DECLARATION IN C++ PROGRAM : EXAMPLES #include <iostream> a) #define SIZE 20 b) using namespace std; int main() { int Marks[SIZE]; char Names[20]; } Execution statements #include <iostream> using namespace std; int main() { const int SIZE = 20; } int Marks[SIZE]; char Names[20]; Execution statements 9 * SIZE : is a size declarator; it must be a constant. ** It is advisable to use named constant as size declarator. This eases program maintenance when the size of the array needs to be changed.

1 D ARRAY INITIALIZATION Initial values are given to the array elements during array declaration. Examples on array initialization: char vowels[5] = {'a', 'e', 'i', 'o', 'u'}; bool anskey[] ={true, true, false, true, false, false}; char word[] = "Hello"; vowels 'a' 'e' 'i' 'o' 'u' anskey true true false true false false word 'H' 'e' 'l' 'l' 'o' '\0' 10

1 D ARRAY INITIALIZATION int scores[9] = {23,45,12,67,95,45,56,34,83}; 11

12 1 D ARRAY INITIALIZATION : SOME VARIATIONS

1-D ARRAY : ACCESSING ARRAY ELEMENTS Subscripts are used to access individual elements of an array. General format to access an array element: array_name[subscript] Example: const int size = 5; double number[size]; for (int i=0; i<=4; ++i) number[i] = double(i) + 0.5; From the above statements, each element of the array is accessed and assigned with a value as follows : 13 number 0.5 1.0 1.5 2.0 2.5

1-D ARRAY : ACCESSING ARRAY ELEMENTS Array elements can be accessed and used as regular variables, such as the following: numbers[0] = 79.5; cout << numbers[0]; cin >> numbers[1]; numbers[4] = numbers[0] + numbers[1]; Arrays must be accessed via individual elements: cout << numbers; // not legal We can copy an array to another array with the same size and type but it is not legal to assign one array to another as shown below : Example: 14 int num1[5]={1,2,3,4,5}; int num2[5]; num2 = num1; //error

CONT ASSIGNING VALUES TO 1-D ARRAY Example : to copy elements of num1 into num2. int num1[5] = {1,2,3,4,5}, num2[5]; for(int i =0 ; i<5; i++) { num2[i]= num1[i]; //correct } 15

MORE EXAMPLES : ASSIGNING VALUES TO 1-D ARRAY int num[5]; int list[10]; 16

INPUT DATA TO 1-D ARRAY Beside Assignment or Initialization, another way to fill the array is by inputting values (read) Can be done using a loop the most appropriate is the for loop int scores[9]; for (i=0;i<9;i++) { cin >> scores[i]; } The input are: 23 45 12 67 95 45 56 34 83 <enter> 17 17

DISPLAY DATA STORED IN 1-D ARRAY for (i=0; i<9; i++) { cout <<scores[i]<< \n ; } Output: 18 18 23 45 12 67 95 45 56 34 83

EXAMPLE OF 1-D ARRAY FLOWCHART int main() { for ( int i = 0; i < 20; i++) cin >> numbers[i]; for ( int i = 0; i < 20; i++) cout << numbers[i]; 19 }

#include <iostream> #include <iomanip> using namespace std; EXAMPLE : INPUT AND OUTPUT OF 1-D ARRAY int main() { int i, a[5]={2,4,6,8,10}, b[5], c[5]; cout<< Enter 5 numbers:\n ; for(i=0; i<5; i++) cin >> b[i]; cout<< setw(15)<< a << setw(10) << b << setw(10) << c << endl; 20 } for(i=0; i<5; i++) { c[i]= a[i] + b[i]; cout<< setw(15) << a[i] << setw(10) << b[i] << setw(10) << c[i] <<endl; } return 0; 20

Output : Enter 5 numbers: 1 2 3 4 5 ary1 ary2 ary3 2 1 3 4 2 6 6 3 9 8 4 12 10 5 15 21 21

EXAMPLE : DETERMINE THE MINIMUM VALUE #include <iostream> using namespace std; void main() { int i, score[5], min; } 22 cout<< Enter 5 scores:\n ; for(i=0; i<5; i++) cin >> score[i]; min = score[0]; Output : for(i=1; i<5; i++) { if(score[i] < min ) min = score[i]; } cout<< The lowest score is << min; Enter 5 scores: 85 60 55 78 95 The minimum score is 55 22

OPERATIONS ON ARRAY : MORE EXAMPLES 23

EXCHANGING VALUES IN 1-D ARRAY : THE INCORRECT WAY Problem: To exchange the values between number[1] and number[3] 24 24

THE CORRECT WAY - USING TEMPORARY VARIABLE 25 25

EXAMPLE : EXCHANGING VALUES #include <iostream> using namespace std; int main() { int temp; int numbers[5] = {3,7,12,24,45}; cout << "Before exchange the value :"<< endl; for(int i=0; i<5; i++) cout << numbers[i] << ' '; temp = numbers[3]; numbers[3] = numbers[1]; numbers[1] = temp; cout<<"\nafter exchange the value :"<<endl; for(int i=0; i<5; i++) cout << numbers[i] << ' '; 26 26 } cout << endl; return 0;

TWO-DIMENSIONAL ARRAYS A two dimensional array stores a fixed number of data as a collection of rows and columns. Sometimes called matrices or tables. Each element of a two-dimensional array has a row position and a column position. The declaration of a two-dimensional array requires a row size and a column size. Declaration syntax: data_type array_name[row_size][column_size]; 27 27 o where row_size and column_size are expressions with positive integer values, and specify the number of rows and the number of columns, respectively, in the array. o Note :number of elements in the array = row_size X column_size

DECLARATION OF 2-D ARRAY First dimension specifies the number of rows in the array Second dimension specifies the number of columns in each row A consecutive block of 50 (row size X column size) memory locations are allocated. 28 28

2-D ARRAY : DECLARATION AND MEMORY LAYOUT The statement int table [5][4]; means array table is an array of one-dimensional array (two-dimensional array) COLUMN SUBSCRIPT [0] [0] [1] [2] [3] [1] ROW SUBSCRIPT [2] [3] [4] 29 29 Array_name

30 30 MEMORY LAYOUT OF 2-D ARRAY

EXAMPLE: DECLARATION OF 2-D ARRAY int data[2][3]; row column [ 0 ] [ 1 ] [ 0 ] [ 1 ] [ 2 ]?????? data 31

2-D ARRAY: DECLARATION AND INITIALIZATION 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, if all elements of a row aren t specified, unspecified ones are set to 0. 32 32

2-D ARRAY: DECLARATION AND INITIALIZATION double t[2][2] = { {0.1,0.2}, {1.1, 1.2} }; [ 0 ] [ 1 ] [ 0 ] [ 1 ] 0.1 0.2 1.1 1.2 t 33 33

2-D ARRAY: DECLARATION AND INITIALIZATION Initialization : Some variations int table [5][4] = {0,1,2,3,10,11,12,13,20,21,22,23,30,31,32, 31,40,41,42,43}; int table [5][4] = {{0,1,2,3},{10,11,12,13},{20,21,22,23}, {30,31,32,31},{40,41,42,43}}; int table [5][4] = {{0,1},{10},{20,21,22},{30},{40,41,42,43}}; 34 34

2-D ARRAY : ACCESSING ARRAY ELEMENTS The name of the array holds the address of the first element of the array. To access an element in a two-dimensional array, you must specify the name of the array followed by: a row subscript, and a column subscript General format to access a 2-D array element: array_name[row_subscript][column_subscript] Nested for loops are often used when accessing elements of a two-dimensional array. 35 35

EXAMPLE : ASSIGNING DATA VALUE TO ARRAY ELEMENT. 36

EXAMPLE : ASSIGNING DATA VALUE TO ARRAY ELEMENTS. Let us assume that we want to assign our 5 x 4 array as shown below. 0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 40 41 42 43 The following code will perform the assignment : int table[5][4]; for(int r=0;r<5;r++) for(int c=0;c<4;c++) table[r][c]= r * 10 + c ; 37 37

EXAMPLE : ASSIGNING DATA VALUE TO ARRAY ELEMENTS. To assign the fifth row to 0: To assign the entire matrix to 0: 38 38

EXAMPLE : ASSIGNING DATA VALUE TO ARRAY ELEMENTS. int v[rsize][csize]; for (int i=0; i<rsize; ++i) //every row for (int j=0; j<csize; ++j )//every col v[i][j] = i+j; [ 1 ] [ 2 ] [ 0 ] [ 1 ] [ 2 ] 0 1 1 2 2 3 39 39 V

EXAMPLE : INPUT DATA VALUES TO 2-D ARRAY ELEMENTS. double table[rsize][csize]; for (int i=0; i<rsize; ++i) //every row for (int j=0; j<csize; ++j )//every col cin >> table[i][j]; for(int r=0;r<5;r++) for(int c=0;c<4;c++) cin >> table[r][c]; 40 40

COMPUTATION AND OUTPUT The for statement is useful when performing computations on arrays. The index variable of the for statement can be used as an array subscript. Computations can be easily performed on an entire two-dimensional array, or on a sub set of the array. 41 41

COMPUTATIONS Compute the average of an array with n rows and m columns. for(int i=0; i<n; ++i) { for(int j=0; j<m; ++j) { sum += array[i][j]; } } average = sum/(n*m); 42 42

COMPUTATIONS Compute the average of the nth row of a twodimensional array with r rows and c columns. for(int col=0; col < c; ++col) { sum += array[n][col]; } rowaverage = sum/c; 43 43

OUTPUT Two dimensional arrays are often printed in a row by row format, using nested for statements. When printing the row values of an array, be sure to print: whitespace (blank space) between the values in a row. a newline character at the end of each row. 44 44

DISPLAYING DATA VALUE OF ARRAY ELEMENTS. int table [5][4] = {{0,1,2,3},{10,11,12,13},{20,21,22,23}, {30,31,32,31},{40,41,42,43}}; for(int r=0;r<5;r++) { for(int c=0;c<4;c++) cout << table[r][c] << ; cout << endl; } 45 45

#include <iostream> #include <iomanip> using namespace std; EXAMPLE: TWO DIMENSIONAL ARRAY int main() { int i,j, a[4][3]; for(i = 0; i < 4; i++) { cout << "Enter 3 numbers for row " << i+1 << " : "; for(j = 0; j < 3; j++) cin >> a[i][j]; cout << endl; } cout<<"elements of array are : "<<endl; 46 } for(i = 0; i < 4; i++) { for(j = 0; j < 3; j++) cout << setw(5) << a[i][j] ; cout << endl; } return 0; 46

EXERCISES 1) Find the output of the following codes: int row = 3; int col = 3; int mark[row][col] = {{1,2,3}, {4,5,6}, {7,8,9}}; cout<<mark[1][1]<<endl; cout<<mark[2][1]<<endl; cout<<mark[3][3]<<endl; 4747 47

2) Find the output of these codes: 48 #define Row 3 #define Col 3 int main() { int i, j; int xyz[row][col] = {{1,2,3}, {4,5,6},{7,8,9}}; for (i = 0; i < Row; i++) for (j = 0; j < Col; j++) cout << xyz[i][j]<<endl; return 0; } // end main

3) Problem : Write a program to enter five names with the maximum length of each name is 25 characters. The program then displays the name in the reverse order of entry. This means that the last name will be displayed first, followed by the fourth, and so on. - END - 49