ARRAYS
Introduction:
So far we have used only single variable name for storing one data item. If we need to store multiple pieces
of the same data, then it is very difficult for the user. To overcome this, a new data structure is used called
arrays.
An array is a linear and homogeneous data structure
An array permits homogeneous data. It means that similar types of elements are stored contiguously
in the memory under one variable name.
Example of an Array:
Suppose we have to store the roll numbers of the 100 students the we have to declare 100 variables named
as roll1, roll2, roll3, ……. roll100 which is very difficult job. Concept of C programming arrays is
introduced in C which gives the capability to store the 100 roll numbersin the contiguous memory which
has 100 blocks and which can be accessed by single variable name.
1. Array is the Collection of Elements
2. Array is collection of the Elements of the same data type.
3. All Elements are stored in the Contiguous memory
4. All elements in the array are accessed using the subscript variable (index).
Pictorial representation of C Arrays
The above array is declared as int a [5];
a[0] = 4; a[1] = 5; a[2] = 33; a[3] = 13; a[4] = 1;
In the above figure 4, 5, 33, 13, 1 are actual data items. 0, 1, 2, 3, 4 are index variables.
Index or Subscript Variable:
1. Individual data items can be accessed by the name of the array and an integer enclosedin square
bracket called subscript variable / index
2. Subscript Variables helps us to identify the item number to be accessed in the contiguousmemory.
What is Contiguous Memory?
1. When Big Block of memory is reserved or allocated then that memory block is called as
Contiguous Memory Block.
2. Alternate meaning of Contiguous Memory is continuous memory.
3. Suppose inside memory we have reserved 1000-1200 memory addresses for specialpurposes then
we can say that these 200 blocks are going to reserve contiguous memory.
Characteristics of an array:
1. The declaration e.g int a [5] creates five variables of int types in memory instead of
declaring five variables for five values.
2. All the elements of an array share the same name and they are distinguished from oneanother
with the help of the element number (index).
3. The element number in an array plays a major role for calling each element.
4. Any particular element of an array can be modified separately without disturbing theother
elements.
5. Any element of an array a[ ] can be assigned or equated to another ordinary variable orarray
variable of its type.
6. Array elements are stored in contiguous memory locations.
Array Declaration:
Array has to be declared before using it in C Program. Array is a collection of elements of similar data
types.
Syntax: datatype arrayname [size1][size2] .................. [sizen];
What does Array Declaration tell to Compiler?
1. Type of the Array
2. Name of the Array
3. Number of Dimension
4. Number of Elements in Each Dimension
Types of Array
1. Single Dimensional Array / One Dimensional Array
2. Multi-Dimensional Array
Single / One Dimensional Array:
1. Single or One Dimensional array is used to represent and store data in a linear form.
2. Array having only one subscript variable is called One-Dimensional array
3. It is also called as Single Dimensional Array or LinearArray
Single Dimensional Array Declaration and initialization:
Syntax for declaration:
datatype arrayname [size];
Examples for declaration:
int iarr[3]; char carr[20]; float farr[3];
Syntax for initialization:
dataype arrayname [size] = {val1, val2, …, valn};
Examples for initialization:
int iarr[3] = {2, 3, 4};
char carr[20] = “program”;
float farr[3] = {12.5, 13.5, 14.5};
Different Methods of Initializing 1-D Array
Whenever we declare an array, we initialize that array directly at compile time.
Method 1: Array Size Specified Directly
In this method, we try to specify the Array Size [Link] num
[5] = {2,8,7,6,0};
In the above example we have specified the size of array as 5 directly in the initialization
statement. Compiler will assign the set of values to particular element of the array.
num[0] = 2;num[1] = 8;num[2] = 7;num[3] = 6; num[4] = 0;
As at the time of compilation all the elements are at specified position So This initializationscheme is
Called as “Compile Time Initialization “.
Graphical Representation:
Method 2: Size Specified Indirectly
In this scheme of compile time Initialization, do not provide size to an array but instead provide set of
values to the array.
int num[ ] = {2,8,7,6,0};
Example
#include<stdio.h>
int main()
int num[] = {2,8,7,6,0};
int i;
for (i=0;i<5;i++) {
printf(“\n Array Element num [%d] = %d”,i, num[i]); }
return 0; }
Output:
Array Element num[0] = 2
Array Element num[1] = 8
Array Element num[2] = 7
Array Element num[3] = 6
Array Element num[4] = 0
Accessing Array
1. Array elements are randomly accessed using the subscript variable.
2. Array can be accessed using array-name and subscript variable written inside pair ofsquare
brackets [ ].
Consider:
In this example we will be accessing array like this
arr[3] is the Forth Element of Array
The elements are assigned to the array as
arr[0] = 51;arr[1] = 32;arr[2] = 43;arr[3] = 24; arr[4] = 5;
arr[5] =26;
Example Program1: Accessing array
#include<stdio.h>
void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++) {
printf("\nElement at arr[%d] is %d\n",i,arr[i]);
}
}
Output:
Element at arr[0] is 51
Element at arr[1] is 32
Element at arr[2] is 43
Element at arr[3] is 24
Element at arr[4] is 5
Element at arr[5] is 26
Assume an array which is declared like int arr[] = { 51,32,43,24,5,26};
As we have elements in an array, so we have track of base address of an array. Below things are important to
access an array.
Expression Description Example
arr It returns the base address of an array Consider 2000
*arr It gives zeroth element of an array 51
*(arr+0) It also gives zeroth element of an array 51
*(arr+1) It gives first element of an array 32
So whenever we tried accessing array using arr[i] then it returns an element at the
location*(arr+ i)
Accessing array a[i] means retrieving element from address (arr+ i).
Example Program2: Accessing array
#include<stdio.h>
void main()
{
int arr[] = {51,32,43,24,5,26};
int i;
for(i=0; i<=5; i++)
printf("\n%d %d %d %d",arr[i],*(i+arr),*(arr+i));
}
Output:
51 51 51
32 32 32
43 43 43
24 24 24
5 5 5
26 26 26
Operations with One Dimensional Array
1. Deletion – Involves deleting specified elements form an array.
2. Insertion – Used to insert an element at a specified position in an array.
3. Searching – An array element can be searched. The process of seeking specific
elements in an array is called searching.
4. Merging – The elements of two arrays are merged into a single one.
5. Sorting – Arranging elements in a specific order either in ascending or in descending order.
1. C Program to find smallest element in an array
#include<stdio>
int main() {
int a[30], i, num, smallest;
printf("\nEnter no of elements :");
scanf("%d", &num);
//Read n elements in an array
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
//Consider first element as small
smallest = a[0];
for (i = 0; i < num;i++)
{
if (a[i] < smallest)
smallest = a[i];
}
// Print out the Result
printf("\nSmallest Element : %d", smallest);
return (0);
}
2. C Program to find largest element in an array
#include<stdio.h>
int main() {
int a[30], i, num, largest;
printf("\nEnter no of elements :");
scanf("%d", &num);
//Read n elements in an array
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
//Consider first element as largest
largest = a[0];
for (i = 0; i < num; i++)
{
if (a[i] > largest)
largest = a[i];
}
// Print out the Result
printf("\nLargest Element : %d", largest);
return (0);
}
3. Program to reverse an array element in an array
#include<stdio.h>
int main() {
int arr[30], i, j, num, temp;
printf("\nEnter no of elements : ");
scanf("%d", &num);
//Read elements in an array
for (i = 0; i < num; i++)
{scanf("%d", &arr[i]);
j = i - 1; // j will Point to last Element
i = 0; // i will be pointing to first element
while (i < j) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++; // increment i
j--; // decrement j
}
//Print out the Result of Insertion
printf("\nResult after reversal : ");
for (i = 0; i < num; i++) {
printf("%d \t", arr[i]); }
return (0);
}
Multi Dimensional Array:
Array having more than one subscript variable is called Multi-Dimensional array.
Syntax:
datatype arrayname [row subscript][column subscript];
Initialization:
int a[3][3] = { {1, 2, 3}, {5, 6, 7}, {8, 9, 0}};
In the above example we are declaring 2D array which has 2 dimensions. First dimension refer
to the row and 2nd dimension refer to the column.
Two Dimensional Arrays:
1. Two Dimensional Array requires Two Subscript Variables
2. Two Dimensional Array stores the values in the form of a matrix.
Declaration and use of 2D Arrays:
int a[3][4];
Method 1: Initializing all Elements row wise
For initializing 2D Array we need to assign values to each element of an array using the below
syntax.
int a[3][2] = { {1, 4}, {5, 2}, {6, 5} };
Example Program
#include<stdio.h>
int main()
{
int i, j;
int a[3][2] = { { 1, 4 }, { 5, 2 }, { 6, 5 } };
// int a[3][2] = {1, 4 , 5, 2 , 6, 5};
for (i = 0; i < 3; i++)
for (j = 0; j < 2; j++)
printf("%d ", a[i][j]);
printf("\n");
}
return 0;
}
Some Elements could be initialized
int a[3][2] = { { 1 }, { 5 , 2 }, { 6 } };
Now we have again going with the way 1 but we are removing some of the elements from the
array. Uninitialized elements will get default 0 value.
#include <stdio.h>
int main() {
int i, j;
int a[3][2] = { { 1 }, { 5, 2 }, { 6 }};
for (i = 0; i < 3; i++) {
for (j = 0; j < 2; j++)
printf("%d ", a[i][j]);
printf("\n"); }
return 0;
}
Limitations of Arrays:
An Array is very useful as it stores multiple data under single name with same data type.
However, arrays have limitations:
A. Static Data
1. Array is Static data Structure
2. Memory Allocated during Compile time.
3. Once Memory is allocated at Compile Time it cannot be changed during Run-time
B. Can only hold data belonging to same Data types
Elements belonging to different data types cannot be stored in array because array data structure can
hold data belonging to same data type.
C. Inserting data in an array is difficult
1. Inserting an element is very difficult because before inserting element in an array we have
to create empty space by shifting other elements one position ahead.
2. This operation is faster if the array size is smaller, but same operation will be more and more
time consuming and non-efficient in case of array with large size.
D. Deletion Operation is difficult
1. Deletion is not easy because the elements are stored in contiguous memory location.
2. Like insertion operation, delete element from the array and after deletion empty space will
be created and thus need to fill the space by moving elements up in the array.
E. Shortage of Memory
Array is Static data structure. Memory can be allocated at compile time only Thus if after executing
program we need more space for storing additional information then we cannot allocate additional
space at run time. Shortage of Memory, if we don‟t know the size of memory in advance.
F. Wastage of Memory
Wastage of Memory, if array of large size is defined
Applications of Arrays:
Array is used for different verities of applications. Array is used to store data or values of
same data type. Below are the some of the applications of array –
A. Stores Elements of Same Data Type
Array is used to store the number of elements belonging to same data type.
B. Array Used for maintaining multiple variable names using single name
C. Array can be used for Sorting Elements
D. Array can perform Matrix Operation
Matrix operations can be performed using the array. We can use 2-D array to store the matrix.
Matrix can be multi-dimensional.
E. Array can be used in CPU Scheduling
CPU Scheduling is generally managed by Queue. Queue can be managed and implemented using
the array. Array may be allocated dynamically i.e at run time.
F. Array can be used in Recursive Function
When the function calls another function or the same function again then the current values are
stores onto the stack and those values will be retrieving when control comes back.
Arrays as Function arguments:
Example Program
#1: #include<stdio.h>
void fun(int arr[ ])
{
int i;
for(i=0;i<5;i++)
arr[i] = arr[i] + 10;
}
void main( )
{
int arr[5],i;
printf("\nEnter the array elements : ");
for(i=0;i< 5;i++)
scanf("%d",&arr[i]);
printf("\nPassing entire array ...................");
fun(arr); // Pass only name of array
for(i=0;i< 5;i++)
printf("\nAfter Function call a[%d] : %d",i,arr[i]);
}
Output :
Enter the array elements : 1 2 3 4 5
Passing entire array .....
After Function call a[0] : 11
After Function call a[1] : 12
After Function call a[2] : 13
After Function call a[3] : 14
After Function call a[4] : 15
STRINGS
A string is a sequence of character enclosed in double quotes (“ ”) but ends with
\0. The compiler puts \0 at the end of string to specify the end of the string.
• To get a value of string variable we can use the two different types of formats.
Using scanf() function as: scanf(“%s”, string variable);
Using gets() function as : gets(string variable);
(STRING HANDLING FUNCTIONS
C library supports a large number of string handling functions. Those functions are stored underthe header
file string.h in the program.
Some of the string handling functions:
(i) strlen() function
strlen() is used to return the length of the string , that means counts the numberof
characters present in a string.
Syntax
integer variable = strlen (string variable);
Example:
#include<stdio.h>
void main()
{
char str[20];int
strlength;
printf(“Enter String:”);
gets(str);
strlength=strlen(str);
printf(“Given String Length Is: %d”, strlength);
}
(ii) strcat() function
The strcat() is used to concatenate two strings. The second string will be appended to the end of
the first string. This process is called concatenation.
Syntax
strcat (StringVariable1, StringVariable 2);
Example:
#include<stdio.h>
void main()
{
char str1[20],str2[20];
printf(“Enter First String:”);
scanf(“%s”,str1);
printf(“Enter Second String:”);
scanf(“%s”,str2);
printf(“Concatenation String is:%s”, strcat(str1,str2));
}
(iii) strcmp() function
strcmp() function is used to compare two strings. strcmp() function does a case sensitive
comparison between two strings. The two strings are compared character by character until there is a
mismatch or end of one of the strings is reached (whichever occurs first). If the two strings are identical,
strcmp( ) returns a value zero. If they‟re not, it returns the numeric difference between the ASCII values
of the first non-matching pairs of characters.
Syntax
strcmp(StringVariable1, StringVariable2);
Example:
#include<stdio>
void main()
{
char str1[20], str2[20];
int res;
printf(“Enter First String:”);
scanf(“%s”,str1);
printf(“Enter Second String:”);
scanf(“%s”,str2);
res = strcmp(str1,str2);
printf(“ Compare String Result is:%d”,res);
}
(iv) strcmpi()/strcasecmp() function
strcmpi() function is used to compare two strings. strcmpi() function is not case sensitive.
Syntax
strcmpi(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
void main()
{
char str1[20], str2[20];int res;
printf(“Enter First String:”);
scanf(“%s”,str1);
printf(“Enter Second String:”);
scanf(“%s”,str2);
res = strcasecmp(str1,str2);
printf(“ Compare String Result is:%d”,res);
}
(v) strcpy() function:
strcpy() function is used to copy one string to another. strcpy() function copy the contents ofsecond
string to first string.
Syntax
strcpy(StringVariable1, StringVariable2);
Example:
#include<stdio.h>
void main()
{
char str1[20], str2[20];
int res;
printf(“Enter First String:”);
scanf(“%s”,str1);
printf(“Enter Second String:”);
scanf(“%s”,str2); strcpy(str1,str2)
printf(“ First String is:%s”,str1);
printf(“Second String is:%s”,str2);
}
(vi) strlwr () function:
This function converts all characters in a given string from uppercase to lowercase letter.
Syntax
strlwr(StringVariable);
Example:
#include<stdio.h>
void main()
{
char str[20];
printf(“Enter String:”);
gets(str);
printf(“Lowercase String : %s”, strlwr(str));
}
(vii) strrev() function:
strrev() function is used to reverse characters in a given string.
Syntax
strrev(StringVariable);
Example:
#include<stdio.h>
void main()
{
char str[20];
printf(“Enter String:”);gets(str);
printf(“Reverse String : %s”, strrev(str));
}
(viii) strupr() function:
strupr() function is used to convert all characters in a given string from lower case to
uppercase letter.
Syntax
strupr(Stringvariable);
Example:
#include<stdio.h>
void main()
{
char str[20];
printf(“Enter String:”);gets(str);
printf(“Uppercase String : %s”, strupr(str));
}
STRUCTURES
Arrays are used for storing a group of SIMILAR data items. In order to store a group of
DIFFERENT data items, we need structures. Structure is a constructed data type for packing different
types of data that are logically related. The structure is analogous to the “record” of a database. Structures
are used for organizing complex data in a simple and meaningful way.
Example for structures:
Student : regno, student_name, age, address
Book : bookid, bookname, author, price, edition, publisher, year Employee
: employeeid, employee_name, age, gender, dateofbirth, Customer
: custid, cust_name, cust_address, cust_phone
Structure Definition
Structures are defined first and then it is used for declaring structure variables.
The syntax for structure definition is given below:
struct tagname
Data_type member1;
Data_type member2;
…………….
……………
};
struct book
int bookid;
char bookname[20];char
author[20]; float price;
int year; int
pages;
char publisher[25]; };
The keyword “struct” is used for declaring a structure. The book structure has six fields and they are known
as structure elements or structure members. Remember each structure member may be of a different data
type. The structure tag name or the structure name can be used to declare variables of the structure data
type.
Declaring Structure Variables
First, the structure format is defined. Then the variables can be declared of that structure type. A structure
can be declared in the same way as the variables are declared. There are twoways for declaring a
structure variable.
1) Declaration of structure variable at the time of defining the structure (i.e structure
definition and structure variable declaration are combined)
struct book
{
int bookid;
char bookname[20];char
author[20]; float price;
int year; int
pages;
char publisher[25];
} b1,b2,b3;
The b1, b2, and b3 are structure variables of type struct book.
2) Declaration of structure variable after defining the structure
struct book
{
int bookid;
char bookname[20];
char author[20];
float price;
int year;
int pages;
char publisher[25];
};
struct book b1, b2, b3;
Accessing Structure Members
There are many ways for storing values into structure variables. The members of astructure can be
accessed using a “dot operator” or ‘arrow operator’
E.g. [Link] => b1 is a structure variable and author is a structure member.
b2->author = > b2 a pointer to a structure variable and author is a structure member.
Syntax
STRUCTURE_Variable.STRUCTURE_Members
The different ways for storing values into structure variable is given below:
Method 1: Using Simple Assignment Statement
[Link] = 786;
[Link] = 786.50;
Method 2: Using strcpy function
strcpy([Link], “Programming in C”);strcpy([Link],
“John”);
Method 3: Using scanf function
scanf(‚%s \n‛, [Link]);
scanf(‚%d \n‛, &[Link])
Example
#include<stdio.h> struct
book
int bookid;
char bookname[20];
char author[20];
float price;
int year;
intpage;
char publisher[25];
};
int main()
{
struct book b1, *b2;
printf("Enter the Book Id: ");
scanf("%d", &[Link]);
printf("Enter the Book Name: ");
scanf("%s", [Link]);
printf("Enter the Author Name: ");
scanf("%s", [Link]);
printf("Enter the Price: ");
scanf("%f", &[Link]);
printf("Enter the Year: ");
scanf("%d", &[Link]);
printf("Enter the Total No. of Pages: ");
scanf("%d", &[Link]);
printf("Enter the Publisher Name: ");
scanf("%s", [Link]);
printf("%d %s %d %f %d %d %s", [Link], [Link],[Link], [Link], [Link],
[Link], [Link]);
return 0;
}
Array of Structures
A Structure variable can hold information of one particular record. For example, single record of
student or employee. Suppose, if multiple records are to be maintained, it is impractical to create
multiple structure variables - use Arrays. With a single name, with a single variable, we can store1000
values. Similarly, to store 1000 records, we cannot declare 1000 structure variables. But we need
“Array of Structures”.
An array of structure is a group of structure elements under the same structurevariables.
struct student s1[1000];
The above code creates 1000 elements of structure type student. Each element will be structure
data type called student. The values can be stored into the array of structures as follows:
s1[0].student_age = 19;
Example
#include<stdio.h> struct
book
{
int bookid;
char bookname[20];
char author[20];
};
struct b1[5];
main()
{
int i;
for (i=0;i<5;i++)
{
printf("Enter the Book Id: ");
scanf("%d", &b1[i].bookid);
printf("Enter the Book Name: ");
scanf("%s", b1[i].bookname);
printf("Enter the Author Name: ");
scanf("%s", b1[i].author);
}
for (i=0;i<5;i++)
{
printf("%d \t %s \t %s \n", b1[i].bookid, b1[i].bookname,b1[i].author);
}
Structure as Function Argument
Example 1:
struct sample
{
int no; float
avg;
} a;
void main( )
{
[Link]=75;
[Link]=90.25;
fun(a);
}
void fun(struct sample p)
{
printf(“The no is=%d Average is %f”,[Link] , [Link]);
}
Example 2:
#include <stdio.h>
struct st
{
char name[20];
int no;
int marks;
};
int main( )
{
struct st x ,y; int res;
printf(“\n Enter the First Record”);
scanf(“%s%d%d”,[Link],&[Link],&[Link]);printf(“\n
Enter the Second Record”);
scanf(“%s%d%d”,[Link],&[Link],&[Link]);
res = compare ( x , y );
if (res == 1)
printf(‚\n First student has got the Highest Marks‛);
else
printf(‚\n Second student has got the Highest Marks‛);
}
void compare ( struct st st1 , struct st st2)
{
if ([Link] > st2. marks)
return ( 1 );
else
return ( 0 );
}
In the above example , x and y are the structures sent from the main ( ) function as the actual
parameter to the formal parameters st1 and st2 of the function compare ( ).
POINTERS
A pointer is a reference to another variable (memory location) in a program
– Used to change variables inside a function (reference parameters)
– Used to remember a particular member of a group (such as an array)
– Used in dynamic (on-the-fly) memory allocation (especially of arrays)
– Used in building complex data structures (linked lists, stacks, queues, trees, etc.)
Variables are allocated at addresses in computer memory (address depends on computer/operating
system). Name of the variable is a reference to that memory address. A pointer variable contains
a representation of an address of another variable (P is a pointer variable in the following):
Name V P
Address v (some value) p (some value)
int V = 101;
Abstract
101
Representation
int *P = &V;
Concrete 4 bytes for 4 bytes for
Representation int value 101 mem address v
Pointer Variable Definition
Basic syntax: Type *Name
Examples:
int *P; /* P is var that can point to an int var */
float *Q; /* Q is a float pointer */
char *R; /* R is a char pointer */
Address (&) operator
The address (&) operator can be used in front of any variable object in C -- the result of the
operation is the location in memory of the variable
Syntax: &VariableReference
Examples:
int V;
int *P;
int A[5];
&V - memory location of integer variable V
&(A[2]) - memory location of array element 2 in array A
&P - memory location of pointer variable P
Pointer Variable Initialization/Assignment
Can initialize/assign pointer vars to a value - use the address (&) op to get address of a variable
– variable in the address operator must be of the right type for the pointer (an integer
pointer points only at integer variables)
Examples:
int V;
int *P = &V;
int A[5];
P = &(A[2]);
Indirection (*) Operator
A pointer variable contains a memory address. To refer to the contents of the variable that the
pointer points to, we use indirection operator
Syntax: *PointerVariable
Example:
int V = 101;
int *P = &V;
/* Then *P would refer to the contents of the variable V (in this case, the integer 101) */
printf(“%d”,*P); /* Prints 101 */
Examples:
int A = 3;
int B;
int *P = &A;
int *Q = P;
int *R = &B;
printf(“Enter value:“);
scanf(“%d”,R);
printf(“%d %d\n”,A,B);
printf(“%d %d %d\n”,
*P,*Q,*R);
Q = &B;
if (P == Q)
printf(“1\n”);
if (Q == R)
printf(“2\n”);
if (*P == *Q)
printf(“3\n”);
if (*Q == *R)
printf(“4\n”);
if (*P == *R)
printf(“5\n”);
// a program to add two numbers using pointers
#include <stdio.h>
int main() {
int num1 = 5, num2 = 10;
int *ptr1, *ptr2, sum;
ptr1 = &num1;
ptr2 = &num2;
sum = *ptr1 + *ptr2;
printf("First number: %d\n", *ptr1);
printf("Second number: %d\n", *ptr2);
printf("Sum of the numbers: %d\n", sum);
return 0;
}
Pointers as parameters to a function
// implementing pass by reference
#include <stdio.h>
void swap_numbers(int *ptr1, int *ptr2) {
int temp;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}
int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
swap_numbers(&num1, &num2);
printf("The swapped numbers are: %d %d", num1, num2);
return 0;
}