Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

The simple built-in data types of the C language such as int, float, - are not sufficient to represent complex data such as lists, tables, vectors, and.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
CHAPTER 10 ARRAYS II Applications and Extensions.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
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.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Arrays (Part II). Two- and Multidimensional Arrays Two-dimensional array: collection of a fixed number of components (of the same type) arranged in two.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
CS1061 C Programmuing Lecture 12 Arrays A. O’Riordan, 2004.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
1 Introduction to Arrays Problem: –Input 5 scores, compute total, average –Input Example –test scores,employees,temperatures.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
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.
Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR
 2006 Pearson Education, Inc. All rights reserved Arrays.
chap8 Chapter 8 Arrays (Hanly) chap8 2 Data Structure Simple data types use a simple memory to store a variable. Data Structure: a.
Chapter 8 Arrays and Strings
Chapter 2 ARRAYS.
Data Strcutures.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman CP 202 Chapter
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 
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
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.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
CSC 211 Data Structures Lecture 13
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 8: Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function.
Chapter 8 Arrays Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
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.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
IN THE NAME OF ALLAH WHO IS THE MOST BENEFICENT AND MOST MERCIFUL.
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.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
1. Searching The basic characteristics of any searching algorithm is that searching should be efficient, it should have less number of computations involved.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
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.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
Objectives You should be able to describe: One-Dimensional Arrays
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Computer Programming BCT 1113
Arrays and Records.
ㅎㅎ Fourth step for Learning C++ Programming Two functions
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Data Structures (CS212D) Week # 2: Arrays.
EECE.2160 ECE Application Programming
ICS103: Programming in C Searching, Sorting, 2D Arrays
Presentation transcript:

Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea

Arrays

Introduction to Programming in CL7.3 Arrays - Introduction Simple data types, that we have seen so far, use a single memory cell to store a single value. For solving some problems efficiently, we require a sequence of values where all value are of the same type. An array is such a data structure. –An array is a collection of adjacent memory cells called array elements that are associated with a single symbolic name.

Introduction to Programming in CL7.4 Arrays - Declaration We must declare: 1.The datatype of the array elements 2.the name of the array 3.the number of data items (i.e. elements) Example: datatype of all array elements name of arraynumber of elements double x[8];

Introduction to Programming in CL7.5 Access of array elements To access an element of some array we specify: 1.The name of the array 2.The number of the element, that we would like to read/write. This number is called subscript x[i] Array name subscript

Introduction to Programming in CL7.6 Arrays indexing start at 0 !!!!!!! The first element is the 0 th element! If you declare an array of n elements, the last one is number n-1. If you try to access element number n it is an error! A subscript can be any integer expression: These are all valid subscripts: x[17] x[i+3] x[a+b+c]

Introduction to Programming in CL7.7 Memory-Picture of an array double x[8]; x[0] x[1] x[7] 8 bytes each double is 8 bytes Note that the last element of the array is referred by x[7] not x[8]

Introduction to Programming in CL7.8 Examples of statements for manipulating some array StatementExplanation printf("%lf", x[0]); Prints the value of x[0] x[3] = 25.0; Stores the value 25.0 in x[3] sum = x[0] + x[1]; Stores the sum of x[0] and x[1] in the variable sum sum += x[2]; Adds the value of x[2] to sum x[3] += 1.0; Adds 1.0 to x[3] x[2] = x[0] + x[1]; Stores the sum of x[0] and x[1] in x[2];

Introduction to Programming in CL7.9 Invalid Subscript Reference To create a valid reference, the value of the array subscript must lie between 0 and one less than the declared size of the array. int x[8]; … printf("%d", x[10]); Invalid reference! Run-time error or incorrect result

Introduction to Programming in CL7.10 Array Initialization Recall that a simple variable can be initialized at the same time when it is declared. Likewise, arrays can also be initialized in declaration: double x[]={16.0,12.0,6.0,8.0,2.5,12.0,14.0,-54.5}; Another example: char vowels[]={'A', 'E', 'I', 'O', 'U'}; int sum = 0; In this case, you don't have to provide the number of array elements

Introduction to Programming in CL7.11 Arrays of char are special C provides a special way to deal with arrays of characters: char s[] = "Some text"; char arrays can be initialized with string literals.

Arrays and Functions

Introduction to Programming in CL7.13 Arrays and Functions - Introduction There are two ways of using arrays as function arguments: –Use the individual array element: the function can use only those array elements that are passed into the function. –Use of the entire array: the function has access to all array elements and can manipulate them.

Introduction to Programming in CL7.14 Passing of single array elements Array elements when passed into a function are treated as if they were simple variables of the underlying data types. Example: int x[8], i, sum; x[0] = 2; x[1] = 3; sum = add(x[0], x[1]); printf("%d", sum); … int add(int a, int b) { return a + b; } Note that the data types match.

Introduction to Programming in CL7.15 Passing of complete Arrays Passing the complete array as argument: Example: double y[10]; fill_array(y, 10, 0.0); … void fill_array(double x[], int n, double in_value) { /* sets all elements of the array to in_value */ int i; for (i = 0; i < n; i++) x[i]=in_value; } the entire array y is passed into the function the number of elements is not specified If the function needs to know the array size, this should be passed as function argument.

Introduction to Programming in CL7.16 Call by Reference When an array is passed entirely to a function this is done by using “call by reference”. Call by reference means: All changes to some array A inside some function are although effective wherever we later use the array A outside this function

Introduction to Programming in CL7.17 Example for use of call by reference At the end sum contains all sums double x[10], y[10], sum[10]; fill_array(x, 10, 2.0); fill_array(y, 10, 3.0); add_arrays(x, y, sum, 10); … void add_arrays(double x[], double y[], double sum[], int n) {int i; for (i=0; i < n; i++) sum[i] = x[i] + y[i]; } input arrays output array

Some important Algorithms for Arrays

Introduction to Programming in CL7.19 Sequential Access Very often we wish to process the elements of an array in sequence, starting with element zero. In C, this can be accomplished using an indexed for- loop whose counter runs form zero to one less than the array size.

Introduction to Programming in CL7.20 Sequential Access Example 1: Storing the squares of the integers 0 to 10. int square[11], i; for (i = 0; i < 11, i++) square[i] = i * i Example 2: Storing data items into an array. int x[8], i; for (i = 0; i < 8, i++) scanf("%d", &x[i]); Example 3: Computing the sum of all data. int x[8], i, sum = 0; for (i = 0; i < 8, i++) sum += x[i];

Introduction to Programming in CL7.21 Array Searching A common problem in processing arrays is searching an array to determine the location of a particular value. Example: #include int search (int[], int, int); void main() { int list[] = {2,5,3,52,32,48,-3,-6}; int location; location = search(list, 52, 8); printf("Location for target 52 is %d\n", location); }

Introduction to Programming in CL7.22 Array Searching The implementation of the search function: int search (int arr[], int target, int n) { int i = 0; while (i < n) { if (arr[i] == target) { break; } else i++; } return i + 1; } In the case that target isn't an element of the array arr, the function returns n + 1.

Introduction to Programming in CL7.23 Sorting of Arrays Simple Algorithm for sorting arrays: Bubble-Sort –The basic idea is to repeatedly compare neighboring objects and to swap them if they are in the wrong order. –Elements move upwards to their final positions like air-bubbles in water

Introduction to Programming in CL7.24 Bubble-Sort in C Given an array a of numbers with length n (the array consists of n elements) for (i=0; i<n-1; i++){ for (j=0; j<n-1-i; j++) if (a[j+1] < a[j]){ tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp; } /* if */ } /* outer for */ swap a[j] and a[j+1]

Introduction to Programming in CL7.25 Bubble-Sort / Description The index j in the inner loop travels up the array, comparing adjacent entries in the array (at j and j+1), while the outer loop causes the inner loop to make repeated passes through the array. After the first pass, the largest element is guaranteed to be at the end of the array, after the second pass, the second largest element is in position, and so on.

Introduction to Programming in CL7.26 Binary Search in Arrays A fast way to search a sorted array is to use a binary search. The idea is to look at the element in the middle: –If the key is equal to that, the search is finished. –If the key is smaller than the middle element, do a binary search on the first half. –If it's greater, do a binary search on the second half. (We denote the element we are searching for the “key”)

Introduction to Programming in CL7.27 Binary-Search in C int binarySearch(int a[], int first, int last, int key) { while (first <= last) { int mid = (first + last) / 2; // compute mid point. if (key > a[mid]) first = mid + 1; // repeat search in top half. else if (key < a[mid]) last = mid - 1; // repeat search in bottom half. else return mid; // found it. return position } return -1; // failed to find key } Parameters: –a : array of sorted (ascending) values. –first, last : lower and upper subscript bounds –key : value to search for.

Multidimensional Arrays

Introduction to Programming in CL7.29 Multidimensional Arrays The arrays, that we have seen so far, are all with one dimension. int x[size]; A multidimensional array is an array with two or more dimensions. double y[size1][size2]; int z[size1][size2]…[sizeN]; there is only one subscript two dimensional array n-dimensional array allocates memory for size1 * size2 * … * sizeN data items

Introduction to Programming in CL D Array: int A[3][4] Col 0Col 1Col 2Col 3 Row 0 A[0][0]A[0][1]A[0][2]A[0][3] Row 1 A[1][0]A[1][1]A[1][2]A[1][3] Row 2 A[2][0]A[2][1]A[2][2]A[2][3]

Introduction to Programming in CL D Memory Organization int A[4][3]; A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2] A[2][0] A[2][1] A[2][2] A[3][0] A[3][1] A[3][2] A[0] A[1] A[2] A[3] { { { { A is an array of size 4. Each element of A is an array of 3 chars

Introduction to Programming in CL7.32 Multidimensional Arrays Two-dimensional arrays are used to represent tables of data, matrices, etc. Example: Multiplication table: Columns Rows #define NROWS 5 #define NCOLS 5 … int table[NROWS][NCOLS]; int i, j; for (i=0; i<NROWS, i++) for (j=0; j<NCOLS; j++) table[i][j]=i*j; printf("%d", table[2][3]);

Introduction to Programming in CL7.33 Initialization of Multidimensional Arrays Multidimensional arrays can be initialized in their declarations, just like one-dimensional arrays are initialized. Instead of listing all table values in one list, these values are grouped by rows. Example: char table[3][2]={{'A','B'}, {'D','G'}, {'1','0'}};

Introduction to Programming in CL7.34 Multidimensional Arrays as Function Arguments Multidimensional arrays can be passed to a function, as individual array elements or entirely, just like one- dimensional arrays. The size of the array, in one-dimensional case, is not specified in the function prototype void function1(int x[]); However, with multidimensional arrays, the size of the array must be specified in the function prototype. void function2(int y[3][2][5]); Therefore, only fixed-size multidimensional arrays can be passed into a function. Here, there is only one exception: the first size of the array can be omitted. Thus, the following function prototype is also valid: void function2(int y[][2][5]);

Introduction to Programming in CL7.35 Multidimensional Arrays as Function Arguments Example: Recall the multiplication table example. Let's also compute the sum of the numbers in each row of the table. #include #define NROWS 5 #define NCOLS 5 void mult_table(int[NROWS][NCOLS]); void sum_table(int[][NCOLS], int[]); int main(){ int table[NROWS][NCOLS]; int sum_row[NROWS]; mult_table(table); sum_table(table, sum_row); return 0; }

Introduction to Programming in CL7.36 void mult_table(int matrix[NROWS][NCOLS]){ /* compute the multiplication table */ int i, j; for (i=0; i<NROWS; i++) for (j=0; j<NCOLS; j++) matrix[i][j]=i*j; } void sum_table(int matrix[][NCOLS], int arr[]){ /* compute the sum of the numbers in each row */ int i, j; for (i=0; i<NROWS; i++){ arr[i] = 0; for (j=0; j<NCOLS; j++) arr[i] += matrix[i][j]; } could be written as [ ] Multidimensional Arrays as Function Arguments