Objectives of This Chapter

Similar documents
C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

Programming for Engineers Arrays

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Lecture 04 FUNCTIONS AND ARRAYS

C Arrays Pearson Education, Inc. All rights reserved.

Introduction to Computer Science Midterm 3 Fall, Points

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

Principles of Programming. Chapter 6: Arrays

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

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017

Chapter 7 C Pointers

C++ PROGRAMMING SKILLS Part 4: Arrays

Chapter 5 C Functions

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

Computer Science & Engineering 150A Problem Solving Using Computers

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

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

Write a C program using arrays and structure

Subject: Computer Science

Multiple-Subscripted Arrays

B. V. Patel Institute of Business Management, Computer & Information Technology, UTU 2013

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Module 6: Array in C

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays

Unit-2 Divide and conquer 2016

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Arrays and Applications

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

Programming in OOP/C++

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Outline Arrays Examples of array usage Passing arrays to functions 2D arrays Strings Searching arrays Next Time. C Arrays.

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

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

Pace University. Fundamental Concepts of CS121 1

Computer Programming Lecture 14 Arrays (Part 2)

PROGRAMMING IN C AND C++:

Columns A[0] A[0][0] = 20 A[0][1] = 30

Function Call Stack and Activation Records

Sample Examination. Family Name:... Other Names:... Signature:... Student Number:...

C: How to Program. Week /Mar/05

One Dimension Arrays 1

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

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

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

INDIAN SCHOOL MUSCAT COMPUTER SCIENCE(083) CLASS XI

Questions Bank. 14) State any four advantages of using flow-chart

Arrays. Arrays are of 3 types One dimensional array Two dimensional array Multidimensional array

Arrays and Strings. Arash Rafiey. September 12, 2017

How to declare an array in C?

Maltepe University Computer Engineering Department. BİL 133 Algoritma ve Programlama. Chapter 8: Arrays and pointers

To become familiar with array manipulation, searching, and sorting.

CS 106 Introduction to Computer Science I

Introduction to C Final Review Chapters 1-6 & 13

Functions. Arash Rafiey. September 26, 2017

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

C: How to Program. Week /Apr/23

C Functions. 5.2 Program Modules in C

Unit 3 Decision making, Looping and Arrays

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

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

Chapter 6 Pointers and Arrays

VALLIAMMAI ENGINEERING COLLEGE SRM NAGAR, KATTANGULATHUR

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

ESC101N: Fundamentals of Computing End-sem st semester

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Programming and Data Structures in C Instruction for students

C++ Programming Chapter 7 Pointers

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

User Manual. Version 3.1. Copyright 2000 Academia Software Solutions All Rights Reserved

Chapter 2: Basic Elements of C++

Unit 1 - Arrays. 1 What is an array? Explain with Example. What are the advantages of using an array?

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

Week - 03 Lecture - 18 Recursion. For the last lecture of this week, we will look at recursive functions. (Refer Slide Time: 00:05)

BLM2031 Structured Programming. Zeyneb KURT

Objectives. In this chapter, you will:

C/C++ Programming Lecture 18 Name:

CS 261 Data Structures. Big-Oh Analysis: A Review

C: How to Program. Week /Apr/16

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #04

Chapter 2 - Introduction to C Programming

Programming Assignment #4 Arrays and Pointers

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

Binary Representation. Decimal Representation. Hexadecimal Representation. Binary to Hexadecimal

Decimal Representation

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

Grade 6 Math Circles November 6 & Relations, Functions, and Morphisms

Fundamentals of Programming Session 15

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Sorting Pearson Education, Inc. All rights reserved.

CSE101-Lec#18. Multidimensional Arrays Application of arrays. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

Introduction to Arrays

UNIVERSITY OF WINDSOR Fall 2007 QUIZ # 2 Solution. Examiner : Ritu Chaturvedi Dated :November 27th, Student Name: Student Number:


Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

Outline. 7.1 Introduction. 7.2 Arrays. 7.2 Arrays

ONE DIMENSIONAL ARRAYS

Transcription:

Chapter 6 C Arrays

Objectives of This Chapter Array data structures to represent the set of values. Defining and initializing arrays. Defining symbolic constant in a program. Using arrays to store, list, and search the set of values in an array. Defining and working with multiple subscripted arrays.

Introduction to Arrays Most of the programming languages provides capability to define set of variables (data items) known as arrays. Use of arrays is an important topic for data structures (2 nd year course). Data means collection of related items (Chapter 10). Arrays also takes up space in the memory as regular variables. Most of the time, this space is limited and can not be changed throughout the program. Chapter 12, we will learn about creating set of variables (arrays) whose sizes may increased or shrunk as needed. Example: Exam results for a Class Set of variables holding the exam results for bunch of students. If you try to sort them, probably it is likely impossible to do without using arrays.

Defining Arrays in C Defining an array in C is very similar to defining a single variable, but for arrays we do also give the size in the square brackets. type name_of_the_array[size]; Example: int c[12] ; /*Creates an array with 12 elements*/ The elements of this array: c[0], c[1],. c[10],c[11] Position number in the brackets called index or subscript. Each element in an array is like a single variable, has integer type with 4 byte. Operations with the elements of the array is similar to operation with single variable: c[0]= 45; /*Assign 45 value to 1 st element of the array*/ c[5]++ ; /*Increase the 6 th element by +1*/

Example: Operations with Arrays Assume that we have an array named c with size of 12. Assume also that the elements initialized/assigned by values Values stored in each array is shown on the right. What do the following operations do? c[10]=553; c[5]++; a=1; b=3; x=(c[a]+c[b])/2; printf( %d,x); c[a+b]=c[a]+c[b]; printf( %d%d%d,c[a],c[a]+c[b],c[5]);

Example: Initializing Elements of an Array to zero p. 230 Write a program. In this program, you define an integer type of array named n with 10 elements. Then assign zero to each elements in the array. Then list them out in tabular form along with the indices.

More on Initializing Elements of an Array There are different ways to assign an initial value to elements of an array. Let s consider the integer type of n[10] array. int n[10]={0}; /*Initialize all elements to 0 */ int n[10]={3}; /*Initialize n[0] to 3 then rest to 0 */ int n[10]={10,15,16,17,24,23, 10,9,0}; /*this is called list initialization*/ means n[0]=10, n[1]=15, n[9]=0 /*list on the right called initialization list*/ int n[10]={1,4,6}; /*Initialize only first three elements to the values in the list then rest to 0 */ int n[10]={[7]=1,[3]=2}; /*Initialize only 8 th and 4th elements to given values and rest to 0 */ What happens if we don t define the size in the brackets? int n[]={1,5,6,4,3}; int m[]={3,5,7}; int x[]={7,5,6,4}; Sizes are automatically assigned as the number of elements given in the initialization list.

Example: Generating Fibonacci Numbers Write a program that generates first 15 Fibonacci numbers and store them in an array called Fibonacci. At the end of the program it should print the calculated Fibonacci numbers along with the indexes. Remember: Definition of Fibonacci Numbers Fibonacci[0]=0; Fibonacci[1]=1; and Fibonacci[n]=Fibonacci[n 1]+Fibonacci[n 2]; for n 2

Example: Rolling Dice 100 Times Write a program that rolls dice (using rand function) for 100 times. This program will determine how frequently (how many times) 1, 2, 3 6 faces appears and keeps these numbers in an array named frequency. Then prints the results in the following tabular form with Histogram. Below is an example output of the program when executed: Face Frequency Histogram 1 14 ************** 2 16 **************** 3 22 ********************** 4 8 ******** 5 24 ************************ 6 16 **************** Page 186

Using #define to define a symbolic constant #define NAME value Expression are called preprocessor directives. Are used at the beginning of the program after #include preprocessor directives. These are used to define constant values. Unlike regular variables, these values doesn t take any space in the memory. The compiler comes and replace the NAME in the program by the value before it start to compile. More details on C preprocessor directives are given in Chapter 13.

Using Character Arrays to Store and Manipulate Strings p 239 Collection of characters is called as STRING. Example: Gaziantep / Turkey So far, we have only seen %s in printf to print out a string to the screen. printf ( %s, Ali ); In programming, a string can be considered as a character array. char a[20]; or char name[10], last_name[10]; char name[10]: Has 10 elements from c[0] to c[9] But it can hold maximum 9 characters, because the last element in the name array is used as termination character which is null character. Null character value in Ascii table is \0 String termination character is placed at the end of the character arrays/strings. This helps programmer to deal with the string more efficiently. This helps us to determine the end of the string.

Initialization and Operations with String Variables p 239 char string[]= first ; /*creates string with 6 elements*/ Element string[0] string[1] string[2] string[3] string[4] Stored Value f i r s string[5] \0 t Initialization can be also done using initialization list: char string[] = { 'f', 'i', 'r', 's', 't', '\0' }; This is character by character initialization. also possible to define then READ IT FROM KEYBOARD A string can also be first defined then read from the keyboard. In this case the size of the string must be determined in the identifier line. char string[20]; /* Creating String that can hold 19 Character*/ printf( Enter the First String ); scanf( %s,string); /* Reading string value from keyboard no &*/ Note: We don t use & while reading string, this is because the name of a string array holds the memory address of the string array.

Example: Program finding the length of a string Write a program which takes a string from keyboard then the program prints the length of the string to the screen. Below is an example output of the program when executed: Enter a string: COMPprog Length of the string: 8

Example: String Reading and Printing Write a program that has two string variables; string1 is defined with size of 20 and string2 is initialized to store Welcome to Gaziantep. In your program stgring1 will be read from keyboard after prompting the user with Enter a String:. Then your program will print the followings to the screen: string1 characters in string1 (one character in a one line) sting2 characters in string2 (one character in a one line)

Example: Printing the a string in character reversed order Write a program that reads a string from screen then it prints to the screen in reversed order. Below is an example output of the program when executed: Enter a string: Welcome to Gaziantep Your string reversed: petanizag ot emoclew

Static Local and Automatic Local Arrays Similar to local or global variables; arrays can be also defined local or global. If the array is defined before the main program, this array becomes a global array and can be accessible from everywhere in the program (program scope). Arrays created in the functions are created and destroyed every time the function is invoked. If an array in a function defined as static int a[20]; similar to the static variables, this array is created only once not destroyed at the end of function. The concept is exactly the same as the variables (Chap 5.).

Passing Arrays to a Functions In order to pass an array to a function, we write only the name of the array without brackets. Example: Assume we have hourlytemperature array defined as below and passed to a function called my function Main program: int hourlytemperature[24]; myfunction (hourlytemperature, 24); Function: void myfunction (int b[], int size){ } Note: As you may notice, also the size of the array is sent to function to inform about the size of it if needed. While we are passing string arrays; because the last value in a string is \0 (null character), we don t need to also pass the size as we do other type of arrays.

More on Passing Arrays to a Functions Unlike passing regular variables, passing arrays to a function is callby reference type. Remember: Call by value and Call by reference Call by value: Function can t do any change on the variable. Call by reference: Function can change the variable/array. While passing array to a function is a call by reference call? Because name of the array hourlytemplate refers to the memory addresses allocated for elements of the array. So that the function can do the change directly on the memory address allocated for the array. How can we do a call by value while passing arrays to a function? This is only possible by sending individual elements of the array. myfunction(a[0],a[1], ); but this is less practical. Or in the function s argument, we define the array as constant array. void myfunction ( const int b[],size) /*so the function can t change */

Page 245 Example: Array name refers to the memory addresses for the array The following program prints the memory address for an array

Example: Function sums the elements of an integer array Write a function named sum which is called from main program to find the sum of the elements of an integer array. The function will return the sum of the elements to the caller at the end of the function.

Example: Function to find the length of a string Write a function which determines the length of the string variable. Call this function from your main program to find the length of a string. The function receives the string from the caller and it returns the length of the string to the caller at the end. Below is an example output of the program when executed: Enter a string: COMPprog Length of the string: 8

Example: Passing an Array to a Function and an Element p.247 Write a program in which define an integer type of array defined as numbers[]={0,1,2,3,4}. Your main program calls a function called multiplyarray which multiples the each element in the array by 2. Then it calls another function named multiplyelement by passing only number[3] (4th element) and this function also multiply it by 2. Print out the array at the beginning of the program and after each calls of functions.

Example: Finding Maximum in an Array Write a complete C program in which define an integer type of integer named numbers and size of 10; numbers[10]. The elements of the numbers array are generated as random numbers using rand() within the range of 1 to 1000 from stdlib C library. After assigning random values to each elements, the program calls a function printarray that prints out the array. Finally, it calls a function called maxarray which finds the maximum number in the number array and the main program finish the program by printing this maximum value.

Example: Statistical Computations Using Arrays Write a C program that computes the mean (average) and standard deviation of an array data with size of 8. Then the program displays computed mean value, standard deviation, and the difference between each value and the mean value as shown in the figure. Below is an example output of the program when executed: Enter 8 Numbers: 16 12 6 8 2.5 12 14 54.5 The mean is 2.00. The standard deviation is 21.75 Index Number Difference 0 16.00 14.00 1 12.00 10.00 2 6.00 4.00 3 8.00 6.00 4 2.50 0.50 5 12.00 10.00 6 14.00 12.00 7 54.50 56.50 Reminder: Statistical Definitions mean SIZE 1 i 0 SIZE 1 x SIZE i i 0 2 std _ dev mean x SIZE i 2

Putting set of numbers/characters in ascending or descending order are called as sorting. Sorting is one the most important application of programming. p 242 So far, we have learned sorting of a few variables as like x, y, z variables. Let s assume: x=1; y=7; z=2 Ascending order of these numbers : 1, 2, 7 (Ascending = Getting Higher) Descending order of these numbers: 7, 2, 1 (Descending = Getting Lower) Sorting can be accomplished by comparing numbers with one another then swapping if needed. Sorting task gets complicated if you have too many numbers to deal with, for example, balances of the costumers in a bank, their credit limits, due dates for the next payment, and so on.

Continues p 242 Sorting of large amount of quantities can be done using arrays. First we load the numbers/quantities to array then sort the array in the order we want. Example: Sorting Array with size of 5: Before Sorting Element Stored Value num[0] 89 num[1] 65 num[2] 121 num[3] 10 num[4] 3 After Sorting in Ascending Order Element Stored Value num[0] 10 num[1] 3 num[2] 65 num[3] 89 num[4] 121 After Sorting in Descending Order Element Stored Value num[0] 121 num[1] 89 num[2] 65 num[3] 3 num[4] 10 Sorting can be done going through each element and compare them with one another.

Algorithms p 248 Sorting of arrays can be done going through each element and compare one element with another element and put them in the order which needed. There are different algorithms to sort arrays. Here we will only study two methods Bubble Sort (Sinking Sort): Most commonly used sorting algorithm. Name is associated with the bubbles goes up in a liquid while the heavier ones sink down. Selection Sort: Another commonly used sorting algorithm. In both algorithms, pair of elements are compared and arranged in the desired orders.

Sorting of Arrays BUBBLE SORT: p 248 In Bubble Sort, successive elements in an array are compared and swapped in the order desired. This process is repeated number of the items. Successive elements : a[i] and a[i+1] If they are in order then do nothing leave them as they are If they are not in order then swap the values (Remember we learned how to swap two values of variable analogy to swapping two glasses of water) This comparison must be done for all elements of the array, so the i value will be starting from 0 and run up to SIZE 1. The whole process will be repeated as many times as the SIZE 1 of the array. In conclusion, the part of C program for bubble sort is given below for (repeat=0 ; repeat < SIZE 1 ; repeat++){ //Repeating whole Process SIZE 1 TIMES for (i=0; i < SIZE 1; i++){ /*Going through each element FIRST TO THE LAST*/ Compare and swap the a[i] and a[i+1] elements if needed. } }

Two Glasses of Waters Analogy to Swapping Elements in Computation Let s assume, we have two glasses of drinks in different colors. We would like to swap/replace the content of one glass to another glass without mixing them. Shall we pour the drinks directly from one to another one? OR This doesn t work it, because destroys/mixes the contents.

Swapping Content of Glasses What if we have a Third Empty Glass We can accomplish this task using a third empty glass in three steps. 1 This will make Before 2 This will make After 3 This will make

Swapping Two Variable or Elements of an Array Swapping two variable or elements of an array requires a third dummy variable similar to empty glass. It can be done in the following case Swapping a and b variables: int a= 7, b=4, hold; /*Hold is the dummy Variable representing the empty glass*/ hold = a; /*First saving the value of a in the hold dummy variable*/ a = b; /*Putting value of b into a*/ b = hold; /*Putting value of hold into b*/ Eventually a becomes 4 and b becomes 7. Swapping Successive elements of an Array a: a[i] and a[i+1] hold = a[i]; a[i] = a[i+1]; a[i+1] = hold; Eventually value of a[i] and value of a[i] interchanged. This procedure will be used while swapping the elements of an array in sorting process if needed.

Sorting of Array a in Ascending Order BUBBLE SORT p 249 Terminal Output Of the Program Swapping Elements

Sorting of Arrays SELECTION SORT: Algorithm Out of Book In Selection Sort, starting from the first element, the element is compared with the rest of elements in the array and swapped in the desired order. This can be achieved by using nested for repetitions similar to bubble sort. The loops should be constructed as shown below, for (i=0; i < SIZE-1; i++){/*ith element to be compared*/ for (j=i+1; j < SIZE; j++){ /*jth element to be compared notice j > i */ Compare and swap the a[i] and a[j] elements if needed. } } By the end of each i loop, the smallest or maximum element among the i to the SIZE 1 is placed to i th element of the loop.

Sorting of Arrays SELECTION SORT: Pictorial Rep. Out of Book Pictorial representation of selection sort of an array with 6 elements in ascending order is shown below. for ( i=0; i < 5; i++) { /* Picks the element to be compared*/ for (j=i+1; j < 6; j++){ /*jth scans the rest of the elements notice j > i */ if (a[i] < a[j]) { /*Swapping the elements if necessary. hold= a[i]; a[i]= a[j]; a[j]=hold; } } /*loop for j finishes here */ } /*loop for i finishes here */

Comparison of Bubble Sort and Selection Sort Bubble Sort for (repeat=0 ; repeat <= SIZE 1 ; repeat++){ /*Repeating whole Process*/ for (i=0; i < SIZE 1; i++){ /*Going through each element*/ Compare and swap the a[i] and a[i+1] elements if needed. }} Number of Comparison: (SIZE 1) 2 Selection Sort for (i=0; i < SIZE 1; i++) { /*ith element to be compared*/ for (j=i+1; j < SIZE; j++){ /*jth element to be compared notice j > i */ Compare and swap the a[i] and a[j] elements if needed. }} Number of Comparison: SIZE*(SIZE 1)/2 Example: If size of array is 10 Bubble Sort does (10 1) 2 = 81 operations to sort out the data. Selection Sort does 10*(10 1)/2 = 45 operations to sort out the data. In conclusion, selection sort exhibits better performance in most cases. There are also other more complex sorting techniques far better in performance, but they are out of scope of this lecture.

Example: Bubble Sort and Selection Sort Descending Order Write a C program in which we define integer type of arrays numa and numb with size of 10. Values of numa and numb will be same and determined randomly within the range of 1 to 10. The program then prints these arrays to screen, then numa will be sent to bublesort function which will sort this array using bubble sort algorithm. numb will be sent to sent to a function named selectionsort where the array will be sorted based upon the selection sort algorithm. By the end of the program print the sorted arrays to screen. Note: Because, we are printing an array several times, it is good to use a function named printarray to do this task. Below is an example output of the program when executed: Before Sorting: numa: 2 6 8 9 1 4 5 7 3 4 numb: 2 6 8 9 1 4 5 7 3 4 After Sorting: numa: 1 2 3 4 4 5 6 7 8 9 numb: 1 2 3 4 4 5 6 7 8 9

Page 251 Analysis of observed data are extensively used for statistical purposes. As like the analysis of results of a survey given to bunch of participators. These analysis includes the sorting of obtained data and determining the frequency of the same results. Then do the analysis using the quantities given below. Following Quantities are Important for Statistical Purposes: Mean: In other word, average value of the data set. Median: In a sorted data, Median value is the value of middle element. Mode: Value repeated most frequently. Study 6.7 Case Study Program at Page 252 yourself.

Example: Mean, Median, and Mode of Series Determine the Mean, Median, and Mode of Series for the following series. Before Sorting Index Number 1 1.00 2 3.00 3 7.00 4 6.00 5 10.00 6 8.00 7 8.00 8 2.00 9 4.00 10 5.00 11 8.00 Sorted Index Number 1 1.00 2 2.00 3 3.00 4 4.00 5 5.00 6 6.00 7 7.00 8 8.00 9 8.00 10 8.00 11 10.00 Mean: 5.64 (Sum of Numbers / # of Elements) Median: 6.00 (Middle Element in sorted Data) Mode: 8.00 (Most Frequent) In this example, number of elements is 11, so the middle value is the 6 th element gives us the median value. If the number of elements are even then two elements will be the middle elements, in this case the median value will be the average of the numbers. For instance, if SIZE=10 then the median is the average of 5 th and 6 th element.

We often work large amount of data and sometimes want to know if it includes a specific value with certain key. Page 255 In order to find the specific value, we need to go through the elements and compare them with the key value. The process of finding a particular element matching certain criteria is called searching. Various algorithms were developed to accomplish searching process. Here, we will only cover two methods. Linear Search : Can be applied to any data. Binary Search : Only applied to sorted data, more efficient.

The Linear Search compares each element in the array with the search key. Page 255 Once the value matching search key is found, the index of the element holding this value is used and searching process terminates. This process, is not very efficient in time of process. Worst Case Scenario: Last element is the searching value. Best Case Scenario: The first element is the searching value. Therefore, the number of comparison needs to be made is N/2. C code that find the key in an array named a with size of SIZE is given below. Initially value variable is set to -1. for ( n = 0; n < size; ++n ){/*loop through array */ if ( a[ n ] == key ) { value = n; break; /* terminate the repetition when found */ } /* end if */ } /* end for */

Page 255 linearsearch function is used to find the index Accepts three arguments: Array: Array within it search will be done. Key value: what to search for. Size of the Array. Returns the index of searched item. If the item can t be found, returns 1 Output of the Program As follows:

The Linear Searching method is sufficient for small or unsorted arrays. However, it is not efficient in sorting large arrays. Page 257 Binary Searching method can be used to search large and sorted arrays. Binary Search: Data is split into two halves. Key value is compared with the middle element. If the middle element matches, the searching process terminates by returning the index value. If the key value is greater than the middle element then the sub array is searched, or if the key value is smaller then the upper array is searched. This process continues until the searched value is returned in the array. This process is very efficient in time of process. Consider searching Array with size of 1024. Linear Search : Requires 1024/2 comparison in average. Binary Search: Requires 10 comparison at worst scenario (Notice: 2 10 =1024)

Implementation of Binary Search In order to understand how we can do the Binary search in a sorted array, let s consider that we are searching for a search key in a set of data sorted in ascending order Sorted Array Index Value 0 0 1 4 2 8 3 12 4 16 5 20 6 24 7 28 8 32 9 36 10 40 11 44 12 48 Procedure is as the followings: Define two variables called low and high Low and High variables determines the boundaries in which the search Initially, low =0 and high = size 1 (first and last elements) Define the third variable middle as the middle element of this range middle = (low + high) / 2 Compare the value of middle element with search key: If the middle element equals to search key DONE! If the middle element is bigger start searching the lower region redefine high = middle 1 (shifting down the high to lower region If the middle element is bigger start searching the upper region redefine low = middle + 1 Repeat this process until finding the search key. Repeat the process as long as low <= high if not found, which means key doesn t exist in the array.

Example: Binary Search See also Page Fig 6.19 Page 258 Write a C program in which we define integer type of array named numbers with size of 20. The values are generated as numbers[i]=2*i where i is the index number of the array. Now, design a function named binarysearch which does the searching of a key. If the search key found, it returns the index/subscript number of the array matching the search key value. If the search key not found, it returns 1. In the main program, user will be asked to enter the search key value then it calls binarysearch to determine the index/subscript matching the entered key value. The main program prints out the index value determined by the function to the screen or printing Key Value. Not Found! if it is not found.

So far, we dealt with arrays with only one subscript numbers[10], str[20], a[100], etc. These arrays are called as single subscripted/one dimensional arrays. Single subscripted arrays are useful to understand the fundamental idea Also, they are sufficient to study simple problems. Page 261 In daily life applications, programs have more complexity and usage of onedimensional arrays might not be sufficient. In C language, it is possible to define arrays with more then one subscript. int a[3][4],char str[10][30], etc. (these are double subscripted arrays) Arrays with more than two subscripted are called multi subscripted arrays. Double subscripted arrays are commonly used in complicated real life programs.

Page 261 Let s Consider that we define a double subscripted array with dimension of 3 by 4. int a[3][4]; This will create array named a with 3x4 = 12 elements as shown below. Elements of this array are: a[0][0], a[0][1],a[0][2], a[0][3],.. a[2][0], a[2][1],a[2][2], a[0][3] Each element is like an int type of variable takes 4bit of space in the memory.

Usage of Double Subscripted Arrays In order to understand benefits of usage of double subscripted arrays. Let s consider the int exam_results[10][3]; 10 row by 3 column array with loaded with some values Rows Columns 0 1 2 Array exam_results 0 37 92 39 1 35 35 81 2 75 91 62 3 95 90 25 4 72 92 35 5 43 39 38 6 3 43 1 7 19 83 31 8 66 20 60 9 49 62 9 This array can be considered as three exam results of a class with 10 students. If so; Row index represents the student. Column index represents the exam. So then; exam_results[0][1] is the exam 1 result for the 1 st student. exam_results[8][2] is the exam 3 result for the 9 th student. This could also be done by defining three different arrays named exam1[10], exam2[10], and exam3[10] but would be less efficient if you would have 10 exams (many columns to deal with).

Example: Initialization of Double Subscripted Array Page 258 Let s consider the following lines in a C program In these three lines, double subscripted integer arrays a, b, and c with size of 2 row by 3 column are created and some of the elements are initialized. int a[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } }; After Initializing Array a [0][0] [0][1] [0][2] [1][0] [1][1] [1][2] int b[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 }; Array b [0][0] [0][1] [0][2] [1][0] [1][1] [1][2] After Initializing Array a 1 2 3 4 5 6 Array b 1 2 3 4 5 0 int c[ 2 ][ 3 ] = { { 1, 2 }, { 4 } }; Array c [0][0] [0][1] [0][2] [1][0] [1][1] [1][2] After Initializing Array c 1 2 0 4 0 0

Example: Initialization of Double Subscripted Array Page 258 Let s now consider the usage of double subscripted character arrays. char city[5][10]={"gaziantep","istanbul","chicago","paris", Mecca"}; Double subscripted character array (5 x 10) named city is defined and initialized to the city names given in the list. It can store up to 5 strings. Each string can have maximum of 9 characters (one for `\0`) [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] city[0] city[1] city[2] city[3] city[4] [0] [1] [2] [3] [4] 'G' 'a' 'z' 'i' 'a' n' 't' 'e' 'p' '\0' 'I' 's' 't' 'a' 'n' 'b' 'u' 'l' '\0' 'C' 'h' 'i' 'c' 'a' 'g' 'o' '\0' 'P' 'a' 'r' 'i' 's' '\0' 'M' 'e' 'c' 'c' 'a' '\0' Here reserved space for each string is 10 but some of them are not used.

Example: Multiple Strings Double Subscripted Char Array The following program keeps track of the name of 5 persons, the names are initialized within the program. Then it lists the 5 names. #include<stdio.h> int main (void){ char str[5][10]={"ali","veli","mehmet","yakup","veysel"}; int i; //Defined as counter to go through each string // Following line can be used to read in the names from keyboard instead of initializing //for ( i =0 ; i < 5 ; i++) {printf("enter the %dth name:",i); scanf("%s",str[i]);} for ( i =0 ; i < 5 ; i++) printf("%2dth name:%10s\n",i+1,str[i]); return 0; } Output of the Program:

Summary of Multi Subscripted Arrays In Summary, benefits of using multi subscripted arrays Easier to work with data with many column values In single subscripted arrays, for each column we need to define a separate array, this sometimes becomes impossible. Defining arrays capable of holding multiple strings is only possible with usage of double subscripted character arrays. In single subscripted arrays, for string we need to define a separate character array, this sometimes becomes impossible. Matrix operations in math is easy to handle by define doublesubscripted arrays. There are algorithms to handle such matrix operations by using singlesubscripted arrays but efficient only for special matrices (like symmetric ones).

Page 275

Page 276

Page 283

Page 283

Matrix Operations in C Programming Array of numbers arranged in rows and columns as rectangular form are called matrix (plural matrices) in mathematics. The individual items in a matrix are called its elements or entries. An example of a matrix A and matrix B with 3 rows and 3 columns is given below: 1 4 17 A 2 7 3 4 12 5 3 4 5 B 5 11 1 1 12 0 Matrices have many applications in most scientific fields. In computer programming, a matrix can be stored in a double subscripted arrays. Most common mathematical operations with matrices are as below: Transpose of a Matrix Basic Math Operations of Matrices (summation subtraction) Multiplication of Matrices Determinant of Matrix. Here, we will only deal with the transpose and summation operations.

Transpose of a Matrix Example Transpose of a matrix is the obtained by swapping rows by columns. Matrix A and transpose of A, A T is shown below; 1 4 17 A 2 7 3 4 12 5 T A 1 2 4 4 7 12 17 3 5 Example: Write a C program that calculates the transpose of a 5 row by 5 column matrix then prints matrix and it s transpose to screen. The elements of the matrix are generated as random number from 10 to 10, inclusively. You may answer the problem, by considering one 5x5 array and do the swapping between elements or by considering two arrays 5x5 and use the first array for the matrix and second array for it s transpose.

Basic Math Operations with Matrices Summation and subtraction of matrices are another matrices with the same size. In matrix sum./subt. operations, elements with the same subscripts are operated, giving the element with the same subscript of resulting matrix. 1 4 17 3 4 5 A 2 7 3 4 12 5 B 5 11 1 1 12 0 For A and B matrices given above, A+B and A B are given below; 1 4 17 3 4 5 1 3 4 4 17 5 4 0 22 A B 2 7 3 5 11 1 2 5 7 11 3 1 7 18 2 4 12 5 1 12 0 4 1 12 12 5 0 5 24 5 1 4 17 3 4 5 1 3 4 4 17 5 2 8 12 A B 2 7 3 5 11 1 2 5 7 11 3 1 3 4 4 4 12 5 1 12 0 4 1 12 12 5 0 3 0 5 Example: Write a C program that sums and subtracts a 5 row by 5 column matrices and prints the results to screen. Elements of matrices are internally generated as random number from 10 to 10, inclusively. Generated matrices, sum matrix, subtraction matrix are printed to screen in square form as shown above