C-PRGM Unit-I8
C-PRGM Unit-I8
C-PRGM Unit-I8
C- Programming
Unit 8: Arrays and string
Syllabus Unit: - 8
Introduction
An array is defined as the collection of elements of the same data type stored at contiguous
memory locations. The elements of the array share the same variable name but each element
has its own unique index number (also known as a subscript). An array is the derived data type
in C programming language which can store the primitive type of data such as int, char, double,
float, etc. And it can also store the collection of derived data types, such as pointers, structure,
etc. Elements of the array can be randomly accessed by using its index number.
Declaration of C Array
Like any other variable, arrays must be declared before they are used. General form of array
declaration is,
data-type variable-name[size];
Example
int arr[10];
Here, int is the data type, arr is the name of the array and 10 is the size of array. It means
array arr can only contain 10 elements of int type.
Index of an array starts from 0 to size-1 i.e first element of arr array will be stored
at arr[0] address and the last element will occupy arr[9].
There are various ways in which we can declare an array. It can be done by
specifying its type and size, by initializing it or both.
Teksan Gharti
BE SEM - I
C- Programming
// Array declaration by specifying size
int arr1[10];
After an array is declared it must be initialized. Arrays may be initialized when they are
declared, just as any other variables.
For example:-
int mark[5] = {19, 10, 8, 17, 9};
We can also initialize each element of the array by using the index. Consider the following
example.
marks[0]=80;
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Element of array can be accessed by using array subscript (or index) . Subscript starts
with 0, which means arr[0] represents the first element in the array arr.the general form of
accessing the array element is as follows…..
Syntax:
arr_name[index];
In general arr[n-1] can be used to access nth element of an array. where n is any integer number.
For example:
Teksan Gharti
BE SEM - I
C- Programming
int mydata[20];
mydata[0] /* first element of array mydata*/
mydata[19] /* last (20th) element of array mydata*/
In c programming language, single dimensional arrays are used to store list of values of same
datatype. In other words, single dimensional arrays are used to store a row of values. In single
dimensional array, data is stored in linear form. Single dimensional arrays are also called
as one-dimensional arrays, Linear Arrays or simply 1-D Arrays.
the following syntax shows the general syntax for declaring a single dimensional array...
Example :-
The above declaration of single dimensional array reserves 60 continuous memory locations of
2 bytes each with the name rollNumbers and tells the compiler to allow only integer values into
those memory locations.
Teksan Gharti
BE SEM - I
C- Programming
Initialization of Single Dimensional Array
Example:-
The above declaration of single dimensional array reserves 6 contiguous memory locations of
2 bytes each with the name marks and initializes with value 89 in first memory location, 90 in
second memory location, 76 in third memory location, 78 in fourth memory location, 98 in
fifth memory location and 86 in sixth memory location.
We can also use the following general syntax to intialize a single dimensional array without
specifying size and with initial values...
The array must be initialized if it is created without specifying any size. In this case, the size
of the array is decided based on the number of values initialized.
Example :-
int marks [] = { 89, 90, 76, 78, 98, 86 } ;
In the above example declaration, size of the array 'marks' is 6 and the size of the
array 'studentName' is 16. This is because in case of character array, compiler stores one exttra
character called \0 (NULL) at the end.
In c programming language, to access the elements of single dimensional array we use array
name followed by index value of the element that to be accessed.
The index value must be enclosed in square braces. The index value of single dimensional
array starts with zero (0) for first element and incremented by one for each element.
We use the following general syntax to access individual elements of single dimensional
array...
arrayName [ indexValue ]
Example :-
marks [2] = 99 ;
In the above statement, the third element of 'marks' array is assinged with value '99'.
Teksan Gharti
BE SEM - I
C- Programming
printf("\n\n");
Output: -
Teksan Gharti
BE SEM - I
C- Programming
Most popular and commonly used multi-dimensional array is two dimensional array. The 2-D
arrays are used to store data in the form of table. We also use 2-D arrays to create
mathematical matrices.
Example :-
We use the following general syntax for declaring and initializing a two-dimensional array with
specific number of rows and columns with initial values.
Example: -
Teksan Gharti
BE SEM - I
C- Programming
The above declaration of two-dimensional array reserves 6 contiguous memory
locations of 2 bytes each in the form of 2 rows and 3 columns. And the first row is initialized
with values 1, 2 & 3 and second row is initialized with values 4, 5 & 6.
We use the following general syntax to access the individual elements of a two-dimensional
array...
Example: -
matrix_A [0][1] = 10 ;
Here, the element with row index 0 and column index 1 of matrix_A array is assigned with
value 10.
Program No: -Accept the value of array and print in matrix form
#include <stdio.h>
void main()
{
int arr1[3][2],i,j;
printf("\n\n Accept the value of array and print the in matrix form of 3x2 :\n");
printf("------------------------------------------------------\n");
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("index position - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
Teksan Gharti
BE SEM - I
C- Programming
}
}
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<2;j++)
printf("%d\t",arr1[i][j]);
}
printf("\n\n");
}
Output: -
Processing an array
(declaring, initialling, assigning all task come in the processing of array)
Teksan Gharti
BE SEM - I
C- Programming
The syntax to pass an array to the function: -
functionName(arrayName);//passing array
The function that receives an array as an argument in three ways by declaring the formal
parameter: -
As shown in above syntax, a pointer can be passed with a help of a pointer variable carrying
the address of the first location of the array. This type of array passing mechanism is
called call by reference. In this case, we pass the address of the array elements while calling
the function. A detailed example is given below:
Program: -
#include <stdio.h>
void disp(int *num)
{
printf(" %d", *num);
printf("\n");
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
int i;
for ( i=0; i<10; i++)
{
disp(&arr[i]);
}
return 0;
}
Teksan Gharti
BE SEM - I
C- Programming
Output: -
#include<stdio.h>
void giveMeArray(int a[]);
int main()
{
int myArray[] = { 2, 3, 4 };
giveMeArray(myArray);
return 0;
}
int index = 0;
for(index= 0; index <3; ++index)
{
printf("%d\n",a[index]);
}
}
Teksan Gharti
BE SEM - I
C- Programming
Output:-
#include <stdio.h>
#define ARRAY_SIZE 8
void ReadArray(int acData[ARRAY_SIZE])
{
int index = 0;
for(index= 0; index < ARRAY_SIZE; ++index)
{
printf("%d\n",acData[index]);
}
}
int main(int argc, char *argv[])
{
//Create an array
int aiData[ARRAY_SIZE] = {1,2,3,4,5,6,7,8};
//Pass array as a parameter
ReadArray(aiData);
return 0;
}
Output:-
Teksan Gharti
BE SEM - I
C- Programming
3) Formal parameters as an unsized array –
#include <stdio.h>
//Size of the created array
#define ARRAY_SIZE 8
void ReadArray(int acData[])
{
int index = 0;
for(index= 0; index < ARRAY_SIZE; ++index)
{
printf("%d\n",acData[index]);
}
}
int main()
{
ReadArray(aiData);
return 0;
}
Output:-
Teksan Gharti
BE SEM - I
C- Programming
Program:-(2) Formal parameters as an unsized array –
#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size);
int main ()
{
return 0;
}
int i;
double avg;
double sum = 0;
return avg;
}
Output:-
Teksan Gharti
BE SEM - I
C- Programming
Note: -
To determine the number of elements in the array, we can divide the total size of the array by
the size of the array element. You could do this with the type, like this:
int a [10];
size n = sizeof(a) / sizeof(int);
Arrays of string
String is a sequence of characters that is treated as a single data item and terminated
by null character '\0'. C language does not support strings as a data type. A string is actually
one-dimensional array of characters in C language. These are often used to create meaningful
and readable programs.
Example:
So, the string is a 1-D array of characters and array of strings is a 2-D array of characters.
Just like we can create a 2-D array of int, float etc; we can also create a 2-D array of character
or array of strings. Here is how we can declare a 2-D array of characters.
Char ch_arr[3][10] = {
{'s', 'p', 'i', 'k', 'e', '\0'},
{'t', 'o', 'm','\0'},
{'j', 'e', 'r', 'r', 'y','\0'}
};
It is important to end each 1-D array by the null character. We can’t use them as
strings. Declaring an array of strings in this way is rather tedious, that’s why C provides an
alternative syntax to achieve the same thing. This above initialization is equivalent to:
char ch_arr[3][10] = {
"spike",
"tom",
"jerry"
};
The first subscript of the array i.e 3 denotes the number of strings in the array and the second
subscript denotes the maximum length of the string.
Teksan Gharti
BE SEM - I
C- Programming
Program:-
#include <stdio.h>
#include <string.h>
#define NUM_OF_STR 4
#define MAX_STR_SZ 40
#define DEST_SIZE 100
int main()
{
printf(dest);
return 0;
}
Output:-
Teksan Gharti
BE SEM - I
C- Programming
String Handling Function: -
There are lots of string handling functions available in string.h header file. Here are some of
the important string manipulation functions.
Teksan Gharti
BE SEM - I
C- Programming
Function Syntax Description
1) function – strlen
Program:-
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "hello";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
Teksan Gharti
BE SEM - I
C- Programming
Output:
2) function – strcmp
Program:-
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "hello";
char s2[20] = "helloworld";
if (strcmp(s1, s2) ==0)
{
printf("string 1 and string 2 are equal");
}
else
{
printf("string 1 and 2 are different");
}
return 0;
}
Output:
3) function – strncmp
Program: -
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "Engineering";
char s2[20] = "EngineeringFirstSem";
/* below it is comparing first 8 characters of s1 and s2*/
if (strncmp(s1, s2, 8) ==0)
{
printf("string 1 and string 2 are equal");
}
else
{
printf("string 1 and 2 are different");
}
return 0;
}
Teksan Gharti
BE SEM - I
C- Programming
Output:
string1 and string 2 are equal
4) function – strcat
Program:-
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
return 0;
}
Output:
5) function – strncat
Program
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strncat(s1,s2, 3);
printf("Concatenation using strncat: %s", s1);
return 0;
}
Output:
6) function – strcpy
Program: -
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2 : I’m going to copied into s1";
Teksan Gharti
BE SEM - I
C- Programming
/* this function has copied s2 into s1*/
strcpy(s1,s2);
printf("String s1 is: %s", s1);
return 0;
}
Output:
7) function – strncpy
Program
#include <stdio.h>
#include <string.h>
int main()
{
char s1[30] = "string 1";
char s2[30] = "string 2: I’m using strncpy now";
/* this function has copied first 12 chars of s2 into s1*/
strncpy(s1,s2, 12);
printf("String s1 is: %s", s1);
return 0;
}
Output:
8) function – strchr
Program
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[30] = "I’m an example of function strchr";
printf ("%s", strchr(mystr, 'f'));
return 0;
}
Output:
f function strchr
Teksan Gharti
BE SEM - I
C- Programming
9) function – Strrchr
Program
#include <stdio.h>
#include <string.h>
int main()
{
char mystr[40] = "I’m an example of function fstrchr";
printf ("%s", strrchr(mystr, 'f'));
return 0;
}
Output:
fstrchr
Output:
Teksan Gharti