Arrays and Matrices.

Slides:



Advertisements
Similar presentations
Etter/Ingber Arrays and Matrices. Etter/Ingber One-Dimensional Arrays 4 An array is an indexed data structure 4 All variables stored in an array are of.
Advertisements

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.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Introduction to Arrays.
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.,
Friday, December 29, 2006 Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration. - Stan Kelly-Bootle.
1 CS 201 Array Debzani Deb. 2 Having trouble linking math.h? Link with the following option gcc –lm –o test test.o.
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
Chapter 8 Multidimensional Arrays C Programming for Scientists & Engineers with Applications by Reddy & Ziegler.
Programming Arrays. Question Write a program that reads 3 numbers from the user and print them in ascending order. How many variables do we need to store.
1 Arrays and Matrices Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Programming Arrays. Example 1 Write a program that reads 3 numbers from the user and print them in reverse order. How many variables do we need to store.
Copyright © 2012 Pearson Education, Inc. Chapter 8 Two Dimensional Arrays.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Chapter 8 Arrays and Strings
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
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.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 3.
Two-Dimensional Arrays ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne.
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.
Computer programming Outline Arrays [chap 7 – Kochan] –The concept of array –Defining arrays –Initializing arrays –Character.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
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.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
Computer Programming for Engineers
CSE 251 Dr. Charles B. Owen Programming in C1 Intro to Arrays Storing List of Data.
Opening Input/Output Files ifstream infile; ofstream outfile; char inFileName[40]; char outFileName[40]; coutinFileName;
© Janice Regan, CMPT 128, January CMPT 128: Introduction to Computing Science for Engineering Students Introduction to Arrays.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Arrays and Matrices. One-Dimensional Arrays An array is an indexed data structure All variables stored in an array are of the same data type An element.
Arrays. Arrays are objects that help us organize large amounts of information.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
1 Midterm 1 Review. 2 Midterm 1 on Friday February 27 Closed book, closed notes No computer can be used 50 minutes 4 or 5 questions write full programs.
1 5.1 One-Dimensional Arrays Suppose, you need to store years of 100 cars. Will you define 100 variables? int y1, y2,…, y100; An array is an indexed data.
1 Agenda Arrays: Definition Memory Examples Passing arrays to functions Multi dimensional arrays.
1-d Arrays.
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. System.out.println(“Please enter grade.
2-D Array.
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
Computer Programming BCT 1113
Lecture 7 Arrays 1. Concept of arrays Array and pointers
C programming---Arrays
Chapter 6 Arrays Lecturer: Mrs Rohani Hassan
Chapter 5 Arrays and Matrices
MULTI-DIMENSIONAL ARRAY
Array 9/8/2018.
INC 161 , CPE 100 Computer Programming
Two Dimensional Arrays
Lecture Arrays.
Engineering Problem Solving with C++, Etter/Ingber
Array Problem Solving & Program Design in C Eighth Edition
CNG 140 C Programming (Lecture set 8)
Lecture 10 Arrays.
Programming with Pointers
Review of Arrays and Pointers
Multidimensional Arrays
7 Arrays.
CS150 Introduction to Computer Science 1
Dr Tripty Singh Arrays.
CS150 Introduction to Computer Science 1
Exercise Arrays.
Arrays Imran Rashid CTO at ManiWeber Technologies.
ICS103 Programming in C Lecture 12: Arrays I
Intro to Arrays Storing List of Data.
Presentation transcript:

Arrays and Matrices

One-Dimensional Arrays Suppose, you need to store years of 100 cars. Will you define 100 variables: int y1, y2,…, y100; An array is an indexed data structure to represent several variables having the same data type: int y[100]; y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99]

One-Dimensional Arrays An element of an array is accessed using the array name and an index or subscript, e.g., y[5] In C, the subscripts always start with 0 and increment by 1, so y[5] is the sixth element The name of the array is the address of the first element and the subscript is the offset y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99]

Definition and Initialization An array is defined using a declaration statement. data_type array_name[size]; allocates memory for size elements subscript of first element is 0 subscript of last element is size-1 size must be a constant

Example int list[5]; allocates memory for 5 integer variables subscript of first element is 0 subscript of last element is 4 C does not check bounds on arrays list[6] =5; /* will give segmentation fault later */ list[0] list[1] list[2] list[3] list[4]

Initializing Arrays Examples: Arrays can be initialized at the time they are declared. Examples: double taxrate[3] ={0.15, 0.25, 0.3}; char list[5] = {‘h’, ’e’, ’l’, ’l’, ’o’}; double vector[100] = {0.0}; /* assigns zero to all 100 elements */ int s[] = {5,0,-5}; /*the size of s is 3*/

Assigning values to an array for loops are often used to assign values to an array Example: int list[5], i; for(i=0; i<5; i++) { list[i] = i; } list[0] list[3] list[4] list[1] list[2] 1 2 3 4

Assigning values to an array Give a for loop to assign the below values to list int list[5], i; for(i=0; i<5; i++) { list[i] = 4-i; } list[0] list[3] list[4] list[1] list[2] 4 3 2 1

Input from a data file Arrays are often used to store information from a data file int k; double time[10], motion[10]; FILE *sensor3; sensor3 = fopen(“sensor3.dat”, “r”); for(k=0; k<10; k++) { fscanf(sensor3, “%lf %lf”, &time[k], &motion[k]); }

Exercise Show the contents of the arrays defined in each of the following sets of statements. int x[10] = {-5, 4, 3}; char letters[] = {'a', 'b', 'c'}; double z[4];

Exercise int data[100], i; Store random numbers [0,99] in data for (i=0; i<100; i++) data[i] = rand() % 100; Store random numbers [10,109] in data data[i] = (rand() % 100) + 10; OR data[i] = rand_int(10,109);

Computations on arrays

Maximum in an array 1 2 3 4 5 6 6 3 3 1 1 9 9 7 7 2 2 9 6 9 max

Find Maximum Find maximum value in data int data[100], max, i; for (i=0; i<100; i++) data[i] = rand() % 100; max = data[0]; for (i=0; i<100; i++){ if (data[i] > max) max = data[i]; } printf("Max = %d\n",max);

Find average Find average of values in data int data[100], sum, i, avg; for (i=0; i<100; i++) data[i] = rand() % 100; sum = 0; for (i=0; i<100; i++){ sum = sum + data[i]; } avg = (double)sum/100; printf(“Avg = %lf\n", avg);

Number of elements greater than average After finding the average as shown in previous slide count = 0; for (i=0; i<100; i++){ if (data[i] > avg) count++; } printf(“%d elements are greater than avg”, count);

Reverse an array Set array B to the reverse of array A A B 1 2 3 4 5 6 1 2 3 4 5 A 6 3 1 9 7 2 2 7 9 1 3 6 B 1 2 3 4 5

Reverse an Array int A[100], B[100]; ... int bindex = 0, aindex = 99; while (bindex < 100) { B[bindex] = A[aindex] bindex = bindex + 1; aindex = aindex -1’ }

} } } Find pair sum data[0]=5 pair[0]=12 data[1]=7 pair[1]=20 Find sum of every pair in data and write into pair array } data[0]=5 data[1]=7 data[2]=15 data[3]=5 … data[98]=3 data[99]=12 pair[0]=12 pair[1]=20 … pair[49]=15 } . }

Solution int data[100], pair[50], i; for (i=0; i<100; i++) data[i] = rand() % 100; for (i=0; i<50; i++){ pair[i]= data[2*i]+ data[2*i+1]; }

Function Arguments Individual elements of an array can be passed as regular arguments. void donothing(int a, int b) { … } int main(void) /* Declare variables and functions */ int array[5] = {1,2,3,4,5}; donothing(array[2], array[4]); .

Passing Arrays to Functions Arrays are always pass by reference Modifications to the array are reflected to main program The array name is the address of the first element The maximum size of the array must be specified at the time the array is declared. The actual number of array elements that are used will vary, so the actual size of the array is usually passed as another argument to the function

Exercise int data[100] Write a function to find maximum value in the array data int maximum(int fdata[], int n) { int i, fmax; fmax = fdata[0]; for (i=0; i<n; i++) if (fdata[i] > fmax) fmax = fdata[i]; return(fmax); } int main() { int data[100],i, max; for (i=0; i<100; i++) data[i] = rand() % 100; max = maximum(data,100); printf("Max = %d\n",max); return(0); }

Exercise What is the output of the following program? Lectute4e3.c void print(int pdata[], int n) { int i; for (i=0; i<n; i++) printf("data[%d]=%d\n",i,pdata[i]); return; } void modify(int fdata[], int n) fdata[i] = 1; int main() { int data[10]; for (i=0; i<10; i++) data[i] = rand() % 100; print(data,10); modify(data,10); return(0); } Lectute4e3.c

Exercise fdata and data use the same copy of the array int main() { int data[10]; … modify(data,10); } void modify(int fdata[], int n) { … }

Sorting an array 1 2 3 4 5 6 3 1 9 7 2 1 3 6 9 7 2 1 2 6 9 7 3 1 2 3 9 7 6 1 2 3 6 7 9 1 2 3 6 7 9

Selection Sort void selection_sort(double x[], int n) { int min_pos, i; for(i=0; i<n-1; i++) min_pos = find_min_pos(x, n, i); swap(x, i, min_pos); } lecture4e4.c

Selection Sort int find_min_pos(double fx[], int fn, int fi) { int i; int index=fi; for (i=fi; i<fn; i++) if (fx[i] <fx[index]) index = i; return(index); }

Selection Sort void swap(double sx[], int si, int smin_pos) { double temp; temp = sx[si]; sx[si] = sx[smin_pos]; sx[smin_pos] = temp; return; }

Reverse an array 1 2 3 4 5 6 3 1 9 7 2 2 7 9 1 3 6

Reverse an Array void reverse(double x[], int n) { int i=0, j=n-1; while (i<j) swap(x,i,j); i = i + 1; j = j - 1; } return;

Matrices in memory Row 0 Row 1 Row 2 A matrix is a set of numbers arranged in a grid with rows and columns. A matrix is defined using a type declaration statement. datatype array_name[row_size][column_size]; int matrix[3][4]; 4 1 2 Row 0 in memory -1 2 4 3 Row 1 Row 0 Row 1 Row 2 -1 3 1 Row 2 Column 0 Column 3 Column 1 Column 2

Accessing Array Elements int matrix[3][4]; matrix has 12 integer elements matrix[0][0] element in first row, first column matrix[2][3] element in last row, last column matrix is the address of the first element matrix[1] is the address of the second row

Initialization for (i=0; i<3; i++) int matrix[3][4]; j for (j=0; j<4; j++) matrix[i][j] = 1; for (i=0; i<12; i++) maxrix[i/4][i %4] = 1; j 0 1 2 3 4 1 2 i -1 2 4 3 1 -1 3 1 2

2-Dim Arrays as Arguments to Functions Print the array int matrix[3][4] void print(int pmatrix[3][4]) { int i,j; for (i=0; i<3; i++) for (j=0; j<4; j++) printf("%.5d ",pmatrix[i][j]); printf("\n"); } return;

Transpose of an array int matrix[3][4]; int transpose[4][3]; j j i i 0 1 2 3 0 1 2 4 1 2 4 -1 i -1 2 4 3 i 1 2 -1 1 1 -1 3 1 4 3 2 2 3 2 3 1

2-Dim Arrays as Arguments to Functions void transpose(int b[NROWS][NCOLS], int bt[NCOLS][NROWS]) { /* Declare Variables. */ int i, j; /* Transfer values to the transpose matrix. */ for(i=0; i<NROWS; i++) for(j=0; j<NCOLS; j++) bt[j][i] = b[i][j]; } return;

Exercise Find the maximum of int matrix[3][4] int max = matrix[0][0]; for (i=0; i<3; i++) for (j=0; j<4; j++) if (matrix[i][j] > max) max = matrix[i][j]; 0 1 2 3 1 2 -1 2 4 3 1 -1 3 1 2

Exercise Find the number of times x appears in int matrix[3][4] int count = 0; for (i=0; i<3; i++) for (j=0; j<4; j++) if (matrix[i][j] == x) count = count + 1; 0 1 2 3 1 2 -1 2 4 3 1 -1 3 1 2

Exercise Compute the addition of two matrices + = 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 1 2 3 -1 3 1 3 3 3 + -1 2 4 3 1 4 2 = 6 6 3 1 1 1 -1 3 1 2 1 1 3 2 4 4 2 2 2

Exercise Compute the addition of two matrices int matrix1[3][4], matrix2[3][4], sum[3][4]; // initialize matrix1 and matrix2 for (i=0; i<3; i++) for (j=0; j<4; j++) sum[i][j] = matrix1[i][j]+matrix2[i][j];

Exercise Insert random numbers into an array so that each number appears in the array at most once. 6 3 1 9 6 2 A for (i=0; i<6; i++) A[i] = rand() % 10; Produces Duplicates

Exercise Insert random numbers into an array so that each number appears in the array at most once. void initialize(int idata[], int n) { int i=0, j, elem; while (i<=n) elem = rand() % 10; if (find_count(idata,i,elem) == 0) idata[i] = elem; i = i + 1; } 6 3 1 9 6 2 A Try a new number

Exercise Counts how many times x appears in first n elements of array cdata int find_count(int cdata[], int n, int x) { int count = 0; int i; for (i = 0; i<n; i++) if (cdata[i] == x) count = count + 1; return (count); } 6 3 1 9 7 2 1 2 3 4 5 find_count(A,6,2) returns 1 find_count(A,4,2) returns 0

Exercise Arrays A and B represents sets. Find the intersection of A and B 6 3 1 9 7 2 4 2 5 6 1 8 A B 6 1 2 Intersection

Exercise int intersection(int ndata1[], int ndata2[], int n, int result[]) { int i=0, j=0 , elem; while (i<=n) elem = ndata1[i]; if (find_count(ndata2,n,elem) == 1) result[j] = elem; j = j + 1; } i = i + 1; return(j); 6 3 1 9 7 2 4 2 5 6 1 8 6 1 2

Exercise: Pairwise Swap 1 2 3 4 5 6 3 1 9 7 2 3 6 9 1 2 7 1 2 3 4 5 47 47

Exercise: Second Largest in an array 1 2 3 4 5 6 3 1 9 7 2 9 6 -1 6 9 7 -1 3 6 max max2 48 48