C Unit - Iii Bca
C Unit - Iii Bca
**************************************************************************
Introduction
When we work with a large number of data values we need that any number of different
variables. As the number of variables increases, the complexity of the program also
increases and so the programmers get confused with the variable names. There may be
situations where we need to work with a large number of similar data values. To make this
work easier, C programming language provides a concept called "Array".
Definition of array:
An array is a special type of variable used to store multiple values of same data type at a time.
Or
An array is a collection of similar data items stored in continuous memory locations with
single name. C provides different types of arrays
1. One dimensional array
2. Two dimensional arrays
3. Multi dimensional array
10 20 3
0
a[0] a[1] a[2]
we can also store values incompletely like
a b c NUL NUL
L L
a[0] a[1] a[2] a[3] a[4]
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
for(i=0;i<500;i++)
{
scanf(“ %d”, &a[i]);
}
Example :
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = { 15, 25, 35, 45, 55 };
// accessing element at index 2 i.e 3rd element
printf("Element at arr[2]: %d\n", arr[2]);
// accessing element at index 4 i.e last element
printf("Element at arr[4]: %d\n", arr[4]);
// accessing element at index 0 i.e first element
printf("Element at arr[0]: %d", arr[0]);
return 0
}
Length of Array in C
The Length of an array in C refers to the number of elements in the array. It must be
specified at the time of declaration. It is also known as the size of an array that is used to
determine the memory required to store all of its elements. In C Programming language,
we don’t have any pre-defined function to find the length of the array but we can
manually determine it by using different methods mentioned below:
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
1. Using sizeof() Operator
2. Using Pointer Arithmetic
3. Using Loop
1. Using sizeof() Operator
The sizeof operator is a compile-time unary operator that calculates the size of the
variables and datatypes. It returns an integer value that represents the size of the
expression or a variable in bytes. The sizeof operator is primarily used for dynamic
memory allocation but it can also be used to find the length of an array.
The trick is to first find the size of the whole array in bytes and the size of a single element
using the sizeof operator and then divide the size of the whole array by the size of a single
element so that we can get the number of elements in the array.
Syntax:
data_type size = sizeof(Array_name) / sizeof(Array_name[index]);
data_type: It is the type of variable in which we want to store the length of the
array.(like int, size_t, etc.).
Array_name: It is the name of the array you want to find the size of.
sizeof(Array_name): It is an operator that returns the size of the entire array in bytes.
sizeof(Array_name[index]): It returns the size of a single element in the array in
bytes.
index: It is the index of any element in the array.
#include <stdio.h>
int main()
{
int Arr[] = { 1, 2, 3, 4, 5 };
// variable to store size of Arr
int length = sizeof(Arr) / sizeof(Arr[0]);
printf("The length of the array is: %d\n", length);
return 0;
}
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
2. Using Pointer Arithmetic
We can also calculate the length of an array in C using pointer arithmetic. This solution of
using a pointer is just a hack that is used to find the number of elements in an array.
Syntax: data_type length = *(&arr + 1) - arr;
In the above syntax:
&arr: Pointer to an array of elements.
(&arr + 1): Address of memory ahead of the array as pointer type is a pointer to an array
of integers.
*(&arr + 1) – arr: Inclusive difference between the start and the end of the array
3. Using Loop
The loop method is used to calculate the length of an array in C. It iterates through all
the elements of an array and increments the count.
Search − Uses the provided index or the value to search for an element.
1) Traversing
Traversing an Array means going through each element of an Array exactly once. We start
from the first element and go to the last element. An example of a program that performs
traversing operations on a linear Array is given below in C language.
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Code:
#include <stdio.h>
void main()
{
int array[] = {1,2,3,4,5};
int i, n = 5;
printf(" The array elements are: \n " );
for( i=0;i < n; i++)
{
printf(" array[%d] = %d \n " , i, array[i] );
}
}
2) Searching
The search operation finds a particular data item or element in an Array. We can search in
an unsorted array with the help of traversal of the Array. The linear traversal from the first
element to the last element can be used to search if a given number is present in an Array
and can also be used to find its position if present.
3) Insertion
Insertion operation is used to add a new element in the Array. When we specify the
particular element and position where it will be added to the Array, we perform an insertion
operation. However, the size of the Array is not disturbed while performing this operation.
An element will be inserted in an array only if it has sufficient space to add it. If the size of
an array is full already, a new element cannot be added. An example to show insert
operation in an unsorted Array in C.
4) Deletion
In the delete operation, the element existing in the Array is searched (using linear search)
and deleted, followed by the shifting of elements. The user enters the element’s position to
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
be deleted from the array. The deletion operation, just like the insertion operation, does not
affect the size of the array. Also, the position of the element to be deleted should be within
the size of the array, since deleting an element beyond the size of Array is impossible. C
program to show delete operation in an unsorted array.
5) Sorting
This operation is performed to sort an Array into a fixed order, i.e., ascending or descending.
A two dimensional array is an array of one dimensional array. In other words two
dimensional array in C is an array of one dimensional array.
Declaration: Before using two dimensional arrays in your C program you must declare it. The
general syntax to declare a two dimensional array is
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
When the array is completely initialized, C permits us to omit the first
dimensional value in its initialization.
When the elements are to be initialized to zero, the following shortcut method may
be used.
To initialize large arrays we use for loop statements. For two dimensional arrays we
use two for loops. One for reading row values and one for reading column values.
int a[50][50];
for(i=0;i<50;i++)
{
for(j=0;j<50;j++)
{
scanf(“%d”,&a[i][j]);
}
}
Accessing: Since two dimensional array consists of two index values we use two for loops to
access / print array elements.
for(i=0;i<50;i++)
{
for(j=0;j<50;j++)
{
printf(“%d”,a[i][j]);
}
}
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
3. Multi dimensional arrays:
Multi dimensional arrays can store values in more than two dimensions. It can also be defined
as an array of two dimensional arrays.
If an array contains ‘n’ dimensions, a particular element is specified by suing ‘n’ subscripts
as A[I1], A[I2], A[I3],A[I4] A[In].
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Chapter-II
Strings
……………………………………………………………………………………………
C Strings
The string can be defined as the one-dimensional array of characters terminated by a null
('\0').
The character array or the string is used to manipulate text such as word or sentences.
Each character in the array occupies one byte of memory, and the last character must
always be 0.
The termination character ('\0') is important in a string since it is the only way to
identify where thestring ends.
When we define a string as char s[10], the character s[10] is implicitly initialized with
the null in the memory.
Declaration:
There are two ways to declare a string in c language.
1. By char array
2. By string literal
1. The example of declaring string by char array in C language
2. char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
As we know, array index starts from 0, so it will be represented as in the figure given below.
While declaring string, size is not mandatory. So we can write the above code as given
below:
char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
3. We can also define the string by the string literal in C language.
For example:char ch[]="javatpoint";
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
In such case, '\0' will be appended at the end of the string by the compiler.
Difference between char array and string literal
There are two main differences between char array and literal.
We need to add the null character '\0' at the end of the array by our self whereas; it
is appended internally by the compiler in the case of the character array.
The string literal cannot be reassigned to another set of characters whereas; we can
reassign the characters of the array.
Reading string from terminal
a) Using scanf function: The familiar input function scanf can be used with ‘%s” format
specification to read a string of characters.
Example: char address[10];
scanf(“%s”, address);
b) Reading a line of Text: C supports a format specification known as the edit set
conversion code %[^\n]that can used to read a line containing a variety of characters,
including whitespaces.
Example: char address[10];
scanf(“%[^\n]”, address);
c) Using getchar and gets functions:
getchar function: used to read a single character from the terminal. We can use this
function to repeatedlyto read successive single characters from the input and place them into a
character array. Thus, an entire lineof text can be read and stored in an array. The reading is
terminated when the new line character (‘\n’) is entered and the null character is then inserted
at the end of the string.
Example: char ch;
ch=getchar();
gets function: It reads all characters from terminal into string until null character encountered.
Example: char line[80];
gets(line);
prints(“%s”, line);
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
Writing strings to screen:
a) Using printf function: we have used extensively the printf function with %s format to
print strings to thescreen. The format %s can be used to display an array of characters that is
terminated by the null character.
For example, the statement
printf(“%s”, name);
The following table provides most commonly used string handling function and their use...
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
1) strlen( ) Function :
strlen( ) This function return the length of the string. i.e. the number of characters in
thestring excluding the terminating NULL character.
It accepts a single argument which is pointer to the first character of the string.
Example: int n;
char st[20] = “Bangalore”;
n = strlen(st);
• This will return the length of the string 9 which is assigned to an integer variable n.
• Note that the null character “\0‟ available at the end of a string is not counted.
2) strcpy( ) Function :
strcpy( ) This function is used to copying one string to another string. The function
strcpy(str1,str2) copies str2 to str1 including the NULL character. Here str2 is the source
string and str1 is the destination string.
The old content of the destination string str1 are lost. The function returns a pointer to
destination string str1.
Syntax: char * strcpy (char * destination, const char * source);
Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
If destination string length is less than source string, entire source string value won’t be
copied into destination string.
For example, consider destination string length is 20 and source string length is 30. Then,
only 20 characters from source string will be copied into destination string and remaining
10 characters won’t be copied and will be truncated.
Example : char city[15];
strcpy(city, “BANGALORE”) ;
This will assign the string “BANGALORE” to the character variable city.
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
3) strcat( ) Function :
strcat( ) function in C language concatenates two given strings. It concatenates source string at
the end of destination string. Syntax for strcat( ) function is given below.
Syntax : char * strcat ( char * destination, const char * source );
Example :
strcat ( str2, str1 ); - str1 is concatenated at the end of str2.
strcat ( str1, str2 ); - str2 is concatenated at the end of str1.
5) strcmp( ) Function :
strcmp( ) function in C compares two given strings and returns zero if they are same. If
length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0
value.
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as different characters.
Example :
char city[20] = “Madras”;
char town[20] = “Mangalore”;
strcmp(city, town);
This will return an integer value “-10‟ which is the difference in the ASCII values of the first
mismatching letters “D‟ and “N‟.
* Note that the integer value obtained as the difference may be assigned to an integer variable
as follows:
int n;
n = strcmp(city, town);
6) strcmpi() function :
strcmpi( ) function in C is same as strcmp() function. But, strcmpi( ) function is not case
sensitive. i.e., “A” and “a” are treated as same characters. Whereas, strcmp() function treats
“A” and “a” as different characters.
• strcmpi() function is non standard function which may not available in standard library.
• Both functions compare two given strings and returns zero if they are same.
• If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0
value.
strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as different characters.
7) strlwr() function :
strlwr() function is non standard function which may not available in standard library in C.
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
8) strupr() function :
strupr() function is non standard function which may not available in standard library in C.
strrev() function :
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED