UNIT- 4
Arrays & Basic Algorithms
An array is a collection of data items, all of the same type, accessed using a common name. A one-dimensional array is like a list; A two dimensional array is like a table; The C language places no limits on the number of dimensions in an array, though specific implementations may. Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant. Declaring Arrays Array variables are declared identically to variables of their data type, except that the variable name is followed by one pair of square [ ] brackets for each dimension of the array. Uninitialized arrays must have the dimensions of their rows, columns, etc. listed within the square brackets. Dimensions used when declaring arrays in C must be positive integral constants or constant expressions. In C99, dimensions must still be positive integers, but variables can be used, so long as the variable has a positive value at the time the array is declared. ( Space is allocated only once, at the time the array is declared. The array does NOT change sizes later if the variable used to declare it changes. )
Examples: int i, j, intArray[ 10 ], number; float floatArray[ 1000 ]; int tableArray[ 3 ][ 5 ]; /* 3 rows by 5 columns */
const int NROWS = 100; // ( Old code would use #define NROWS 100 ) const int NCOLS = 200; // ( Old code would use #define NCOLS 200 ) float matrix[ NROWS ][ NCOLS ];
4.1.1 Array notation and representation Array is defined as a collection of elements of same data type. Hence it is also called as homogeneous variable. Total number of elements in array defines size of array. Position of element in an array defines index or subscript of particular element. Array index always starts with zero. If the size of array is n then index ranges from 0 to n–1. There can be array of integer, floating point or character values. Character array is called as String. Eg.1 A= 0 1 2 3 4
4.1.2 Manipulating 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 the 10th element from the array and assign the value to salary variable. The following example Shows how to use all the three above mentioned 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 */ }
/* output each array element's value */ for (j = 0; j < 10; j++ ) { printf("Element[%d] = %d\n", j, n[j] ); }
return 0; } When the above 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
4.1.3 Using multi-dimensional arrays 1-D array has 1 row and multiple columns but multidimensional array has of multiple rows and multiple columns.
Two Dimensional array: It is the simplest multidimensional array. They are also called as matrix.
Declaration: data-type array_name[no.of rows][no. of columns];
Total no of elements= No.of rows * No. of Columns
Example 3: int a[2][3] This example illustrates two dimensional array a of 2 rows and 3 columns.
Col 0 Col 1 Col 2
Row 0
Row 1 Fig.2: Index positions of elements of a[2][3]
Total no of elements: 2*3=6 Total no of bytes occupied: 6( total no.of elements )*2(Size of one element)=12 Initialization and Storage Representation: In C, two dimensional arrays can be initialized in different number of ways. Specification of no. of columns in 2 dimensional array is mandatory while no of rows is optional. int a[2][3]={{1,3,0}, // Elements of 1st row {-1,5,9}}; // Elements of 2nd row
OR
int a[][3]={{1,3,0}, // Elements of 1st row {-1,5,9}}; // Elements of 2nd row
OR
int a[2][3]={1,3,0,-1,5,9};
Fig. 3 gives general storage representation of 2 dimensional array
Col 0 Col 1 Col n
Row 0
Row 1
- - Row m Fig.3 General Storage Representation of 2 dimensional array.
Eg 4. int a[2][3]={1,3,0,-1,5,9}
Row 0 Row 1 Col 0 col1 col2
Accessing Two-Dimensional Array Elements: 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[1][2]; The above statement will access element from the 2nd row and third column of the array A i.e. element 9.
4.1.4 Character arrays and strings If the size of array is n then index ranges from 0 to n-1. There can be array of integer, floating point or character values. Character array is called as String.
Eg.1 A= 0 1 2 3 4
Arrays can be categorized in following types
These are described below. The abstract model of string is implemented by defining a character array data type and we need to include header file ‘string.h’, to hold all the relevant operations of string. The string header file enables user to view complete string and perform various operation on the string. E.g. we can call ‘strlen’ function to find length of string, ‘strcat’ to concatenate two string, ‘strcpy’ to copy one string to another, ‘strrev’ to reverse the string. The definitions of all these functions are stored in the header file ‘string.h’. So string functions with the user provided data becomes the new data type in ‘C’. Fig. 4.1 : String data type To use the functions related to strings, user only need to include ‘string.h’ header file. All the definitions details of these functions are keep hidden from the user, user can directly use these function without knowing all the implementation details. This is known as abstraction or hiding. String Manipulation in C Language Strings are also called as the array of character.
Char string name[size of string]; Char is the data type, user can give any name to the string by following all the rules of defining name of variable. Size of the string is the number of alphabet user wants to store in string. Example:
Following are the list of string manipulation function
4.1.5 Structure A structure can be considered as a template used for defining a collection of variables under a single name. Structures help programmers to group elements of different data types into a single logical unit (Unlike arrays which permit a programmer to group only elements of same data type).
• Ordinary variables can hold one piece of information • arrays can hold a number of pieces of information of the same data type. For example, suppose you want to store data about a book. You might want to store its name (a string), its price (a float) and number of pages in it (an int). If data about say 3 such books is to be stored, then we can follow two approaches: Construct individual arrays, one for storing names, another for storing prices and still another for storing number of pages. Use a structure variable. Suppose we want to create a employee database. Then, we can define a structure called employee with three elements id, name and salary. The syntax of this structure is as follows: struct employee { int id; char name[50]; float salary; }; Note:
We can declare the variable of structure in two ways
1. Declare the structure inside main function Following example show you, how structure variable is declared inside main function struct employee { int id; char name[50]; float salary; }; int main() { struct employee e1, e2; return 0; } In this example the variable of structure employee is created inside main function that e1 ,e2. 2. Declare the structure outside main function Following example show you, how structure variable is declared outside the main function
struct employee { int id; char name[50]; float salary; }e1,e2;
Memory is allocated to the structure only when we create the variable of structure. Consider following example
1. When we declare a structure, memory is not allocated for un-initialized variable. 2. Let us discuss very familiar example of structure student , we can initialize structure variable in different ways – Way 1 : Declare and Initialize struct student { char name[20]; int roll; float marks; }std1 = { "Poonam",89,78.3 }; In the above code snippet, we have seen that structure is declared and as soon as after declaration we have initialized the structure variable. std1 = { "Poonam",89,78.3 } This is the code for initializing structure variable in C programming Way 2 : Declaring and Initializing Multiple Variables struct student { char name[20]; int roll; float marks; } std1 = {"Poonam" ,67, 78.3}; std2 = {"Vishal",62, 71.3}; In this example, we have declared two structure variables in above code. After declaration of variable we have initialized two variable. std1 = {"Poonam" ,67, 78.3}; std2 = {"Vishal",62, 71.3}; Way 3 : Initializing Single member struct student { int mark1; int mark2; int mark3; } sub1={67}; Though there are three members of structure,only one is initialized , Then remaining two members are initialized with Zero. If there are variables of other data type then their initial values will be – Data Type Default value if not initialized integer 0 float 0.00 char NULL Way 4 : Initializing inside main struct student { int mark1; int mark2; int mark3; }; void main() { struct student s1 = {89,54,65}; - - - - -- - - - - -- - - - - -- }; When we declare a structure then memory won’t be allocated for the structure. i.e only writing below declaration statement will never allocate memory struct student { int mark1; int mark2; int mark3; }; We need to initialize structure variable to allocate some memory to the structure. struct student s1 = {89,54,65};
4.1.6 Union Unions are quite similar to the structures in C. Union is also a derived type as structure. Union can be defined in same manner as structures just the keyword used in defining union in union where keyword used in defining structure was struct. union car { char name[50]; int price; }; Union variables can be created in similar manner as structure variable. union car { char name[50]; int price; }c1, c2, *c3;
OR;
union car { char name[50]; int price; }; -------Inside Function----------- union car c1, c2, *c3; In both cases, union variables c1, c2 and union pointer variable c3 of type union car is created.
Like structure memory is allocated to union only when we create the variable of it. The memory is allocated to union according to the largest data members of the union.
union employee { int id; char name[50]; float salary; } ; void main() { union employee e1= { 1, “ABC”, 50000 }; printf(“%d”, e. id); printf(“%s”, e. name); } O/P- garbage value, ABC
4.1.7 Enumerated data types
Enumeration is a user defined datatype in C language. It is used to assign names to the integral constants which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration. Here is the syntax of enum in C language, enum enum_name{const1, const2, ....... }; The enum keyword is also used to define the variables of enum type. There are two ways to define the variables of enum type as follows. enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday}; enum week day;
4.1.8 Array of structures Structure is collection of different data type. An object of structure represents a singlerecord in memory, if we want more than one record of structure type, we have tocreate an array of structure or object. As we know, an array is a collection of similartype, therefore an array can be of structure type. Syntax for declaring structure array struct struct-name { datatype var1; datatype var2; - - - - - - - - - - - - - - - - - - - - datatype varN; }; struct struct-name obj [ size ]; Example for declaring structure array #include<stdio.h> struct Employee { int Id; char Name[25]; int Age; long Salary; }; void main() { int i; struct Employee Emp[ 3 ]; //Statement 1 for(i=0;i<3;i++) { printf("\nEnter details of %d Employee",i+1); printf("\n\tEnter Employee Id : "); scanf("%d",&Emp[i].Id); printf("\n\tEnter Employee Name : "); scanf("%s",&Emp[i].Name); printf("\n\tEnter Employee Age : "); scanf("%d",&Emp[i].Age); printf("\n\tEnter Employee Salary : "); scanf("%ld",&Emp[i].Salary); } printf("\nDetails of Employees"); for(i=0;i<3;i++) printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary); } Output : Enter details of 1 Employee Enter Employee Id : 101 Enter Employee Name : Suresh Enter Employee Age : 29 Enter Employee Salary : 45000 Enter details of 2 Employee Enter Employee Id : 102 Enter Employee Name : Mukesh Enter Employee Age : 31 Enter Employee Salary : 51000 Enter details of 3 Employee Enter Employee Id : 103 Enter Employee Name : Ramesh Enter Employee Age : 28 Enter Employee Salary : 47000 Details of Employees 101 Suresh 29 45000 102 Mukesh 31 51000 103 Ramesh 28 47000 In the above example, we are getting and displaying the data of 3 employee using array of object. Statement 1 is creating an array of Employee Emp to store the records of 3 employees. Array within Structure As we know, structure is collection of different data type. Like normal data type, It can also store an array as well. Syntax for array within structure struct struct-name { datatype var1; // normal variable datatype array [size]; // array variable - - - - - - - - - - - - - - - - - - - - datatype varN; }; struct struct-name obj; Example for array within structure struct Student { int Roll; char Name[25]; int Marks[3]; //Statement 1 : array of marks int Total; float Avg; }; void main() { int i; struct Student S; printf("\n\nEnter Student Roll : "); scanf("%d",&S.Roll); printf("\n\nEnter Student Name : "); scanf("%s",&S.Name); S.Total = 0; for(i=0;i<3;i++) { printf("\n\nEnter Marks %d : ",i+1); scanf("%d",&S.Marks[i]); S.Total = S.Total + S.Marks[i]; } S.Avg = S.Total / 3; printf("\nRoll : %d",S.Roll); printf("\nName : %s",S.Name); printf("\nTotal : %d",S.Total); printf("\nAverage : %f",S.Avg); } Output : Enter Student Roll : 10 Enter Student Name : Kumar Enter Marks 1 : 78 Enter Marks 2 : 89 Enter Marks 3 : 56 Roll : 10 Name : Kumar Total : 223 Average : 74.00000 In the above example, we have created an array Marks[ ] inside structure representing 3 marks of a single student. Marks[ ] is now a member of structure student and to access Marks[ ] we have used dot operator(.) along with object S.
4.1.9 Passing arrays to functions Passing array to function using call by value method As we already know in this type of function call, the actual parameter is copied to the formal parameters. #include <stdio.h> void disp( char ch) { printf("%c ", ch); } int main() { char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'}; for (int x=0; x<10; x++) { /* I’m passing each element one by one using subscript*/ disp (arr[x]); }
return 0; } Output: a b c d e f g h i j
Passing array to function using call by reference When we pass the address of an array while calling a function then this is called function call by reference. When we pass an address as an argument, the function declaration should have a pointer as a parameter to receive the passed address.
#include <stdio.h> void disp( int *num) { printf("%d ", *num); }
int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; for (int i=0; i<10; i++) { /* Passing addresses of array elements*/ disp (&arr[i]); }
return 0; } Output:
1 2 3 4 5 6 7 8 9 0 |
References:
- The C Programming Language. 2nd Edition Book by Brian Kernighan and Dennis Ritchie
- C Programming: A Modern Approach Book by Kim N. King
- C Programming Absolute Beginner’s Guide book by S.D Perry