0% found this document useful (0 votes)
6 views17 pages

C Unit - Iii Bca

This document provides an overview of arrays and strings in C programming, including their declaration, initialization, and operations such as accessing, inserting, deleting, and sorting elements. It explains one-dimensional and two-dimensional arrays, as well as multi-dimensional arrays, and introduces string handling, including declaration, reading, and writing strings. Key concepts include the use of the sizeof operator to determine array length and the importance of the null character in strings.

Uploaded by

harshithavennu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views17 pages

C Unit - Iii Bca

This document provides an overview of arrays and strings in C programming, including their declaration, initialization, and operations such as accessing, inserting, deleting, and sorting elements. It explains one-dimensional and two-dimensional arrays, as well as multi-dimensional arrays, and introduces string handling, including declaration, reading, and writing strings. Key concepts include the use of the sizeof operator to determine array length and the importance of the null character in strings.

Uploaded by

harshithavennu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIT - III

Arrays: Introduction, Declaration of Arrays, accessing elements of the Array – Storing


Values in Array, Calculating the length of the Array, Operations that can be performed
on Array, Passing one dimensional array to function. Two dimensional Arrays,
accessing two dimensional arrays, Passing two dimensional arrays to functions.

Strings: Introduction, String Operations using String functions.

**************************************************************************

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

Q) One dimensional array


A one dimensional array is a group of elements of same type and stored under one subscript
or index.
OR
A One dimensional array is single subscript variable which hold more than one value under a
single name.
i) Declaration of Array
Like variables, arrays must be declared before storing values into it. The following is the
syntax to declare aone dimensional array.
Syntax: type array_name[size];

Example: int a[3];


PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
A declaration tells to the compiler three things
1. Array type
2. Array name
3. Number of elements stored in the array (size of array)

ii) Storing Values in Array or initialization


We can store values in array on the same way as the ordinary variable when they are declared.
The general syntax is
Syntax: Type array_name={ list of values};
Example: int a[3]={ 10,20,30};
a

10 20 3
0
a[0] a[1] a[2]
we can also store values incompletely like

Example: char ch[5]={ ‘a’, ‘b’, ‘c’};


a

a b c NUL NUL
L L
a[0] a[1] a[2] a[3] a[4]

We can copy an entire array into another array like


int b[3];
b=a;
we can also store values into individually using subscript likech[3]=’d’;
we can store values into large arrays using for loop like int
a[500];

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
for(i=0;i<500;i++)
{
scanf(“ %d”, &a[i]);
}

iii) Accessing elements of the Array


The individual elements of an array are identified using the combination of 'arrayName' and
'indexValue'. We use the following general syntax to access individual elements of an array...
Syntax: array_name[index_value];
Example:
for(i=0;i<500;i++)
{
printf(“ %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]);

In the above syntax,

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

Basic Array Operations

Following are the basic Array operations.

 Traverse − Print each element in the array one by one.

 Insertion − At the specified index, adds an element.

 Deletion − The element at the specified index is deleted.

 Search − Uses the provided index or the value to search for an element.

 Update − The element at the specified index is updated.

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.

 Two dimensional arrays

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

Syntax: type array_name[number of rows][number of columns];

Example: int a[2][3];

Declaration tells to the complier three things.

1. The type of the array.


2. The name of the array.
3. The number of elements stored in it
Initialization: Declaration of array reserves only memory for the elements in the array. No
values will bestored. The values of array elements are stored when it is initialized.

 A two dimensional array may be initialized at the time of its declaration.

Example: int a[2][2]={10,20,30,40};


 Two dimensional arrays may be initialized row by row.

Example: int a[2][2]={ {10,20},{30,40}};

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.

Example: int a[][2]={10,20,30,40};

 When the elements are to be initialized to zero, the following shortcut method may
be used.

Example: int a[2][2]={ {0},{0}};

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

can be used to display the entire contents of the array name.


b) Using putchar and puts functions:
The putchar function is used to output single character. It takes the following form
Example: char ch=”A”;
putchar(ch);
We can use putchar function to repeatedly to output a string of characters stored in an array
using a loop.
Example: char name[6]=”PARIS”
for(i=0;i<5;i++)
putchar(name[i]);
If you want to display the entire string at a time use puts function.
Example: puts(name);

String Handling Functions in C

C programming language provides a set of pre-defined functions called string handling


functions to workwith string values. The string handling functions are defined in a header
file called string.h. Whenever wewant to use any string handling function we must include
the header file called string.h.

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.

• As you know, each string in C is ended up with null character (‘\0′).


• In strcat( ) operation, null character of destination string is overwritten by source string’s
first character and null character is added at the end of new destination string which is
created after strcat( ) operation.
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = “ ftl” ;
char target[ ]= “ welcome to” ;
printf (“\n Source string = %s”, source ) ;
printf ( “\n Target string = %s”, target ) ;
strcat ( target, source ) ;
printf ( “\n Target string after strcat( ) = %s”, target ) ;
}

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.

Syntax : int strcmp ( const char * str1, const char * str2 );

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.

Syntax : int strcmpi ( const char * str1, const char * str2 );

Example : m=strcmpi(“ DELHI ”, “ delhi ”);  m = 0.

7) strlwr() function :

strlwr() function converts a given string into lowercase.

Syntax : char *strlwr(char *string);

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 converts a given string into uppercase.

Syntax : char *strupr(char *string);

strupr() function is non standard function which may not available in standard library in C.

strrev() function :

strrev() function reverses a given string in C language.

Syntax : char *strrev(char *string); Examples:

PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED
PATAN ARIFOON.,MCA.,M.Tech
UGC NET & APSET QUALIFIED

You might also like