CMPE 150: Introduction to Computing Arrays. TT - Spring'08CMPE150: Introduction to Computing1 Motivation You may need to define many variables of the.

Slides:



Advertisements
Similar presentations
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Advertisements

Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
1 Chapter 9 Arrays and Pointers. 2  One-dimensional arrays  The Relationship between Arrays and Pointers  Pointer Arithmetic and Element Size  Passing.
1 Lecture 9  Arrays  Declaration  Initialization  Applications  Pointers  Declaration  The & and * operators  NULL pointer  Initialization  Readings:
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
1 Chapter 8 Functions, Pointers, and Storage Classes  Pointer  Pointers to void  Call-by-Reference  Basic Scope Rules  Storage Classes  Default Initialization.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Pointers Applications
Arrays.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
Systems Programming Concepts
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: Arrays.
C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.
 2006 Pearson Education, Inc. All rights reserved Arrays.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
CMPE 150: Introduction to Computing Functions. A function groups a set of related statements under a single title. You can "call" the function using its.
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Topics to be covered  Introduction to array Introduction to array  Types of array Types of array  One dimensional array One dimensional array  Declaration.
ARRAY Prepared by MMD, Edited by MSY1.  Introduction to arrays  Declaring arrays  Initializing arrays  Examples using arrays  Relationship with pointers.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
UNIT 14 Functions with Pointer Parameters.
Arrays Array –Group of consecutive memory locations –Same name and type To refer to an element, specify –Array name –Position number Format: arrayname.
C Arrays Systems Programming. Systems Programming: Arrays 22 ArraysArrays  Arrays  Defining and Initializing Arrays  Array Example  Subscript Out-of-Range.
Pointers OVERVIEW.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
Chapter 8: Arrays Introduction to arrays Declaring arrays Initializing arrays Examples using arrays Relationship with pointers Array passing to a function.
Implementing Subprograms What actions must take place when subprograms are called and when they terminate? –calling a subprogram has several associated.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 3.
EEE 145 Programming in C++ Arrays 0. Motivation You may need to define many variables of the same type. –Defining so many variables one by one is cumbersome.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
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 10 Multidimensional Arrays.
Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
Computer Programming for Engineers
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
CSE 251 Dr. Charles B. Owen Programming in C1 Intro to Arrays Storing List of Data.
8. ARRAYS. Aggregate variables Scalar variables –Single value Aggregate variables –Collection of values –Arrays: elements have the same type.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
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.
Pointers. Pointer Fundamentals  When a variable is defined the compiler (linker/loader actually) allocates a real memory address for the variable. –int.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
1 Agenda Arrays: Definition Memory Examples Passing arrays to functions Multi dimensional arrays.
Arrays and Pointers (part 1) CSE 2031 Fall July 2016.
1-d Arrays.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Lecture 6 C++ Programming
C Arrays Systems Programming.
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Lecture 10 Arrays.
Arrays.
7 Arrays.
To refer to an element, specify
Functions.
Lecture 14: Problems with Lots of Similar Data
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Presentation transcript:

CMPE 150: Introduction to Computing Arrays

TT - Spring'08CMPE150: Introduction to Computing1 Motivation You may need to define many variables of the same type. –Defining so many variables one by one is cumbersome. Probably you would like to execute similar statements on these variables. –You wouldn't want to write the same statements over and over for each variable.

TT - Spring'08CMPE150: Introduction to Computing2 Example #1 Write a program that reads the grades of 350 students in CMPE150 and finds the average.

TT - Spring'08CMPE150: Introduction to Computing3 Example #1 (cont'd) Sol n : #include int main() { int i, sum=0, grade; float avg; for (i=0; i<350; i++) { scanf("%d", &grade); sum += grade; } avg = sum/350.0; printf("Average = %f\n",avg); return 0; } This was simple. Since we don't need to store all values, taking the sum is enough. So, we don't need an array.

TT - Spring'08CMPE150: Introduction to Computing4 Example #2 Write a program that reads the grades of 350 students in CMPE150 and finds those that are below the average.

TT - Spring'08CMPE150: Introduction to Computing5 Example #2 (cont'd) Sol n #1: #include int main() { int i, sum=0, grade; float avg; for (i=0; i<350; i++) { scanf("%d", &grade); sum += grade; } avg = sum/350.0; for (i=0; i<350; i++) if (grade<avg) printf("Below avg: %d\n",grade); return 0; } WRONG! "grade" contains the score of the last student. You have already lost the previous 349 scores.

TT - Spring'08CMPE150: Introduction to Computing6 Example #2 (cont'd) Sol n #2: #include int main() { int i,sum,gr0,gr1,gr2,...,gr349; float avg; scanf("%d", &gr0); scanf("%d", &gr1); scanf("%d", &gr2);... scanf("%d", &gr349); sum = gr0+gr1+gr2+...+gr349; avg = sum/350.0; if (gr0<350) printf("Below avg: %d\n",gr0); if (gr1<350) printf("Below avg: %d\n",gr1); if (gr2<350) printf("Below avg: %d\n",gr2);... if (gr349<350) printf("Below avg: %d\n",gr349); return 0; } You cannot skip these with "..." You have to repeat each of these statements 350 times. What is still wrong here?

TT - Spring'08CMPE150: Introduction to Computing7 Example #2 (cont'd) Sol n #3: #include int main() { int i, sum=0, grade[350]; float avg; for (i=0; i<350; i++) { scanf("%d", &grade[i]); sum += grade[i]; } avg = sum/350.0; for (i=0; i<350; i++) if (grade[i]<avg) printf("Below avg: %d\n",grade[i]); return 0; } Defines an array consisting of 350 integer values. In the definition, the value in the brackets is the number of elements (size). This means the i th element of the array. Here, the value in the brackets is the index, not the size.

TT - Spring'08CMPE150: Introduction to Computing8 Arrays An array is a variable that is a collection of multiple values of the same type. Syntax: type array_name[int_constant_value]={initializer_list}; The size has to be of int type and must be a fixed value (i.e., known at compile time). You can define an array of any type (eg: int, float, enum student_type, etc.) All elements of the array have the same type. You cannot use the {} format for initialization after variable definition, ie, int a[3]={5,8,2} is correct, but int a[3];... a={5,8,2} is wrong.

TT - Spring'08CMPE150: Introduction to Computing9 Arrays The index must of int type. int k[5]; k[k[4]/k[1]]=2; /* Correct as long as k[4]/k[1] is nonnegative*/ k[1.5] = 3; /* Error since 1.5 is not int */

TT - Spring'08CMPE150: Introduction to Computing10 Arrays The lower bound must be nonnegative. float m[8]; int i; m[-2] = 9.2; /* Syntax error */ i=-2; m[i] = 9.2; /* Run-time error */

TT - Spring'08CMPE150: Introduction to Computing11 Initializing Arrays The elements of a local array are arbitrary (as all other local variables). The elements of a global array are initialized to zero by default (as all other global variables).

TT - Spring'08CMPE150: Introduction to Computing12 Initializing Arrays You may initialize an array during definition as follows: int array[5] = {10, 8, 36, 9, 13}; However, you cannot perform such an initialization after the definition, i.e., int array[5]; array = {10, 8, 36, 9, 13}; is syntactically wrong.

TT - Spring'08CMPE150: Introduction to Computing13 Initializing Arrays If the number of initializers is less than the size of the array: –initialization starts by assigning the first value to the first element and continues as such, –remaining elements are initialized to zero (even if the array was local) Eg: For the definition int array[5] = {10, 8, 36}; the first 3 elements get the values 10, 8, and 36, respectively. array[3] and array[4] become 0.

TT - Spring'08CMPE150: Introduction to Computing14 Initializing Arrays If the number of initializers is more than the size of the array, it is a syntax error. It is also possible to skip the size of the array iff the array is explicitly initialized. –In this case, the compiler fills in the size to the number of initializers. –Eg: For the definition int array[ ] = {5, 9, 16, 3, 5, 2, 4}; the compiler acts as if the array was defined as follows: int array[7] = {5, 9, 16, 3, 5, 2, 4};

TT - Spring'08CMPE150: Introduction to Computing15 Example #3 Read 100 integers and find the unbiased variance. #include int main() { int X[100], i; float avg=0,var=0; for (i=0; i<100; i++) { scanf("%d",&X[i]); avg += X[i]; } avg /= 100; for (i=0; i<100; i++) var += (X[i]-avg) * (X[i]-avg); var /= 99; printf("variance:%f\n", var); return 0; } Unbiased variance of a sample is defined as

TT - Spring'08CMPE150: Introduction to Computing16 Example #4 Find the histogram of the scores in Midterm 1. #include int main() { int i, hist[101]={0}, score; for (i=0; i<350; i++) { scanf("%d", &score); hist[score]++; } for (i=0; i<101; i++) printf("%d student(s) got %d\n", hist[i], i); return 0; }

TT - Spring'08CMPE150: Introduction to Computing17 Example #5 Check if the array in the input is symmetric (eg: 8, 10, 6, 2, 6, 10, 8) #include #define SIZE 10 int main() { int numbers[SIZE], i; for (i=0; i<SIZE; i++) scanf("%d",&numbers[i]); for (i=0; i<SIZE/2; i++) if (numbers[i] != numbers[SIZE-1-i]) break; printf("It is "); if (i!=SIZE/2) printf("not "); printf("symmetric\n"); return 0; }

TT - Spring'08CMPE150: Introduction to Computing18 Arrays Have Fixed Size! The size of an array must be stated at compile time. This means you cannot define the size when you run the program. You should fix it while writing the program. This is a very serious limitation for arrays. Arrays are not fit for dynamic programming. –You should use pointers for this purpose, but we will not cover pointers in this course.

TT - Spring'08CMPE150: Introduction to Computing19 Arrays Have Fixed Size! What you can do is to define very large arrays, making the size practically infinite  Wastes too much memory. Your program may exceed the maximum memory limit for the process.

Example #6 Read two polynomials. Perform addition and multiplication operations. #include #define MAX 100 int main() { int p1[MAX]={0}, p2[MAX]={0}, result[MAX]={0}, i, n; printf("Enter the degree of first polynom:"); scanf("%d",&n); if (n >= MAX) return 0; printf("Enter coefficients:"); for (i=n; i>=0; i--) scanf("%d",&p1[i]); printf("Enter the degree of second polynom:"); scanf("%d",&n); if (n >= MAX) return 0; printf("Enter coefficients:"); for (i=n; i>=0; i--) scanf("%d",&p2[i]); /* Multiply */ for (i=0; i<MAX; i++) for (n=0; n<MAX; n++) if (p1[i] * p2[n] != 0) result[i+n] += p1[i] * p2[n]; return 0; }

TT - Spring'08CMPE150: Introduction to Computing21 Arrays as Parameters Although you write like a value parameter, an array is always passed by reference (variable parameter). –Therefore, when you make a change in an element of an array in the function, the change is visible from the caller.

TT - Spring'08CMPE150: Introduction to Computing22 Example #7 Fill in an array of integer from input. #include void read_array(int ar[10]) { int i; for (i=0; i<10; i++) scanf("%d", &ar[i]); } int main() { int a[10], i; read_array(a); for (i=0; i<10; i++) printf("%d ",a[i]); return 0; }

TT - Spring'08CMPE150: Introduction to Computing23 Arrays as Parameters The size you specify in the function header is not important; you may even skip it. Eg: void func(int arr[5]) { int i; for (i=0; i<10; i++) arr[i]=i; } int main() { int a[10], i; func(a); for (i=0; i<10; i++) printf("%d ",a[i]); return 0; } This will work without any problems though the function header is misleading.

TT - Spring'08CMPE150: Introduction to Computing24 Example #8 Write a function that inverts its array parameter. void invert(int ar[10]) { int i, temp; for (i=0; i<10; i++) { temp=ar[i]; ar[i] = ar[9-i]; ar[9-i] = temp; } What is wrong here?

TT - Spring'08CMPE150: Introduction to Computing25 Example #9: Bubble Sort Sort the values in an array in ascending order. #include void read_array(int ar[], int size) { int i; for (i=0; i<size; i++) scanf("%d", &ar[i]); } void print_array(int ar[], int size) { int i; for (i=0; i<size; i++) printf("%3d", ar[i]); printf("\n"); } void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; }

TT - Spring'08CMPE150: Introduction to Computing26 Example #9: Bubble Sort (cont'd) void bubble_sort(int ar[], int size) { int i, j; for (i = 0; i < size; i++) for (j = i + 1; j < size; j++) if (ar[i] > ar[j]) swap(&ar[i],&ar[j]); } int main() { int ar[10]; read_array(ar,10); bubble_sort(ar,10); print_array(ar,10); return 0; }

TT - Spring'08CMPE150: Introduction to Computing27 Example #10: Insertion Sort void insertion_sort(int ar[], int size) { int value, i, j; for (i=1; i<size; i++) { value = ar[i]; j = i-1; while ((j>=0) && (ar[j]>value)) { ar[j+1] = ar[j]; j--; } ar[j+1] = value; }

TT - Spring'08CMPE150: Introduction to Computing28 Example #11: Binary Search Given a sorted array, search for a specific value and return its index. int binary_search(int A[], int number, int N) { int low = 0, high = N - 1, mid; while (low <= high) { mid = (low + high) / 2; if (A[mid] == number) return mid; if (A[mid] < number) low = mid + 1; else high = mid - 1; } return -1; }