Arrays a kind of data structure that can store a fixedsize sequential collection of elements of the same type. An array is used to store a collection

Size: px
Start display at page:

Download "Arrays a kind of data structure that can store a fixedsize sequential collection of elements of the same type. An array is used to store a collection"

Transcription

1 Morteza Noferesti

2 Arrays a kind of data structure that can store a fixedsize sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1,..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

3 All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

4 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 type arrayname [ arraysize ]; This is called a single-dimensional array. The arraysize must be an integer constant greater than zero and type can be any valid C data type.

5 For example, to declare a 10-element array called balance of type double, use this statement double balance[10]; Here balance is a variable array which is sufficient to hold up to 10 double numbers.

6 You can initialize an array in C either one by one or using a single statement as follows double balance[5] = , 2.0, 3.4, 7.0, 50.0; The number of values between braces cannot be larger than the number of elements that we declare for the array between square brackets [ ].

7 If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write double balance[] = , 2.0, 3.4, 7.0, 50.0; You will create exactly the same array as you did in the previous example.

8 Following is an example to assign a single element of the array balance[4] = 50.0; The above statement assigns the 5th element in the array with a value of All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be total size of the array minus 1. Shown below is the pictorial representation of the array we discussed above

9 An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example double salary = balance[9]; The above statement will take the 10th element from the array and assign the value to salary variable.

10 #include <stdio.h> int main () int n[ 10 ]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) n[ i ] = i + 100; /* set element at location i to i */ /* output each array element's value */ for (j = 0; j < 10; j++ ) printf("element[%d] = %d\n", j, n[j] ); return 0;

11 #include <stdio.h> int main() int marks[10], i, n, sum = 0, average; printf("enter n: "); scanf("%d", &n); for(i=0; i<n; ++i) printf("enter number%d: ",i+1); scanf("%d", &marks[i]); sum += marks[i]; average = sum/n; printf("average marks = %d", average); return 0;

12

13 Each name refers to a constant pointer Space for array elements is allocated at declaration time Can t change where the array name refers to but you can change the array elements, via pointer arithmetic int m[4]; (int [])??? (int)??? (int)??? (int)??? (int) m 13

14 array[subscript] equivalent to *(array + (subscript)) Strange but true: Given earlier declaration of m, the expression 2[m] is legal! Not only that: it s equivalent to *(2+m) *(m+2) m[2] 14

15 int m[3]; (int [])??? (int)??? (int)??? (int) m int *mid = m + 1; int *right = mid[1]; int *left = mid[-1]; int *beyond = mid[2]; 15

16 int m[3]; (int [])??? (int)??? (int)??? (int) m int *mid = m + 1; (int []) int *right = mid[1]; mid (int []) right int *left = mid[-1]; (int []) int *beyond = mid[2]; left compiler may not catch this runtime environment certainly won t (int []) beyond 16

17 But, functions that take arrays as arguments can exhibit what looks like pass-by-reference behavior, where the array passed in by the callee does get changed Remember the special status of arrays in C They are basically just pointers. So arrays are indeed passed by value but only the pointer is copied, not the array elements! Note the advantage in efficiency (avoids a lot of copying) But the pointer copy points to the same elements as the callee s array These elements can easily be modified via pointer manipulation 17

18 Ret_type fun (int array[length]). int main() int N=10; int A[N]; fun(a); Ret_type fun (int array[],int length). int main() int N=10; int A[N]; fun(a,n); Method 1 Method 2 18

19 #include <stdio.h> float print_array(int x[],int N) int i; for (i=0;i<n;i++) printf("%d\n",x[i]); void fill_array(int x[],int N) int i; for(i=0;i<n;i++) x[i]=i+1; int main() int N=10; int x[n]; fill_array(x,n); print_array(x,n); 19

20 How to interpret a declaration like: int d[2][4]; This is an array with two elements: Each element is an array of four int values The elements are laid out sequentially in memory, just like a one-dimensional array Row-major order: the elements of the rightmost subscript are stored contiguously (int) (int) (int) (int) (int) (int) (int) (int) d[0][0] d[0][1] d[0][2] d[0][3] d[1][0] d[1][1] d[1][2] d[1][3] d[0] d[1] 20

21 int d[2][4]; d [1] [2] *(d+1) Increment by the size of 1 array of 4 ints (int) (int) (int) (int) (int) (int) (int) (int) d[0][0] d[0][1] d[0][2] d[0][3] d[1][0] d[1][1] d[1][2] d[1][3] d[0] d[1] 21

22 int d[2][4]; d [1] [2] *(*(d+1)+2)*(d+1) Then increment by the size of 2 ints (int) (int) (int) (int) (int) (int) (int) (int) d[0][0] d[0][1] d[0][2] d[0][3] d[1][0] d[1][1] d[1][2] d[1][3] d[0] d[1] 22

23 If you use tricks with pointer arithmetic, the order matters a lot It also matters for initialization To initialize d like this: use this: int d[2][4] = 0, 1, 2, 3, 4, 5, 6, 7; CS 3090: Safety Critical Programming in C 23

24 Only the first subscript may be left unspecified void f(int matrix[][10]); /* OK */ void g(int (*matrix)[10]); /* OK */ void h(int matrix[][]); /* not OK */ Why? Because the other sizes are needed for scaling when evaluating subscript expressions (see slide 10) This points out an important drawback to C: Arrays do not carry information about their own sizes! If array size is needed, you must supply it somehow (e.g., when passing an array argument, you often have to pass an additional array size argument) bummer 24

25 Matrix multiplication int main() int X[N][N],Y[N][N],Res[N][N],i,j,k; printf("enter X>>\n"); initial_matrix(n,x); printf("enter Y>>\n"); initial_matrix(n,y); //multiply the two matrix: for (i=0;i<n;i++) for (j=0;j<n;j++) Res[i][j]=0; for (k=0;k<n;k++) Res[i][j]+=X[i][k]*Y[k][j]; //print the result: print_matrix(res); 25

26 void initial_matrix(int N,int X[][N]) int i,j; for (i=0;i<n;i++) for (j=0;j<n;j++) scanf("%d",&x[i][j]); void print_matrix(int mat[][n]) int i,j; for(i=0;i<n;i++) for (j=0;j<n;j++) printf("%3d",mat[i][j]); printf("\n");

27 Search: locate an item in a list of information Two algorithms we will examine: Linear search Binary search

28 Also called the sequential search Starting at the first element, this algorithm sequentially steps through an array examining each element until it locates the value it is searching for.

29 Array numlist contains: Searching for the the value 11, linear search examines 17, 23, 5, and 11 Searching for the the value 7, linear search examines 17, 23, 5, 11, 2, 29, and 3

30 Algorithm: set found to false; set position to 1; set index to 0 while index < number of elts. and found is false if list[index] is equal to search value found = true position = index end if add 1 to index end while return position

31 #include<stdio.h> int main() int N,key;int A[N];int i,indx=-1; printf("enter the number of elements:"); scanf("%d",&n); printf("enter the array\'s elements:"); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("enter the key:"); scanf("%d",&key); for(i=0;i<n;i++) if(a[i]==key) indx=i; break; if(indx==-1) printf("the key does not exist"); else printf("the key does exist at index: %d ",indx); return 0;

32 Benefits: Easy algorithm to understand Array can be in any order Disadvantages: Inefficient (slow): for array of N elements, examines N/2 elements on average for value in array, N elements for value not in array

33 Requires array elements to be in order 1. Divides the array into three sections: middle element elements on one side of the middle element elements on the other side of the middle element 2. If the middle element is the correct value, done. Otherwise, go to step 1. using only the half of the array that may contain the correct value. 3. Continue steps 1. and 2. until either the value is found or there are no more elements to examine

34 Array numlist2 contains: Searching for the the value 11, binary search examines 11 and stops Searching for the the value 7, linear search examines 11, 3, 5, and stops

35 Set first index to 0. Set last index to the last subscript in the array. Set found to false. Set position to -1. While found is not true and first is less than or equal to last Set middle to the subscript half-way between array[first] and array[last]. If array[middle] equals the desired value Set found to true. Set position to middle. Else If array[middle] is greater than the desired value Set last to middle - 1. Else Set first to middle + 1. End If. End While. Return position.

36 int binarysearch(int array[], int size, int value) int first = 0, // First array element last = size - 1, // Last array element middle, // Mid point of search position = -1; // Position of search value bool found = false; // Flag while (!found && first <= last) middle = (first + last) / 2; if (array[middle] == value) found = true; position = middle; // Calculate mid point // If value is found at mid else if (array[middle] > value) // If value is in lower half last = middle - 1; else first = middle + 1; return position; // If value is in upper half

37 log 2 N

38 Benefits: Much more efficient than linear search. For array of N elements, performs at most log 2 N comparisons Disadvantages: Requires that array elements be sorted

39 Sort: arrange values into an order: Ascending numeric Descending numeric Two algorithms considered here: Bubble sort Selection sort

40 Bubble sort algorithm starts by comparing the first two elements of an array and swapping if necessary, i.e., if you want to sort the elements of array in ascending order and if the first element is greater than second then, you need to swap the elements but, if the first element is smaller than second, you mustn't swap the element. Then, again second and third elements are compared and swapped if it is necessary and this process go on until last and second last element is compared and swapped. This completes the first step of bubble sort. If there are n elements to be sorted then, the process mentioned above should be repeated n-1 times to get required result. But, for better performance, in second step, last and second last elements are not compared becuase, the proper element is automatically placed at last after first step. Similarly, in third step, last and second last and second last and third last elements are not compared and so on. A figure is worth a thousand words so, acknowledge this figure for better understanding of bubble sort.

41 Here, there are 5 elements to the sorted

42 Bubble Sort Algorithm(cont.)

43 Bubble Sort Algorithm(cont.)

44 Bubble Sort Algorithm(cont.)

45 Bubble Sort Algorithm(cont.)

46 /*C Program To Sort data in ascending order using bubble sort.*/ #include <stdio.h> int main() int data[100],i,n,step,temp; printf("enter the number of elements to be sorted: "); scanf("%d",&n); for(i=0;i<n;++i) printf("%d. Enter element: ",i+1); scanf("%d",&data[i]); for(step=0;step<n-2;++step) for(i=0;i<n-step-1;++i) if(data[i]>data[i+1]) /* To sort in descending order, change > to < in this line. */ temp=data[i]; data[i]=data[i+1]; data[i+1]=temp; printf("in ascending order: "); for(i=0;i<n;++i) printf("%d ",data[i]); return 0;

47 Benefit: Easy to understand and implement Disadvantage: Inefficient: slow for large arrays

48 The list is divided into two sublists, sorted and unsorted, which are divided by an imaginary wall. We find the smallest element from the unsorted sublist and swap it with the element at the beginning of the unsorted data. After each selection and swapping, the imaginary wall between the two sublists move one element ahead, increasing the number of sorted elements and decreasing the number of unsorted ones. Each time we move one element from the unsorted sublist to the sorted sublist, we say that we have completed a sort pass. A list of n elements requires n-1 passes to completely rearrange the data. CENG 213 Data Structures

49 Sorted Unsorted Original List After pass After pass After pass After pass After pass 5 CENG 213 Data Structures

50 #include <stdio.h> int main() int indexmin,i,j; int intarray[]=5,3,6,8,1,9; int MAX=6; // loop through all numbers for(i = 0; i < MAX; i++) // set current element as minimum indexmin = i; // check the element to be minimum for(j = i+1; j<max; j++) if(intarray[j] < intarray[indexmin]) indexmin = j; if(indexmin!= i) printf("items swapped: [ %d, %d ]\n", intarray[i], intarray[indexmin]); // swap the numbers int temp = intarray[indexmin]; intarray[indexmin] = intarray[i]; intarray[i] = temp; printf("iteration %d#:\n",(i+1)); for (i=0;i<max;i++) printf("%d\n",intarray[i]);

51 Benefit: More efficient than Bubble Sort, since fewer exchanges Disadvantage: May not be as easy as Bubble Sort to understand

8.1. Chapter 8: Introduction to Search Algorithms. Linear Search. Linear Search. Linear Search - Example 8/23/2014. Introduction to Search Algorithms

8.1. Chapter 8: Introduction to Search Algorithms. Linear Search. Linear Search. Linear Search - Example 8/23/2014. Introduction to Search Algorithms Chapter 8: Searching and Sorting Arrays 8.1 Introduction to Search Algorithms Introduction to Search Algorithms Search: locate an item in a list of information Two algorithms we will examine: Linear search

More information

LECTURE 08 SEARCHING AND SORTING ARRAYS

LECTURE 08 SEARCHING AND SORTING ARRAYS PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 08 SEARCHING AND

More information

Sorting & Searching. Hours: 10. Marks: 16

Sorting & Searching. Hours: 10. Marks: 16 Sorting & Searching CONTENTS 2.1 Sorting Techniques 1. Introduction 2. Selection sort 3. Insertion sort 4. Bubble sort 5. Merge sort 6. Radix sort ( Only algorithm ) 7. Shell sort ( Only algorithm ) 8.

More information

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

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size]; Arrays An array is a collection of two or more adjacent memory cells, called array elements. Array is derived data type that is used to represent collection of data items. C Array is a collection of data

More information

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-1-0) Introduction to arrays 1 What are Arrays? Arrays are our first example of structured data. Think of a book with pages numbered 1,2,...,400.

More information

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

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) In this lecture, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of

More information

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

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 Unti 4: C Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type An array is used to store a collection of data, but it is often more useful

More information

Bubble sort starts with very first two elements, comparing them to check which one is greater.

Bubble sort starts with very first two elements, comparing them to check which one is greater. Bubble Sorting: Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they

More information

Government Polytechnic Muzaffarpur.

Government Polytechnic Muzaffarpur. Government Polytechnic Muzaffarpur. Name of the Lab: COMPUTER PROGRAMMING LAB (MECH. ENGG. GROUP) Subject Code: 1625408 Experiment: 1 Aim: Programming exercise on executing a C program. If you are looking

More information

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Science & Engineering 150A Problem Solving Using Computers Computer Science & Engineering 150A Problem Solving Using Computers Lecture 06 - Stephen Scott Adapted from Christopher M. Bourke 1 / 30 Fall 2009 Chapter 8 8.1 Declaring and 8.2 Array Subscripts 8.3 Using

More information

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

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd El-Shorouk Academy Acad. Year : 2013 / 2014 High Institute of Computer Science & Information Technology Term : 1 st Year : 2 nd Computer Science Department Object Oriented Programming Section (1) Arrays

More information

Introduction to Arrays

Introduction to Arrays Introduction to Arrays One Dimensional Array. Two Dimensional Array. Inserting Elements in Array. Reading Elements from an Array. Searching in Array. Sorting of an Array. Merging of 2 Arrays. What is an

More information

2-D Arrays. Of course, to set each grid location to 0, we have to use a loop structure as follows (assume i and j are already defined):

2-D Arrays. Of course, to set each grid location to 0, we have to use a loop structure as follows (assume i and j are already defined): 2-D Arrays We define 2-D arrays similar to 1-D arrays, except that we must specify the size of the second dimension. The following is how we can declare a 5x5 int array: int grid[5][5]; Essentially, this

More information

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 10: Arrays Readings: Chapter 9 Introduction Group of same type of variables that have same

More information

Searching, Sorting. Arizona State University 1

Searching, Sorting. Arizona State University 1 Searching, Sorting CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 9 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State

More information

Lecture (07) Arrays. By: Dr. Ahmed ElShafee. Dr. Ahmed ElShafee, ACU : Fall 2015, Programming I

Lecture (07) Arrays. By: Dr. Ahmed ElShafee. Dr. Ahmed ElShafee, ACU : Fall 2015, Programming I Lecture (07) Arrays By: Dr Ahmed ElShafee ١ introduction An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type Instead

More information

Introduction to Computer Science Midterm 3 Fall, Points

Introduction to Computer Science Midterm 3 Fall, Points Introduction to Computer Science Fall, 2001 100 Points Notes 1. Tear off this sheet and use it to keep your answers covered at all times. 2. Turn the exam over and write your name next to the staple. Do

More information

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

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables 1 6 C Arrays 6.2 Arrays 2 Array Group of consecutive memory locations Same name and type To refer to an element, specify Array name + position number arrayname[ position number ] First element at position

More information

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

CSE101-Lec#18. Multidimensional Arrays Application of arrays. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming CSE101-Lec#18 Multidimensional Arrays Application of arrays Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Defining and processing 1D array 2D array Applications of arrays 1-D array A

More information

APS105. Collecting Elements 10/20/2013. Declaring an Array in C. How to collect elements of the same type? Arrays. General form: Example:

APS105. Collecting Elements 10/20/2013. Declaring an Array in C. How to collect elements of the same type? Arrays. General form: Example: Collecting Elements How to collect elements of the same type? Eg:., marks on assignments: APS105 Arrays Textbook Chapters 6.1-6.3 Assn# 1 2 3 4 5 6 Mark 87 89 77 96 87 79 Eg: a solution in math: x 1, x

More information

Arrays. Week 4. Assylbek Jumagaliyev

Arrays. Week 4. Assylbek Jumagaliyev Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

More information

Arrays and Applications

Arrays and Applications Arrays and Applications 60-141: Introduction to Algorithms and Programming II School of Computer Science Term: Summer 2014 Instructor: Dr. Asish Mukhopadhyay What s an array Let a 0, a 1,, a n-1 be a sequence

More information

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

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 2 (Minor modifications by the instructor) 1 Scope Rules A variable declared inside a function is a local variable Each local variable in a function comes into existence when the function

More information

C/C++ Programming Lecture 18 Name:

C/C++ Programming Lecture 18 Name: . The following is the textbook's code for a linear search on an unsorted array. //***************************************************************** // The searchlist function performs a linear search

More information

UNIT-1. Chapter 1(Introduction and overview) 1. Asymptotic Notations 2. One Dimensional array 3. Multi Dimensional array 4. Pointer arrays.

UNIT-1. Chapter 1(Introduction and overview) 1. Asymptotic Notations 2. One Dimensional array 3. Multi Dimensional array 4. Pointer arrays. UNIT-1 Chapter 1(Introduction and overview) 1. Asymptotic Notations 2. One Dimensional array 3. Multi Dimensional array 4. Pointer arrays. Chapter 2 (Linked lists) 1. Definition 2. Single linked list 3.

More information

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto Adapted from the slides Revisões sobre Programação em C, Sérgio Crisóstomo Compilation #include int main()

More information

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

Unit 1 - Arrays. 1 What is an array? Explain with Example. What are the advantages of using an array? 1 What is an array? Explain with Example. What are the advantages of using an array? An array is a fixed-size sequenced collection of elements of the same data type. An array is derived data type. The

More information

Chapter 8 Algorithms 1

Chapter 8 Algorithms 1 Chapter 8 Algorithms 1 Objectives After studying this chapter, the student should be able to: Define an algorithm and relate it to problem solving. Define three construct and describe their use in algorithms.

More information

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

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 7/e This chapter serves as an introduction to data structures. Arrays are data structures consisting of related data items of the same type. In Chapter 10, we discuss C s notion of

More information

8 Algorithms 8.1. Foundations of Computer Science Cengage Learning

8 Algorithms 8.1. Foundations of Computer Science Cengage Learning 8 Algorithms 8.1 Foundations of Computer Science Cengage Learning 8.2 Objectives After studying this chapter, the student should be able to: Define an algorithm and relate it to problem solving. Define

More information

C++ PROGRAMMING SKILLS Part 4: Arrays

C++ PROGRAMMING SKILLS Part 4: Arrays C++ PROGRAMMING SKILLS Part 4: Arrays Outline Introduction to Arrays Declaring and Initializing Arrays Examples Using Arrays Sorting Arrays: Bubble Sort Passing Arrays to Functions Computing Mean, Median

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 8 Array typical problems, Search, Sorting Department of Computer Engineering Outline

More information

Programming for Engineers Arrays

Programming for Engineers Arrays Programming for Engineers Arrays ICEN 200 Spring 2018 Prof. Dola Saha 1 Array Ø Arrays are data structures consisting of related data items of the same type. Ø A group of contiguous memory locations that

More information

Chapter 10 - Notes Applications of Arrays

Chapter 10 - Notes Applications of Arrays Chapter - Notes Applications of Arrays I. List Processing A. Definition: List - A set of values of the same data type. B. Lists and Arrays 1. A convenient way to store a list is in an array, probably a

More information

Procedural Programming

Procedural Programming Universität Duisburg-Essen PRACTICAL TRAINING TO THE LECTURE Procedural Programming Session Five: Arrays Name: First Name: Tutor: Matriculation-Number: Group-Number: Date: Prof. Dr.Ing. Axel Hunger Dipl.-Ing.

More information

MTH 307/417/515 Final Exam Solutions

MTH 307/417/515 Final Exam Solutions MTH 307/417/515 Final Exam Solutions 1. Write the output for the following programs. Explain the reasoning behind your answer. (a) #include int main() int n; for(n = 7; n!= 0; n--) printf("n =

More information

Module 6: Array in C

Module 6: Array in C 1 Table of Content 1. Introduction 2. Basics of array 3. Types of Array 4. Declaring Arrays 5. Initializing an array 6. Processing an array 7. Summary Learning objectives 1. To understand the concept of

More information

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

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty! Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns

More information

Principles of C and Memory Management

Principles of C and Memory Management COMP281 Lecture 8 Principles of C and Memory Management Dr Lei Shi Last Lecture Pointer Basics Previous Lectures Arrays, Arithmetic, Functions Last Lecture Pointer Basics Previous Lectures Arrays, Arithmetic,

More information

Classification s of Data Structures

Classification s of Data Structures Linear Data Structures using Sequential organization Classification s of Data Structures Types of Data Structures Arrays Declaration of arrays type arrayname [ arraysize ]; Ex-double balance[10]; Arrays

More information

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

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays Arrays Outline 1 Introduction 2 Arrays 3 Declaring Arrays 4 Examples Using Arrays 5 Passing Arrays to Functions 6 Sorting Arrays 7 Case Study: Computing Mean, Median and Mode Using Arrays 8 Searching Arrays

More information

Principles of Programming. Chapter 6: Arrays

Principles of Programming. Chapter 6: Arrays Chapter 6: 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 Simple Searching

More information

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency Introduction Fundamentals Declaring arrays Indexing arrays Initializing arrays Arrays and functions Multidimensional arrays Sorting and algorithm efficiency An array is a sequence of values of the same

More information

BITS PILANI, DUBAI CAMPUS DUBAI INTERNATIONAL ACADEMIC CITY, DUBAI FIRST SEMESTER

BITS PILANI, DUBAI CAMPUS DUBAI INTERNATIONAL ACADEMIC CITY, DUBAI FIRST SEMESTER BITS PILANI, DUBAI CAMPUS DUBAI INTERNATIONAL ACADEMIC CITY, DUBAI FIRST SEMESTER 2017-2018 COURSE : COMPUTER PROGRAMMING (CS F111) COMPONENT : Tutorial#4 (SOLUTION) DATE : 09-NOV-2017 Answer 1(a). #include

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 06 / 11 / 2015 Instructor: Michael Eckmann Today s Topics Comments and/or Questions? Sorting Searching Michael Eckmann - Skidmore College - CS 106 - Summer 2015

More information

Chapter 9: Functions. Chapter 9. Functions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 9: Functions. Chapter 9. Functions. Copyright 2008 W. W. Norton & Company. All rights reserved. Chapter 9 Functions 1 Introduction A function is a series of statements that have been grouped together and given a name. Each function is essentially a small program, with its own declarations and statements.

More information

Algorithms. Chapter 8. Objectives After studying this chapter, students should be able to:

Algorithms. Chapter 8. Objectives After studying this chapter, students should be able to: Objectives After studying this chapter, students should be able to: Chapter 8 Algorithms Define an algorithm and relate it to problem solving. Define three construct and describe their use in algorithms.

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #43 Multidimensional Arrays In this video will look at multi-dimensional arrays. (Refer Slide Time: 00:03) In

More information

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

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) Chapter - Arrays 1.1 Introduction 2.1 Introduction.2 Arrays.3 Declaring Arrays. Examples Using Arrays.5 Passing Arrays to Functions.6 Sorting Arrays. Case Study: Computing Mean, Median and Mode Using Arrays.8

More information

CSE101-lec#19. Array searching and sorting techniques. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

CSE101-lec#19. Array searching and sorting techniques. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming CSE101-lec#19 Array searching and sorting techniques Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Introduction Linear search Binary search Bubble sort Introduction The process of finding

More information

Chapter4: Data Structures. Data: It is a collection of raw facts that has implicit meaning.

Chapter4: Data Structures. Data: It is a collection of raw facts that has implicit meaning. Chapter4: s Data: It is a collection of raw facts that has implicit meaning. Data may be single valued like ID, or multi valued like address. Information: It is the processed data having explicit meaning.

More information

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

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will: Chapter 8 Arrays and Strings Objectives In this chapter, you will: Learn about arrays Declare and manipulate data into arrays Learn about array index out of bounds Learn about the restrictions on array

More information

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

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using

More information

Arrays. Systems Programming Concepts

Arrays. Systems Programming Concepts Arrays Systems Programming Concepts Arrays Arrays Defining and Initializing Arrays Array Example Subscript Out-of-Range Example Passing Arrays to Functions Call by Reference Multiple-Subscripted Arrays

More information

Arrays and Pointers in C & C++

Arrays and Pointers in C & C++ Arrays and Pointers in C & C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++,

More information

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Basic Science and Humanities

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Basic Science and Humanities PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Basic Science and Humanities Continuous Internal Evaluation Test 2 Date: 0-10- 2017 Marks: 0 Subject &

More information

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

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections C++ Programming Chapter 6 Arrays and Vectors Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics

More information

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos. UNIT 2 ARRAYS Arrays Structure Page Nos. 2.0 Introduction 23 2.1 Objectives 24 2.2 Arrays and Pointers 24 2.3 Sparse Matrices 25 2.4 Polynomials 28 2.5 Representation of Arrays 30 2.5.1 Row Major Representation

More information

Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That

Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That Physics 306 Computing Lab 5: A Little Bit of This, A Little Bit of That 1. Introduction You have seen situations in which the way numbers are stored in a computer affects a program. For example, in the

More information

Subject: Fundamental of Computer Programming 2068

Subject: Fundamental of Computer Programming 2068 Subject: Fundamental of Computer Programming 2068 1 Write an algorithm and flowchart to determine whether a given integer is odd or even and explain it. Algorithm Step 1: Start Step 2: Read a Step 3: Find

More information

Lecture 6 Sorting and Searching

Lecture 6 Sorting and Searching Lecture 6 Sorting and Searching Sorting takes an unordered collection and makes it an ordered one. 1 2 3 4 5 6 77 42 35 12 101 5 1 2 3 4 5 6 5 12 35 42 77 101 There are many algorithms for sorting a list

More information

Subject: Computer Science

Subject: Computer Science Subject: Computer Science Topic: Data Types, Variables & Operators 1 Write a program to print HELLO WORLD on screen. 2 Write a program to display output using a single cout statement. 3 Write a program

More information

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

Maltepe University Computer Engineering Department. BİL 133 Algoritma ve Programlama. Chapter 8: Arrays and pointers Maltepe University Computer Engineering Department BİL 133 Algoritma ve Programlama Chapter 8: Arrays and pointers Basics int * ptr1, * ptr2; int a[10]; ptr1 = &a[2]; ptr2 = a; // equivalent to ptr2 =

More information

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING APS 105 Computer Fundamentals Final Examination December 16, 2013 2:00 p.m. 4:30 p.m. (150 minutes) Examiners: J. Anderson, B. Korst, J.

More information

UNIT III ARRAYS AND STRINGS

UNIT III ARRAYS AND STRINGS UNIT III ARRAYS AND STRINGS Arrays Initialization Declaration One dimensional and Two dimensional arrays. String- String operations String Arrays. Simple programs- sorting- searching matrix operations.

More information

Write a C program using arrays and structure

Write a C program using arrays and structure 03 Arrays and Structutes 3.1 Arrays Declaration and initialization of one dimensional, two dimensional and character arrays, accessing array elements. (10M) 3.2 Declaration and initialization of string

More information

ARRAYS(II Unit Part II)

ARRAYS(II Unit Part II) ARRAYS(II Unit Part II) Array: An array is a collection of two or more adjacent cells of similar type. Each cell in an array is called as array element. Each array should be identified with a meaningful

More information

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

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 Arrays Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 6 - Arrays 6.1 Introduction 6.2 Arrays 6.3 Declaring Arrays 6.4 Examples Using Arrays

More information

C Arrays Pearson Education, Inc. All rights reserved.

C Arrays Pearson Education, Inc. All rights reserved. 1 6 C Arrays 2 Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end:

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 3 Monday, April 17, 2017 Total - 100 Points B Instructions: Total of 11 pages, including this cover and the last page. Before starting the exam,

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 3 Monday, April 17, 2017 Total - 100 Points A Instructions: Total of 11 pages, including this cover and the last page. Before starting the exam,

More information

Functions. Arash Rafiey. September 26, 2017

Functions. Arash Rafiey. September 26, 2017 September 26, 2017 are the basic building blocks of a C program. are the basic building blocks of a C program. A function can be defined as a set of instructions to perform a specific task. are the basic

More information

UIC. C Programming Primer. Bharathidasan University

UIC. C Programming Primer. Bharathidasan University C Programming Primer UIC C Programming Primer Bharathidasan University Contents Getting Started 02 Basic Concepts. 02 Variables, Data types and Constants...03 Control Statements and Loops 05 Expressions

More information

Search,Sort,Recursion

Search,Sort,Recursion Search,Sort,Recursion Searching, Sorting and Recursion Searching Linear Search Inserting into an Array Deleting from an Array Selection Sort Bubble Sort Binary Search Recursive Binary Search Searching

More information

Multiple-Subscripted Arrays

Multiple-Subscripted Arrays Arrays in C can have multiple subscripts. A common use of multiple-subscripted arrays (also called multidimensional arrays) is to represent tables of values consisting of information arranged in rows and

More information

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Review what an array is Review how to declare arrays Review what reference variables are Review how to pass arrays to methods Review

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS Syllabus: Pointers and Preprocessors: Pointers and address, pointers and functions (call by reference) arguments, pointers and arrays, address arithmetic, character pointer and functions, pointers to pointer,initialization

More information

Content. In this chapter, you will learn:

Content. In this chapter, you will learn: ARRAYS & HEAP Content In this chapter, you will learn: To introduce the array data structure To understand the use of arrays To understand how to define an array, initialize an array and refer to individual

More information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

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

Arrays. Defining arrays, declaration and initialization of arrays. Designed by Parul Khurana, LIECA. Arrays Defining arrays, declaration and initialization of arrays Introduction Many applications require the processing of multiple data items that have common characteristics (e.g., a set of numerical

More information

Searching and Sorting (Savitch, Chapter 7.4)

Searching and Sorting (Savitch, Chapter 7.4) Searching and Sorting (Savitch, Chapter 7.4) TOPICS Algorithms Complexity Binary Search Bubble Sort Insertion Sort Selection Sort What is an algorithm? A finite set of precise instruc6ons for performing

More information

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University 9/5/6 CS Introduction to Computing II Wayne Snyder Department Boston University Today: Arrays (D and D) Methods Program structure Fields vs local variables Next time: Program structure continued: Classes

More information

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

CSCE 110 PROGRAMMING FUNDAMENTALS. Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays Prof. Amr Goneid, AUC 1 Arrays Prof. Amr Goneid, AUC 2 1-D Arrays Data Structures The Array Data Type How to Declare

More information

V2 3/5/2012. Programming in C. Introduction to Arrays. 111 Ch 07 A 1. Introduction to Arrays

V2 3/5/2012. Programming in C. Introduction to Arrays. 111 Ch 07 A 1. Introduction to Arrays Programming in C 1 Introduction to Arrays A collection of variable data Same name Same type Contiguous block of memory Can manipulate or use Individual variables or List as one entity 2 Celsius temperatures:

More information

Structured programming

Structured programming Exercises 6 Version 1.0, 25 October, 2016 Table of Contents 1. Arrays []................................................................... 1 1.1. Declaring arrays.........................................................

More information

Unit 3 Decision making, Looping and Arrays

Unit 3 Decision making, Looping and Arrays Unit 3 Decision making, Looping and Arrays Decision Making During programming, we have a number of situations where we may have to change the order of execution of statements based on certain conditions.

More information

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8 Pointers Variables vs. Pointers: A variable in a program is something with a name and a value that can vary. The way the compiler and linker handles this is that it assigns a specific block of memory within

More information

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

To become familiar with array manipulation, searching, and sorting. ELECTRICAL AND COMPUTER ENGINEERING 06-88-211: COMPUTER AIDED ANALYSIS LABORATORY EXPERIMENT #2: INTRODUCTION TO ARRAYS SID: OBJECTIVE: SECTIONS: Total Mark (out of 20): To become familiar with array manipulation,

More information

'C' Programming Language

'C' Programming Language F.Y. Diploma : Sem. II [DE/EJ/ET/EN/EX] 'C' Programming Language Time: 3 Hrs.] Prelim Question Paper Solution [Marks : 70 Q.1 Attempt any FIVE of the following : [10] Q.1(a) Define pointer. Write syntax

More information

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff and Arrays Comp Sci 1570 Introduction to C++ Outline and 1 2 Multi-dimensional and 3 4 5 Outline and 1 2 Multi-dimensional and 3 4 5 Array declaration and An array is a series of elements of the same type

More information

PDS Class Test 2. Room Sections No of students

PDS Class Test 2. Room Sections No of students PDS Class Test 2 Date: October 27, 2016 Time: 7pm to 8pm Marks: 20 (Weightage 50%) Room Sections No of students V1 Section 8 (All) Section 9 (AE,AG,BT,CE, CH,CS,CY,EC,EE,EX) V2 Section 9 (Rest, if not

More information

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

COP 3223 Introduction to Programming with C - Study Union - Fall 2017 COP 3223 Introduction to Programming with C - Study Union - Fall 2017 Chris Marsh and Matthew Villegas Contents 1 Code Tracing 2 2 Pass by Value Functions 4 3 Statically Allocated Arrays 5 3.1 One Dimensional.................................

More information

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

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size

More information

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section :

CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart Q-2) Explain basic structure of c language Documentation section : CP FAQS Q-1) Define flowchart and explain Various symbols of flowchart ANS. Flowchart:- A diagrametic reperesentation of program is known as flowchart Symbols Q-2) Explain basic structure of c language

More information

COP 3223 Introduction to Programming with C - Study Union - Fall 2017

COP 3223 Introduction to Programming with C - Study Union - Fall 2017 COP 3223 Introduction to Programming with C - Study Union - Fall 2017 Chris Marsh and Matthew Villegas Contents 1 Code Tracing 2 2 Pass by Value Functions 4 3 Statically Allocated Arrays 5 3.1 One Dimensional.................................

More information

MODULE 1. Introduction to Data Structures

MODULE 1. Introduction to Data Structures MODULE 1 Introduction to Data Structures Data Structure is a way of collecting and organizing data in such a way that we can perform operations on these data in an effective way. Data Structures is about

More information

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

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

Chapter 3: Arrays and More C Functionality

Chapter 3: Arrays and More C Functionality Chapter 3: Arrays and More C Functionality Objectives: (a) Describe how an array is stored in memory. (b) Define a string, and describe how strings are stored. (c) Describe the implications of reading

More information

CSE202- Lec#6. (Operations on CSE202 C++ Programming

CSE202- Lec#6. (Operations on CSE202 C++ Programming Arrays CSE202- Lec#6 (Operations on Arrays) Outline To declare an array To initialize an array Operations on array Introduction Arrays Collection of related data items of same data type. Static entity

More information