Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Chapter 8 Arrays

2 A First Book of ANSI C, Fourth Edition2 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

3 A First Book of ANSI C, Fourth Edition3 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

4 A First Book of ANSI C, Fourth Edition4 Fixed-size, sequence collection of elements of the same data type. Used to represent a list of numbers, or a list of names. Examples: –List of employees in organization –Test scores of a class of students –List of customers and their telephone numbers Introduction (continued)

5 A First Book of ANSI C, Fourth Edition5 Scalar Variables vs Arrays Scalar Variables: a variable to hold a single value Arrays: a group of variables of the same type, individually accessed using an index Arrays are also called homogeneous type (identical / consistent / all the same)

6 A First Book of ANSI C, Fourth Edition6 Why arrays? Say, we need to create a program that accepts the PSI (Pollution Standard Index) readings over a week and finds the average value.

7 A First Book of ANSI C, Fourth Edition7 Solution 1: This program makes use of 7 variables for the PSI readings #include int main () { int psi0, psi1, psi2, psi3, psi4, psi5, psi6; float avg; printf(“Input the PSI for day 0: ”); scanf(“%d”, &psi0); printf(“Input the PSI for day 1: ”); scanf(“%d”, &psi1); ……… printf(“Input the PSI for day 6: ”); scanf(“%d”, &psi6); avg = psi0 + psi1 + psi2 + psi3 + psi4 + psi5 + psi6 / 7.0; printf(“\nAverage = %.2f”, avg); return 0; }

8 A First Book of ANSI C, Fourth Edition8 Solution 2: This program uses an array to store and process the 7 PSI readings efficiently #include int main () { int psi[7];// declare psi as an array of 7 elements int i, sum = 0; float avg; for (i = 0; i < 7; i++) { printf(“Input the PSI for day %d: ”, i); scanf(“%d”, &psi[i]); sum = sum + psi[i]; } avg = sum / 7.0; printf(“\nAverage = %.2f”, avg); return 0; }

9 A First Book of ANSI C, Fourth Edition9 Dimension of arrays In C, arrays can be of one, two or more dimensions Single dimensional array –to store multiple values in a list-like manner Two-dimensional array – data represented as rows and columns; in table-like manner

10 A First Book of ANSI C, Fourth Edition10 Boundary of Array index All arrays in C starts with index 0 Index of last element in array of size n is n-1 Accessing elements beyond the boundaries will cause an index out- of-bound run-time error

11 Single-Dimensional Arrays

12 A First Book of ANSI C, Fourth Edition12 Declaration General form of array declaration: datatype arrayname [Size]; Datatype - the type of element that will be contained in the array Size - the maximum number of elements that can be stored inside the array Example: int scores [9]; char name [10]; float gpa [40];

13 A First Book of ANSI C, Fourth Edition13 One-Dimensional Arrays 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

14 A First Book of ANSI C, Fourth Edition14 One-Dimensional Arrays

15 A First Book of ANSI C, Fourth Edition15 Initializing the array elements Can be initialized during declaration Values must be enclosed in braces and, if there is more than one, separated by commas. Example: int scores [5] = { 3, 5, 7, 2, 4};

16 A First Book of ANSI C, Fourth Edition16 Reading in the array elements Read values from the keyboard or a file Can be done using a loop (for loop) Example: int scores [5]; for (i = 0; i < 5; i++) scanf (“%d”, &scores [i]);

17 A First Book of ANSI C, Fourth Edition17 Assigning array elements Assign values to individual elements using the assignment operator Example: Say, we have the following array variable called x int x[5]; x [0] = 3; x [1] = 5; x [2] = 7; x [3] = 2; x [4] = 4; x[0]x[1]x2]x[3]x[4] 35724 Memory layout

18 A First Book of ANSI C, Fourth Edition18 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)

19 A First Book of ANSI C, Fourth Edition19 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 Input and Output of Array Values

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

21 A First Book of ANSI C, Fourth Edition21 Array Initialization The individual elements of all arrays (local or global) are, by default, set to 0 at compilation time 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 */ The NULL character, which is the escape sequence \0, is automatically appended to all strings by the C compiler

22 A First Book of ANSI C, Fourth Edition22 Array Initialization Initially, assume the first value (index 0) is the max Check the next value (index 1), is it greater than max? If yes, now the current value is the max, and the loop continues until the last index

23 A First Book of ANSI C, Fourth Edition23 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

24 A First Book of ANSI C, Fourth Edition24 Size can be omitted Arrays as Function Arguments

25 A First Book of ANSI C, Fourth Edition25 Arrays as Function Arguments

26 A First Book of ANSI C, Fourth Edition26 Exchanging values in an array Used when we need to swap between numbers Example: int temp; int numbers [5]={4,1,7,10,21}; temp = numbers [3]; numbers [3] = numbers [1]; numbers [1] = temp; Question: What is the new contents of this array?

27 A First Book of ANSI C, Fourth Edition27 Displaying array elements To print the contents of an array Usually done by using for loop Example: int i; int scores[9]={2,4,6,8,10,12,14,16,18}; for (i=0; i < 5; i++) printf (“%d\n”, scores [i]); Question: What is the output of this program?

28 A First Book of ANSI C, Fourth Edition28 Example of using Single- Dimensional Arrays int Number[5]={1,2,3,4,5}; int i=0, Sum=0; for (i = 0; i < 4; i++) Sum = Sum + Number [i]; printf (“Sum of numbers is %d\n”, Sum); Question: What is the purpose of this program? And what is the output?

29 A First Book of ANSI C, Fourth Edition29 Exercise: Declare marks as an integer type array with 15 elements. Assign the value 32, 100 and 31 to the 2 nd, 9 th and last element of the array respectively. Read the values from the user into the 4 th, 7 th and 10 th elements.

30 A First Book of ANSI C, Fourth Edition30 Exercise: Write program segments for the following question with a given definition of array: double ABC[5]; 1.Assign a value 12.3456 to each array element 2.Print all the array elements with 2 decimal places 3.Print all the array elements in reverse order with 3 decimal places 4.Print only those array elements with odd indexes.


Download ppt "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."

Similar presentations


Ads by Google