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

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

Chapter 7 : Arrays (pp )

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

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.

C for Engineers and Scientists: An Interpretive Approach. Chapter 10: Arrays

Week 8: Arrays and File I/O. BJ Furman 21OCT2009

C++ for Engineers and Scientists. Third Edition. Chapter 12 Pointers

Multiple-Subscripted Arrays

Unit 3 Decision making, Looping and Arrays

Chapter 3: Arrays and More C Functionality

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

Special PRG Lecture No. 2. Professor David Brailsford Special PRG Lecture: Arrays

CSCI 171 Chapter Outlines

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

Computer Science & Engineering 150A Problem Solving Using Computers

How to declare an array in C?

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

Single Dimension Arrays

A First Book of ANSI C Fourth Edition. Chapter 12 Structures

Programming for Electrical and Computer Engineers. Pointers and Arrays

Lecture 04 FUNCTIONS AND ARRAYS

Array Initialization

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology 8/23/2014. Arrays Hold Multiple Values

Chapter 9 Introduction to Arrays. Fundamentals of Java

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

Programming for Engineers Arrays

Module 6: Array in C

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

Abstract Data Type (ADT) & ARRAYS ALGORITHMS & DATA STRUCTURES I COMP 221

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

Chapter 7: Arrays Copyrig opy ht rig 2012 Pea e rson a Educa Educ ti a on, Inc I. nc

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

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. A single variable can only hold one value. Declared using [] operator:

Unit 7. Functions. Need of User Defined Functions

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

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

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

C Programming

ONE DIMENSIONAL ARRAYS

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

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

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

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

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

Procedural Programming

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

Binghamton University. CS-220 Spring Arrays in C

Computer Programming Unit 3

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Chapter 8 :: Composite Types

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

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

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

Engineering program development 6. Edited by Péter Vass

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

Pointers. Memory. void foo() { }//return

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

EC312 Chapter 4: Arrays and Strings

MA 511: Computer Programming Lecture 2: Partha Sarathi Mandal

Yacoub Sabatin Muntaser Abulafi Omar Qaraeen

ARRAYS(II Unit Part II)

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

Lecture 3 Tao Wang 1

Function Call Stack and Activation Records

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

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved.

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

Arrays and Strings. Arash Rafiey. September 12, 2017

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

Chapter 7 Functions. Now consider a more advanced example:

APSC 160 Review Part 2

C: How to Program. Week /Mar/05

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

by Pearson Education, Inc. All Rights Reserved.

Arrays in C. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute of Technology Kharagpur. Basic Concept

Lecture 04 FUNCTIONS AND ARRAYS

Fundamental of Programming (C)

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

Introduction to Computer Science Midterm 3 Fall, Points

More non-primitive types Lesson 06

Arrays / Lists. In this section of notes you will be introduced to new type of variable that consists of other types. Types Of Variables

Review of the C Programming Language for Principles of Operating Systems

Recursion. Data and File Structures Laboratory. DFS Lab (ISI) Recursion 1 / 27

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

STRUCTURED DATA TYPE ARRAYS IN C++ ONE-DIMENSIONAL ARRAY TWO-DIMENSIONAL ARRAY

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

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting

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

Write a C program using arrays and structure

Pointers and Arrays A QUICK PREVIEW OF FOR CHAPTERS 10 AND 11 CMPE13. Cyrus Bazeghi

C-LANGUAGE CURRICULAM

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

BLM2031 Structured Programming. Zeyneb KURT

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

CSE 230 Intermediate Programming in C and C++ Arrays and Pointers

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology

Goals of this Lecture

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

Review of the C Programming Language

Transcription:

A First Book of ANSI C Fourth Edition Chapter 8 Arrays

One-Dimensional Arrays Array Initialization Objectives Arrays as Function Arguments Case Study: Computing Averages and Standard Deviations Two-Dimensional Arrays Common Programming and Compiler Errors A First Book of ANSI C, Fourth Edition 2

Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in data type Also called a scalar variable Data structure (aggregate data type): data type with two main characteristics 1. Its values can be decomposed into individual data elements, each of which is either atomic or another data structure 2. It provides an access scheme for locating individual data elements within the data structure A First Book of ANSI C, Fourth Edition 3

Introduction (continued) One of the simplest data structures, called an array, is used to store and process a set of values, all of the same data type, that forms a logical group A First Book of ANSI C, Fourth Edition 4

Introduction (continued) A First Book of ANSI C, Fourth Edition 5

One-Dimensional Arrays A one-dimensional array, also called a singledimensional array and a single-subscript array, is a list of values of the same data type that is stored using a single group name A First Book of ANSI C, Fourth Edition 6

One-Dimensional Arrays (continued) A First Book of ANSI C, Fourth Edition 7

One-Dimensional Arrays (continued) To create a one-dimensional array: #define NUMELS 5 int grades[numels]; In C, the starting index value for all arrays is 0 Each item in an array is called an element or component of the array Any element can be accessed by giving the name of the array and the element s position The position is the element s index or subscript Each element is called an indexed variable or a subscripted variable A First Book of ANSI C, Fourth Edition 8

One-Dimensional Arrays (continued) A First Book of ANSI C, Fourth Edition 9

One-Dimensional Arrays (continued) A First Book of ANSI C, Fourth Edition 10

One-Dimensional Arrays (continued) A First Book of ANSI C, Fourth Edition 11

One-Dimensional Arrays (continued) Subscripted variables can be used anywhere scalar variables are valid grades[0] = 98; grades[1] = grades[0] - 11; Any expression that evaluates an integer may be used as a subscript #define NUMELS 5 total = 0; /* initialize total to zero */ for (i = 0; i < NUMELS; i++) total = total + grades[i]; /* add a grade */ A First Book of ANSI C, Fourth Edition 12

Input and Output of Array Values Individual array elements can be assigned values using individual assignment statements or, interactively, using the scanf() function #define NUMELS 5 for(i = 0; i < NUMELS; i++) { printf("enter a grade: "); scanf("%d", &grades[i]); } Be careful: C does not check the value of the index being used (called a bounds check) A First Book of ANSI C, Fourth Edition 13

Input and Output of Array Values (continued) Sample output: Enter a grade: 85 Enter a grade: 90 Enter a grade: 78 Enter a grade: 75 Enter a grade: 92 grades 0 is 85 grades 1 is 90 grades 2 is 78 grades 3 is 75 grades 4 is 92 A First Book of ANSI C, Fourth Edition 14

Input and Output of Array Values (continued) Statement is outside of the second for loop; total is displayed only once, after all values have been added A First Book of ANSI C, Fourth Edition 15

Array Initialization The individual elements of all global and static arrays (local or global) are, by default, set to 0 at compilation time The values within auto local arrays are undefined Examples of initializations: int grades[5] = {98, 87, 92, 79, 85}; double length[7] = {8.8, 6.4, 4.9, 11.2}; char codes[6] = {'s', 'a', 'm', 'p', 'l', e'}; char codes[] = {'s', 'a', 'm', 'p', 'l', 'e'}; char codes[] = "sample"; /* size is 7 */ A First Book of ANSI C, Fourth Edition 16

Array Initialization (continued) 1 #define SIZE1 20 2 #define SIZE2 25 3 #define SIZE3 15 4 5 int gallons[size1]; /* a global array */ 6 static int dist[size2]; /* a static global array */ 7 8 int main() 9 { 10 int miles[size3]; /* an auto local array */ 11 static int course[size3]; /* static local array */ 12. 13. 14 return 0; 15 } A First Book of ANSI C, Fourth Edition 17

Array Initialization (continued) The NULL character, which is the escape sequence \0, is automatically appended to all strings by the C compiler A First Book of ANSI C, Fourth Edition 18

Array Initialization (continued) A First Book of ANSI C, Fourth Edition 19

Array Initialization (continued) A First Book of ANSI C, Fourth Edition 20

Arrays as Function Arguments Individual array elements are passed to a function by including them as subscripted variables in the function call argument list findmin(grades[2], grades[6]); Pass by value When passing a complete array to a function, the called function receives access to the actual array, rather than a copy of the values in the array findmax(grades); Pass by reference A First Book of ANSI C, Fourth Edition 21

Arrays as Function Arguments (continued) Size can be omitted A First Book of ANSI C, Fourth Edition 22

Arrays as Function Arguments (continued) A First Book of ANSI C, Fourth Edition 23

Arrays as Function Arguments (continued) A First Book of ANSI C, Fourth Edition 24

Arrays as Function Arguments (continued) A First Book of ANSI C, Fourth Edition 25

Case Study: Computing Averages and Standard Deviations Two statistical functions are created to determine the average and standard deviation, respectively, of an array of numbers A First Book of ANSI C, Fourth Edition 26

Requirements Specification Need two functions Determine the average Determine the standard deviation of a list of integer numbers Each function must accept the numbers as an array and return the calculated values to the calling function We now apply the top-down development procedure to developing the required functions A First Book of ANSI C, Fourth Edition 27

Analyze the Problem Determine the input items: list of integer numbers Determine the desired outputs: (1) average, and (2) standard deviation List the algorithms relating the inputs and outputs: Average Function: Calculate the average by adding the grades and dividing by the # of added grades Standard Deviation Function: 1. Subtract the average from each individual grade. Each number in the new set is called a deviation. 2. Square each deviation found in Step 1. 3. Add the squared deviations and divide the sum by the number of deviations. 4. The square root of the number found in Step 3 is the standard deviation. A First Book of ANSI C, Fourth Edition 28

Select an Overall Solution Problem-Solver Algorithm is adapted: Initialize an array of integers Call the average function Call the standard deviation function Display the returned value of the average function Display the returned value of the standard deviation function A First Book of ANSI C, Fourth Edition 29

Write the Functions A First Book of ANSI C, Fourth Edition 30

Write the Functions (continued) A First Book of ANSI C, Fourth Edition 31

Test and Debug the Functions Write a main() program unit to call the function and display the returned results (see Program 8.6) A test run using Program 8.6 produced the following display: The average of the numbers is 76.40 The standard deviation of the numbers is 13.15 Testing is not complete without verifying the calculation at the boundary points Checking the calculation with all of the same values, such as all 0s and all 100s Use five 0s and five 100s A First Book of ANSI C, Fourth Edition 32

Two-Dimensional Arrays A two-dimensional array, or table, consists of both rows and columns of elements int val[3][4]; A First Book of ANSI C, Fourth Edition 33

Two-Dimensional Arrays (continued) A First Book of ANSI C, Fourth Edition 34

Two-Dimensional Arrays (continued) Initialization: #define NUMROWS 3 #define NUMCOLS 4 int val[numrows][numcols] = { {8,16,9,52}, {3,15,27,6}, {14,25,2,10} }; The inner braces can be omitted: int val[numrows][numcols] = {8,16,9,52,3,15,27, 6,14,25,2,10}; Initialization is done in row order A First Book of ANSI C, Fourth Edition 35

Two-Dimensional Arrays (continued) A First Book of ANSI C, Fourth Edition 36

Two-Dimensional Arrays (continued) A First Book of ANSI C, Fourth Edition 37

Two-Dimensional Arrays (continued) The display produced by Program 8.7 is Display of val array by explicit element 8 16 9 52 3 15 27 6 14 25 2 10 Display of val array using a nested for loop 8 16 9 52 3 15 27 6 14 25 2 10 A First Book of ANSI C, Fourth Edition 38

Two-Dimensional Arrays (continued) A First Book of ANSI C, Fourth Edition 39

Two-Dimensional Arrays (continued) Row size can be omitted A First Book of ANSI C, Fourth Edition 40

Two-Dimensional Arrays (continued) A First Book of ANSI C, Fourth Edition 41

Two-Dimensional Arrays (continued) A First Book of ANSI C, Fourth Edition 42

Internal Array Element Location Algorithm Each element in an array is reached by adding an offset to the starting address of the array Address element i = starting array address + offset For single-dimensional arrays: Offset = i * the size of an individual element For two-dimensional arrays: Offset = column index value * the size of an individual element + row index value * # of bytes in a complete row # of bytes in a complete row = maximum column specification * the size of an individual element A First Book of ANSI C, Fourth Edition 43

Internal Array Element Location Algorithm (continued) A First Book of ANSI C, Fourth Edition 44

Larger Dimensional Arrays A three-dimensional array can be viewed as a book of data tables (the third subscript is called the rank) int response[4][10][6]; A four-dimensional array can be represented as a shelf of books where the fourth dimension is used to declare a desired book on the shelf A five-dimensional array can be viewed as a bookcase filled with books where the fifth dimension refers to a selected shelf in the bookcase Arrays of three, four, five, six, or more dimensions can be viewed as mathematical n-tuples A First Book of ANSI C, Fourth Edition 45

Common Programming Errors Forgetting to declare the array Using a subscript that references a nonexistent array element Not using a large enough conditional value in a for loop counter to cycle through all the array elements Forgetting to initialize the array A First Book of ANSI C, Fourth Edition 46

Common Compiler Errors A First Book of ANSI C, Fourth Edition 47

Summary A single-dimensional array is a data structure that can store a list of values of the same data type Elements are stored in contiguous locations Referenced using the array name and a subscript Single-dimensional arrays may be initialized when they are declared Single-dimensional arrays are passed to a function by passing the name of the array as an argument A First Book of ANSI C, Fourth Edition 48

Summary (continued) A two-dimensional array is declared by listing both a row and a column size with the data type and name of the array Two-dimensional arrays may be initialized when they are declared Two-dimensional arrays are passed to a function by passing the name of the array as an argument A First Book of ANSI C, Fourth Edition 49