Chapter 7: Arrays In this chapter, you will learn about

Slides:



Advertisements
Similar presentations
Topic Reviews For Unit ET156 – Introduction to C Programming Topic Reviews For Unit
Advertisements

4 Control Statements: Part 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Introduction to C Programming
Problem Solving & Program Design in C
Outline lecture Revise arrays Entering into an array
1.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 10 Arrays and Tile Mapping Starting Out with Games & Graphics.
Chapter 10: Applications of Arrays and the class vector
1 Arrays … The Sequel Applications and Extensions Chapter 10.
Topic 14 Searching and Simple Sorts "There's nothing in your head the sorting hat can't see. So try me on and I will tell you where you ought to be." -The.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Structures Functions and Arrays Dale Roberts, Lecturer Computer.
Review Pseudo Code Basic elements of Pseudo code
1 Chapter Eleven Arrays. 2 A Motivating Example main( ) { int n0, n1, n2, n3, n4; scanf(“%d”, &n0); scanf(“%d”, &n1); scanf(“%d”, &n2); scanf(“%d”, &n3);
1 Review Quisioner Kendala: Kurang paham materi. Praktikum Pengaruh teman.
Arrays.
C Language.
CS 141 Computer Programming 1 1 Arrays. Outline  Introduction  Arrays  Declaring Arrays  Examples Using Arrays  Sorting Arrays  Multiple-Subscripted.
Pointers and Arrays Chapter 12
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 13 – Salary Survey Application: Introducing.
Data Structures Using C++ 2E
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 3 Loops.
One Dimensional Arrays
By Senem Kumova Metin 1 DATA TYPES. by Senem Kumova Metin 2 DATA TYPE? …… x; // DECLARATION OF VARIABLE X printf(“Do you want to go on? \n”) printf(“Please.
Programming and Data Structure
Kernighan/Ritchie: Kelley/Pohl:
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays 6.3Declaring Arrays 6.4Examples Using Arrays 6.5Passing.
1 Lecture 9  Arrays  Declaration  Initialization  Applications  Pointers  Declaration  The & and * operators  NULL pointer  Initialization  Readings:
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Introduction to Programming with C++ Fourth Edition
Chapter 8 Arrays and Strings
 2007 Pearson Education, Inc. All rights reserved C Arrays.
CS1061 C Programmuing Lecture 12 Arrays A. O’Riordan, 2004.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 8 Arrays and Strings
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Algorithm and Programming Array Dr. Ir. Riri Fitri Sari MM MSc International Class Electrical Engineering Dept University of Indonesia 15 March 2009.
ARRAY Prepared by MMD, Edited by MSY1.  Introduction to arrays  Declaring arrays  Initializing arrays  Examples using arrays  Relationship with pointers.
ARRAYS 1 Week 2. Data Structures  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently 
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.
C Lecture Notes 1 Arrays Lecture 6. C Lecture Notes 2 6.1Introduction Arrays –Structures of related data items –Static entity – same size throughout program.
Chapter 8: Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function.
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.
Computer Programming Lecture 8 Arrays. 2 switch-statement Example (3) If use press left arrowIf use press right arrow If use press up arrow If use press.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
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.
CHAPTER 7: Arrays CSEB113 PRINCIPLES of PROGRAMMING CSEB134 PROGRAMMING I by Badariah Solemon 1BS (Feb 2012)
Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Arrays Department of Computer Science. C provides a derived data type known as ARRAYS that is used when large amounts of data has to be processed. “ an.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Computer Programming BCT 1113
Numeric Arrays Numeric Arrays Chapter 4.
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
7 Arrays.
EKT150 : Computer Programming
Review of Arrays and Pointers
Data Structures (CS212D) Week # 2: Arrays.
7 Arrays.
Presentation transcript:

Chapter 7: Arrays In this chapter, you will learn about Introduction to Array Array declaration Array initialization Assigning values to array elements Reading values from array elements Relationship with pointers Passing array to function 2 Dimensional arrays Simple Searching Simple Sorting NI S1 2009/10

Introduction to Array In C, a group of items of the same type can be set up using Array An array is a group of consecutive memory locations related by the fact that they all have the same name and the same type. The compiler must reserve storage (space) for each element/item of a declared array. The size of an array is static (fixed) throughout program execution. To refer to a particular location or element in the array, we specify the name of the array and its index (the position number of the particular element in the array).

Let say we have an array called a. Name of the array The position number within the square brackets is formally called a subscript. A subscript can be an integer or an integer expression. For example if x = 1 and y = 2, then a[x+y] is equal to a[3]. Notice that the position starts from 0. -10 99 -8 100 27 10 1976 -2020 1

Array Declaration Array declaration is made by specifying the data type, it’s name and the number of space (size) so that the computer may reserve the appropriate amount of memory. General syntax: data_type array_name[size]; Examples: int my_array[100]; char name[20]; double bigval[5*200]; int a[27], b[10], c[76];

Array Initialization There are 2 ways to initialize an array: during compilation and during execution. During compilation: int arr[ ] = {1, 2, 3, 4, 5}; Unsized array : We can define how many elements that we want since the array size is not given. int arr[3] = {90, 21, 22}; We can define only 3 elements since the array size is already given. int arr[5] = {2,4}; Initialize the first two elements to the value of 2 and 4 respectively, while the other elements are initialized to zero. int arr[5] = {0}; Initialize all array elements to zero.

Array Initialization cont… During execution: Using loop to initialize all elements to zero int arr[3], index; for (index = 0; index < 3; index++) arr[index] = 0; Using loop and asking the user to specify the value for each element. { printf (“arr[%d]:”,index); scanf(“%d”,&arr[index]); }

Assigning value to array element We can assign a value to a specific array element by using its index number. Example: let’s say we have an array that represent the number of inhabitant in 5 unit apartments. int apartment[5]={3,2,6,4,5}; The above initialization indicates that there are 3 people living in apartment 0, 2 people living in apartment 1 and so on. Let say that we have a new born in apartment 3, so we need to change the number of inhabitant living in apartment three. apartment[3] = apartment[3] + 1; Now, we have the following values in our array: [0] [1] [2] [3] [4] apartment 3 2 6 5

Reading values from array elements We can read a value from a specific array element by referring to the index. For example, let’s say we want to know how many people leaving in apartment 3, we could simple do this: int apartment[5] = {3,2,6,4,5}; int no_of_people; no_of_people = apartment[3]; printf(“Apartment 3 has %d people”,no_of_people); The above C code will produce the following output: Apartment 3 has 4 people Press any key to continue Hint!!! Remember that array’s index starts at 0

Example 1: finding total inhabitants #include <stdio.h> #define size 5 int main(void) { int apartment[size] = {3,2,6,4,5}; int index, total = 0; for (index = 0; index < size; index++) total = total + apartment[index]; } printf("There are total of %d inhabitants",total); return(0); There are total of 20 inhabitants Press any key to continue

Example 2: list down number of inhabitants in each apartment #include <stdio.h> int main(void) { int apartment[5] = {3,2,6,4,5}; int index, total = 0; printf("%-7s %-15s\n","Apt No", "No of people"); for (index = 0; index < 5; index++) printf("%4d %10d\n",index, apartment[index]); } return(0); Apt No No of people 3 1 2 6 4 5 Press any key to continue

Passing Array to a Function When we pass an array to a function, we are actually passing the reference (address) of the first element in the array to the function. Therefore, any changes to the array inside the function will also change the actual array inside the calling function. When we want to pass an array to a function, we need to know these 3 things. How to write the function prototype? How to do function call? How does the function header would look like?

Passing Array to a Function Assume that we have the following array declaration. float marks[10] = {0.0}; Say for example we want to write a function, called get_marks, which will read marks from the user and store the marks inside the array. Function prototype: /* data type with square bracket */ void get_marks(float [ ]); Function call: get_marks(marks); /* just pass the array name */ Function header: void get_marks(float marks[ ])

Example: passing array to a function #include <stdio.h> #define size void get_marks(float [ ]); float calc_average(float [ ]); int main(void) { float marks[size] = {0.0}; /*initializing the array get_marks(marks); /* function call */ printf(“Average for marks given is %.2f”, calc_average(marks)); return(0); } void get_marks(float marks[ ]) /* reading the marks from the users */ int i; for (i = 0; i < size; i++) printf("Marks for student %d:",i + 1); scanf("%f",&marks[i]); float calc_average(float marks[ ]) float total = 0.0; total = total + marks[i]; return (total / size); Example: Passing Array to a Function Example: passing array to a function Marks for student 1: 56 Marks for student 2: 96 Marks for student 3: 78 Marks for student 4: 35 Marks for student 5: 66 Average for marks given is 66.2 Press any key to continue

2-Dimensional Array It is possible to create an array which has more than one dimension. For example: 2D array: int array[4][2]; 3D array: int array[4][2][10]; Graphical representation of a 2D array: int myarray[4][2] = {1,2,3,4,5,6,7,8}; 1 2 3 4 5 6 7 8 This array has 4 rows and 2 columns. Col 1 Col2 Row 1 Row 2 Row 3 Row 4

2-Dimensional Array cont… Variable initialization can also be done this way: int myarray[4][2] = {{1,2},{3,4},{5,6},{7,8}}; This method is less confusing since we can see the rows and columns division more clearly. To initialize a 2D array during execution, we need to use a nested for loop: for (row = 0; row < 4; row++) { for (column = 0; column < 2; column++) myarray[row][column] = 0; } Although it is possible to create a multi-dimensional array, arrays above 2-dimensions are rarely used.

Passing a 2D array to a function When a 2D (or higher dimensional) array is passed to a function, the size of the second (or subsequent) subscript needs to be specified. For example, if we have: int twoD[4][5]; Then the function header which would take twoD as an argument should be declared like this: void Process2D(int twoD[ ][5]) An array is stored consecutively in memory regardless of the number of dimensions. Therefore, specifying the subscripts in the function parameter will help the compiler to know the boundary of the different dimensions.

Data Searching Searching is the process of determining whether an array contains a value that matches a certain key value/search key. The process of finding a particular element of an array is called searching. There are more than one algorithms that can be used to do a search. The most commonly used searching techniques are linear search and binary search. Here, we will discuss how to do searching by using linear search on an array.

Linear Search Search key is a data element of the same type as the list elements. If search key == list element value, the search is said to be successful. Otherwise, it is unsuccessful. Linear search is a simple searching algorithm where: data are stored in an array a search key is compared with each elements in the array starting from the first element.

Example: Linear Search #include <stdio.h> int main(void) { int list[ ] = {34, 53, 21, 23, 4}; int i, search_key, found = 0; printf(“Enter the number that you want to find: ”); scanf(“%d”, &search_key); for (i = 0; i < 5; i++) if (list[i] = = search_key) found = 1; printf(“%d is found at index %d\n”, search_key, i); } if (found = = 0) printf(“%d cannot be found in the list\n”,search_key); return(0); Enter the number that you want to find: 53 53 is found at index 1 Press any key to continue

Sorting Sorting is the process of placing data into a particular order such as ascending or descending. The following example shows the C code for sorting unsorted list to a list sorted in ascending order. Explanation for the working program and the concept behind it will be done during lecture hour… (so please attend the class!!!!).

Example: Simple Sort #include <stdio.h> #define size 5 void sort(int [ ]); int main(void) { int index, list[size] = {0}; /*array initialisation by user */ for (index = 0; index < size; index++) printf("list[%d]:",index); scanf("%d",&list[index]); } sort(list); /* calling function to sort the array */ printf("\nList sorted in ascending order:\n"); /* printing the array element */ printf("%d\t",list[index]); return(0); List [0]: 6 List [1]: 9 List [2]: 2 List [3]: 8 List [4}: 3 List sorted in ascending order: 2 3 6 8 9 Press any key to continue

Example: Simple Sort cont… void sort(int list[ ]) { int pivot, checker, temp; for (pivot = 0; pivot < (size - 1); pivot++) for (checker = (pivot + 1); checker < size; checker++) if (list[checker] < list[pivot]) /* swap the elements */ temp = list[pivot] ; list[pivot] = list[checker]; list[checker] = temp; }

Summary In this chapter, we have looked at: Array declaration and initialization Reading and writing from/to array elements Passing array to function 2 dimensional array Simple search Array sorting

Exercise printf(“%f”, number[2+2] ); printf(“%f”, number[2]+2 ); Assume the following array declaration float number[5] = {2.3, 4.2, 5.0, 7.9, 6.2}; What will be the output of the following statement? printf(“%f”, number[2+2] ); printf(“%f”, number[2]+2 ); printf(“%f”, number[1*2] ); printf(“%f”, number[1]*2 );

Exercise printf(“%d”, result[1]); printf(“%d”, result[4]); Assume the following array declaration int result[5] = {56, 69, 89}; int i = 2; What will be the output of the following statement? printf(“%d”, result[1]); printf(“%d”, result[4]); printf(“%d”, result[0] + result[1]); printf(“%d %d”, i, result[i]);

Exercise Assume the following array declaration int result[3*2]; Write C statements that would read the values for the array element from the user. Write C statements that would list down all the values in the array. Write C statements that would sum up all the values in the array. Rewrite the above task as separate function!!