SlideShare a Scribd company logo
Fundamentals Of Programming in C

                Presented By:
               saket kr Pathak
                  M.sc. nt & M
        aMIty InstItute Of InfOrMatIOn
                 technOlOgy




                                         1
Recursion
Recursion is said as a mathematical concept which states that an
expression such that each term is generated by repeating a particular
mathematical operation. Here repeating is the iterative manner to
perform same operation.

As the approach of the programming language C, it can be performed
and are in practice within the definition part of functions. Syntactically
language provides the freedom to call function within it’s body
defined.

Definition of ‘Recursion’ as the logical prospective view states simply
the iterative manner to perform any code snippet in C, but we always
need a terminating condition to control the going on iterations. In the
following sections we will discuss the iterative manner of recursion
and the terminating condition in bit expanded form.
                                           Fundamentals Of Programming in C   2
Recursive Functions
Recursive functions are not different from the syntactical structure of
the general functions that we had discussed in previous sections.
They have same return type, function name, parameters enclosed
within parenthesis.

Declaration:
         int Think_and_ Play (int, char);

We had discussed the syntactical view of the function, where return
type is ‘int’, function name is ‘Think_and_Play’ and within the
parenthesis we had defined the parameters as of data type integer
with another one that is of data type character.




                                         Amity Institute Of Information Technology   3
Now let us manipulate the definition of the our function, that we had
declared in the previous slide from the general aspect of definition
we had practiced till now.

Definition:
         int _iFlag =0, _iTerminate = 0;
         int Think_and_Play(int _iBat, char _chBall)
         {
                    if (_iFlag ==0)
                               printf(“This is game cricket going on.”);
                    _iFlag++;
                    if(_iTerminate < 6)
                    {
                               printf(“Hit the Ball with the Bat.”);
                               ++ _iTerminate;
                               Think_and_Play(1, ‘0’);
                               return 1;
                    }
         }


                                              Amity Institute Of Information Technology   4
As in sequence of explanation, this snippet code has few syntactical
statements. In the very first the program counter encounters with the
Variables of type integer that are global to the function.

Then it encounters the return type of the function following with the
function name, and the parameters defined. All of these has the
considerable part in function definition structure of C language that
we had discussed in the previous sections of declaration.

As encounter with the right curly braces comes into just next
statement, it considers the following structure is for definition.

In the definition part, the first if condition is doing its formal
responsibility to control the execution of print function where the
defined condition will be true i.e. when the value of the variable
‘_iFlag’ is strictly equal to 0.

                                          Amity Institute Of Information Technology   5
The next statement is simply incrementing the value stored in the
memory location termed as ‘_iFlag’ (the variable name).

Then our point of consideration comes into picture in the execution
of second ‘if’ structure. Here in this ‘if’ structure program counter
will execute the statements defined within ‘if’ body, if and only if
the condition gets true. It means whenever the condition defined
with the if statements returns ‘Boolean True’ value then the further
body will execute. So we can consider the controlling system of the
execution of ‘if-body’ is properly controlled through the condition
defined there in if statement.

Now within the body concerned, we have a print function that
supports its definition with two arguments defined as ‘String type’
and another is ‘Variable Length Argument’ (i.e. null in the snippet).
Function performs the role successfully and control passes further.

                                         Amity Institute Of Information Technology   6
The followed statement says to increment the value stored in the
memory location corresponds to the variable name ‘_iTerminate’.
Here logically this increasing value of ‘_iTerminate’ and the if
condition defined above will cause the terminating condition.

At the near end of the body, we have a function call as
‘Think_and_Play(…, …)’. Since here we are calling the same
function that is executing, is said as recursion. Therefore, calling of
the function from its own body forms a loop like execution pattern
and is said as recursion. It is also considered as the alternative
programming pattern of looping structure (i.e. of ‘for loop’ and
‘while loop’).

The end statement says to return the value to the calling function as
‘return 1’, that declares the successful completion of all other
statements defined above.

                                          Amity Institute Of Information Technology   7
Discussion

Typically, recursion is quite elegant and requires fewer variables to
make the same calculation as iterative looping structural programs.
It take care of its assigned records by maintaining the stack of
arguments and variables for each invocation. It has been calculated
in some machines a simple recursive program call with snippet
defining one integer argument can be requires 8 32-bit words on the
stack.

Let us consider a snippet code of fibonacci sequence and calculate
it’s efficiency in the following section.




                                        Amity Institute Of Information Technology   8
Snippet-Code:

         int fibonacci (int _iNam)
         {
                    if (_iNam <= 1)
                               return _iNam;
                    else
                               return (fibonacci(_iNam-1)+fibonacci(_iNam-2)) }

Through ‘main()’ call the ‘fibonacci()’ with the index value to next generate
recursive value.




                                           Amity Institute Of Information Technology   9
Dissection of ‘fibonacci’ Program:

 int fibonacci (int _iNam)

         Here in the above statement the function name ‘fibonacci’
has the parameter type defined as ‘integer’ having the return type as
‘integrer’. The right braces comes as the starting point of the snippet
code.

 if (_iNam <= 1)
    return _iNam;

          Here in the above two statements the condition followed by
    ‘if’, is establised as the terminating point if condition gets it
    satisfied. On the satisfactory mode of ‘if’ statement the value
    stored in _iNam return back to the calling.

                                         Amity Institute Of Information Technology   10
 else
    return (fibonacci(_iNam -1) + fibonacci(_iNam - 2));

    In the else part of the consecutive ‘if’ statement the return value
    is a bit complex. At first the recursion takes place for the first part
    from left and returns 1 decremented value i.e. ‘-1’ to the previous
    value, simultaneously it maintains a stack of all the new variables
    and concern values for each invocation. That will be come in use
    for the next recursive call. The next recursive call initializes the
    variable with the decremented value as ‘-2’. At the end when
    function call completes then the respective sum of the value
    returns back to the calling statement in ‘main()’.

    The left braces shows the termination of the code snippet.




                                           Amity Institute Of Information Technology   11
As in the following we have the table showing 10 number of
function calls in simultaneous recursion.
 Value of _iNam   Return Value of    Number of Function calls in recursive
                  fibonacci(_iNam)   computation.
 0                0                  1
 1                1                  1
 2                1                  3
 3                2                  5
 4                3                  9
 5                5                  15
 6                8                  25
 7                13                 41
 8                21                 67




                                          Amity Institute Of Information Technology   12
As in the above table describes, the value passed through the
parameter, the value that the function returns and the number of
recursive steps a function can perform up to 9 sequential calls.

Cons:
   Recursive programs typically use a large amount of computer
   memory and the greater the recursion, the more memory used.
   Recursive programs can be confusing to develop and
   extremely complicated to debug.

Pros:
    Recursion is a natural fit for some types of problems as
    ‘Tower of Hanoi’.




                                        Amity Institute Of Information Technology   13
Practice ‘Towers of Hanoi’

Problem:
The Classical Towers of Hanoi - an initial position of all disks is on
post 'A‘.




                                         Amity Institute Of Information Technology   14
The target solution of the puzzle is to build the tower on post 'C'.




The number of discs can vary, but there are only three towers.
The goal is to transfer the discs from one tower another tower.
However you can move only one disk at a time and you can never
place a bigger disc over a smaller disk.



                                           Amity Institute Of Information Technology   15
Algorithm to solve the above problem:

Move the top 3 disks from Source to Auxiliary tower,
Move the 4th disk from Source to Destination tower,
Move the 3 disks from Auxiliary tower to Destination tower.
Transfer the top 3 disks from Source to Auxiliary tower can again
be thought as a fresh problem and can be solve in the same manner.




                                       Amity Institute Of Information Technology   16
Let us do it step by step:

 At first move the ‘Disc1’ to ‘B’ and ‘Disc2’ to ‘C’ as in
following figure:




                                      Amity Institute Of Information Technology   17
Move the ‘Disc1’ to the top of the ‘Disc2’ at ‘C’ and ‘Disc3’ at
‘B’.




 Move the ‘Disc1’ to ‘A’ at the top of ‘Disc4’ and ‘Disc2’ at ‘B’ to the top
of ‘Disc3’.




                                            Amity Institute Of Information Technology   18
 Move the ‘Disc1’ at ‘B’ to the top of ‘Disc2’ and ‘Disc4’ at ‘A’.




 Move the ‘Disc1’ at ‘C’ to the top of ‘Disc4’ and ‘Disc2’ at ‘A’.




                                        Amity Institute Of Information Technology   19
 Move the ‘Disc1’ at ‘A’ to the top of ‘Disc2’ and ‘Disc3’ to the top of
‘disc4’ at ‘A’.




  Move the ‘Disc1’ at ‘B’ and ‘Disc2’ at ‘B’ to the top of ‘Disc3’.




                                          Amity Institute Of Information Technology   20
 Move the ‘Disc1’ at the top of ‘Disc2’ at ‘C’.




  Congratulations you got your answer. Code implementation is up to
  you people as hint use the concept of stack and just follow the steps
  Above described.




                                          Amity Institute Of Information Technology   21
/
***********************************************************//
/Here in the following Program, towers are considered as character A, B
//and C and disks are considered as integral numbers.
/***********************************************************/

#include   <stdio.h>
#include   <stdlib.h>
#include   <stdbool.h>
#include   <string.h>
#include   <math.h>




                                        Amity Institute Of Information
                                                          Technology      22
void generate_moves_toh(int i_disk_num, char from_peg,
char to_peg, char aux_peg)
{
/* If only 1 disk, make the move and return */
       if(i_disk_num == 1)
       {
              printf("nMove disk 1 from peg %c to peg
%c", from_peg, to_peg);
              return;
       }




                               Amity Institute Of Information
                                                 Technology     23
/*Move top n-1 disks from A to B, using C as auxiliary
*/
       generate_moves_toh(i_disk_num-1, from_peg,
aux_peg, to_peg);

       printf("nMove disk %d from peg %c to peg %c",
i_disk_num, from_peg, to_peg);

/* Move n-1 disks from B to C using A as auxiliary */
       generate_moves_toh(i_disk_num-1, aux_peg, to_peg,
from_peg);
}




                               Amity Institute Of Information
                                                 Technology     24
void gen_tow_of_honoi()
{
       printf("WAP to display the steps required in
solving 'Tower of Hanoi' for 'n' number of disks.");
       printf("nLimitation: nt-> Disks are
represented as integral numbers in assending order.");
        printf("nnn");
       int i_num_disk;
       printf("Enter the number of disks : ");
       scanf("%d",&i_num_disk);
       printf("The Tower of Hanoi involves the moves
:nn");
        generate_moves_toh(i_num_disk, 'A', 'C', 'B');
}




                               Amity Institute Of Information
                                                 Technology     25
int main()
{
       gen_tow_of_honoi();
       printf("nnn");
       getch();
       return 0;
}




                             Amity Institute Of Information
                                               Technology     26
•The C Programming Language (by Dennis M. Ritchie and Brain W.
Kernighan).
•A book on C (by Al Kelley and Ira Pohl).

•Let us C (by Yashavant Kanetkar).




                                    Amity Institute Of Information
                                                      Technology     27
Ad

More Related Content

What's hot (20)

Functions in c language
Functions in c language Functions in c language
Functions in c language
tanmaymodi4
 
Function Pointer
Function PointerFunction Pointer
Function Pointer
Dr-Dipali Meher
 
String Library Functions
String Library FunctionsString Library Functions
String Library Functions
Nayan Sharma
 
Function in C
Function in CFunction in C
Function in C
Dr. Abhineet Anand
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
Harsh Pathak
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
RubaNagarajan
 
Function C programming
Function C programmingFunction C programming
Function C programming
Appili Vamsi Krishna
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
Pointer to function 1
Pointer to function 1Pointer to function 1
Pointer to function 1
Abu Bakr Ramadan
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
Abu Zaman
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
Neeru Mittal
 
Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
Abdul Rehman
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in C
Jeya Lakshmi
 
File Management in C
File Management in CFile Management in C
File Management in C
Paurav Shah
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Data types
Data typesData types
Data types
Nokesh Prabhakar
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
tanmaymodi4
 
String Library Functions
String Library FunctionsString Library Functions
String Library Functions
Nayan Sharma
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
Harsh Pathak
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
 
Presentation on function
Presentation on functionPresentation on function
Presentation on function
Abu Zaman
 
Variables in C++, data types in c++
Variables in C++, data types in c++Variables in C++, data types in c++
Variables in C++, data types in c++
Neeru Mittal
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in C
Jeya Lakshmi
 
File Management in C
File Management in CFile Management in C
File Management in C
Paurav Shah
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 

Similar to Recursion in c (20)

Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
cogaxor346
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
Mehul Desai
 
computer notes - Reference variables
computer notes -  Reference variablescomputer notes -  Reference variables
computer notes - Reference variables
ecomputernotes
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
TeshaleSiyum
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
TeshaleSiyum
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
Muhammad Hammad Waseem
 
structured Programming Unit-7-Functions.pptx
structured Programming Unit-7-Functions.pptxstructured Programming Unit-7-Functions.pptx
structured Programming Unit-7-Functions.pptx
SuryaBasnet1
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
hara69
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxJLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
vrickens
 
e computer notes - Reference variables
e computer notes - Reference variablese computer notes - Reference variables
e computer notes - Reference variables
ecomputernotes
 
Full_Fixed_Enhanced_Recursion_Presentation.pptx
Full_Fixed_Enhanced_Recursion_Presentation.pptxFull_Fixed_Enhanced_Recursion_Presentation.pptx
Full_Fixed_Enhanced_Recursion_Presentation.pptx
AliAbbas574107
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
Vikram Nandini
 
Notes on c++
Notes on c++Notes on c++
Notes on c++
Selvam Edwin
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )
Ziyauddin Shaik
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Sampath Kumar
 
Understanding Python Programming Language -Functions
Understanding Python Programming Language -FunctionsUnderstanding Python Programming Language -Functions
Understanding Python Programming Language -Functions
elharriettm
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
jamvantsolanki
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
Sowri Rajan
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
umar78600
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
Syed Farjad Zia Zaidi
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
cogaxor346
 
computer notes - Reference variables
computer notes -  Reference variablescomputer notes -  Reference variables
computer notes - Reference variables
ecomputernotes
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
TeshaleSiyum
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
TeshaleSiyum
 
structured Programming Unit-7-Functions.pptx
structured Programming Unit-7-Functions.pptxstructured Programming Unit-7-Functions.pptx
structured Programming Unit-7-Functions.pptx
SuryaBasnet1
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
hara69
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxJLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
vrickens
 
e computer notes - Reference variables
e computer notes - Reference variablese computer notes - Reference variables
e computer notes - Reference variables
ecomputernotes
 
Full_Fixed_Enhanced_Recursion_Presentation.pptx
Full_Fixed_Enhanced_Recursion_Presentation.pptxFull_Fixed_Enhanced_Recursion_Presentation.pptx
Full_Fixed_Enhanced_Recursion_Presentation.pptx
AliAbbas574107
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )
Ziyauddin Shaik
 
Understanding Python Programming Language -Functions
Understanding Python Programming Language -FunctionsUnderstanding Python Programming Language -Functions
Understanding Python Programming Language -Functions
elharriettm
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
jamvantsolanki
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
umar78600
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
Syed Farjad Zia Zaidi
 
Ad

More from Saket Pathak (14)

Wan Important Questions
Wan Important QuestionsWan Important Questions
Wan Important Questions
Saket Pathak
 
Wan notes
Wan notesWan notes
Wan notes
Saket Pathak
 
C++ lab assignment
C++ lab assignmentC++ lab assignment
C++ lab assignment
Saket Pathak
 
Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)
Saket Pathak
 
A Guy and gal in STL
A Guy and gal in STLA Guy and gal in STL
A Guy and gal in STL
Saket Pathak
 
Lab. Programs in C
Lab. Programs in CLab. Programs in C
Lab. Programs in C
Saket Pathak
 
GNU GCC - what just a compiler...?
GNU GCC - what just a compiler...?GNU GCC - what just a compiler...?
GNU GCC - what just a compiler...?
Saket Pathak
 
C++ friendship
C++ friendshipC++ friendship
C++ friendship
Saket Pathak
 
C++ Template
C++ TemplateC++ Template
C++ Template
Saket Pathak
 
Copy constructor
Copy constructorCopy constructor
Copy constructor
Saket Pathak
 
Malloc, calloc, realloc
Malloc, calloc, reallocMalloc, calloc, realloc
Malloc, calloc, realloc
Saket Pathak
 
Pointers in c
Pointers in cPointers in c
Pointers in c
Saket Pathak
 
C++ diamond problem
C++ diamond problemC++ diamond problem
C++ diamond problem
Saket Pathak
 
Multiple inheritance in c++
Multiple inheritance in c++Multiple inheritance in c++
Multiple inheritance in c++
Saket Pathak
 
Wan Important Questions
Wan Important QuestionsWan Important Questions
Wan Important Questions
Saket Pathak
 
C++ lab assignment
C++ lab assignmentC++ lab assignment
C++ lab assignment
Saket Pathak
 
Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)
Saket Pathak
 
A Guy and gal in STL
A Guy and gal in STLA Guy and gal in STL
A Guy and gal in STL
Saket Pathak
 
Lab. Programs in C
Lab. Programs in CLab. Programs in C
Lab. Programs in C
Saket Pathak
 
GNU GCC - what just a compiler...?
GNU GCC - what just a compiler...?GNU GCC - what just a compiler...?
GNU GCC - what just a compiler...?
Saket Pathak
 
Malloc, calloc, realloc
Malloc, calloc, reallocMalloc, calloc, realloc
Malloc, calloc, realloc
Saket Pathak
 
C++ diamond problem
C++ diamond problemC++ diamond problem
C++ diamond problem
Saket Pathak
 
Multiple inheritance in c++
Multiple inheritance in c++Multiple inheritance in c++
Multiple inheritance in c++
Saket Pathak
 
Ad

Recently uploaded (20)

How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 

Recursion in c

  • 1. Fundamentals Of Programming in C Presented By: saket kr Pathak M.sc. nt & M aMIty InstItute Of InfOrMatIOn technOlOgy 1
  • 2. Recursion Recursion is said as a mathematical concept which states that an expression such that each term is generated by repeating a particular mathematical operation. Here repeating is the iterative manner to perform same operation. As the approach of the programming language C, it can be performed and are in practice within the definition part of functions. Syntactically language provides the freedom to call function within it’s body defined. Definition of ‘Recursion’ as the logical prospective view states simply the iterative manner to perform any code snippet in C, but we always need a terminating condition to control the going on iterations. In the following sections we will discuss the iterative manner of recursion and the terminating condition in bit expanded form. Fundamentals Of Programming in C 2
  • 3. Recursive Functions Recursive functions are not different from the syntactical structure of the general functions that we had discussed in previous sections. They have same return type, function name, parameters enclosed within parenthesis. Declaration: int Think_and_ Play (int, char); We had discussed the syntactical view of the function, where return type is ‘int’, function name is ‘Think_and_Play’ and within the parenthesis we had defined the parameters as of data type integer with another one that is of data type character. Amity Institute Of Information Technology 3
  • 4. Now let us manipulate the definition of the our function, that we had declared in the previous slide from the general aspect of definition we had practiced till now. Definition: int _iFlag =0, _iTerminate = 0; int Think_and_Play(int _iBat, char _chBall) { if (_iFlag ==0) printf(“This is game cricket going on.”); _iFlag++; if(_iTerminate < 6) { printf(“Hit the Ball with the Bat.”); ++ _iTerminate; Think_and_Play(1, ‘0’); return 1; } } Amity Institute Of Information Technology 4
  • 5. As in sequence of explanation, this snippet code has few syntactical statements. In the very first the program counter encounters with the Variables of type integer that are global to the function. Then it encounters the return type of the function following with the function name, and the parameters defined. All of these has the considerable part in function definition structure of C language that we had discussed in the previous sections of declaration. As encounter with the right curly braces comes into just next statement, it considers the following structure is for definition. In the definition part, the first if condition is doing its formal responsibility to control the execution of print function where the defined condition will be true i.e. when the value of the variable ‘_iFlag’ is strictly equal to 0. Amity Institute Of Information Technology 5
  • 6. The next statement is simply incrementing the value stored in the memory location termed as ‘_iFlag’ (the variable name). Then our point of consideration comes into picture in the execution of second ‘if’ structure. Here in this ‘if’ structure program counter will execute the statements defined within ‘if’ body, if and only if the condition gets true. It means whenever the condition defined with the if statements returns ‘Boolean True’ value then the further body will execute. So we can consider the controlling system of the execution of ‘if-body’ is properly controlled through the condition defined there in if statement. Now within the body concerned, we have a print function that supports its definition with two arguments defined as ‘String type’ and another is ‘Variable Length Argument’ (i.e. null in the snippet). Function performs the role successfully and control passes further. Amity Institute Of Information Technology 6
  • 7. The followed statement says to increment the value stored in the memory location corresponds to the variable name ‘_iTerminate’. Here logically this increasing value of ‘_iTerminate’ and the if condition defined above will cause the terminating condition. At the near end of the body, we have a function call as ‘Think_and_Play(…, …)’. Since here we are calling the same function that is executing, is said as recursion. Therefore, calling of the function from its own body forms a loop like execution pattern and is said as recursion. It is also considered as the alternative programming pattern of looping structure (i.e. of ‘for loop’ and ‘while loop’). The end statement says to return the value to the calling function as ‘return 1’, that declares the successful completion of all other statements defined above. Amity Institute Of Information Technology 7
  • 8. Discussion Typically, recursion is quite elegant and requires fewer variables to make the same calculation as iterative looping structural programs. It take care of its assigned records by maintaining the stack of arguments and variables for each invocation. It has been calculated in some machines a simple recursive program call with snippet defining one integer argument can be requires 8 32-bit words on the stack. Let us consider a snippet code of fibonacci sequence and calculate it’s efficiency in the following section. Amity Institute Of Information Technology 8
  • 9. Snippet-Code: int fibonacci (int _iNam) { if (_iNam <= 1) return _iNam; else return (fibonacci(_iNam-1)+fibonacci(_iNam-2)) } Through ‘main()’ call the ‘fibonacci()’ with the index value to next generate recursive value. Amity Institute Of Information Technology 9
  • 10. Dissection of ‘fibonacci’ Program:  int fibonacci (int _iNam) Here in the above statement the function name ‘fibonacci’ has the parameter type defined as ‘integer’ having the return type as ‘integrer’. The right braces comes as the starting point of the snippet code.  if (_iNam <= 1) return _iNam; Here in the above two statements the condition followed by ‘if’, is establised as the terminating point if condition gets it satisfied. On the satisfactory mode of ‘if’ statement the value stored in _iNam return back to the calling. Amity Institute Of Information Technology 10
  • 11.  else return (fibonacci(_iNam -1) + fibonacci(_iNam - 2)); In the else part of the consecutive ‘if’ statement the return value is a bit complex. At first the recursion takes place for the first part from left and returns 1 decremented value i.e. ‘-1’ to the previous value, simultaneously it maintains a stack of all the new variables and concern values for each invocation. That will be come in use for the next recursive call. The next recursive call initializes the variable with the decremented value as ‘-2’. At the end when function call completes then the respective sum of the value returns back to the calling statement in ‘main()’. The left braces shows the termination of the code snippet. Amity Institute Of Information Technology 11
  • 12. As in the following we have the table showing 10 number of function calls in simultaneous recursion. Value of _iNam Return Value of Number of Function calls in recursive fibonacci(_iNam) computation. 0 0 1 1 1 1 2 1 3 3 2 5 4 3 9 5 5 15 6 8 25 7 13 41 8 21 67 Amity Institute Of Information Technology 12
  • 13. As in the above table describes, the value passed through the parameter, the value that the function returns and the number of recursive steps a function can perform up to 9 sequential calls. Cons: Recursive programs typically use a large amount of computer memory and the greater the recursion, the more memory used. Recursive programs can be confusing to develop and extremely complicated to debug. Pros: Recursion is a natural fit for some types of problems as ‘Tower of Hanoi’. Amity Institute Of Information Technology 13
  • 14. Practice ‘Towers of Hanoi’ Problem: The Classical Towers of Hanoi - an initial position of all disks is on post 'A‘. Amity Institute Of Information Technology 14
  • 15. The target solution of the puzzle is to build the tower on post 'C'. The number of discs can vary, but there are only three towers. The goal is to transfer the discs from one tower another tower. However you can move only one disk at a time and you can never place a bigger disc over a smaller disk. Amity Institute Of Information Technology 15
  • 16. Algorithm to solve the above problem: Move the top 3 disks from Source to Auxiliary tower, Move the 4th disk from Source to Destination tower, Move the 3 disks from Auxiliary tower to Destination tower. Transfer the top 3 disks from Source to Auxiliary tower can again be thought as a fresh problem and can be solve in the same manner. Amity Institute Of Information Technology 16
  • 17. Let us do it step by step:  At first move the ‘Disc1’ to ‘B’ and ‘Disc2’ to ‘C’ as in following figure: Amity Institute Of Information Technology 17
  • 18. Move the ‘Disc1’ to the top of the ‘Disc2’ at ‘C’ and ‘Disc3’ at ‘B’.  Move the ‘Disc1’ to ‘A’ at the top of ‘Disc4’ and ‘Disc2’ at ‘B’ to the top of ‘Disc3’. Amity Institute Of Information Technology 18
  • 19.  Move the ‘Disc1’ at ‘B’ to the top of ‘Disc2’ and ‘Disc4’ at ‘A’.  Move the ‘Disc1’ at ‘C’ to the top of ‘Disc4’ and ‘Disc2’ at ‘A’. Amity Institute Of Information Technology 19
  • 20.  Move the ‘Disc1’ at ‘A’ to the top of ‘Disc2’ and ‘Disc3’ to the top of ‘disc4’ at ‘A’.  Move the ‘Disc1’ at ‘B’ and ‘Disc2’ at ‘B’ to the top of ‘Disc3’. Amity Institute Of Information Technology 20
  • 21.  Move the ‘Disc1’ at the top of ‘Disc2’ at ‘C’. Congratulations you got your answer. Code implementation is up to you people as hint use the concept of stack and just follow the steps Above described. Amity Institute Of Information Technology 21
  • 22. / ***********************************************************// /Here in the following Program, towers are considered as character A, B //and C and disks are considered as integral numbers. /***********************************************************/ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> Amity Institute Of Information Technology 22
  • 23. void generate_moves_toh(int i_disk_num, char from_peg, char to_peg, char aux_peg) { /* If only 1 disk, make the move and return */ if(i_disk_num == 1) { printf("nMove disk 1 from peg %c to peg %c", from_peg, to_peg); return; } Amity Institute Of Information Technology 23
  • 24. /*Move top n-1 disks from A to B, using C as auxiliary */ generate_moves_toh(i_disk_num-1, from_peg, aux_peg, to_peg); printf("nMove disk %d from peg %c to peg %c", i_disk_num, from_peg, to_peg); /* Move n-1 disks from B to C using A as auxiliary */ generate_moves_toh(i_disk_num-1, aux_peg, to_peg, from_peg); } Amity Institute Of Information Technology 24
  • 25. void gen_tow_of_honoi() { printf("WAP to display the steps required in solving 'Tower of Hanoi' for 'n' number of disks."); printf("nLimitation: nt-> Disks are represented as integral numbers in assending order."); printf("nnn"); int i_num_disk; printf("Enter the number of disks : "); scanf("%d",&i_num_disk); printf("The Tower of Hanoi involves the moves :nn"); generate_moves_toh(i_num_disk, 'A', 'C', 'B'); } Amity Institute Of Information Technology 25
  • 26. int main() { gen_tow_of_honoi(); printf("nnn"); getch(); return 0; } Amity Institute Of Information Technology 26
  • 27. •The C Programming Language (by Dennis M. Ritchie and Brain W. Kernighan). •A book on C (by Al Kelley and Ira Pohl). •Let us C (by Yashavant Kanetkar). Amity Institute Of Information Technology 27