Lecture-06
Lecture-06
(C Programming Language)
Introduction
Arrays
Definition and Examples
Passing Arrays to Functions
Sorting Arrays
Array Case Study
Search Arrays
Multiple-Subscripted Arrays
Array
• Array
Group of consecutive memory locations
Same name and type
• Format:
arrayname[ position number ]
First element at position 0
n element array named c:
c[ 0 ], c[ 1 ]...c[ n – 1 ]
Array
Array
• Defining arrays:
Name
Type of array
Number of elements
int c[ 10 ];
float myArray[ 3284 ];
int b[ 100 ], x[ 27 ];
Array
• 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
#include <stdio.h>
int main(){
int arrayA[5], sum=0;
for (int i=0; i<5; ++i){
printf("\n arrayA[%d]= ",i);
scanf("%d", &arrayA[i]);
}
for (int i=0; i<5; ++i)
sum += arrayA[i];
printf("Sum of all elements in an array: %d", sum);
}
Exercises
• How to declare?
int arrayA[3][4]
float arrayB[2][4][3]
• Initializing a 3D array
int arrayA[2][3][4]={{{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 21,
-4}}, {{13, 4, 56,3},{5, 9, 3, 5} ,{3, 1, 4, 9}}};
Multi-dimensional Arrays
#include <stdio.h>
int main(){
float a[2][2], b[2][2], sum[2][2];
printf("Enter elements of 1st matrix \n");
for (int i=0; i<2; ++i)
for (int j=0; j<2; ++j){
printf("Enter a[%d][%d]: ", i+1, j+1);
scanf("%f", &a[i][j]);}
for (int i=0; i<2; ++i)
for (int j=0; j<2; ++j){
printf("Enter b[%d][%d]: ", i+1, j+1);
scanf("%f", &b[i][j]);}
Multi-dimensional Arrays
• Character arrays
String “first” is really a static array of characters
Character arrays can be initialized using string literals
• Declare a string
char stringA[5];
• Initialize strings
char stringA[]="abcd";
char stringA[50]="abcd";
char stringA[]={'a','b','c','d','\0'};
char stringA[5]={'a','b','c','d','\0'};
• Notes
char c[5]="abcde";
• We are trying to assign 6 characters (the last character is ) to a char array having
5 characters. This is bad and you should never do this
Character Arrays
char c[100];
c = "C programming"; //Error! array type is not assignable
Character Arrays
#include <stdio.h>
int main (){
char stringA[20];
char stringB[] = "C programming language";
int i;
// read string from user into array stringA
printf("Enter a string: ");
scanf("%s", stringA);
//output strings
printf("stringA is: %s\nstringB is: %s\n"
"stringA with spaces between characters is: \n", stringA, stringB);
// output characters until nill character is reached
for (i=0; stringA[i]!='\0';i++){
printf("%c ", stringA[i]);}
printf("\n");
return 0;}
Examples
void staticArrayInit(void){
static int arrayA[3];
int i;
printf("\nValues on entering staticArrayInit:\n");
//output contents of arrayA
for (i=0; i<=2; ++i)
printf("arrayA[%d] = %d ", i, arrayA[i]);
printf("\nValues on existing staticArrayInit:\n");
//modify and ouput contents of arrayA
for (i = 0; i<=2; ++i)
printf("arrayA[%d] = %d ", i, arrayA[i]+=5);}
Examples
void automaticArrayInit(void){
int arrayB[3]={1,2,3};
int i;
printf("\nValues on entering automaticArrayInit:\n");
//output contents of arrayA
for (i=0; i<=2; ++i)
printf("arrayB[%d] = %d ", i, arrayB[i]);
printf("\nValues on existing staticArrayInit:\n");
//modify and ouput contents of arrayA
for (i = 0; i<=2; ++i)
printf("arrayB[%d] = %d ", i, arrayB[i]+=5);}
Character Arrays
• Function prototype
void modifyArray(int b[]), int arraySize);
• Parameter names optional in prototype (not recommend)
int b[] could be written int []
int arraySize could be simply int
Passing Array to Function
• Write a short program to check whether an element in an array is the prime number
or not
Passing Array to Function
• Sorting data
Important computing application
Virtually every organization must sort some data
• Bubble sort
Several passes through the array
Successive pairs of elements are compared
If increasing order (or identical) -> no change
If decreasing order -> elements exchanged
Repeat
• Example
Original: 3 4 2 6 7
Pass 1: 3 2 4 6 7
Pass 2: 2 3 4 6 7
Small elements “bubble” to the top
Bubble Sort
#include <stdio.h>
#define SIZE 10
int main(){
int a[SIZE]={2,6,4,8,5,7,89,23,54,100};
int pass, hold;
printf("Data items in original order \n");
for (int i=0; i<SIZE; ++i)
printf("%4d", a[i]);
for (pass=1; pass<SIZE; ++pass){
for (int i=0; i<SIZE-1; ++i)
if(a[i]>a[i+1]){
hold=a[i];
a[i]=a[i+1];
a[i+1]=hold;}
}
printf("\nData items in ascending order\n");
for (int i=0; i<SIZE; ++i)
printf("%4d", a[i]);
return 0;}
Case Study
1, 2, 3, 4, 5
3 is the median value
Mode – number that occurs most often
1, 1, 1, 2, 3, 3, 4, 5
Mean of An Array
#include <stdio.h>
#define SIZE 30
void mean(const int answer[]);
void median(int answer[]);
void mode(int freq[], const int answer[]);
void bubbleSort(int array[]);
void printArray(const int array[]);
int main(){
int frequency[10]={0};
int response[SIZE]={3,4,5,6,3,4,5,8,2,4,4,7,4,1,2,9,7,4,2,1,1,1,2,3,4,9,2,3,4,8};
mean(response);}
void mean(const int answer[]){
int total=0;
for (int j=0; j<SIZE; ++j)
total +=answer[j];
printf("the mean value of array: %f", (float) total/SIZE);}
Median of An Array
#include <stdio.h>
#define SIZE 30
void median(int answer[]);
void bubbleSort(int array[]);
void printArray(const int array[]);
int main (){
int frequency[10]={0};
int response[SIZE]={3,4,5,6,3,4,5,8,2,4,4,7,4,1,2,9,7,4,2,1,1,1,2,3,4,9,2,3,4,8};
median(response);}
void median(int answer[]){
printArray(answer);
bubbleSort(answer);
printf("\n\nThe sorted array is ");
printArray(answer);
printf("\nThe median element is %d", answer[SIZE/2]);}
void bubbleSort(int array[]){
int pass, i, hold;
for (pass=1; pass<SIZE; ++pass)
for (i=0; i<SIZE-1; ++i)
if (array[i]>array[i+1]){
hold=array[i];
array[i]=array[i+1];
array[i+1]=hold;}}
void printArray(const int array[]){
for (int i=0; i<SIZE; ++i)
printf("%d ", array[i]);}
Mode of An Array
#include <stdio.h>
#define SIZE 30
void mode(int freq[], const int answer[]);
int main(){
int frequency[10]={0};
int response[SIZE]={3,4,5,6,3,4,5,8,2,4,4,7,4,1,2,9,7,4,2,1,1,1,2,3,4,9,2,3,4,8};
mode(frequency, response);
return 0;}
void mode(int freq[], const int answer[]){
int rating, i, h, largest=0, modeValue=0;
for (rating=0; rating<=9; ++rating)
freq[rating]=0;
for (i=0; i<SIZE; ++i)
++freq[answer[i]];
for (rating=1; rating<=9; ++rating){
printf("%8d%11d ", rating, freq[rating]);
if (freq[rating]>largest){
largest = freq[rating];
modeValue = rating;}
for (h=1; h<=freq[rating]; ++h)
printf("*");
printf("\n"); }
printf("The mode of the most frequency value. \nFor this run the mode is %d which occured %d time. \n", modeValue,
largest);}
Exercises
• Binary search
For sorted arrays only
Compares middle element with key
If equal, match found
If key < middle, looks in first half of array
If key > middle, looks in last half
Repeat
Very fast: at most n steps, where 2n > number of elements
30 elements array takes at most 5 steps
25 > 30 so at most 5 steps
Examples
• Read the code example 6.19 in pages 275-278 and understand it <binary
search of a sorted array>
• Read the code example 6.22 in pages 282-284 and understand it <two-
dimensional array multiplications>
Exercises