Basic Array Definition

Slides:



Advertisements
Similar presentations
CHAPTER 10 ARRAYS II Applications and Extensions.
Advertisements

Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT5: Array (1D and 2D) CS2311 Computer Programming.
TK1914: C++ Programming Array II. Objective In this chapter you will explore how to manipulate data in a two-dimensional array. 2FTSM :: TK1914,
Arrays Programming COMP102 Prog. Fundamentals I: Arrays / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g.,
Simple Arrays COMP104 Lecture 11 / Slide 2 Arrays * An array is a collection of data elements that are of the same type (e.g., a collection of integers,characters,
1 Lecture 21:Arrays and Strings(cont.) Introduction to Computer Science Spring 2006.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
 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.
Chapter 9: Arrays and Strings
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.
1 Lecture 22:Applications of Arrays Introduction to Computer Science Spring 2006.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR
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.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Chapter 9: Arrays J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second Edition.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
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.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Sahar Mosleh California State University San MarcosPage 1 One Dimensional Arrays: Structured data types.
 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.
Opening Input/Output Files ifstream infile; ofstream outfile; char inFileName[40]; char outFileName[40]; coutinFileName;
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Introduction to Programming Lecture 12. Today’s Lecture Includes Strings ( character arrays ) Strings ( character arrays ) Algorithms using arrays Algorithms.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Arrays Chapter 7.
Chapter 6 Arrays in C++ 2nd Semester King Saud University
EGR 2261 Unit 10 Two-dimensional Arrays
EGR 2261 Unit 9 One-dimensional Arrays
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
Computer Programming BCT 1113
Siti Nurbaya Ismail Senior Lecturer
Arrays … The Sequel Applications and Extensions
Programming -2 برمجة -2 المحاضرة-5 Lecture-5.
7 Arrays.
Arrays Kingdom of Saudi Arabia
EKT150 : Computer Programming
Review for Final Exam.
Review of Arrays and Pointers
Lecture 9 Objectives Learn about arrays.
Data Structures (CS212D) Week # 2: Arrays.
Arrays Topics to cover: Arrays Data Types One-dimensional Arrays
Engineering Problem Solving with C++, Etter
COMS 261 Computer Science I
Review for Final Exam.
7 Arrays.
Capitolo 4 - Arrays Outline 4.1 Introduction 4.2 Arrays
Arrays Arrays A few types Structures of related data items
COMS 261 Computer Science I
Dr. Khizar Hayat Associate Prof. of Computer Science
Presentation transcript:

Basic Array Definition // Subscripts are 0 through 99

Example Definitions Suppose const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000; Then the following are all correct array definitions int A[10]; // array of 10 ints char B[MaxStringSize]; // array of 80 chars double C[M*N]; // array of 800 floats int Values[MaxListSize]; // array of 1000 ints Rational D[N-15]; // array of 5 Rationals

Subscripting Suppose int A[10]; // array of 10 ints A[0], … A[9] To access individual element must apply a subscript to list name A A subscript is a bracketed expression also known as the index First element of list has index 0 A[0] Second element of list has index 1, and so on A[1] Last element has an index one less than the size of the list A[9] Incorrect indexing is a common error A[10] // does not exist

Array Elements Suppose int A[10]; // array of 10 uninitialized ints To access an individual element we must apply a subscript to list name A

Array Element Manipulation Consider int i = 7, j = 2, k = 4; A[0] = 1;

Array Element Manipulation Consider int i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5;

Array Element Manipulation Consider int i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5; A[j] = A[i] + 3;

Array Element Manipulation Consider int i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5; A[j] = A[i] + 3; A[j+1] = A[i] + A[0];

Array Element Manipulation Consider int i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5; A[j] = A[i] + 3; A[j+1] = A[i] + A[0]; A[A[j]] = 12;

Array Element Manipulation Consider int i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5; A[j] = A[i] + 3; A[j+1] = A[i] + A[0]; A[A[j]] = 12; cin >> A[k]; // where next input value is 3

Array Initialization During Declaration suppose int x[10] = {8,5,4} x = {8,5,4,0,0,0,0,0,0,0} int y[10] = {0} y = {0,0,0,0,0,0,0,0,0,0}

Array Element Manipulation For loop is the typical construct to be used for array element manipulation Declare and initializes a double type array of ten elements with 10.0 stored at each index/location of the array, use for loop for initialization double arr1[10]; for (int index= 0; index<10; index++) arr1[index] = 10.0;

Array As an Entity Suppose int x[10]; int y[10]; y = x; illegal cin>>x; illegal cout<<y illegal if (x<=y) ... illegal

Array Element Input/Output To fill an array from user’s input double arr1[10]; for (int index= 0; index<10; index++) cin>>arr1[index]; To output an array onto the screen cout<<arr1[index] <<“ “;

Array Element Manipulation Write down a code that declares two double type arrays of 10 elements each, it gets them initialized from the user and finally decides and prints whether the arrays are equal or not.

Array Element Manipulation double arr1[10]; double arr2[10]; for (int index= 0; index<10; index++) { cin>>arr1[index]; cin>>arr2[index]; } if (arr1[index] != arr2[index] ...

Printing in reverse order using arrays How to print an array in the reverse order

Printing in reverse order using arrays int main() { int item[5]= {5,6,7,8,9}; //Declare an array item of five //components for (counter = 4; counter >= 0; counter--) cout << item[counter] << " "; cout << endl; return 0; }

How to check whether an Array is sorted Write down a code that checks whether an array (named arr2 of 10 ints, already initialized) is already sorted in ascending order or not.

How to check whether an Array is sorted int arr2[10]; …//array initialized bool sorted = true; for (int index=0; index<9; index++) { if (arr2[index + 1]<arr2[index]) {sorted = false; break; }

(Generic and complete code) const int size = 5; int arr2[size]= {1,2,3,4,5}; bool sorted = true; for (int index=0; index<size-1; index++) { if (arr2[index +1]<arr2[index]) {sorted = false; break; }

(Generic and complete code) if (sorted==true) cout<< "sorted"; else cout<< "unsorted";

Max of an array How to start? Write down a code that finds out the element having maximum value within the array, the code finds out the location of the max as well. How to start?

Max of an array const int listSize= 100; int list[listSize]; int index; for (index = 0; index < listSize; index++) cin>>list[index]; int maxIndex = 0; //Assume the first element is the largest for (index = 1; index < listSize; index++) if (list[maxIndex] < list[index]) maxIndex = index; cout<<list[maxIndex]<<“ “<< maxIndex;

Sorting of Arrays Bubble Sort (Ascending order) Compare the first element with the second one, swap if second is smaller Do the same process with element 2 and 3, and so on, till the end of the array (Name this process as a “Pass”) Choose the worst case that is an array already sorted in descending order to find out the number of passes Choose the following array to apply the above algorithm {9, 8,7, 5, 4, 3, 2, 1} Find out the number of comparisons/pass and no. of passses

Sorting of arrays 9 8 6 4

Sorting of arrays 8 9 6 4

Sorting of arrays 8 6 9 4

Sorting of arrays 8 6 4 9 One “Pass” completed

Sorting of arrays 8 6 4 9

Sorting of arrays 6 8 4 9

Sorting of arrays 6 4 8 9

Sorting of arrays 6 4 8 9 2nd “Pass” completed

Sorting of arrays 6 4 8 9

Sorting of arrays 4 6 8 9

Sorting of arrays 4 6 8 9

Sorting of arrays 4 6 8 9 3rd “Pass” completed. Sorting completed.

Sorting (Bubble Sort) int main() { const int arraySize = 10; int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; int hold; // temporary variable // bubble sort // loop to control number of passes for ( int pass = 0; pass < arraySize - 1; pass++ ) // loop to control number of comparisons per pass for ( int j = 0; j < arraySize - 1; j++ )

Sorting (Bubble Sort) // compare side-by-side elements and swap them if // first element is greater than second element if ( a[ j ] > a[ j + 1 ] ) { hold = a[ j ]; a[ j ] = a[ j + 1 ]; a[ j + 1 ] = hold; } // end if return 0; } // end main

Base Address of a Function int main() { int myList[5] = {0, 2, 4, 6, 8}; int yourList[5]; cout << "Line 3: Base address of myList: " << myList << endl; return 0; }

Base Address of a Function A sample run of this program is: // Line 3: Base address of myList: 0012FEC4 This is hexadecimal representation of the binary number 00000000000100101111111011000100 The decimal representation of this number is 1,244,868

Passing Arrays to Functions Passed by reference only The symbol & not used Normally size of the array also passed as another int type variable Functions cannot return a value of type array

Passing Arrays to Functions const int ARRAY_SIZE = 10; void fillArray(int x[],int sizeX); int main() { int listA[ARRAY_SIZE] = {0}; fillArray(listA, ARRAY_SIZE); return 0; } void fillArray(int list[], int listSize) { int index; for (index = 0; index < listSize; index++) cin >> list[index]; }

Passing Arrays to Functions We can prevent an array from being changed by the function being called by using the reserve word “const”

Passing Arrays to Functions const int ARRAY_SIZE = 10; int sumArray(const int x[],int sizeX); void fillArray(int x[],int sizeX); void copyArray(const int x[], int y[], int length); int main() { int listA[ARRAY_SIZE] = {0}; int listB[ARRAY_SIZE]; fillArray(listA, ARRAY_SIZE); cout << sumArray(listA, ARRAY_SIZE) << endl; copyArray(listA, listB, ARRAY_SIZE); return 0; }

Passing Arrays to Functions int sumArray(const int list[], int listSize) { int index; int sum = 0; for (index = 0; index < listSize; index++) sum = sum + list[index]; return sum; } void copyArray(const int listOne[], int listTwo[], int listOneSize) for (index = 0; index < listOneSize; index++) listTwo[index] = listOne[index];

Character Arrays Character Array: An array of Characters Can be declared by user Its size is determined by the user’s statement E.g. char name[5]= {‘A’, ‘l’, ‘i’} char name[5]=“Ali” char name[]=“Ali”

C Strings A predefined data type in C++, that is similar to character arrays, but has the following differences Size of strings is automatic A string always terminates at null character (‘\0’) We shall use the concept of character arrays and strings interchangeably therefore we redefine the previous examples as follows char name[5]= {‘A’, ‘l’, ‘i’, ‘\0’} char name[5]=“Ali” char name[]=“Ali” Now we can treat them as strings

Length of the character array Write down a code segment that finds out and displays the length (excluding the null character), of a character array. character array is obviously null terminated and defined and initialized somewhere else in the code. int len =0; while (arr1[len] != '\0') { len++; }

Question Write down a code segment that finds the smallest number present in five different int arrays. The arrays are already initialized and have the names arr1 having arrSize1 arr2 having arrSize2 and so on Last array is arr5 having arrSize5 Use a general function smallestNumber to find the smallest within an array. You can use this function repeatedly to solve the problem. You can use a temporary array having size equal to 5, if required. Do not declare or initialize the actual five arrays, they are already declared and initialized.

Two dimensional arrays A collection of fixed number of components arranged in rows and columns dataType arrayName[int rows][int cols] For example double sales[10][5]

Two dimensional arrays [0][0] [0][1] [0][2] [0][3] [0][4] [1][0] … [9][4]

Two dimensional arrays (Initialization) const int NUMBER_OF_ROWS = 6; const int NUMBER_OF_COLUMNS = 5; int board[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS] = {0}; 0 0 0 0 0

Two dimensional arrays (Initialization) const int NUMBER_OF_ROWS = 6; const int NUMBER_OF_COLUMNS = 5; int board[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS] = {{23, 5}, {4, 16, 24, 67, 10}, {12, 54, 23, 76, 11}, {1, 12, 34, 22, 8}, {81, 54, 32, 67, 33}, };

Two dimensional arrays (Initialization) 23 5 0 0 0 4 16 24 67 10 12 54 23 76 11 1 12 34 22 8 81 54 32 67 33 0 0 0 0 0

Two dimensional arrays (Printing) Write down code to print the above mentioned two dimensional array if a difference of 5 spaces is to be printed between two adjacent row elements. int row, col; for (row = 0; row < NUMBER_OF_ROWS; row++) { for (col = 0; col < NUMBER_OF_COLUMNS; col++) cout << setw(5) << board[row][col] << " "; cout << endl; }

Two dimensional arrays (Printing) Write down code to print the above mentioned two dimensional array into a file. int row, col; ofstream o; o.open("d:\\twodARR2.txt"); for (row = 0; row < NUMBER_OF_ROWS; row++) { for (col = 0; col < NUMBER_OF_COLUMNS; col++) o << setw(5) << matrix[row][col] << " "; o << endl; }

Two dimensional arrays int row, col; int X; for (row = 0; row < NUMBER_OF_ROWS; row++) { X = 0; for (col = 0; col < NUMBER_OF_COLUMNS; col++) X = X + matrix[row][col]; cout << X<< endl; } Sum of each individual row

Two dimensional arrays int row, col; int x; for (row = 0; row < NUMBER_OF_ROWS; row++) { x = matrix[row][0]; for (col = 1; col < NUMBER_OF_COLUMNS; col++) if (x < matrix[row][col]) x = matrix[row][col]; cout << x << endl; } Largest element in each row

Two dimensional arrays (diagonal reversing algo ) 1 2 3 4

Two dimensional arrays (diagonal reversing algo ) 4 2 3 1

Two dimensional arrays (diagonal reversing algo ) 4 3 2 1

Two dimensional arrays (diagonal reversing algo ) for (row=0; row<ROWS/2; row++){ temp = matrix[row][row]; matrix[row][row] = matrix[ROWS-1-row][ROWS-1-row]; matrix[ROWS-1-row][ROWS-1-row] = temp; }

Passing Two D Arrays to Functions C++ stores a 2d array as if it is a collection of 1d arrays placed row wise with in the memory Therefore the function call must have the number of columns within it e.g. Consider the following function definition void funone(int table[][5], int rowSize) i.e A two d array having 5 columns is accepted as a parameter. Row size comes as a separate parameter.

Passing Two D Arrays to Functions const int ROWS = 6; const int COLUMNS = 5; void printMatrix(int matrix[][COLUMNS], int ROWS); void sumRows(int matrix[][COLUMNS], int ROWS); void largestInRows(int matrix[][COLUMNS], int ROWS); int main() { int board[ROWS][COLUMNS] = {...}; printMatrix(board, ROWS); sumRows(board, ROWS);

Passing Two D Arrays to Functions void sumRows(int matrix[][COLUMNS], int noOfRows) { int row, col; int sum; for (row = 0; row < noOfRows; row++) sum = 0; for (col = 0; col < COLUMNS; col++) sum = sum + matrix[row][col]; cout << "Sum of row " << (row + 1) << " = " << sum<< endl;