CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel
Introduction to Arrays Arrays Structures of related data items same types of data and same name Represented as a group of consecutive memory locations Static entity – same size throughout program F. Alakeel
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 ]; F. Alakeel
- Examples- Defining Arrays int A[10] An array of ten integers A[0], A[1], …, A[9] double B[20] An array of twenty long floating point numbers B[0], B[1], …, B[19] Array indexes always start at zero in C
Example- Defining Arrays Examples Define an array temperature of float with size 5 : float temperature [5]; F. Alakeel
Initializing Arrays Initializers 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 it int n[ ] = { 1, 2, 3, 4, 5 }; 5 initializers, therefore 5 element array F. Alakeel
Initializing Arrays int A[5] = {2, 4, 8, 16, 32}; int B[20] = {2, 4, 8, 16, 32}; Unspecified elements are guaranteed to be zero int C[4] = {2, 4, 8, 16, 32}; Error — compiler detects too many initial values int D[5] = {2*n, 4*n, 8*n, 16*n, 32*n}; Automatically only; array initialized to expressions
Initializing Arrays - Example double temperature [5]= {12.3,7.5,65,72.1,87.5}; Or - double temperature[]= {12.3,7.5,65,72.1,87.5}; temperature [0] temperature [1] temperature [2] temperature [3] temperature [4] F. Alakeel
double temperature [5]; Elements temperature [0] temperature [1] temperature [2] temperature [3] temperature [4] F. Alakeel
double temperature [5]; Subscript or Index temperature [0] temperature [1] temperature [2] temperature [3] temperature [4] F. Alakeel
1.Use assignment statements. See the next slide. 2.Initialize arrays in the variable declaration statement ex:double temperature [5]= {12.3,7.5,65,72.1,87.5}; 3.Read input values into the array from the keyboard or from a file Three ways to get values into array elements F. Alakeel
declaration: int score [6]; score: index: (Subscript) score[0]=49; score[1]=75; score[2] = 65; score[3] = 90; score[4]=77; score[5]=70; F. Alakeel
Array Element May be used wherever a variable of the same type may be used In an expression (including arguments) On left side of assignment Examples:– A[3] = x + y; x = y – A[3]; z = sin(A[i]) + cos(B[j]);
Accessing Array Elements temperature [4] = 12.7; or N = 4; temperature [N] = 12.7; F. Alakeel
Accessing Array Elements To refer to an element, specify Array name Position number Format: arrayname [ position number ] First element at position 0 n element array named c: c[ 0 ], c[ 1 ]...c[ n – 1 ] F. Alakeel
Accessing Array Elements Array elements are like normal variables c[ 0 ] = 3; printf( "%d", c[ 0 ] ); Perform operations in 4th subscript. (x=3) c[ ] == c[ 3 ] == c[ x ] F. Alakeel
Assigning Values We cannot use assignment statements with entire arrays. Instead, we must assign values to individual elements We can use them as values in assignment statements: score[0] = 30; grade[3] = ‘A’; price[2] = 10.39; F. Alakeel
Using Array Elements All of the following are valid: score[0] = 4; score[0] += 7; score[1] = score[0] -2; score[2] = score[1] + 5 * score[0]; score[j] = score[j + 1]; Note: index can be any integral expression. F. Alakeel
Example Array elements are commonly used in loops E.g., for(i=0; i < max; i++) A[i] = i*i; for(sum = 0, j=0; j < max; j++) sum += B[j]; F. Alakeel
Note The index of array starts at 0. To access the seventh element in array C, we type: C[6] =10; Note that we used 6 instead of 7. F. Alakeel
Manipulating Arrays To access all elements of an array a for loop is used. For loop will start from index 0 to the last element in the array which has an index of array size-1 F. Alakeel
Note When looping through an array, the array index should never go below 0 and always be less than the total number of elements in the array (size – 1). Make sure the loop-terminating condition prevents accessing elements outside this range. F. Alakeel
Manipulating Arrays For loops are used to: Initializing array elements Reading elements Printing elements Performing operations Sum elements Find largest/ smallest element Search for an element Sort elements F. Alakeel
Initializing Array Elements –Using For loop Example: to initialize array a of size 10 with zeros, the for loop should go from 0 until 9, the syntax is: int size=10; int a[size],index; for(index =0; index<=size-1; index++) a[index] = 0; F. Alakeel
Reading Elements – without For Loop Examples: float temperature [5]; Reading: scanf(“%f”, &temperature [0]); scanf(“%f”, &temperature [1]); scanf(“%f”, &temperature [2]); scanf(“%f”, &temperature [3]); scanf(“%f”, &temperature [4]); F. Alakeel
Reading Elements – using For Loop Ex1: int i; for(i=0; i<5; i++) { scanf(“%f”,&temperature[i]); } Ex2: for(index =0; index<=size-1; index++) { printf(“Enter value>”); scanf(“%d”,&a[index]); } F. Alakeel
Printing Elements – without For Loop Examples: float temperature [5]; Printing: printf(“%f”,temperature [0]); printf(“%f”,temperature [1]); printf(“%f”,temperature [2]); printf(“%f”,temperature [3]); printf(“%f”,temperature [4]); F. Alakeel
Printing Elements – Using For Loop Ex1: int i; for(i=0; i<5; i++) { printf(“%f”,temperature[i]); } Ex2: for(index =0; index<=size-1; index++) { printf(“%d”,a[index]); } F. Alakeel
Sum the elements int sum=0; for(index =0; index<=size-1; index++) { sum = sum + a[index]; } F. Alakeel
for loop initializes each array element separately for loop outputs all array elements Element Value F. Alakeel
initializer list initializes all array elements simultaneously Element Value F. Alakeel
Outline fig06_05.c (1 of 2 ) #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 for loop initializes each array element separately F. Alakeel
Outline fig06_05.c (2 of 2 ) F. Alakeel
Outline fig06_06.c initializer list initializes all array elements simultaneously for loop adds each element of the array to variable total F. Alakeel
Array Practice 1. Declare an array to hold the tax for up to 10 different sales. 2. Declare an array to hold the final letter grades for a class with up to 40 students 3. Declare an array of integers which holds the final average for those 40 students and initialize its values to 0 4. Declare an array of characters called letter_ary with initial values ‘a’, ‘d’, ‘y’, and ‘w’. What is the value of letter_ary[1]? F. Alakeel
More Array Practice Write a loop to initialize all 50 elements of array salary_ary to 100. Write C code to read values from the keyboard to fill the array scores. Input should stop when a negative number is entered. The maximum size of the array is in a constant ARR_SIZE. Write C code to add up the first num_elements values in the array my_vals and store the sum in the variable my_sum. F. Alakeel
ARRAY OF CHARACTERS F. Alakeel
Array of Characters Character arrays String “first” is really a static array of characters Character arrays can be initialized using string literals char string1[] = "first"; Null character '\0' terminates strings string1 actually has 6 elements It is equivalent to char string1[] = { 'f', 'i', 'r', 's', 't', '\0' }; Can access individual characters string1[ 3 ] is character ‘s’ Array name is address of array, so & not needed for scanf scanf( "%s", string2 ); Reads characters until whitespace encountered Be careful not to write past end of array, as it is possible to do so F. Alakeel
Common Programming Error 6.7 Not providing scanf with a character array large enough to store a string typed at the keyboard can result in destruction of data in a program and other runtime errors. This can also make a system susceptible to worm and virus attacks. F. Alakeel
Outline fig06_10.c (1 of 2 ) string2 array is defined with one element for each character, so 15 elements including null character /0 for loop prints characters of string1 array with spaces in between F. Alakeel
Outline fig06_10.c (2 of 2 ) F. Alakeel