0% found this document useful (0 votes)
21 views

Unit 7

Uploaded by

elitetube1
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)
21 views

Unit 7

Uploaded by

elitetube1
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/ 31

U23CSTC01–Programming In C Regulation 2023

UNIT III

ARRAYS AND FUNCTIONS


Arrays - Initialization- Declaration - One Dimensional and Two Dimensional Arrays –
String – String operations - String Arrays - Simple Programs - Sorting – Searching- Matrix
operations- Functions - Definition - Declaration - Pass By value - Pass By reference-
Recursion
U23CSTC01–Programming In C Regulation 2023

ARRAY INTRODUCTION
An array is a group of related data items that share a common name. The value is indicated by
writing a number called index number or subscript in brackets after the array name.
Example:
int salary[10];

PROPERTIES OF AN ARRAY
 All the elements of an array share the same name and they are distinguished from one
another with the help of an element number.
 The element number in an array plays major role for calling each element.
 The type of an array is the data type of its elements.
 The array elements are stored in continuous memory locations.
 The location of an array is the location of its first element.
 The length of an array is the no. of data elements in the array.
 The size of an array is the length of the array times the size of an elements.

TYPES OF ARRAY
(i) One dimensional array
(ii) Two dimensional array
(iii) Multi dimensional array

ONE DIMENSIONAL ARRAY


An array with a single subscript is known as one dimensional array.
It is otherwise known as single-subscribed (or) linear (or) one-dimensional arrays.

Example:
int number[5];

The memory representation of above example is given below in pictorial form.


U23CSTC01–Programming In C Regulation 2023

Array name rollno[0] rollno[1] rollno[2] rollno[3] rollno[4]


Valuestored 12 15 6 17 25

Address 1024 1026 1028 1030 1032

INITIALIZATION OF ARRAYS
We can also initialize the elements of arrays like an ordinary variable initialization.
An array can be initialized in two way, they are
a) Compile time initialization.
b) Run time initialization.

a) Compile time Initialization


Initialization in made at the time of declaration (in the declaration part) is known as compile
time initialization. The general form of initialization of arrays is:

Syntax:
datatype array-name[size] = {list of values};

Example:
int rollno[3] = {26,32,12};

 The value of array are enclosed in braces and separated by commas.


 The values are assigned to the array by assignment operator (=).
 If the number of values in the list is less than the number of elements, then only that many
elements will be initialized.
 The remaining elements will be set to zero automatically.

We can use the word ‘static’ before type declaration. This declares the variable as a static
variable.

Example:
static int counter[] = {1,1,1};
for(i =0; i < 100; i = i+1)
U23CSTC01–Programming In C Regulation 2023

{
if (i < 50) sum[i] = 0.0; else
sum[i] = 1.0;

}
……….
……….

type variable-name[size];
static type array-name[size] = {list of values};
b) Run time Initialization
When the users have to initialize more number of elements means it is difficult to use
compile time initialization. To avoid this situation the user can initialize elements in run time.

Program
/*Program showing one-dimensional array*/

#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],sum=0,i,n;
clrscr();
printf(“Enter no. of terms:”);
scanf(“%d”,&n);
printf("Enter %d integer numbers\n",n);
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("The sum of given numbers is : %d\n",sum);
getch();
}
U23CSTC01–Programming In C Regulation 2023

The entire sorting & searching algorithm must use the one-dimensional array.

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50],i,n,large,small;
clrscr();
printf("Enter size of the array");
scanf("%d",&n);
printf("Enter elements in the array:");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
large=small=a[0];
for(i=1;i<n;i++)
{
if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}
printf("\nLarge element = %d",large);
printf("\nSmall element =%d",small);
getch();
}
Output
Enter size of the array: 10
Enter elements in the array: -10 10 0 20 -2 50 100 20 -1 10 Large element = 100
Small element = -10
U23CSTC01–Programming In C Regulation 2023

DECLARATION OF ARRAYS

The general form of array declaration is

Synatx:
type variable-name[size];

 The type specifies the type of element, such as int, float, or char.
 The size indicates the maximum number of elements that can be stored inside the
array.

Example:
float height[50];int
group[10]; char
name[10];

TWO-DIMENSIONAL ARRAYS
Arrays whose elements are specified by two subscripts are called Two-
dimensional arrays (or) double-subscripted arrays.
Syntax:
datatype array-name[row_size][column_size];

Example:
int a[3][3];

The pictorial representation of the above example.


column 0 column 1 column 2

row 0 a[0][0] a[0][1] a[0][2]

row 1 a[1][0] a[1][1] a[1][2]

row 2 a[2][0] a[2][2] a[2][2]


U23CSTC01–Programming In C Regulation 2023

Example :1 Matrix Transpose

/*Program for two dimensional array*/


#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,a[3][3]; clrscr();
printf("Enter the First Matrix");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
scanf("%d",&a[i][j]);
}

}
printf("Transpose Matrix");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
printf("%d\t",a[j][i]);
}
printf(“\n”);
}
getch();
}
Output
Enter the First Matrix
123
2 3 4
5 8 7
Transpose Matrix
125
2 3 8
3 4 7
U23CSTC01–Programming In C Regulation 2023

Example :2 Matrix Addition


#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,a[3][3],b[3][3],c[3][3];
clrscr();
printf("Enter the First Matrix");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
scanf("%d",&a[i][j]);
}

}
printf("Enter the Second Matrix");
for(i=1;i<=3;i++)
for(j=1;j<=3;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
U23CSTC01–Programming In C Regulation 2023

printf("Display Addition Matrix");


for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
printf("%d \t",c[i][j]);
}
printf("\n");
}
getch();}

Output
Enter the First Matrix
1 2 3
2 1 2
3 1 1
Enter the second Matrix
1 2 3
2 1 2
3 1 1
Display Addition matrix
2 4 6
4 2 4
6 2 2

Example :3 Matrix Multiplication

#include<stdio.h>
#include<conio.h>
void main( )
U23CSTC01–Programming In C Regulation 2023

{
int a[2][2], b[2][2],c[2][2],i,j;
int i,j,k;
clrscr();
printf("Enter first matrix:\n" );
for( i=1;i<=3;i++)
{
for( j=1;j<=3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter second matrix:\n");
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
scanf("%d",&b[i][j]);
}
}

for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
c[i][j]=0; for(k=1;k<=3;k++)
{
c[i][j] =c[i][j]+a[i][k]*b[k][j];
}
}
U23CSTC01–Programming In C Regulation 2023

}
printf("Matrix Multiplication Is: \n");
for(i=1;i<=3;i++)
{
for (j=1;j<=3;j++)
{
printf("%d\n",c[i][j]);
}
}
getch();
}
Output
Enter the First Matrix
1 2 3
4 5 6
7 8 9
Enter the second Matrix
2 4 1
6 7 4
3 5 7
Matrix Multiplication
23 33 30
56 81 66
89 129 102

INITIALIZATION OF TWO DIMENSIONAL ARRAY:


There are two types of array initialization, they are given below.
Types:
c) Compile time initialization.
d) Run time initialization.
U23CSTC01–Programming In C Regulation 2023

a) Compile time initialization.


The two dimensional array can be initialized at the time of declaration is known as
Compile time initialization.

b) Run time initialization.


An array can be explicitly initialized at run time by using scanf() function.

Simple program for printing the elements of 2D array.


#include <stdio.h>
void main()
{
int score[3][2]= {10,20,30,40,50,60};
int i,j;
for(i=0;i<3;i++)
{
printf("\n");
for(j=0;j<2;j++)
{
printf("%d\t",score[i][j]);
}
}
}
Output:

10 20
30 40
50 60
MULTIDIMENSIONAL ARRAY
C allows arrays of three or more dimensions. The exact limit is determined by the
compiler. The general form of a multidimensional array is
U23CSTC01–Programming In C Regulation 2023

Syntax:
datatype array_name[s1][s2][s3]…s[m];

Example:int s[3][5][12];
float t[5][4][5][3];

Advantages of arrays
 It is capable of storing many elements at a time.
 It allows random access of elements.

Disadvantages of arrays
 The elements in the array must be same data type.
 Predetermining the size of array is must.
 Memory wastage will be there, if the array of large size is defined. To delete
an element of an array we need to traverse throughout array.

/* Example 1 for Multi Dimensional Array in C programming */


#include<stdio.h>
int main()
{
int tables, rows, columns;
int Employees[2][2][3] = { { {9, 99, 999}, {8, 88, 888} },{ {225, 445, 665}, {333,
555, 777} } };
for (tables = 0; tables < 2; tables++)
{
for (rows = 0; rows < 2; rows++)
{
for (columns =0; columns < 3; columns++)
{
printf("Employees[%d][%d][%d] = %d\n", tables, rows, columns,
U23CSTC01–Programming In C Regulation 2023

Employees[tables][rows][columns]);
}
}
}
return 0;
}

STRINGS
Introduction
The group of character, digits and symbols enclosed within quotation marks
are called as string; otherwise strings are array of characters. Null character (‘\0’)
is used to mark the end of the string.
Example:
char name[]={‘g’,’o’,’o’,’d’,’\0’};
Each character is stored in one byte of memory.
Example:

String G o o d \0
Address 1004 1005 1006 1007 1008

The operations that are performed on character strings are


 Reading and writing strings.
 Combining strings together.
 Copying one string to another.
 Comparing strings for equality.
 Extracting a portion of a string.

DECLARING AND INITIALIZING STRING VARIABLES


A string variable is any valid C variable name and is always declared as an
array.
U23CSTC01–Programming In C Regulation 2023

The general form of declaration of a string variable is


Syntax:
char string_name[size];

Example:

char city[10];
char name[30];

When the compiler assigns a character string to a character array, it


automatically supplies a null character (‘\0’) at the end of the string. Therefore, the
size should be equal to the maximum number of characters in the string plus one.
C permits a character array to be initialized in either of the following two
forms

char str[] = “THINK POSITIVE”;


char str[] = {‘T’, ‘H’, ‘I’,’N’,’K’, ‘ ‘, ‘P’, ‘O’, ‘S’, ‘I’,’T’,’I’,’V’,’E’, ‘\0’};

Reading Words
The familiar input function scanf() can be used with %s format specification to
read in a string of characters.

Example:

char address[15];
scanf(“%s”,address);

Program
/*Reading a series of words using scanf function*/
U23CSTC01–Programming In C Regulation 2023

#include<stdio.h>
#include<conio.h>
main()
{
char w1[40],w2[40],w3[40],w4[40];
clrscr();
printf(“Enter text:\n”);
scanf(“%s%s%s%s”,w1,w2,w3,w4); printf(“\n”);
printf(“word1 = %s \n word2 = %s \n”,w1, w2);
printf(“word3 = %s \n word4 = %s \n”,w3, w4);
getch();
}

Output

Enter text:
Hello How are you
word1=Hello
word2=How
word3=are
Note: scanf() function terminates its input on the first white space it finds.
Reading a Line of Text
 It is not possible to use scanf function to read a line containing more than one
word.
 This is because the scanf terminates reading as soon as a space is encountered
in the input.
 We can use the getchar() function repeatedly to read single character from
the terminal, using the function getchar(). Thus an entire line of text can be read
and stored in an array.
We have used extensively the printf() function with %s format to print strings
to the screen. The format %s can be used to display an array of characters that is
terminated by the null character.
Example:
printf(“%s”, name);
U23CSTC01–Programming In C Regulation 2023

STRING FUNCTIONS
C library supports a large number of string-handling functions that can be used to carry outmany of the
string manipulation activities.

All the string handling functions are prototyped in:


#include <string.h>
ByteString Description

strcpy() copies one string to another


writes exactly n bytes/wchar_t, copying from
strncpy() source or adding nulls
Sting
strcat() appends one string to another
Manipulation
appends no more than n bytes/wchar_t from one
strncat() string to another

strxfrm() transforms a string according to the current locale

strlen() returns the length of the string


strcmp() compares two strings
strncmp() compares a specific number of bytes/wchar_t in
String two strings
Examination strcoll() compares two strings according to the current
locale
strchr() finds the first occurrence of a byte/wchar_t in a
string
strrchr() finds the last occurrence of a byte/wchar_t in a
string
strspn() finds in a string the first occurrence of a
byte/wchar_t not in a set
strcspn() finds in a string the last occurrence of a
byte/wchar_t not in a set
U23CSTC01–Programming In C Regulation 2023

strpbrk() finds in a string the first occurrence of a


byte/wchar_t in a set
strstr() finds the first occurrence of a substring in a string

strtok() splits string into tokens

Miscellaneous strerror() returns a string containing a message derived


from an error code

Following are the most commonly used string handling functions.

 strcat( ) Concatenates two strings.


 strcmp( ) Compares two strings.
 strcpy( ) Copies one string over another.
 strlen( ) Finds the length of the string.
 strrev() Finds the reverse string

#include <stdio.h>
#include <string.h>

int main () {

char str1[20] = "Jane";


char str2[20] = "Doe";
char str3[20];
int len ;

// Copy str1 into str3


strcpy(str3, str1);
printf("strcpy( str3, str1) : %s", str3 );

//Concatenates str1 and str2


U23CSTC01–Programming In C Regulation 2023

strcat( str1, str2);


printf("strcat( str1, str2): %s", str1 );

//Length of str1 after concatenation


len = strlen(str1);
printf("strlen(str1) : %d", len );
return 0;
}

SORTING
Arranging in an ordered sequence is called "sorting". Sorting is a common
operation in many applications, and efficient algorithms to perform it have been
developed.
Common sorting algorithms
Bubble/Shell sort: Exchange two adjacent elements if they are out of order.
Repeat until array is sorted.
Insertion sort: Scan successive elements for an out-of-order item, then insert
the item in the proper place.
Selection sort: Find the smallest (or biggest) element in the array, and put it
in the proper place. Swap it with the value in the first position. Repeat until array is
sorted.
Quick sort: Partition the array into two segments. In the first segment, all
elements are less than or equal to the pivot value. In the second segment, all
elements are greater than or equal to the pivot value. Finally, sort the two segments
recursively.
Merge sort: Divide the list of elements in two parts, sort the two parts
individually and then merge it.

Bubble sort is a sorting algorithm that compares two adjacent elements and swaps
them if they are not in the intended order.
U23CSTC01–Programming In C Regulation 2023

Example:
#include<stdio.h>
void main()
{
int a[20], n, temp, i, j;
printf("Enter the number of terms: ");
scanf("%d",&n);
printf("Enter the elements of the array:");
for(i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
for(i=0; i<n; i++)
{
for(j=0; j<n-i-1; j++)
{
if(a[j] > a[j+1])
{
temp = a[j]; a[j] = a[j+1]; a[j+1] =
temp;
}
}
U23CSTC01–Programming In C Regulation 2023

}
printf("After Sorting:\n");
for(i=0; i<n; i++)
{
printf("%d\t", a[i]);
}
}

Output

Enter the number of terms: 5

Enter the elements of the


array:12 10 14 5 16

After Sorting:
5 10 12 14 16

SEARCHING :
It check for an element or retrieve an element from any data structure where the data is
stored. Based on the type of search operation, there are generally two algorithms defined in C:
 Linear Search or Sequential Search
 Binary Search
Linear Search or Sequential Search - Find whether a value is exist in a given array. If it is
exist then return the current position. In this algorithm we check the value one by one in
given list.

Binary Search - Search in the given sorted elements. In this algorithm we divide sorted elements
frommiddle and check the lie between which part. Same process we try until the all element not
read.
U23CSTC01–Programming In C Regulation 2023

Linear search is a very simple search algorithm. In this type of search, a


sequential search is madeover all items one by one. Every item is checked and if a
match is found then that particular item is returned, otherwise the search continues
till the end of the data collection

Example:
#include<stdio.h>
#inlcude<conio.h>
main()
{
int i,n,a[30],key,flag=100;
clrscr();
printf(“Enter the no. of terms:”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“Enter the search element:”);
scanf(“%d”,&key);
for(i=0;i<n;i++)
{
if(key==a[i])
{
printf(“The searching element is %d present in location %d”,key,i);
flag=i;
}
}
U23CSTC01–Programming In C Regulation 2023

if(flag==i)
printf(“The searching element is not present”);
getch();
}
Output 1
Enter the no. of terms:5
10 12 14 16 18
Enter the search element:18
The searching element is 18 present in location 5
FUNCTIONS:

INTRODUCTION
The C language is allows the use of functions, self contained "modules"
of code that take inputs (raw data), do a computation, and produce a new piece of
information based on the parameter information.
“Function is a block of statement that is used to execute for a specific
task which repeatedly occurs in the main program. This is known as function”.

A large C program is divided into basic building blocks called C function. C


function contains set of instructions enclosed by “{ }” which performs specific
operation in a C program.
Purpose

➢ To improve re-usability

➢ Modularity (Understandability and to keep track on them)


Types
In general, functions are classified into two types. They are given below.
U23CSTC01–Programming In C Regulation 2023

Example for pre defined functions are sqrt(), pow(), tan() and etc…. Let see about
user defined function in details.

Example:
U23CSTC01–Programming In C Regulation 2023

#include<stdio.h>
int sum(int, int);/* Function prototype*/
void main()
{
int a,b,c;
printf(“\nEnter the values for A and B:\n”);
scanf(“%d%d”,&a,&b);
c=sum(a,b); /* Function Call */ Actual arguments
printf(“\nAnswer is%d”,c); getch();
}
int sum(int x, int y) /* Called Function */
{ Formal arguments
int z; z=x+y;;
return(z); /* Return statement */
}
A function is a group of statements that together perform a task. Every C program has at
least one function, which is main(), and all the most trivial programs can define additional
functions.You can divide up your code into separate functions. How you divide up your code
among different functions is up to you, but logically the division is such that each function
performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For
example, strcat() to concatenate two strings, memcpy() to copy one memory location to another
location, and many more functions.
A function can also be referred as a method or a sub-routine or a procedure, etc.
U23CSTC01–Programming In C Regulation 2023

FUNCTION DEFINITION
Defining a Function
The general form of a function definition in C programming language is as follows −

return_type function_name( parameter list )


{
body of the function
}
A function definition in C programming consists of a function header and a function body. Here are
all the parts of a function −
 Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
 Function Body − The function body contains a collection of statements that define what
the function does.
Example
Given below is the source code for a function called max(). This function takes two parameters
num1 and num2 and returns the maximum value between the two −

/* function returning the max between two numbers */


int max(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}
FUNCTION DECLARATIONS
A function declaration tells the compiler about a function name and how to call the function. The
U23CSTC01–Programming In C Regulation 2023

actual body of the function can be defined separately.


A function declaration has the following parts −

return_type function_name( parameter list );

For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so the
following is also a valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you call that
function in another file. In such case, you should declare the function at the top of the file calling
the function.

Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a function,
you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A called
function performs a defined task and when its return statement is executed or when its function-
ending closing brace is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name,
and if the function returns a value, then you can store the returned value. For example −

#include <stdio.h>

/* function declaration */
int max(int num1, int num2);

int main () {

/* local variable definition */


int a = 100;
int b = 200;
int ret;

/* calling a function to get max value */


ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;
U23CSTC01–Programming In C Regulation 2023

/* function returning the max between two numbers */


int max(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}
We have kept max() along with main() and compiled the source code. While running the final
executable, it would produce the following result −
Max value is : 200
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments.
These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit.

Sr.No. Call Type & Description

1 Call by value
This method copies the actual value of an argument into the formal parameter of the function.
In this case, changes made to the parameter inside the function have no effect on the
argument.

2 Call by reference
This method copies the address of an argument into the formal parameter. Inside the function,
the address is used to access the actual argument used in the call. This means that changes
made to the parameter affect the argument.

While calling a function, there are two ways in which arguments can be passed to a function −
U23CSTC01–Programming In C Regulation 2023

By default, C uses call by value to pass arguments. In general, it means the code within a function
cannot alter the arguments used to call the function.

PASS BY VALUE
Pass by value is a way to pass a variable to a function. The variable is passed by value, not
by reference. This means that the function does not have access to the variable’s memory address.
The function can only access the variable’s value.
In the case of pass by value, the space allocated for the variable is copied to the function’s
memory space. This means that the function can modify the variable’s value without affecting the
variable’s memory address.

/*
* C program to demonstrate pass by Value.
*/
#include <stdio.h>
void swap (int a, int b)
{
int temp = a;
a = b;
b = temp;
}
int main ()
{
int a = 10;
int b = 20;
printf ("Before swap, a = %d, b = %d\n", a, b);
swap (a, b);
printf ("After swap, a = %d, b = %d\n", a, b);
return 0;
}
Program Output
Before swap, a = 10, b = 20
After swap, a = 20, b = 10
U23CSTC01–Programming In C Regulation 2023

PASS BY REFERENCE
In pass by reference, we pass the address of the variable instead of passing the value
of the variable and access the variable using the pointers in the Function. All the changes
made to variable in the function will be reflected in the main Program

/** C Program to Illustrate Pass by Reference by Swapping Numbers*/


#include <stdio.h>
void swap(int *a,int *b)
{ //*(asterix) is used to de-reference the variable
int temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int a,b;
printf("Enter two numbers:");
scanf("%d %d",&a,&b);
printf("Numbers Before Swapping: %d and %d\n",a,b);
//Calling swap function by passing address
swap(&a,&b);
printf("Numbers After Swapping: %d and %d",a,b);
return 0;
}

Program Output
Enter two numbers: 1 2
Numbers Before Swapping: 1 and 2
Numbers After Swapping: 2 and 1
U23CSTC01–Programming In C Regulation 2023

RECURSIVE FUNCTION
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.

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

int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function; otherwise
it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as
calculating the factorial of a number, generating Fibonacci series, etc.

Number Factorial
The following example calculates the factorial of a given number using a recursive function −

#include <stdio.h>

unsigned long long int factorial(unsigned int i) {

if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600

You might also like