0% found this document useful (0 votes)
39 views44 pages

UNIT 3 Notes

The document discusses arrays and functions in C programming. It defines arrays as a linear and homogeneous data structure that allows storing similar data types contiguously in memory. It describes one-dimensional arrays and their declaration and initialization. Functions are defined as blocks of code that perform a specific task and can be called multiple times. Function types and passing parameters by value or reference are also covered.

Uploaded by

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

UNIT 3 Notes

The document discusses arrays and functions in C programming. It defines arrays as a linear and homogeneous data structure that allows storing similar data types contiguously in memory. It describes one-dimensional arrays and their declaration and initialization. Functions are defined as blocks of code that perform a specific task and can be called multiple times. Function types and passing parameters by value or reference are also covered.

Uploaded by

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

UNIT-III ARRAYS AND FUNCTIONS

Contents
Arrays: Introduction – One dimensional Array – Two dimensional arrays –
Multidimensional arrays. Strings: Operations of Strings.
Functions – Definition of function – Declaration of Function – Function Prototype – Types
of Functions – Pass by value – Pass by reference – recursion – Programming Examples.

ARRAYS

Introduction:

If we need to store multiple copies of the same data then it is very difficult for the user. To
overcome the difficulty 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.
An array can be declared of any standard or custom data type.

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 numbers
in the contiguous memory which has 100 blocks and which can be accessed by single variable
name.
1. C Programming Arrays is the Collection of Elements

2. C Programming Arrays 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 Programming 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 enclosed in
square bracket called subscript variable / index

2. Subscript Variables helps us to identify the item number to be accessed in the contiguous
memory.

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 special
purposes then we can say that these 200 blocks are going to reserve contiguous memory.

Contiguous Memory Allocation

1. Two registers are used while implementing the contiguous memory scheme. These
registers are base register and limit register.
2. When OS is executing a process inside the main memory then content of each register are
as

Register Content of register

Base register Starting address of the memory location where process


execution is happening

Limit register Total amount of memory in bytes consumed by process

Here diagram 1 represents the contiguous allocation of memory and diagram 2 represents non-
contiguous allocation of memory.
3. When process try to refer a part of the memory then it will firstly refer the base address
from base register and then it will refer relative address of memory location with respect to
base address.

How to allocate contiguous memory?

1. Using static array declaration.

2. Using alloc ( ) / malloc ( ) function to allocate big chunk of memory dynamically.

Array Terminologies:

Size: Number of elements or capacity to store elements in an array. It is always mentioned in


square brackets [ ].
Type: Refers to data type. It decides which type of element is stored in the array. It is also
instructing the compiler to reserve memory according to the data type.
Base: The address of the first element is a base address. The array name itself stores address of
the first element.
Index: The array name is used to refer to the array element. For example num[x], num is array
and x is index. The value of x begins from 0.The index value is always an integer value.
Range: Value of index of an array varies from lower bound to upper bound. For example in
num[100] the range of index is 0 to 99.
Word: It indicates the space required for an element. In each memory location, computer can
store a data piece. The space occupation varies from machine to machine. If the size of element
is more than word (one byte) then it occupies two successive memory locations. The variables
of data type int, float, long need more than one byte in memory.

Characteristics of an array:

1. The declaration int a [5] is nothing but creation of five variables of integer 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 one
another with the help of the element number.
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 the
other elements.
5. Any element of an array a[ ] can be assigned or equated to another ordinary variable or
array 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 nothing but the collection of
elements of similar data types.

Syntax: <data type> array name [size1][size2].....[sizen];

Syntax Parameter Significance

Data type Data Type of Each Element of the array

Array name Valid variable name

Size Dimensions of the Array


Array declaration requirements

Requirement Explanation

Data Type specifies the type of the array. We can compute the size
Data Type required for storing the single cell of array.

Valid identifier is any valid variable or name given to the array.


Valid Identifier Using this identifier name array can be accessed.

Size of Array It is maximum size that array can have.

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 Linear Array

Single Dimensional Array

Syntax for declaration: <data type> <array name> [size];

Examples for declaration: int iarr[3]; char carr[20]; float farr[3];


Syntax for initialization: <data type> <array name> [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.

Initializing 1-D Array is called as compiler time initialization if and only if we assign certain set
of values to array element before executing program. i.e. at compilation time.

Here we are learning the different ways of compile time initialization of an array.

Ways of Array Initializing 1-D Array:

1. Size is Specified Directly

2. Size is Specified Indirectly


Method 1: Array Size Specified Directly

In this method, we try to specify the Array Size directly.

int 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 initialization
scheme is Called as “Compile Time Initialization“.

Graphical Representation

Method 2: Size Specified Indirectly

In this scheme of compile time Initialization, We do not provide size to an array but instead we
provide set of values to the array.

int num[ ] = {2,8,7,6,0};

Explanation:

1. Compiler Counts the Number Of Elements Written Inside Pair of Braces and Determines
the Size of An Array.
2. After counting the number of elements inside the braces, The size of array is considered
as 5 during complete execution.
3. This type of Initialization Scheme is also Called as “Compile Time Initialization“

Example Program
#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

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 display array elements with addresses

#include<stdio.h>
#include<stdlib.h>
#define size 10 int
main()

{
int a[3] = { 11, 22, 33 };

printf("\n a[0],value=%d : address=%u", a[0], &a[0]);

printf("\n a[1],value=%d : address=%u", a[1], &a[1]);


printf("\n a[2],value=%d : address=%u", a[2], &a[2]); return (0);
}

Output:

a[0],value=11 : address=2358832
a[1],value=22 : address=2358836
a[2],value=33 : address=2358840

2. C Program for Reading and printing Array Elements

#include<stdio.h>

int main()
{
int i, arr[50], num;
printf("\nEnter no of elements :");
scanf("%d", &num);
//Reading values into Array printf("\
nEnter the values :");
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
//Printing of all elements of array
for (i = 0; i < num; i++) ]
{
printf("\narr[%d] = %d", i, arr[i]);
}
return (0);
}

Output:

Enter no of elements : 5

Enter the values : 10 20 30 40 50


arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50

3. C Program to calculate addition of all elements in an array

#include<stdio.h>

int main()

{
int i, arr[50], sum, num;
printf("\n Enter no of elements :");
scanf("%d", &num);
//Reading values into Array printf("\
nEnter the values :");
for (i = 0; i < num; i++)
scanf("%d", &arr[i]);
//Computation of total
sum = 0;

for (i = 0; i < num; i++)

sum = sum + arr[i];


//Printing of all elements of array
for (i = 0; i < num; i++) printf("\
na[%d]=%d", i, arr[i]);
//Printing of total
printf("\nSum=%d", sum);
return (0);
}

Output:

Enter no of elements : 3

Enter the values : 11 22 33

a[0]=11
a[1]=22
a[2]=33
Sum=66

4. C Program to find smallest element in an array

#include<stdio.h>

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


}

Output:
Enter no of elements : 5 11 44 22 55 99
Smallest Element : 11

5. 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);


}

Output:

Enter no of elements : 5 11 55
33 77 22
Largest Element : 77

Multi Dimensional Array:

1. Array having more than one subscript variable is called Multi-Dimensional array.

2. Multi Dimensional Array is also called as Matrix.

Syntax: <data type> <array name> [row subscript][column subscript];

Example: Two Dimensional


Arrays Declaration: Char name[50]
[20]; 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 will
refer the row and 2nd dimension will refer the column.

Example: Three Dimensional


Arrays Declaration: Char name[80]
[20][40];
The following information are given by the compiler after the declaration

Array Dimensio No. of Elements in


Example Type
Name n No. Each Dimension

1 integer roll 1 10

2 character name 2 80 and 20

3 character name 3 80 and 20 and 40

Two Dimensional Arrays

1. Two Dimensional Array requires Two Subscript Variables

2. Two Dimensional Array stores the values in the form of matrix.

3. One Subscript Variable denotes the “Row” of a matrix.

4. Another Subscript Variable denotes the “Column” of a matrix.

Declaration and use of 2D Arrays:

int a[3][4];
for(i=0;i<row,i++)
for(j=0;j<col,j++)
{
printf("%d",a[i][j]);
}

Meaning of Two Dimensional


Arrays:
1. Matrix is having 3 rows ( i takes value from 0 to 2 )

2. Matrix is having 4 Columns ( j takes value from 0 to 3 )

3. Above Matrix 3×4 matrix will have 12 blocks having 3 rows & 4 columns.

4. Name of 2-D array is „a„ and each block is identified by the row & column number.

5. Row number and Column Number Starts from 0.

Two-Dimensional Arrays: Summary with Sample Example:

Summary Point Explanation

No of Subscript Variables Required 2

Declaration a[3][4]

No of Rows 3

No of Columns 4

No of Cells 12

No of for loops required to iterate 2

Memory Representation:

1. 2-D arrays are stored in contiguous memory location row wise.

2. 3 X 3 Array is shown below in the first Diagram.

3. Consider 3×3 Array is stored in Contiguous memory location which starts from 4000.

4. Array element a[0][0] will be stored at address 4000 again a[0][1] will be stored to next
memory location i.e. Elements stored row-wise
5. After Elements of First Row are stored in appropriate memory locations, elements of

next row get their corresponding memory locations.

6. This is integer array so each element requires 2 bytes of memory.

Basic Memory Address Calculation:

a[0][1] = a[0][0] + Size of Data Type

Element Memory Location

a[0][0] 4000

a[0][1] 4002

a[0][2] 4004

a[1][0] 4006

a[1][1] 4008

a[1][2] 4010

a[2][0] 4012

a[2][1] 4014

a[2][2] 4016
Initializing 2D Array

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 } };

for (i = 0; i < 3; i++)

for (j = 0; j < 2; j++)

printf("%d ", a[i][j]);

printf("\n");

}
return 0;

Output:

1 4
5 2
6 5

We have declared an array of size 3 X 2, it contains overall 6 elements.


Row 1: {1, 4},

Row 2: {5, 2},

Row 3: {6, 5}

We have initialized each row independently a[0][0] = 1


a[0][1] = 4
Method 2: Combine and Initializing 2D Array

Initialize all Array elements but initialization is much straight forward. All values are assigned
sequentially and row-wise
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 };

for (i = 0; i < 3; i++)

for (j = 0; j < 2; j++)

{ printf("%d ", a[i][j]); }


printf("\n");

}
return 0;

Output:

1 4
5 2
6 5

Accessing 2D Array Elements:

1. To access every 2D array we requires 2 Subscript variables.

2. i – Refers the Row number

3. j – Refers Column Number


4. a[1][0] refers element belonging to first row and zeroth
column

1. C Program for addition of two matrices

#include<stdio.h>

int main()

{
int i, j,
mat1[10][10],
mat2[10][10],
mat3[10][10];
int row1, col1, row2, col2;
printf("\nEnter the number of Rows of Mat1 : ");
scanf("%d", &row1);
printf("\nEnter the number of Cols of Mat1 : ");
scanf("%d", &col1);
printf("\nEnter the number of Rows of Mat2 : ");
scanf("%d", &row2);
printf("\nEnter the number of Columns of Mat2 : ");
scanf("%d", &col2);

/* before accepting the Elements Check if no of rows and columns of both matrices is equal
*/
if (row1 != row2 || col1 != col2)
{ printf("\nOrder of two matrices is not same "); exit(0); }

//Accept the Elements in Matrix 1


for (i = 0; i < row1; i++)
{
for (j = 0; j < col1; j++)
{

printf("Enter the Element a[%d][%d] : ", i, j);


scanf("%d", &mat1[i][j]);

//Accept the Elements in Matrix 2


for (i = 0; i < row2; i++)
for (j = 0; j < col2; j++)
{

printf("Enter the Element b[%d][%d] : ", i, j);

scanf("%d", &mat2[i][j]);

//Addition of two matrices


for (i = 0; i < row1; i++)
for (j = 0; j < col1; j++)
{
mat3[i][j] = mat1[i][j] + mat2[i][j];
}

//Print out the Resultant Matrix

printf("\nThe Addition of two Matrices is : \n");

for (i = 0; i < row1; i++)

{
for (j = 0; j < col1; j++)
{
printf("%d\t", mat3[i][j]);
}
printf("\n"); }
return (0);

}
Output:

Enter the number of Rows of Mat1 : 3 Enter the


number of Columns of Mat1 : 3
Enter the number of Rows of Mat2 : 3

Enter the number of Columns of Mat2 : 3


Enter the Element a[0][0] : 1
Enter the Element a[0][1] : 2
Enter the Element a[0][2] : 3
Enter the Element a[1][0] : 2
Enter the Element a[1][1] : 1
Enter the Element a[1][2] : 1
Enter the Element a[2][0] : 1
Enter the Element a[2][1] : 2
Enter the Element a[2][2] : 1
Enter the Element b[0][0] : 1
Enter the Element b[0][1] : 2
Enter the Element b[0][2] : 3
Enter the Element b[1][0] : 2
Enter the Element b[1][1] : 1
Enter the Element b[1][2] : 1
Enter the Element b[2][0] : 1
Enter the Element b[2][1] : 2
Enter the Element b[2][2] : 1

The Addition of two Matrices is :

246

422

242
2. C Program to Multiply two 3 X 3 Matrices

#include<stdio.h>

int main()

{
int a[10][10], b[10][10], c[10][10], i, j, k;

int sum = 0;
printf("\nEnter First Matrix : "); for (i = 0; i < 3; i++)

{
for (j = 0; j < 3; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("\nEnter Second Matrix :");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
scanf("%d", &b[i][j]);
}
}
printf("The First Matrix is : \n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf(" %d ", a[i][j]);
}
printf("\n");
}
printf("The Second Matrix is : \n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
printf(" %d ", b[i][j]);
}
printf("\n");
}
//Multiplication Logic

for (i = 0; i <= 2; i++)

for (j = 0; j <= 2; j++)

sum = 0;
for (k = 0; k <= 2; k++)
{

sum = sum + a[i][k] * b[k][j];

c[i][j] = sum;

}
printf("\nMultiplication Of Two Matrices : \n");
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{ printf(" %d ", c[i][j]); }
printf("\n"); }
return (0);

Output:

Enter First Matrix :


1 1 1
1 1 1
1 1 1

Enter Second Matrix :

2 2 2
2 2 2
2 2 2
The First Matrix is :
1 1 1
1 1 1
1 1 1
The Second Matrix is :
2 2 2
2 2 2
2 2 2

Multiplication Of Two Matrices :

6 6 6
6 6 6
6 6 6

Limitations of Arrays

Array is very useful which stores multiple data under single name with same data type.
Following are some listed limitations of Array in C Programming.
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 hold data belonging to same Data types

1. Elements belonging to different data types cannot be stored in array because array data
structure can hold data belonging to same data type.
2. Example : Character and Integer values can be stored inside separate array but cannot
be stored in single array
C. Inserting data in an array is difficult

1. Inserting 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 , we have to delete element from the array and after deletion
empty space will be created and thus we need to fill the space by moving elements up in
the array.
E. Bound Checking

1. If we specify the size of array as „N‟ then we can access elements up to „N-1‟ but in C if
we try to access elements after „N-1‟ i.e. Nth element or N+1th element then we does not
get any error message.
2. Process of checking the extreme limit of array is called Bound Checking and C does not
perform Bound Checking.
3. If the array range exceeds then we will get garbage value as result.
F. Shortage of Memory

1. 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.
2. Shortage of Memory , if we don‟t know the size of memory in advance

G. Wastage of Memory

1. 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 the 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.

int arr[30];

Above array is used to store the integer numbers in an array.


arr[0] = 10;
arr[1] = 20;

arr[2] = 30;

arr[3] = 40;

arr[4] = 50;

Similarly if we declare the character array then it can hold only character. So in short character
array can store character variables while floating array stores only floating numbers.
B. Array Used for maintaining multiple variable names using single name

Suppose we need to store 5 roll numbers of students then without declaration of array we need
to declare following –
int roll1, roll2, roll3, roll4, roll5;

1. Now in order to get roll number of first student we need to access roll1.
2. Guess if we need to store roll numbers of 100 students then what will be the procedure.

3. Maintaining all the variables and remembering all these things is very difficult.

Consider the Array int roll[5]; Here we are using array which can store multiple values and we
have to remember just single variable name.
C. Array can be used for Sorting Elements

We can store elements to be sorted in an array and then by using different sorting technique we
can sort the elements.
Different Sorting Techniques are:

1. Bubble Sort

2. Insertion Sort

3. Selection Sort

4. Bucket Sort

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. [Animation will Explain more
about Round Robin Scheduling Algorithm | Video Animation]
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. This is
similar operation like stack.

Arrays as Function arguments:

Passing array to function:

Array can be passed to function by two ways:

1. Pass Entire array

2. Pass Array element by element


1. Pass Entire array

Here entire array can be passed as a argument to function.

Function gets complete access to the original array.


While passing entire array address of first element is passed to function, any changes made
inside function, directly affects the Original value.
Function Passing method : “Pass by Address“

2. Pass Array element by element

Here individual elements are passed to function as argument.

Duplicate carbon copy of Original variable is passed to function.

So any changes made inside function do not affect the original value.

Function doesn‟t get complete access to the original array element.


Function passing method is “Pass by Value“

Passing entire array to function:


Parameter Passing Scheme : Pass by Reference
Pass name of array as function parameter.
Name contains the base address i.e. ( Address of 0th element )
Array values are updated in function.
Values are reflected inside main function also.

STRINGS

String is a sequence of character enclosed with 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 under
the header file string.h in the program.

Let us see about some of the string handling functions.

(i) strlen() function


strlen() is used to return the length of the string , that means counts the number
of characters present in a string.

Syntax

integer variable = strlen (string variable);

Example:
#include<stdio.h>
#include<conio.h>
void main()
{

char str[20]; int


strlength; clrscr();
printf(‚Enter String:‛); gets(str);
strlength=strlen(str);
printf(‚Given String Length Is: %d‛, strlength); getch();
}

Output:

Enter String
Welcome
Given String Length Is:7

(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>
#include<conio.h>
void main()
{

char str1[20],str2[20]; clrscr();


printf(‚Enter First String:‛);
scanf(‚%s‛,str1);

printf(‚Enter Second String:‛);


scanf(‚%s‛,str2);
printf(‚ Concatenation String is:%s‛, strcat(str1,str2)); getch();
}

Output:

Enter First String Good


Enter Second String
Morning
Concatenation String is: GoodMorning

(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.h>
#include<conio.h>
void main()
{
char str1[20], str2[20]; int res;
clrscr();

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); getch();


}

Output:

Enter First String Good


Enter Second String
Good
Compare String Result is: 0

(iv) strcmpi() function

strcmpi() function is used to compare two strings. strcmpi() function is not case sensitive.

Syntax

strcmpi(StringVariable1, StringVariable2);

Example:

#include<stdio.h>
#include<conio.h>
void main()
{

char str1[20], str2[20]; int res;


clrscr();

printf(‚Enter First String:‛);


scanf(‚%s‛,str1);
printf(‚Enter Second String:‛);
scanf(‚%s‛,str2);
res = strcmpi(str1,str2);

printf(‚ Compare String Result is:%d‛,res); getch();


}
Output:

Enter First String


WELCOME
Enter Second String
welcome
Compare String Result is: 0

(v) strcpy() function

strcpy() function is used to copy one string to another. strcpy() function copy the contents of
second string to first string.

Syntax

strcpy(StringVariable1, StringVariable2);

Example:

#include<stdio.h>
#include<conio.h>
void main()
{

char str1[20], str2[20]; int res;


clrscr();

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); getch();
}

Output:

Enter First String Hello


Enter Second String welcome
First String is: welcome Second String
is: welcome

(vi) strlwr () function

This function converts all characters in a given string from uppercase to lowercase letter.

Syntax

strlwr(StringVariable);

Example:

#include<stdio.h>
#include<conio.h> void
main()
{

char str[20]; clrscr();


printf(‚Enter String:‛); gets(str);
printf(‚Lowercase String : %s‛, strlwr(str)); getch();
}

Output:

Enter String
WELCOME
Lowercase String : welcome

(vii) strrev() function

strrev() function is used to reverse characters in a given string.

Syntax
strrev(StringVariable);

Example:

#include<stdio.h>
#include<conio.h>
void main()
{

char str[20]; clrscr();


printf(‚Enter String:‛); gets(str);
printf(‚Reverse String : %s‛, strrev(str)); getch();
}

Output:

Enter String
WELCOME
Reverse String : emoclew

(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>
#include<conio.h> void
main()
{

char str[20]; clrscr();


printf(‚Enter String:‛); gets(str);
printf(‚Uppercase String : %s‛, strupr(str)); getch();
}

Output:
Enter String welcome
Uppercase String : WELCOME
FUNCTIONS IN C

A function is a block of code that performs a particular task.


There are many situations where we might need to write same line of code for more than once in a
program. This may lead to unnecessary repetition of code, bugs and even becomes boring for the
programmer.
So, C language provides an approach in which you can declare and define a group of statements once
in the form of a function and it can be called and used whenever required.
These functions defined by the user are also known as User-defined Functions

C functions can be classified into two categories,

1. Library functions
2. User-defined functions

Library functions are those functions which are already defined in C library, example
printf(), scanf(), strcat() etc. You just need to include appropriate header files to use these
functions. These are already declared and defined in C libraries.

A User-defined functions on the other hand, are those functions which are defined by the user
at the time of writing program. These functions are made for code reusability and for saving
time and space.
Benefits of Using Functions

1. It provides modularity to your program's structure.

2. It makes your code reusable. You just have to call the function by its name to use it,
wherever required.
3. In case of large programs with thousands of code lines, debugging and editing
becomes easier if you use functions.
4. It makes the program more readable and easy to understand.

Function Declaration

General syntax for function declaration is,

returntypefunctionName(type1 parameter1, type2 parameter2,...);

Like any variable or an array, a function must also be declared before its used.

Function declaration informs the compiler about the function name, parameters is accept,
and its return type.

The actual body of the function can be defined separately. It's also called as Function
Prototyping.

Function declaration consists of 4 parts.

i. returntype

ii. function name

iii. parameter list

iv. terminating semicolon


1. returntype

When a function is declared to perform some sort of calculation or any operation and is expected
to provide with some result at the end, in such cases, a return statement is added at the end of
function body. Return type specifies the type of value(int, float, char, double) that function is
expected to return to the program which called the function.

Note: In case your function doesn't return any value, the return type would be void.

2. functionName

Function name is an identifier and it specifies the name of the function. The function name is
any valid C identifier and therefore must follow the same naming rules like other variables in C
language.
3. parameter list

The parameter list declares the type and number of arguments that the function expects when it
is called. Also, the parameters in the parameter list receives the argument values when the
function is called. They are often referred as formal parameters.

Function definition Syntax

returntypefunctionName(type1 parameter1, type2 parameter2,...)


{
// function body goes here
}

The first line returntype functionName(type1 parameter1, type2 parameter2,...) is known as function
header and the statement(s) within curly braces is called function body

functionbody

The function body contains the declarations and the statements(algorithm) necessary for
performing the required task. The body is enclosed within curly braces { ... } and consists of
three parts.

 local variable declaration(if required).

 function statements to perform the task inside the function.

 a return statement to return the result evaluated by the function(if return type
is void, then no return statement is required).

Calling a function

When a function is called, control of the program gets transferred to the function.
functionName(argument1, argument2,...);

Passing Arguments to a function


Arguments are the values specified during the function call, for which the formal parameters are declared
while defining the function
.

Type of User-defined Functions in C

There can be 4 different types of user-defined functions, they are:

1. Function with no arguments and no return value

2. Function with no arguments and a return value

3. Function with arguments and no return value

4. Function with arguments and a return


value
1. Function with no arguments and no return value
#include<stdio.h>

Void greatNum(); // function


declaration

Int main()
{
// function
greatNum();
call
return0;
}

Void greatNum() // function


definition
{
inti, j;

printf("Enter 2 numbers that you want to


compare..."); scanf("%d%d", &i, &j);
if(i> j) {
printf("The greater number is: %d", i);
}
else {
printf("The greater number is: %d", j);
}
}

2. Function with no arguments and a return value

#include<stdio.h>

intgreatNum(); // function
declaration

int main()
{
int result;
result = greatNum(); // function
callis: %d",
printf("The greater number
result);
return0;
}

intgreatNum() // function definition


{
inti, j, greaterNum;
printf("Enter 2 numbers that you want
to compare..."); scanf("%d%d", &i, &j);
if(i> j) {
greaterNum =
i;
}
else {
greaterNum =
j;
}
// returning

3. Function with arguments and no return value

#include<stdio.h>

voidgreatNum(int a, int b); // function


declaration

intmain()
{
inti, j;

printf("Enter 2 numbers that you want to


compare..."); scanf("%d%d", &i, &j);
greatNum(i, j);// function call return0;
}

voidgreatNum(int x, int y) // function


definition
{
if(x > y) {
printf("The greater number is: %d", x);
}
else
{
printf("The greater number
is: %d", y);
}

4. Function with arguments and a return value

#include<stdio.h>

intgreatNum(int a,int b);//

function declaration intmain()


{
inti, j, result;
printf("Enter 2 numbers that you want
to compare..."); scanf("%d%d",&i,&j);
result=greatNum(i, j);//
function call printf("The
greater number is: %d",
result); return0;
}

intgreatNum(int x,int y)// function definition


{
if(x >
y){
return
x;
}
else{
RECURSION
 Recursion is the process of repeating items in a self-similar way.

 In programming languages, if a program allows you to call a function


inside the same function, then it is called a recursive call of the function.

 Recursion cannot be applied to all the problem, but it is more useful for
the tasks that can be defined in terms of similar subtasks.

 For Example, recursion may be applied to sorting, searching, and


traversal problems.

void recursion() {
recursion(); /* function calls itself */
}

int main()
{ recurs
ionn();
}

You might also like