C Programming Lesson 6
C Programming Lesson 6
KIIT 2014
Objectives
After completing this lesson, you should be able to do the following:
• Define an array
– Declaration
– Initialization
• Use of an array element
• Define types of arrays
– Single – dimensional
– Multi - dimensional
• Pass arrays to functions
• Return array from function
• Pointer to an array
KIIT 2014
Array
• C programming language provides a data structure called the array.
• Can store a fixed-size sequential collection of elements of the same
type
• Is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type
• All arrays consist of contiguous memory locations. The lowest
address corresponds to the first element and the highest address to
the last element.
KIIT 2014
Declaring Arrays
• 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:
double balance[10];
char text[80];
KIIT 2014
Initializing Arrays
• You can initialize array in C either one by one or using a single
statement as follows.
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
• The number of values between braces { } can not be larger than the
number of elements that we declare for the array between square
brackets [ ].
• If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write
KIIT 2014
Initializing Arrays Conti..
• You can assign a single element of the array:
double balance[4] = 50.0;
KIIT 2014
Accessing Array Elements
• An element is accessed by indexing the array name. This is
done by placing the index of the element within square
brackets after the name of the array. For example:
• The above statement will take 10th element from the array
and assign the value to salary variable.
KIIT 2014
Accessing Array Elements Cont..
• Following is an example which will use all the above mentioned three
concepts viz. declaration, assignment and accessing arrays:
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j; /* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
KIIT 2014
Accessing Array Elements Cont..
• When the previous slide code is compiled and executed, it produces
the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
KIIT 2014
Array Sorting
• C language provides five sorting techniques, which
are as follows −
– Bubble sort (or) Exchange Sort.
– Selection sort.
– Insertion sort (or) Linear sort.
– Quick sort (or) Partition exchange sort.
– Merge Sort (or) External sort.
KIIT 2014
Array Sorting (Bubble Sort)
• Is the simplest sorting technique which is also called
as an exchange sort.
• Compare the first element with the remaining
elements in the list and exchange(swap) them if they
are not in order.
• Repeat the same for other elements in the list until
all the elements gets sorted.
KIIT 2014
Array Sorting (Bubble Sort)
• Procedure
for (i=0; i<n-1; i++)
{
for (j=i+1; j<n; j++)
{
if (a[i] > a[j])
{
t=a[i];
a[i] = a[j];
a[j] = t;
}
}
}
KIIT 2014
Array Sorting (Selection)
• Selection sort is a sorting algorithm that selects the smallest
element from an unsorted list in each iteration and places that
element at the beginning of the unsorted list.
• Set the first element as minimum
KIIT 2014
Array Sorting (Selection)
KIIT 2014
Array Sorting (Selection)
• Following is an example which will selection sort method to arrange
array :
#include <stdio.h>
int main()
{
int a[100], n, i, j, position, swap;
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d Numbers", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i = 0; i < n - 1; i++)
{
position=i;
for(j = i + 1; j < n; j++)
{
if(a[position] > a[j])
KIIT 2014
Array Sorting (Selection)
• Example using selection sort method to arrange array conti..
position=j;
}
if(position != i)
{
swap=a[i];
a[i]=a[position];
a[position=swap;
}
}
printf("Sorted Array:n");
for(i = 0; i < n; i++)
printf("%dn", a[i]);
return 0;
}
KIIT 2014
Array Sorting (Insertion)
• Insertion Sort in C is a simple and efficient sorting algorithm, that
creates the final sorted array one element at a time.
• It is usually implemented when the user has a small data set.
• Insertion sort is a simple sorting algorithm that works similar to the
way you sort playing cards in your hands.
• The array is virtually split into a sorted and an unsorted part. Values
from the unsorted part are picked and placed at the correct
position in the sorted part.
KIIT 2014
Working of Insertion Sort
• Consider an example: arr[]: {12, 11, 13, 5, 6}
12 11 13 5 6
11 12 13 5 6
11 12 5 13 6
11 5 12 13 6
5 11 12 13 6
5 11 12 6 13
5 11 6 12 13
5 6 11 12 13
KIIT 2014
Array Sorting (Quick)
Quicksort is a sorting algorithm based on the divide and conquer
approach where
• Step 1 − Pick an element from an array, call it as pivot element.
• Step 2 − Divide an unsorted array element into two arrays.
• Step 3 − If the value less than pivot element come under first sub
array, the remaining elements with value greater than pivot come in
second sub array.
KIIT 2014
Array Sorting (Quick)
KIIT 2014
Multi-dimensional Arrays
• C programming language allows multidimensional arrays. The
general form of a multidimensional array declaration is:
type name[size1][size2]...[sizeN];
int threedim[5][10][4];
KIIT 2014
Two-dimensional Arrays
• The simplest form of the multidimensional array is the two-
dimensional array. A two-dimensional array is, in essence, a
list of one-dimensional arrays. To declare a two-dimensional
integer array of size x,y you would write something as follows
type arrayName [ x ][ y ];
• Where type can be any valid C data type and arrayName will
be a valid C identifier. A two-dimensional array can be think as
a table which will have x number of rows and y number of
columns.
KIIT 2014
Two-dimensional Arrays
• A 2-dimensional array a, which contains three rows and four
columns can be shown as below:
KIIT 2014
Initializing 2-dimensional Arrays
• Multidimensional arrays may be initialized by specifying
bracketed values for each row. Following is an array with 3
rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
KIIT 2014
Accessing 2-dimensional Arrays
• An element in 2-dimensional array is accessed by using the
subscripts, i.e., row index and column index of the array. For
example:
int val = a[3][4];
• The above statement will take 4th element from the 3rd row
of the array. You can verify it in the above diagram.
KIIT 2014
2-dimensional Arrays
• Example:
#include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("a[%d][%d] = %d\n",a[i][j]);
}
}
return 0;
}
KIIT 2014
2-dimensional Arrays
• Output:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
KIIT 2014
Passing Arrays to Function
• Arrays can be passed to a function in the following ways:
– Parameter as a Pointer
void myFunction(int *param)
KIIT 2014
Passing Arrays to Function
• Write a function to pass an array as an argument along with
another argument. This function should return average of the
numbers passed through the array.
double getAverage(int arr[], int size)
{
int i;
double avg;
double sum;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = sum / size;
return avg;
}
KIIT 2014
Passing Arrays to Function
• Call getAverage function of the previous slide,
#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size);
int main ()
{
/* an int array with 5 elements */
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
KIIT 2014
Passing Arrays to Function
• Output
Average value is: 214.400000
KIIT 2014
Pointer to an Array
• An array name is a constant pointer to the first element of the
array.
double balance[50];
p = balance;
KIIT 2014
Pointer to an Array
• It is legal to use array names as constant pointers, and vice
versa. Therefore, *(balance + 4) is a legitimate way of
accessing the data at balance[4].
KIIT 2014
Pointer to an Array
• Below example shows the concepts
#include <stdio.h>
int main ()
{
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;
p = balance;
printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ )
{
printf("*(p + %d) : %f\n", i, *(p + i) );
}
printf( "Array values using balance as address\n");
for ( i = 0; i < 5; i++ )
{
printf("*(balance + %d) : %f\n", i, *(balance + i) );
} return 0;
}
KIIT 2014
Pointer to an Array
• Output:
Array values using pointer
*(p + 0) : 1000.000000
*(p + 1) : 2.000000
*(p + 2) : 3.400000
*(p + 3) : 17.000000
*(p + 4) : 50.000000
Array values using balance as address
*(balance + 0) : 1000.000000
*(balance + 1) : 2.000000
*(balance + 2) : 3.400000
*(balance + 3) : 17.000000
*(balance + 4) : 50.000000
KIIT 2014
String and Char Array
• String is a sequence of character that is treated as a single
data item and terminated by null character ‘\0’.
• C does not support strings as a data type.
• String is actually single dimensional array of character in C
language.
• For example:
– Null character is added at the end of the string by the compiler.
KIIT 2014
Declaring and Initializing string
variable
• There are different ways to initialize a character array
variable:
char name[10]=“StudyTonight”;
char name[10]={‘L’,’e’,’s’,’s’,’o’,’n’,’s’,’\0’};
char str[4];
Str=“hell”;
KIIT 2014
String Handling Functions
• These functions are packaged in string.h
– strcat() - It is used to concatenate two strings
KIIT 2014
String Functions – strcat()
• SYNTAX
– char *strcat(char *s1, const char *s2);
KIIT 2014
String Handling Functions –
strcat()
#include <stdio.h>
#include <string.h>
int main()
{
char example[100];
strcpy(example, "TechOnTheNet.com ");
strcat(example, "is ");
strcat(example, "over ");
strcat(example, "10 ");
strcat(example, "years ");
strcat(example, "old.");
printf("%s\n", example);
return 0;
}
KIIT 2014
String Handling Functions –
strcat()
#include <stdio.h>
#include <string.h>
int main()
{
char string1[20];
char string2[20];
strcpy(string1, "Hello");
strcpy(string2, "Hellooo");
printf("Returned String : %s\n", strcat( string1, string2 ));
printf("Concatenated String : %s\n", string1 );
return 0;
}
KIIT 2014
String Functions – strlen()
• SYNTAX
size_t strlen(const char *s);
• RETURNS
– The strlen function returns the length of the string pointed to by s.
It does not include the null character in the length calculation.
KIIT 2014
String Functions – strrev()
• SYNTAX
char *strrev(char *s);
• RETURNS
– The strrev function returns the reverse string.
KIIT 2014
String Functions – strrev()
#include<stdio.h>
#include<string.h>
int main()
{
char name[30] = "Hello";
return 0;
}
KIIT 2014
String Functions – strrev()
#include <stdio.h>
#include<string.h>
void main(void)
{
char str1[31],str2[31];
printf("\nEnter any string");
gets(str1);
strcpy(str2,str1);
strrev(str2);
if((strcmp(str1,str2))== 0)
printf("Word%s is a palindrome\n");
else
printf("Word %s is not a palindrome\n");
}
KIIT 2014
String Functions – strcpy()
• SYNTAX
char *strcpy(char *s1, const char *s2);
• RETURNS
KIIT 2014
String Functions – strcpy()
#include <stdio.h>
#include <string.h>
int main()
{
char example[50];
strcpy (example, "strcpy is a string function!");
printf("%s\n", example);
return 0;
}
KIIT 2014
String Functions – strcmp()
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[15];
char str2[15];
int ret;
strcpy(str1, "abcdef");
strcpy(str2, "ABCDEF");
ret = strcmp(str1, str2);
if(ret > 0)
{
printf("str1 is less than str2");
}
else
if(ret < 0)
{
printf("str2 is less than str1");
}
else
{
printf("str1 is equal to str2"); } return(0); }
KIIT 2014
Return Arrays from Function
• C does not allow to return an entire array as an argument to a
function.
• You can return a pointer to an array by specifying the array's
name without an index.
• To return a single-dimension array from a function, declare a
function returning a pointer as in the following example:
int * myFunction()
{
.
.
.
}
KIIT 2014
Return Arrays from Function
• C does not advocate to return the address of a local variable
to outside of the function so define the local variable
as static variable.
• Write a function to generate 5 random numbers and return
them using an array from function.
KIIT 2014
Return Arrays from Function
#include <stdio.h>
int * getRandom( )
{
static int r[5];
int i;
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 5; ++i)
{
r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}
return r;
}
KIIT 2014
Return Arrays from Function
int main ()
{
int *p;
int i;
p = getRandom();
for ( i = 0; i < 5; i++ )
{
printf( "*(p + %d) : %d\n", i, *(p + i));
}
return 0;
}
KIIT 2014
Return Arrays from Function
• Output:
r[0] = 313959809
r[1] = 1759055877
r[2] = 1113101911
r[3] = 2133832223
r[4] = 2073354073
*(p + 0) : 313959809
*(p + 1) : 1759055877
*(p + 2) : 1113101911
*(p + 3) : 2133832223
*(p + 4) : 2073354073
KIIT 2014
Summary
In this lesson, you should have learned how to:
• Define an array
– Declaration
– Initialization
• Use of an array element
• Define types of arrays
– Single – dimensional
– Multi - dimensional
• Pass arrays to functions
• Return array from function
• Pointer to an array
KIIT 2014