0% found this document useful (0 votes)
20 views

C Programming Lesson 6

The document discusses arrays in C programming. It defines arrays as fixed-size collections of elements of the same type stored contiguously in memory. It covers declaring, initializing, and accessing single and multi-dimensional arrays. It also discusses passing arrays to functions, returning arrays from functions, and using pointers to arrays. Various sorting techniques for arrays like bubble, selection, insertion, and quick sort are explained as well.

Uploaded by

rajeev0305
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

C Programming Lesson 6

The document discusses arrays in C programming. It defines arrays as fixed-size collections of elements of the same type stored contiguously in memory. It covers declaring, initializing, and accessing single and multi-dimensional arrays. It also discusses passing arrays to functions, returning arrays from functions, and using pointers to arrays. Various sorting techniques for arrays like bubble, selection, insertion, and quick sort are explained as well.

Uploaded by

rajeev0305
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Arrays

 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:

type arrayName [ arraySize ];

• This is called a single-dimensional array. The arraySize must be an


integer constant greater than zero and type can be any valid C data
type. For example, to declare a 10-element array called balance of
type double, use this statement:

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

double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};

 KIIT 2014
Initializing Arrays Conti..
• You can assign a single element of the array:
double balance[4] = 50.0;

• The above statement assigns element number 5th in the array


with a value of 50.0. All arrays have 0 as the index of their first
element which is also called base index and last index of an
array will be total size of the array minus 1. Following is the
pictorial representation of the same array we discussed
above:

 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:

double salary = balance[9];

• 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

• Compare minimum with the second element. If the second


element is smaller than minimum, assign the second element
as minimum.
• Compare minimum with the third element. Again, if the third
element is smaller, then assign minimum to the third element
otherwise do nothing. The process goes on until the last element.

 KIIT 2014
Array Sorting (Selection)

• After each iteration, minimum is placed in the front of the unsorted


list.

 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];

• For example, the following declaration creates a three


dimensional 5 . 10 . 4 integer array

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:

• Thus, every element in array a is identified by an element


name of the form a[ i ][ j ], where a is the name of the array,
and i and j are the subscripts that uniquely identify each
element in a.

 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 */
};

• Another way is to initialize


int a[3][4] = {0, 1, 2, 3,4, 5, 6, 7,8, 9, 10, 11};

 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

• You can have arrays with any number of dimensions, although


it is likely that most of the arrays you create will be of one or
two dimensions.

 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)

– Parameter as a sized array


void myFunction(int param[10])

– Parameter as an unsized array


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;

/* pass pointer to the array as an argument */


avg = getAverage( balance, 5 ) ;

/* output the returned value */


printf( "Average value is: %f ", avg );
return 0;
}

 KIIT 2014
Passing Arrays to Function
• Output
Average value is: 214.400000

• The length of the array doesn't matter as far as the function is


concerned because C performs no bounds checking for the
formal parameters.

 KIIT 2014
Pointer to an Array
• An array name is a constant pointer to the first element of the
array.
double balance[50];

• balance is a pointer to &balance[0], which is the address of


the first element of the array balance. Thus, the following
program fragment assigns p the address of the first element
of balance:
double *p;
double balance[10];

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].

• Once you store the address of first element in p, you can


access array elements using *p, *(p+1), *(p+2) and so on.

 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

• Here, p is a pointer to double, which means it can store address of a


variable of double type. Once we have address in p, then *p will give us
value available at the address stored in p, as we have shown in the above
example.

 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’};

• When you initialize a character array by listings all its


characters separately then you must supply the ‘\0’ character
explicitly.
char ch[3]=“hell”;

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

– strlen() - It is used to shwo length of a string

– strrev() - It is used to show reverse of a string

– strcpy() - copies one string into another

– strcmp() - It is used to compare two strings

 KIIT 2014
String Functions – strcat()
• SYNTAX
– char *strcat(char *s1, const char *s2);

– s1 is a pointer to a string that will be modified. s2 will be copied to the


end of s1.
– s2 is a pointer to a string that will be appended to the end of s1.
• RETURNS
– The strcat function returns a pointer to s1 (where the resulting
concatenated string resides).

 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);

– s is the string whose length you want to calculate.

• 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);

– s is the string to reverse.

• 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";

printf("String before strrev( ) : %s\n",name);

printf("String after strrev( ) : %s",strrev(name));

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);

– s1 is an array where s2 will be copied to.


– s2 is the string to be copied.

• RETURNS

– The strcpy function returns s1.

 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

You might also like