You are on page 1of 30

TECHNOLOGICAL UNIVERSITY (MAUBIN)

DEPARTMENT OF ELECTRONIC ENGINEERING

EcE_22014, Technical Programming II


Chapter_6, C Arrays

By: Daw Moe Moe San


Assistant Lecturer
Outlines of Presentation
 Objectives
 Introduction
 Defining Arrays
 One-Dimensional Arrays
 Initializing Arrays
 Array Manipulations
 Passing Arrays to Functions
 Sorting Arrays
 Searching Arrays
 Multiple-Subscripted (Multidimensional) Arrays

2
Objectives
 To use the array data structure to represent lists and tables of values.
 To define and initialize an array.
 To refer to individual elements of an array.
 To define symbolic constants.
 To manipulate the values of array’s elements.
 To use one-dimensional and multidimensional-arrays.

3
Introduction
 An array is a group of memory locations related by the fact that
they all have the same name and the same type.

 c[10], This array contains 10 elements.


 The first element in every array is the zeroth element.
 The first element of array c is c[0], the second element of array c is c[1].
 The ith element of array c is c[i-1].

 The position number contained within square brackets is more formally called
a subscript (or index).

4
Defining Arrays
 Specify the following things for defining array.
 The data type of the values stored in the array
 The name of the array
 The dimensionality of the array: One dimensional array or two-dimensional array.
 The size of each dimension.

 Examples:
 int c[ 5 ]; /* an integer array named c with size 5 */
 float a[ 10 ]; /* a float array named a with size 10 */
 int marks[ 10 ][ 7 ]; /*a two-dimensional array to store 7 subject marks for 10 students
*/

5
One-Dimensional Arrays
 Use one-dimensional arrays to store and access list of data values.
c[ 5 ]
c[ 0 ] 7
c[ 1 ] 9
c[ 2 ] 5
c[ 3 ] 6
c[ 4 ] 2

 Examples:
 int c[ 5 ]; /* an integer array named c with size 5 */
 There are five elements in array c.
 All values are named c.
 The value of first element is c[ 0 ] = 7.
 The second value is c[ 1 ] = 9
 And, the value of fifth element, c[ 4 ] is 2.
6
Initializing Arrays
 Using for loop to initialize the elements of a 5-element integer array c to zero.

 First step, define array as follow:


int c [ 5 ];

 Then, initialize the array c:


for( i = 0; i < 5; i++ )
{ c [ i ] = 0; }
c[ 5 ]
i=0 c[ 0 ] = 0 c[ 0 ] 0
i=1 c[ 1 ] = 0 c[ 1 ] 0
i=2 c[ 2 ] = 0
i=3 c[ 3 ] = 0 c[ 2 ] 0
i=4 c[ 4 ] = 0 c[ 3 ] 0
c[ 4 ] 0

7
Cont;
 Using initializer list to initialize the elements of a 5-element integer
array c to zero.

 First step, define array as follow:


int c [ 5 ];

 Then, initialize the array c:


int c [ 5 ] = { 0 };

 Note:
 Arrays are not automatically initialized to zero.
 Must at least initialize the first element to zero for the remaining elements to be
automatically zeroed.

8
Cont;
 Example-1: Write a program that uses for loop to initialize the elements of a 10-element integer
array n to zeros and print the array in tabular format.

#include <stdio.h> /* Output contents of array n in tabular format*/


int main(void) printf( "%s%13s\n", "Element", "Value" );
{
int n[10]; /* n is an array of 10 integers */ for( i=0; i<10; i++ )
int i; /* counter */ {
printf( "%7d%13d\n", i, n[i] );
for( i=0; i<10; i++ ) } /* End for loop */
{
n[i] = 0; /* Set element at location i to 0 */ return 0;
} } /* End main */
9
Cont;
 Example-2: Write a program that initializes an integer array with 10 values using initializer list
and print the array in tabular format.

#include <stdio.h>
for( i=0; i<10; i++ )
int main(void)
{
{
printf( "%7d%13d\n", i, n[i] );
/* use initializer list to initialize array n */
} /* End for loop */
int n[10] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
int i; /* counter */
return 0;
} /* End main */
/* Output contents of array n in tabular format*/
printf( "%s%13s\n", "Element", "Value" );

10
Array Manipulations
 Example-3: Write a program that specify an array’s size with a symbolic constant
and initializes the10-element array s to the values 2, 4, 6, …, 20 with calculation
and print the array in tabular format.

#include <stdio.h> /* Output contents of array n in tabular format*/


#define SIZE 10 /* maximum size of array */ printf( "%s%13s\n", "Element", "Value" );
int main(void) for( i=0; i<SIZE; i++ )
{ {
/*symbolic constant SIZE can be used to specify array size*/ printf( "%7d%13d\n", i, s[i] );
int s[SIZE]; } /* End for loop */
int i; /* counter */
for( i=0; i<SIZE; i++ ) return 0;
{ s [ i ] = 2 + 2 * i; } /* Set the values */ } /* End main */
11
Cont;
 Example-4: Write a program that sums the values contained in the 12-elements integer array a
and print the total values.

#include <stdio.h> /* Output of total*/


#define SIZE 12 /* maximum size of array */ printf( “Total of array element values is %d\n”,
int main(void) total);
{ /* use initializer list to initialize array*/ return 0;
int a[SIZE]={1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, } /* End main */
45};
int i; /* counter */
int total=0; /* sum of array */

for( i=0; i<SIZE; i++ ) /*Sum contents of array a */


{ total += a [ i ]; } /* End for loop */
12
Cont;
 Example-5: Write a program to roll a single six-sided die 6000 times to test whether the random
number generator actually produces random numbers. (Using an array instead of switch)
#include <stdio.h> /* output frequency elements 1-6 in tabular format */
#include <stdlib.h>
printf( “%s%17s\n”, “Face”, “Frequency” );
#include <time.h>
#define SIZE 7 /* maximum size of array */ for( face=1; face < SIZE; face++ )
int main(void) {
{
printf( “%4d%17d\n”, face, frequency[ face ] );
int face;/* random die value 1-6 */
int roll; /* roll counter 1-6000 */ } /* End for loop */
int frequency[SIZE]={ 0 }; /* clear counts */ return 0;
srand( time( NULL ) ); /*seed random-number generator*/ } /* End main */

for( roll = 0; roll <= 6000; roll++ ) /* roll die 6000 times*/
{
face = 1 + rand( ) % 6;
++frequency[ face ];
}
13
Passion Arrays to Functions
 Pass by Reference
 C automatically passes (entire) arrays to functions by reference.
 The called functions can modify the element values .
 The name of array evaluates the address of the first element.

 Pass by Value
 C passes individual array elements to functions by value.
 The called functions can’t modify the element values.

 const Type Qualifier


 To prevent modification of array values in a function.
 const int a[ ];

14
Cont;
 Pass by Reference
#include<stdio.h> for( i = 0; i< SIZE; i++)
#define SIZE 5
void array( int b[ ], int size ); { printf("%3d", a[ i ] ); }
int main(void) return 0;
{ }
int a[SIZE] = { 0, 1, 2, 3, 4};
void array( int b[ ], int size )
int i;
{
printf("The values of the original array are:\n"); int j;
for( i = 0; i< SIZE; i++)
for( j=0; j <size; j++)
{ printf("%3d", a[ i ] ); }
{ b[ j ] *= 2; }
printf("\n"); }

array( a, SIZE );

printf("The values of the modified array are:\n");

15
Cont;
 Pass by Value
#include<stdio.h> void array( int e )
#define SIZE 5
void array( int e ); {
int main(void) printf("Modified element value is: %d\n", e *= 2);
{ }
int a[SIZE] = { 0, 1, 2, 3, 4};
int i;

printf("The values of the element a[ 3 ] is: %d\n", a[ 3 ]);

array( a[ 3 ]);

printf("The values of the modified element a[ 3 ] is: %d\n", a[ 3 ]);

return 0;
}

16
Sorting Arrays
 One of the most important computing applications.
 Placing the data into a particular order such as ascending or descending.
 Bubble Sort or Sinking Sort
 For Ascending Order
 The smaller values upward to the top of the array like air bubbles rising in water.
 The larger values sink to the bottom of the array.
 Temporary location is used to swap array elements. (e.g. hold, temp, …)
2 hold
2
1
1 a[ 0 ] > a[ 1 ]
2 2
3 a[ 0 ] a[ 1 ]
1
3

17
Cont;
 Sorting the 10-element integer array into ascending order with bubble sort.
#include<stdio.h>
#define SIZE 10 if( a[ i ] > a[ i+1 ] )
int main( void ) {
{ hold = a[ i ];
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
a[ i ] = a[ i+1 ];
int pass; /* passes counter */
a[ i+1 ] = hold;
int i; /* comparisons counter */
} /* end if */
int hold; /* temporary location */
} /* end inner for */
printf("\nData items in original order\n"); } /* end outer for */
for( i = 0; i < SIZE; i++ )
{ printf("%4d", a[ i ]); } printf("\nData items in ascending order\n");
for( i = 0; i < SIZE; i++ )
for( pass = 1; pass < SIZE; pass++) { printf("%4d", a[ i ]); }
{ return 0;
for( i = 0; i < SIZE-1; i++) } /* end main */
{
18
Cont;
 Sorting the 10-element integer array into ascending order with bubble sort.

19
Searching Arrays
 Determine whether an array contains a value that matches a certain kay value.
 Finding a particular element of an array.

 Linear Search Technique


 The Linear Search compares each element of the array with search key.
 The technique works well for small or unsorted arrays.

 Binary Search Technique


 The array is sorted.
 The Binary Search eliminates from consideration one-half of the elements in a sorted array
after each comparison.

20
Cont;
 Searching an array with Linear Search.
0 2 4 6 8 10 12 14 16 18
int linearSearch(int a[ ], int key, int size)
{ a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
int n;
for( n = 0; n < size; n++ )
{ key=6
if( a[ n ] == key ) n=0

{ a[0] 0 0 != 6 n++

return n; n=1
} a[1] 2 2 != 6 n++

}
n=2
return -1; 4 != 6 n++
a[2] 4
}
n=3
a[3] 6 6 == 6 return 3
21
Cont;
 Searching an array with Linear Search.
#include<stdio.h> if( element != -1) for( n = 0; n < size; n++ )
#define SIZE 100 { {
int linearSearch(int array[ ], int key, int size); printf("Found value in element %d\n",
int main( void ) if( array[ n ] == key )
element);
{ {
}
int a[ SIZE ]; return n;
else
int x;
{ }
int searchKey;
int element; printf("Value not found\n"); }
for( x = 0; x < SIZE; x++ ) } return -1;
{ return 0;
}
a[ x ] = 2 * x; }
}
printf("\nEnter search key: "); int linearSearch(int array[ ], int key, int
scanf("%d", &searchKey); size)
{
element = linearSearch( a, searchKey, SIZE);
int n;
22
Cont;
 Searching an array with Binary Search.
#include<stdio.h> result = binarySearch( a, key, 0, SIZE-1 );
#define SIZE 15
int binarySearch( int b[ ], int searchKey, int low, int high); if( result != -1 )
int main( void ) {
{
printf("\n%d found in array element %d\n", key, result);
int a[ SIZE ];
}
int i;
else
int key;
int result; {
printf("\n%d not found\n", key);
for( i = 0; i < SIZE; i++) }
{
a[ i ] = 2 * i; return 0;
} }

printf("Enter a number between 0 and 28: ");


scanf("%d", &key);
23
Cont;
else
int binarySearch( int b[ ], int searchKey, int low, int high) {
{
low = middle +1;
int middle;
}
}
while( low <= high )
{
middle = ( low + high ) / 2; return -1;
}
if( searchKey == b[ middle ] )
{
return middle;
}
else if( searchKey < b[ middle ] )
{
high = middle - 1;
}

24
Cont;
int binarySearch( int b[ ], int searchKey, int low, int high) key=4
{
int middle; 0 2 4 6 8 10 12 14 16 18

while( low <= high ) b[0] b[1] b[2] b[3] b[4] b[5] b[6] b[7] b[8] b[9]
{
middle = ( low + high ) / 2; low=0
high=9
if( searchKey == b[ middle ] )
{ mid=(0+9)/2=4 b[4]=8 4 != 8
return middle;
} 4<8
else if( searchKey < b[ middle ] ) high=4-1=3
{
high = middle - 1; mid=(0+3)/2=1 b[1]=2 4 != 2
}
4<2
else { 4>2
low = middle +1; low=1+1=2
}
} mid=(2+3)/2=2 4 == 4 return 2
b[2]=4
return -1;
} 25
Multiple-Subscripted (Multidimensional) Arrays
 To represent the tables of values consisting of information arranged in rows and columns.
 To identify a particular table element, two subscripts are specified.
 The first identifies the element’s row and the second identifies the element’s column.
 Tables or arrays that required two subscripts to identify a particular element are called two
double-subscripted arrays.
 The m rows and n column array is called m-by-n array.
 For example: int c[ m ][ n ];
int c[ 3 ][ 4 ];
Table or array has 3 rows and 4 columns.

26
Cont;
 Initializing Multidimensional Arrays
#include<stdio.h> void printArray( int a[ ][ 3 ] )
void printArray( int a[ ][ 3 ] ); {
int main( void ) int i;
{ int j;
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6} };
for( i = 0; i <= 1; i++ )
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5, 6 };
{
int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
for( j = 0; j <= 2; j++ )
printf("\nValue in array1 by row are:\n");
printArray( array1 ); {
printf("\t");
printf("\nValue in array2 by row are:\n"); printf( "%d", a[ i ][ j ] );
printArray( array2 ); }
printf("\n");
printf("\nValue in array3 by row are:\n"); }
printArray( array3 ); }
return 0;
}
27
Cont; Two-dimensional Array Manipulations (Average Grade)
#include<stdio.h>
#define STUDENTS 3
#define EXAMS 4
double average( const int setOfGrade[ ], int tests);
void printArray( const int grades[ ][ EXAMS ], int pupils, int tests);
int main( void )
{
int student;
const int studentGrades[ STUDENTS ][ EXAMS ] = { { 77, 68, 86, 73 }, { 96, 87, 89, 78}, { 70, 90,86, 81} };

printf("The array is: \n");


printArray( studentGrades, STUDENTS, EXAMS);
for( student = 0; student < students; student++ )
{
printf("the average grade for student %d is %.2f\n", student, average( studentgrades[ student ], exams) );
}
return 0;
}
28
Cont; Two-dimensional Array Manipulations
double average( const int setOfGrade[ ], int tests) for( j = 0; j < tests; j++ )
{ {
int i; printf("%-5d", grades[ i ][ j ]);
int total = 0; } /* end inner for */
for( i = 0; i < tests; i++ ) } /* end outer for */
{
total += setOfGrade[ i ]; printf("\n\n");
} } /* end function printArray */
return (double) total / tests;
}

void printArray( const int grades[ ][ EXAMS ], int pupils, int tests)
{
int i, j;
printf("%18c[0] [1] [2] [3]", ' '); /* output column head*/
for( i =0; i < pupils; i++ )
{
printf("\nstudentGrades[%d] ", i);
29
 
References:
Text Book, EcE_22014, Technical Programming II

How to Program, Sixth Edition By P.J.Deitel and H.M.Deitel, 2010.


(ISBN-10: 0-13-612356-2), (ISBN-13: 978-0-13-612356-9)

THANK YOU

30

You might also like