Arrays. Systems Programming Concepts

Similar documents
Array. Arrays. Declaring Arrays. Using Arrays

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

C Arrays Pearson Education, Inc. All rights reserved.

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

C: How to Program. Week /Apr/23

C++ PROGRAMMING SKILLS Part 4: Arrays

Multiple-Subscripted Arrays

BBS 514 YAPISAL PROGRAMLAMA (STRUCTURED PROGRAMMING)

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

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

Lecture 04 FUNCTIONS AND ARRAYS

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) A few types

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.

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

Content. In this chapter, you will learn:

Arrays and Applications

C: How to Program. Week /Apr/16

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

Programming for Engineers Arrays

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

Computer Science & Engineering 150A Problem Solving Using Computers

Two Dimensional Array - An array with a multiple indexs.

Chapter 5 - Functions

Introduction to C Final Review Chapters 1-6 & 13

FOR Loop. FOR Loop has three parts:initialization,condition,increment. Syntax. for(initialization;condition;increment){ body;

by Pearson Education, Inc. All Rights Reserved. 2

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

CSE101-Lec#17. Arrays. (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

Two Dimensional Array - An array with a multiple indexs.

AMCAT Automata Coding Sample Questions And Answers

C: How to Program. Week /Mar/05

ONE DIMENSIONAL ARRAYS

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

In this session we will cover the following sub-topics: 1.Identifiers 2.Variables 3.Keywords 4.Statements 5.Comments 6.Whitespaces 7.Syntax 8.

C Functions. 5.2 Program Modules in C

Basic Elements of C. Staff Incharge: S.Sasirekha

C Programming Review CSC 4320/6320

Yacoub Sabatin Muntaser Abulafi Omar Qaraeen

Lesson 7. Reading and Writing a.k.a. Input and Output

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

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

Fundamental of Programming (C)

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays

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

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

Loops / Repetition Statements

Structured Program Development in C

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

Programming in C. What is C?... What is C?

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

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

by: Lizawati, Norhidayah & Muhammad Noorazlan Shah Computer Engineering, FKEKK, UTeM

Chapter 3 Structured Program Development

ARRAYS(II Unit Part II)

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

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

UNIT-IV. Structure is a user-defined data type in C language which allows us to combine data of different types together.

Computer Programming Lecture 14 Arrays (Part 2)

Chapter 2 - Introduction to C Programming

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.

12 CREATING NEW TYPES

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

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

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

Procedural Programming

by Pearson Education, Inc. All Rights Reserved.

Q1: Functions / 33 Q2: Arrays / 47 Q3: Multiple choice / 20 TOTAL SCORE / 100 Q4: EXTRA CREDIT / 10

CS 108 Computing Fundamentals. October/November Array Bootcamp

CSE123. Program Design and Modular Programming Functions 1-1

ESC101N Fundamentals of Computing

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Chapter 1 & 2 Introduction to C Language

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

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

How to declare an array in C?

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Programming. Structures, enums and unions

Structured Programming. Dr. Mohamed Khedr Lecture 9

The four laws of programs

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

Preview from Notesale.co.uk Page 2 of 79

Functions. Systems Programming Concepts

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

Data Types and Computer Storage Arrays and Pointers. K&R, chapter 5

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

Arrays. Arizona State University 1

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

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

Fundamentals of Programming Session 8

공학프로그래밍언어 (PROGRAMMING LANGUAGE FOR ENGINEERS) -CONTROL FLOW : LOOP- SPRING 2015, SEON-JU AHN, CNU EE

Note: unless otherwise stated, the questions are with reference to the C Programming Language. You may use extra sheets if need be.

Day06 A. Young W. Lim Wed. Young W. Lim Day06 A Wed 1 / 26

Lecture 3. The syntax for accessing a struct member is

Chapter 3: Arrays and More C Functionality

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

More non-primitive types Lesson 06

QUIZ: loops. Write a program that prints the integers from -7 to 15 (inclusive) using: for loop while loop do...while loop

Transcription:

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 Double-Subscripted Array Example enum and switch Systems Programming Arrays 2

Arrays Arrays:: Structures of related data items Static entities, namely, the size of an array remains constant throughout the program execution. A group of contiguous memory locations with the same name and type. Systems Programming Arrays 3

Arrays To refer to an array element, specify the array name the position number {in C this is an offset} Referred to as a subscript. Format: arrayname[position number] First element is at position 0 n element array named c: c[ 0 ], c[ 1 ]...c[ n 1 ] Systems Programming Arrays 4

Fig. 6.1 12-element Array Systems Programming Arrays 5

Arrays Array elements are like normal variables. c[ 0 ] = 3; printf( "%d", c[ 0 ] ); One can perform operations within the subscript which must be an integer or an integer expression. Examples: c[ x- 2 ] = 6; c[i+j- 4] = c[x-2]; c[intfcn(i)] = 0; Systems Programming Arrays 6

6.3 Defining Arrays When defining arrays, specify Name Type of array Number of elements arraytype arrayname[ numberofelements ]; Examples: int c[ 10 ]; float myarray[ 3284 ]; Defining multiple arrays of same type Format similar to regular variables Example: int b[ 100 ], x[ 27 ]; Systems Programming Arrays 7

Initializing Array int n[ 5 ] = { 1, 2, 3, 4, 5 }; If not enough initializers, rightmost elements become 0. int n[ 5 ] = { 0 } All elements 0 If too many initializers, a syntax error occurs! C arrays have no bounds checking!! If size omitted, initializers determine size. int n[ ] = { 1, 2, 3, 4, 5 }; 5 initializer elements, therefore n is a 5 element array. Systems Programming Arrays 8

Fig. 6.5 Array Example [old] 1 /* Fig. 6.5: fig06_05.c 2 Initialize the elements of array s to the even integers from 2 to 20 */ 3 #include <stdio.h> 4 #define SIZE 10 /* maximum size of array */ 5 6 /* function main begins program execution */ 7 int main( void ) 8 { 9 /* symbolic constant SIZE can be used to specify array size */ 10 int s[ SIZE ]; /* array s has SIZE elements */ 11 int j; /* counter */ 12 13 for ( j = 0; j < SIZE; j++ ) { /* set the values */ 14 s[ j ] = 2 + 2 * j; 15 } /* end for */ 16 17 printf( "%s%13s\n", "Element", "Value" ); 18 19 /* output contents of array s in tabular format */ 20 for ( j = 0; j < SIZE; j++ ) { 21 printf( "%7d%13d\n", j, s[ j ] ); 22 } /* end for */ 23 24 return 0; /* indicates successful termination */ 25 26 } /* end main */ #define directive tells compiler to replace all instances of the word SIZE with 10. SIZE is replaced with 10 by the compiler, so array s has 10 elements. Systems Programming Arrays 9

Fig. 6.5 Array Example [new] size_t type is shorthand for unsigned int printf also needs to indicated unsigned int 1992-2013 by Pearson Education, Inc. All Rights Reserved. Systems Programming Arrays 10

Fig. 6.5 Array Example [new] 1992-2013 by Pearson Education, Inc. All Rights Reserved. Systems Programming Arrays 11

Arrays Arrays are dangerous in C because: There is no default initialization. There is no bounds checking for subscripts out-of-range. Systems Programming Arrays 12

Scary Out-of-Range Example /* Bizarre Example of subscripting out of range */ int main () { int i, m, n, j; int a[100], k, p; j = 77; k = 88; p = 99; p a[-2] k a[-1] a[0] a[1] 99-2 } for (i= -1; i<=103; i++) { a[i] = 2*i; if (i > 98) printf("i =%d, a[i] = %d\n", i, a[i]); } printf("j = %d, n = %d, m = %d, i = %d, k = %d, p = %d\n", j, n, m, i, k, p); printf("%d %d %d %d %u\n", a[-1], a[99], a[100], a[102], a[i]); return 0; a[99] j a[100] n a[101] m a[102] i a[103] 198 200 202 204 206 i =99, a[i] = 198 i =100, a[i] = 200 i =101, a[i] = 202 i =102, a[i] = 204 i =206, a[i] = 15 j = 200, n = 202, m = 204, i = 207, k = -2, p = 99-2 198 200 204 3220526203 Systems Programming Arrays 13

6.5 Passing Arrays to Functions To pass an array argument to a function, specify the name of the array without any brackets. The array size is usually passed to the function. int myarray[ 24 ]; myfunction( myarray, 24 ); Arrays are passed by-reference. The name of the array is associated with the address of the first array element. The function knows where the array is stored and it can modify the original memory locations. Systems Programming Arrays 14

6.5 Passing Arrays to Functions Individual array elements Are passed by value. Pass the subscripted name (i.e., myarray[ 3 ]) to function. Function prototype void modifyarray( int b[], int arraysize ); Parameter names are optional in prototype. int b[] could be written int [] int arraysize could be simply int Systems Programming Arrays 15

Passing Arrays to Functions /* Arrays are passed using Call by Reference */ #include <math.h> #define SIZE 6 void flip (float fray [], int fsize) { float temp; int i,j; i = fsize - 1; for (j = 0; j < fsize/2 ; j++) { temp = fray[j]; fray[j] = fray[i]; fray[i] = temp; i--; } return; } Systems Programming Arrays 16

Passing Arrays to Functions int main () { float var[size]; int i,j; for (i=0; i < SIZE; i++) { var[i] = 1.0/pow (2.0,i); printf(" %5.3f", var[i]); } printf("\n"); $./passray 1.000 0.500 0.250 0.125 0.062 0.031 0.031 0.062 0.125 0.250 0.500 1.000 1.000 0.500 0.250 0.125 0.062 0.031 for (j=0; j < 2; j++) { flip (var, SIZE); for (i=0; i < SIZE; i++) printf(" %5.3f", var[i]); printf("\n"); } } Systems Programming Arrays 17

6.9 Multiple-Subscripted Arrays Multiple subscripted arrays Tables with rows and columns (m by n array) Like matrices: specify row, then column Initialization int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; Initializers grouped by row in braces If not enough, unspecified elements set to zero int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; Referencing elements Specify row, then column printf( "%d", b[ 0 ][ 1 ] ); Systems Programming Arrays 18

Fig. 6.20 Double-Subscripted array Three rows and four columns. Systems Programming Arrays 19

Double-Subscripted Array Example 1 /* Fig. 6.22: fig06_22.c 2 Double-subscripted array example */ 3 #include <stdio.h> 4 #define STUDENTS 3 5 #define EXAMS 4 6 7 /* function prototypes */ 8 int minimum( const int grades[][ EXAMS ], int pupils, int tests ); 9 int maximum( const int grades[][ EXAMS ], int pupils, int tests ); 10 double average( const int setofgrades[], int tests ); 11 void printarray( const int grades[][ EXAMS ], int pupils, int tests ); 12 13 /* function main begins program execution */ 14 int main( void ) 15 { 16 int student; /* student counter */ 17 18 /* initialize student grades for three students (rows) */ 19 const int studentgrades[ STUDENTS ][ EXAMS ] = 20 { { 77, 68, 86, 73 }, 21 { 96, 87, 89, 78 }, 22 { 70, 90, 86, 81 } }; 23 24 /* output array studentgrades */ 25 printf( "The array is:\n" ); 26 printarray( studentgrades, STUDENTS, EXAMS ); 27 Notice const Each row in the array corresponds to a single student s set of grades Systems Programming Arrays 20

Double-Subscripted Array Example 28 /* determine smallest and largest grade values */ 29 printf( "\n\nlowest grade: %d\nhighest grade: %d\n", 30 minimum( studentgrades, STUDENTS, EXAMS ), 31 maximum( studentgrades, STUDENTS, EXAMS ) ); 32 33 /* calculate average grade for each student */ 34 for ( student = 0; student < STUDENTS; student++ ) { 35 printf( "The average grade for student %d is %.2f\n", 36 student, average( studentgrades[ student ], EXAMS ) ); 37 } /* end for */ 38 39 return 0; /* indicates successful termination */ 40 41 } /* end main */ 42 average function is passed a row of the array Systems Programming Arrays 21

Double-Subscripted Array Example 43 /* Find the minimum grade */ 44 int minimum( const int grades[][ EXAMS ], int pupils, int tests ) 45 { 46 int i; /* student counter */ 47 int j; /* exam counter */ 48 int lowgrade = 100; /* initialize to highest possible grade */ 49 50 /* loop through rows of grades */ 51 for ( i = 0; i < pupils; i++ ) { 52 53 /* loop through columns of grades */ 54 for ( j = 0; j < tests; j++ ) { 55 56 if ( grades[ i ][ j ] < lowgrade ) { 57 lowgrade = grades[ i ][ j ]; 58 } /* end if */ 59 60 } /* end inner for */ 61 62 } /* end outer for */ 63 64 return lowgrade; /* return minimum grade */ 65 66 } /* end function minimum */ 67 Systems Programming Arrays 22

Double-Subscripted Array Example 68 /* Find the maximum grade */ 69 int maximum( const int grades[][ EXAMS ], int pupils, int tests ) 70 { 71 int i; /* student counter */ 72 int j; /* exam counter */ 73 int highgrade = 0; /* initialize to lowest possible grade */ 74 75 /* loop through rows of grades */ 76 for ( i = 0; i < pupils; i++ ) { 77 78 /* loop through columns of grades */ 79 for ( j = 0; j < tests; j++ ) { 80 81 if ( grades[ i ][ j ] > highgrade ) { 82 highgrade = grades[ i ][ j ]; 83 } /* end if */ 84 85 } /* end inner for */ 86 87 } /* end outer for */ 88 89 return highgrade; /* return maximum grade */ 90 91 } /* end function maximum */ 92 Systems Programming Arrays 23

Double-Subscripted Array Example 93 /* Determine the average grade for a particular student */ 94 double average( const int setofgrades[], int tests ) 95 { 96 int i; /* exam counter */ 97 int total = 0; /* sum of test grades */ 98 99 /* total all grades for one student */ 100 for ( i = 0; i < tests; i++ ) { 101 total += setofgrades[ i ]; 102 } /* end for */ 103 104 return ( double ) total / tests; /* average */ 105 106 } /* end function average */ 107 108 /* Print the array */ 109 void printarray( const int grades[][ EXAMS ], int pupils, int tests ) 110 { 111 int i; /* student counter */ 112 int j; /* exam counter */ 113 114 /* output column heads */ 115 printf( " [0] [1] [2] [3]" ); 116 Systems Programming Arrays 24

Double-Subscripted Array Example 117 /* output grades in tabular format */ 118 for ( i = 0; i < pupils; i++ ) { 119 120 /* output label for row */ 121 printf( "\nstudentgrades[%d] ", i ); 122 123 /* output grades for one student */ 124 for ( j = 0; j < tests; j++ ) { 125 printf( "%-5d", grades[ i ][ j ] ); 126 } /* end inner for */ 127 128 } /* end outer for */ 129 130 } /* end function printarray */ The array is: [0] [1] [2] [3] studentgrades[0] 77 68 86 73 studentgrades[1] 96 87 89 78 studentgrades[2] 70 90 86 81 Lowest grade: 68 Highest grade: 96 The average grade for student 0 is 76.00 The average grade for student 1 is 87.50 The average grade for student 2 is 81.75 Systems Programming Arrays 25

An enum and switch Example /* A program that uses enumerated types, switch and a sentinel to terminate input */ #define SENTINEL 10 int main () { int day; /* enum starts assigning positional integers beginning with 0 */ enum days {SUN, MON, TUES, WED, THUR, FRI, SAT}; scanf("%d", &day); while( day!= SENTINEL) { switch (day) { case MON: case WED: case FRI: printf("%d - Go to class\n", day); break; Systems Programming Arrays 26

An enum and switch Example case TUES: printf("%d - Sleep in until 10\n", day); break; case THUR: printf("%d - Do laundry\n", day); break; case SAT: printf("%d - Go to gym. ", day); printf("go out to a movie\n"); break; case SUN: printf("%d - Study lots!\n", day); break; default: printf("%d - This invalid input. Try again.", day); break; } scanf("%d", &day); } printf("sentinal encountered.\n"); return 0; } Systems Programming Arrays 27

Review of Arrays Arrays Defining and Initializing Arrays Array Example Subscript Out-of-Range Example Passing Arrays to Functions Call by Reference Multiple-Subscripted Arrays Double-Subscripted Array Example Enum and Switch Example Systems Programming Arrays 28