SlideShare a Scribd company logo
11Mar2022: Recursion, Pointers, Dynamic memory management
PROGRAMMING FOR
PROBLEM SOLVING (PPS)
B.Tech I Sem CST
Schedule
Date Topic
11 Mar 2022 Recursion, Pointers:
Intro,Dynam mem.mgmt
17 Mar 2022 Pointer arrays,functions
24 Mar 2022 Multidime.arrays;
Structures: Intro
25 Mar 2022 Structures: arrays,
functions; Selfref.strc
Date Topics
31 Mar 2022 Typedef,union
1 Apr 2022 Tutorial (Lab
pgms)
7 Apr 2022 Files:open,clos
e,read,write
8 Apr 2022 File error
handlng
Quiz & Internal Lab exam dates
Date Details
30 Mar 2022
(6.30 to 8.00pm)
Quiz 3 & Quiz 4
6 Apr 2022 Internal Lab exam
Today’s Topics
 Recursion
 Pointers
 Pointers, address, pointer to pointer
 Initialization of pointer arrays
 Dynamic memory management
Recursion: process of repeating the similar steps.
Recursive function: a function that calls itself.
Recursive functions types : Direct and Indirect recursive
functions
Direct recursive
A function is said to be
direct recursive if it calls
itself directly.
Ex:
int fun1 (int n)
{
if (cond) return 1;
else return (fun1(n-1));
}
Indirect Recursive
A function is said to be indirect recursive if
it calls another function and this new function
calls the first calling function again.
Ex:
int func1(int n)
{
if (cond1) return 1;
else return func2(n);
}
int func2(int n)
{
return func1(n);
}
f1
f1 f2 fn
…
Sum of ‘n’ natural
numbers
int sum(int n) {
if (n!=0) return n+sum(n-1); else return n; }
Factorial of given
number
int factorial(int n) {
if(n==1) return 1; else return n*factorial(n-1); }
Fibonacci series int fib(int n) {
if(n==0) return 0; else if(n==1) return 1;
else return(fib(n-1)+fib(n-2)); }
GCD of two no’s int gcd(int m,int n) {
if(n==0) return m; else return (gcd(n,m%n)); }
Towers of Hanoi void TOH(n,s,d,i) {
If(n==1) { Print s, d; return; }
TOH(n-1,s,i,d);
Print n,s,d
TOH(n-1,i,d,s); }
A Classical Case: Towers of Hanoi
• The towers of Hanoi problem involves moving a
number of disks (in different sizes) from one
tower (or called “peg”) to another.
– The constraint is that the larger disk can never be
placed on top of a smaller disk.
– Only one disk can be moved at each time
– Assume there are three towers available.
Towers of Hanoi
Towers of Hanoi
void TOH(int n, char s, char d, char i)
{
if (n == 1)
{
printf("n Move disk 1 from tower %c to %c", s, d);
return;
}
TOH(n-1, s, i, d);
printf("n Move disk %d from tower %c to %c", n, s, d);
TOH(n-1, i, d, s);
}
10-16
A Classical Case: Towers of Hanoi
The execution result of calling TOH(n, 'A','C','B');
C Recursion, Pointers, Dynamic memory management
Unit 4
 Pointers and Arrays:
 Pointers and address, dynamic memory management,
Pointers and Function Arguments, Pointers and Arrays,
Address Arithmetic, character Pointers and Functions,
Pointer Arrays,
 Pointer to Pointer, Multi-dimensional array and Row/column
major formats, Initialization of Pointer Arrays, Command
line arguments, Pointer to functions, complicated declarations
and how they are evaluated
Pointers and address
int* pc, c;
c = 10;
pc = &c;
int* pc, c;
c = 20;
pc = &c;
c = 10;
printf("%d", c);
printf("%d", *pc);
int* pc, c, d;
c = 20;
d = 30;
pc = &c; printf("%d", *pc);
pc = &d; printf("%d", *pc)
What is a pointer
 A pointer is a variable that stores the memory address of
another variable.
C Recursion, Pointers, Dynamic memory management
int x=1, y=2;
int *ip;
ip = &x;
y = *ip;
x = ip;
*ip = 3
Pointers and address
int a = 10, b = 2;
int *p1, *p2;
p1 = &a;
p2 = &b;
printf("%pn %p n", p1, p2);
printf("%dn %d n", *p1, *p2);
OUTPUT
0xbfffdac4
0xbfffdac0
10
2
Add two numbers using pointers
int *ptr1, *ptr2;
int num;
printf("nEnter two numbers : ");
scanf("%d %d", ptr1, ptr2);
num = *ptr1 + *ptr2;
printf("Sum = %d", num);
Pointers and Function Arguments
Ex: 1
int* larger(int*, int*);
.......
int *p;
p = larger(&a, &b);
printf("%d is larger",*p);
.......
int* larger(int *x, int *y)
{
if(*x > *y) return x;
else return y; }
Ex: 2
void salaryhike(int *var, int b)
{
*var = *var+b;
}
......
salaryhike(&salary, bonus)
Pointer to Pointer
int i = 5, j = 6; k = 7;
int *ip1 = &i, *ip2 = &j;
int **ipp;
ipp = &ip1;
Pointer to Pointer: Example
int var;
int *ptr;
int **pptr;
var = 3000;
ptr = &var;
pptr = &ptr;
printf("Value of var = %dn", var );
printf("Value available at *ptr = %dn", *ptr );
printf("Value available at **pptr = %dn", **pptr);
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
int x[4];
int i;
for(i = 0; i < 4; ++i)
printf("&x[%d] = %pn", i, &x[i]);
printf("Address of array x: %p", x);
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");
for(i = 0; i < 6; ++i)
{
scanf("%d", x+i);
sum += *(x+i);
}
printf("Sum = %d", sum);
Pointers and Arrays
int x[5] = {1, 2, 3, 4, 5};
int* ptr;
ptr = &x[2];
printf("*ptr = %d n", *ptr);
printf("*(ptr+1) = %d n", *(ptr+1));
printf("*(ptr-1) = %d", *(ptr-1));
Pointers and Arrays
Operations on Pointers/Pointer Arithmetic
 Increment Pointers
 Decrement Pointers
 Compare Pointers
 Difference between Pointers
Increment Pointers
const int MAX = 3;
int main ()
{
int var [ ] = {10, 100, 200};
int i, *ptr;
ptr = var;
for ( i = 0; i < MAX; i++)
{
printf("Address of var[%d] = %xn", i, ptr );
printf("Value of var[%d] = %dn", i, *ptr );
ptr++;
}
return 0;
}
Address of var[0] = bfcf60ac
Value of var[0] = 10
Address of var[1] = bfcf60b0
Value of var[1] = 100
Address of var[2] = bfcf60b4
Value of var[2] = 200
Increment Pointers
int main()
{
int *ptr=(int *)1000;
ptr=ptr+3;
printf("New Value of ptr: %u",ptr);
}
New Value of ptr : 1012
It will store 1000 in the pointer variable
considering 1000 is memory location for any
of the integer variable.
Decrement Pointers: Example
const int MAX = 3;
int main ( )
{
int var[ ] = {10, 100, 200};
int i, *ptr;
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--)
{
printf("Address of var[%d] = %xn", i, ptr );
printf("Value of var[%d] = %dn", i, *ptr );
ptr--;
}
}
Address of var[3] = bff4fb44
Value of var[3] = 200
Address of var[2] = bff4fb40
Value of var[2] = 100
Address of var[1] = bff4fb3c
Value of var[1] = 10
Pointer Comparison
int *ptr1,*ptr2;
ptr1 = (int *)1000;
ptr2 = (int *)2000;
if(ptr2 > ptr1)
printf("Ptr2 is far from ptr1");
Ptr2 is far from ptr1
Difference between
pointers
int num , *ptr1 ,*ptr2 ;
ptr1 = &num ;
ptr2 = ptr1 + 2 ;
printf("%ld",ptr2 - ptr1);
2
Passing Pointers to a function
int main( )
{
int v1 = 11, v2 = 77 ;
printf("Before swapping:");
printf("nValue of v1 is: %d", v1);
printf("nValue of v2 is: %d", v2);
swapnum ( &v1, &v2 );
printf("nAfter swapping:");
printf("nValue of v1 is: %d", v1);
printf("nValue of v2 is: %d", v2);
}
swapnum ( int *num1, int *num2
)
{
int tempnum ;
tempnum = *num1 ;
*num1 = *num2 ;
*num2 = tempnum ;
}
Dynamic memory Allocation
malloc()
Allocates the memory of requested size and returns the
pointer to the first byte of allocated space.
calloc()
Allocates the space for elements of an array. Initializes
the elements to zero and returns a pointer to the memory.
realloc()
It is used to modify the size of previously allocated
memory space.
free() Frees or empties the previously allocated memory space.
malloc()
Syntax:
ptr = (castType*) malloc(size);
Example
ptr = (int*) malloc(10 * sizeof(int));
Example Program
int n,i,*ptr,sum=0;
// Accept n
ptr=(int*)malloc(n*sizeof(int));
// code to check if memory not allotted
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
calloc()
Syntax:
ptr = (castType*)calloc(n, size);
Example
ptr = (int*) calloc(8, sizeof(int));
Example Program
int n,i,*ptr,sum=0;
// Accept n
ptr=(int*)calloc(n,sizeof(int));
// code to check if memory not allotted
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
realloc()
Syntax:
ptr = realloc(ptr, x);
Example
ptr = (char *) malloc(10);
ptr = (char *) realloc(ptr,20);
Example Program
int *ptr,n,i;
n = 2;
ptr = malloc(n * sizeof(int));
*(ptr + 0) = 1; *(ptr + 1) = 2;
for(i = 0; i < n; i++)
printf("%dn",ptr[i]);
n = 5;
ptr = realloc(ptr, n * sizeof(int));
*(ptr + 2) = 3; *(ptr + 3) = 4;
*(ptr + 4) = 5;
for(i = 0; i < size; i++)
printf("%dn",ptr[i]);
Ad

More Related Content

What's hot (20)

Function
FunctionFunction
Function
jayesh30sikchi
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programming
Priyansh Thakar
 
C functions
C functionsC functions
C functions
University of Potsdam
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
 
String.ppt
String.pptString.ppt
String.ppt
ajeela mushtaq
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Sunil OS
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
DevoAjit Gupta
 
Function in c
Function in cFunction in c
Function in c
Raj Tandukar
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
PRN USM
 
Chapter 8 c solution
Chapter 8 c solutionChapter 8 c solution
Chapter 8 c solution
Azhar Javed
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
Shuvongkor Barman
 
02 data types in java
02 data types in java02 data types in java
02 data types in java
রাকিন রাকিন
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
Sujan Mia
 
Function in c
Function in cFunction in c
Function in c
savitamhaske
 
Access specifier
Access specifierAccess specifier
Access specifier
zindadili
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
Java operators
Java operatorsJava operators
Java operators
Shehrevar Davierwala
 
C Programming
C ProgrammingC Programming
C Programming
Sumant Diwakar
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Burhan Ahmed
 

Similar to C Recursion, Pointers, Dynamic memory management (20)

L25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxL25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptx
happycocoman
 
dynamic_v1-memory-management-in-c-cpp.ppt
dynamic_v1-memory-management-in-c-cpp.pptdynamic_v1-memory-management-in-c-cpp.ppt
dynamic_v1-memory-management-in-c-cpp.ppt
SuwoebBeisvs
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
madan reddy
 
Algoritmos e Estruturas de Dados - Pointers
Algoritmos e Estruturas de Dados - PointersAlgoritmos e Estruturas de Dados - Pointers
Algoritmos e Estruturas de Dados - Pointers
martijnkuipersandebo
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
kinan keshkeh
 
l7-pointers.ppt
l7-pointers.pptl7-pointers.ppt
l7-pointers.ppt
ShivamChaturvedi67
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
Md. Imran Hossain Showrov
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
NewsMogul
 
Algoritmos e Estruturas de Dados - dynamic memory allocation
Algoritmos e Estruturas de Dados - dynamic memory allocationAlgoritmos e Estruturas de Dados - dynamic memory allocation
Algoritmos e Estruturas de Dados - dynamic memory allocation
martijnkuipersandebo
 
7 functions
7  functions7  functions
7 functions
MomenMostafa
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
Emertxe Information Technologies Pvt Ltd
 
Dynamic Memory Allocation.pptx for c language and basic knowledge.
Dynamic Memory Allocation.pptx for c language and basic knowledge.Dynamic Memory Allocation.pptx for c language and basic knowledge.
Dynamic Memory Allocation.pptx for c language and basic knowledge.
2024163103shubham
 
Pointer
PointerPointer
Pointer
Shankar Gangaju
 
Chapter5.pptx
Chapter5.pptxChapter5.pptx
Chapter5.pptx
dhanajimirajkar1
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
AmIt Prasad
 
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptxComputer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
ab11167
 
SIMPLE C PROGRAMS - SARASWATHI RAMALINGAM
SIMPLE C PROGRAMS - SARASWATHI RAMALINGAMSIMPLE C PROGRAMS - SARASWATHI RAMALINGAM
SIMPLE C PROGRAMS - SARASWATHI RAMALINGAM
SaraswathiRamalingam
 
06 Recursion in C.pptx
06 Recursion in C.pptx06 Recursion in C.pptx
06 Recursion in C.pptx
MouDhara1
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
Rabin BK
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
rajatryadav22
 
L25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxL25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptx
happycocoman
 
dynamic_v1-memory-management-in-c-cpp.ppt
dynamic_v1-memory-management-in-c-cpp.pptdynamic_v1-memory-management-in-c-cpp.ppt
dynamic_v1-memory-management-in-c-cpp.ppt
SuwoebBeisvs
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
madan reddy
 
Algoritmos e Estruturas de Dados - Pointers
Algoritmos e Estruturas de Dados - PointersAlgoritmos e Estruturas de Dados - Pointers
Algoritmos e Estruturas de Dados - Pointers
martijnkuipersandebo
 
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays 2 BytesC++ course_2014_c9_ pointers and dynamic arrays
2 BytesC++ course_2014_c9_ pointers and dynamic arrays
kinan keshkeh
 
Algoritmos e Estruturas de Dados - dynamic memory allocation
Algoritmos e Estruturas de Dados - dynamic memory allocationAlgoritmos e Estruturas de Dados - dynamic memory allocation
Algoritmos e Estruturas de Dados - dynamic memory allocation
martijnkuipersandebo
 
Dynamic Memory Allocation.pptx for c language and basic knowledge.
Dynamic Memory Allocation.pptx for c language and basic knowledge.Dynamic Memory Allocation.pptx for c language and basic knowledge.
Dynamic Memory Allocation.pptx for c language and basic knowledge.
2024163103shubham
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
AmIt Prasad
 
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptxComputer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
Computer Programming for Engineers Spring 2023Lab 8 - Pointers.pptx
ab11167
 
SIMPLE C PROGRAMS - SARASWATHI RAMALINGAM
SIMPLE C PROGRAMS - SARASWATHI RAMALINGAMSIMPLE C PROGRAMS - SARASWATHI RAMALINGAM
SIMPLE C PROGRAMS - SARASWATHI RAMALINGAM
SaraswathiRamalingam
 
06 Recursion in C.pptx
06 Recursion in C.pptx06 Recursion in C.pptx
06 Recursion in C.pptx
MouDhara1
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
Rabin BK
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
rajatryadav22
 
Ad

More from Sreedhar Chowdam (20)

DBMS Nested & Sub Queries Set operations
DBMS Nested & Sub Queries Set operationsDBMS Nested & Sub Queries Set operations
DBMS Nested & Sub Queries Set operations
Sreedhar Chowdam
 
DBMS Notes selection projection aggregate
DBMS Notes selection projection aggregateDBMS Notes selection projection aggregate
DBMS Notes selection projection aggregate
Sreedhar Chowdam
 
Database management systems Lecture Notes
Database management systems Lecture NotesDatabase management systems Lecture Notes
Database management systems Lecture Notes
Sreedhar Chowdam
 
Advanced Data Structures & Algorithm Analysi
Advanced Data Structures & Algorithm AnalysiAdvanced Data Structures & Algorithm Analysi
Advanced Data Structures & Algorithm Analysi
Sreedhar Chowdam
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture Notes
Sreedhar Chowdam
 
Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)
Sreedhar Chowdam
 
DCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPDCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCP
Sreedhar Chowdam
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer Networks
Sreedhar Chowdam
 
DCCN Unit 1.pdf
DCCN Unit 1.pdfDCCN Unit 1.pdf
DCCN Unit 1.pdf
Sreedhar Chowdam
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer Networks
Sreedhar Chowdam
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operations
Sreedhar Chowdam
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
Sreedhar Chowdam
 
Big Data Analytics Part2
Big Data Analytics Part2Big Data Analytics Part2
Big Data Analytics Part2
Sreedhar Chowdam
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, Exceptions
Sreedhar Chowdam
 
Python Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfPython Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdf
Sreedhar Chowdam
 
Python Programming Strings
Python Programming StringsPython Programming Strings
Python Programming Strings
Sreedhar Chowdam
 
Python Programming
Python Programming Python Programming
Python Programming
Sreedhar Chowdam
 
Python Programming
Python ProgrammingPython Programming
Python Programming
Sreedhar Chowdam
 
Big Data Analytics
Big Data AnalyticsBig Data Analytics
Big Data Analytics
Sreedhar Chowdam
 
DBMS Nested & Sub Queries Set operations
DBMS Nested & Sub Queries Set operationsDBMS Nested & Sub Queries Set operations
DBMS Nested & Sub Queries Set operations
Sreedhar Chowdam
 
DBMS Notes selection projection aggregate
DBMS Notes selection projection aggregateDBMS Notes selection projection aggregate
DBMS Notes selection projection aggregate
Sreedhar Chowdam
 
Database management systems Lecture Notes
Database management systems Lecture NotesDatabase management systems Lecture Notes
Database management systems Lecture Notes
Sreedhar Chowdam
 
Advanced Data Structures & Algorithm Analysi
Advanced Data Structures & Algorithm AnalysiAdvanced Data Structures & Algorithm Analysi
Advanced Data Structures & Algorithm Analysi
Sreedhar Chowdam
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture Notes
Sreedhar Chowdam
 
Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)
Sreedhar Chowdam
 
DCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPDCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCP
Sreedhar Chowdam
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer Networks
Sreedhar Chowdam
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer Networks
Sreedhar Chowdam
 
PPS Arrays Matrix operations
PPS Arrays Matrix operationsPPS Arrays Matrix operations
PPS Arrays Matrix operations
Sreedhar Chowdam
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
Sreedhar Chowdam
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, Exceptions
Sreedhar Chowdam
 
Python Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfPython Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdf
Sreedhar Chowdam
 
Python Programming Strings
Python Programming StringsPython Programming Strings
Python Programming Strings
Sreedhar Chowdam
 
Ad

Recently uploaded (20)

railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 

C Recursion, Pointers, Dynamic memory management

  • 1. 11Mar2022: Recursion, Pointers, Dynamic memory management PROGRAMMING FOR PROBLEM SOLVING (PPS) B.Tech I Sem CST
  • 2. Schedule Date Topic 11 Mar 2022 Recursion, Pointers: Intro,Dynam mem.mgmt 17 Mar 2022 Pointer arrays,functions 24 Mar 2022 Multidime.arrays; Structures: Intro 25 Mar 2022 Structures: arrays, functions; Selfref.strc Date Topics 31 Mar 2022 Typedef,union 1 Apr 2022 Tutorial (Lab pgms) 7 Apr 2022 Files:open,clos e,read,write 8 Apr 2022 File error handlng
  • 3. Quiz & Internal Lab exam dates Date Details 30 Mar 2022 (6.30 to 8.00pm) Quiz 3 & Quiz 4 6 Apr 2022 Internal Lab exam
  • 4. Today’s Topics  Recursion  Pointers  Pointers, address, pointer to pointer  Initialization of pointer arrays  Dynamic memory management
  • 5. Recursion: process of repeating the similar steps. Recursive function: a function that calls itself. Recursive functions types : Direct and Indirect recursive functions
  • 6. Direct recursive A function is said to be direct recursive if it calls itself directly. Ex: int fun1 (int n) { if (cond) return 1; else return (fun1(n-1)); } Indirect Recursive A function is said to be indirect recursive if it calls another function and this new function calls the first calling function again. Ex: int func1(int n) { if (cond1) return 1; else return func2(n); } int func2(int n) { return func1(n); } f1 f1 f2 fn …
  • 7. Sum of ‘n’ natural numbers int sum(int n) { if (n!=0) return n+sum(n-1); else return n; } Factorial of given number int factorial(int n) { if(n==1) return 1; else return n*factorial(n-1); } Fibonacci series int fib(int n) { if(n==0) return 0; else if(n==1) return 1; else return(fib(n-1)+fib(n-2)); } GCD of two no’s int gcd(int m,int n) { if(n==0) return m; else return (gcd(n,m%n)); } Towers of Hanoi void TOH(n,s,d,i) { If(n==1) { Print s, d; return; } TOH(n-1,s,i,d); Print n,s,d TOH(n-1,i,d,s); }
  • 8. A Classical Case: Towers of Hanoi • The towers of Hanoi problem involves moving a number of disks (in different sizes) from one tower (or called “peg”) to another. – The constraint is that the larger disk can never be placed on top of a smaller disk. – Only one disk can be moved at each time – Assume there are three towers available.
  • 10. Towers of Hanoi void TOH(int n, char s, char d, char i) { if (n == 1) { printf("n Move disk 1 from tower %c to %c", s, d); return; } TOH(n-1, s, i, d); printf("n Move disk %d from tower %c to %c", n, s, d); TOH(n-1, i, d, s); }
  • 11. 10-16 A Classical Case: Towers of Hanoi The execution result of calling TOH(n, 'A','C','B');
  • 13. Unit 4  Pointers and Arrays:  Pointers and address, dynamic memory management, Pointers and Function Arguments, Pointers and Arrays, Address Arithmetic, character Pointers and Functions, Pointer Arrays,  Pointer to Pointer, Multi-dimensional array and Row/column major formats, Initialization of Pointer Arrays, Command line arguments, Pointer to functions, complicated declarations and how they are evaluated
  • 14. Pointers and address int* pc, c; c = 10; pc = &c; int* pc, c; c = 20; pc = &c; c = 10; printf("%d", c); printf("%d", *pc); int* pc, c, d; c = 20; d = 30; pc = &c; printf("%d", *pc); pc = &d; printf("%d", *pc)
  • 15. What is a pointer  A pointer is a variable that stores the memory address of another variable.
  • 17. int x=1, y=2; int *ip; ip = &x; y = *ip; x = ip; *ip = 3
  • 18. Pointers and address int a = 10, b = 2; int *p1, *p2; p1 = &a; p2 = &b; printf("%pn %p n", p1, p2); printf("%dn %d n", *p1, *p2); OUTPUT 0xbfffdac4 0xbfffdac0 10 2
  • 19. Add two numbers using pointers int *ptr1, *ptr2; int num; printf("nEnter two numbers : "); scanf("%d %d", ptr1, ptr2); num = *ptr1 + *ptr2; printf("Sum = %d", num);
  • 20. Pointers and Function Arguments Ex: 1 int* larger(int*, int*); ....... int *p; p = larger(&a, &b); printf("%d is larger",*p); ....... int* larger(int *x, int *y) { if(*x > *y) return x; else return y; } Ex: 2 void salaryhike(int *var, int b) { *var = *var+b; } ...... salaryhike(&salary, bonus)
  • 21. Pointer to Pointer int i = 5, j = 6; k = 7; int *ip1 = &i, *ip2 = &j; int **ipp; ipp = &ip1;
  • 22. Pointer to Pointer: Example int var; int *ptr; int **pptr; var = 3000; ptr = &var; pptr = &ptr; printf("Value of var = %dn", var ); printf("Value available at *ptr = %dn", *ptr ); printf("Value available at **pptr = %dn", **pptr); Value of var = 3000 Value available at *ptr = 3000 Value available at **pptr = 3000
  • 23. int x[4]; int i; for(i = 0; i < 4; ++i) printf("&x[%d] = %pn", i, &x[i]); printf("Address of array x: %p", x); int i, x[6], sum = 0; printf("Enter 6 numbers: "); for(i = 0; i < 6; ++i) { scanf("%d", x+i); sum += *(x+i); } printf("Sum = %d", sum); Pointers and Arrays
  • 24. int x[5] = {1, 2, 3, 4, 5}; int* ptr; ptr = &x[2]; printf("*ptr = %d n", *ptr); printf("*(ptr+1) = %d n", *(ptr+1)); printf("*(ptr-1) = %d", *(ptr-1)); Pointers and Arrays
  • 25. Operations on Pointers/Pointer Arithmetic  Increment Pointers  Decrement Pointers  Compare Pointers  Difference between Pointers
  • 26. Increment Pointers const int MAX = 3; int main () { int var [ ] = {10, 100, 200}; int i, *ptr; ptr = var; for ( i = 0; i < MAX; i++) { printf("Address of var[%d] = %xn", i, ptr ); printf("Value of var[%d] = %dn", i, *ptr ); ptr++; } return 0; } Address of var[0] = bfcf60ac Value of var[0] = 10 Address of var[1] = bfcf60b0 Value of var[1] = 100 Address of var[2] = bfcf60b4 Value of var[2] = 200 Increment Pointers int main() { int *ptr=(int *)1000; ptr=ptr+3; printf("New Value of ptr: %u",ptr); } New Value of ptr : 1012 It will store 1000 in the pointer variable considering 1000 is memory location for any of the integer variable.
  • 27. Decrement Pointers: Example const int MAX = 3; int main ( ) { int var[ ] = {10, 100, 200}; int i, *ptr; ptr = &var[MAX-1]; for ( i = MAX; i > 0; i--) { printf("Address of var[%d] = %xn", i, ptr ); printf("Value of var[%d] = %dn", i, *ptr ); ptr--; } } Address of var[3] = bff4fb44 Value of var[3] = 200 Address of var[2] = bff4fb40 Value of var[2] = 100 Address of var[1] = bff4fb3c Value of var[1] = 10
  • 28. Pointer Comparison int *ptr1,*ptr2; ptr1 = (int *)1000; ptr2 = (int *)2000; if(ptr2 > ptr1) printf("Ptr2 is far from ptr1"); Ptr2 is far from ptr1 Difference between pointers int num , *ptr1 ,*ptr2 ; ptr1 = &num ; ptr2 = ptr1 + 2 ; printf("%ld",ptr2 - ptr1); 2
  • 29. Passing Pointers to a function int main( ) { int v1 = 11, v2 = 77 ; printf("Before swapping:"); printf("nValue of v1 is: %d", v1); printf("nValue of v2 is: %d", v2); swapnum ( &v1, &v2 ); printf("nAfter swapping:"); printf("nValue of v1 is: %d", v1); printf("nValue of v2 is: %d", v2); } swapnum ( int *num1, int *num2 ) { int tempnum ; tempnum = *num1 ; *num1 = *num2 ; *num2 = tempnum ; }
  • 30. Dynamic memory Allocation malloc() Allocates the memory of requested size and returns the pointer to the first byte of allocated space. calloc() Allocates the space for elements of an array. Initializes the elements to zero and returns a pointer to the memory. realloc() It is used to modify the size of previously allocated memory space. free() Frees or empties the previously allocated memory space.
  • 31. malloc() Syntax: ptr = (castType*) malloc(size); Example ptr = (int*) malloc(10 * sizeof(int)); Example Program int n,i,*ptr,sum=0; // Accept n ptr=(int*)malloc(n*sizeof(int)); // code to check if memory not allotted for(i=0;i<n;++i) { scanf("%d",ptr+i); sum+=*(ptr+i); } printf("Sum=%d",sum); free(ptr);
  • 32. calloc() Syntax: ptr = (castType*)calloc(n, size); Example ptr = (int*) calloc(8, sizeof(int)); Example Program int n,i,*ptr,sum=0; // Accept n ptr=(int*)calloc(n,sizeof(int)); // code to check if memory not allotted for(i=0;i<n;++i) { scanf("%d",ptr+i); sum+=*(ptr+i); } printf("Sum=%d",sum); free(ptr);
  • 33. realloc() Syntax: ptr = realloc(ptr, x); Example ptr = (char *) malloc(10); ptr = (char *) realloc(ptr,20); Example Program int *ptr,n,i; n = 2; ptr = malloc(n * sizeof(int)); *(ptr + 0) = 1; *(ptr + 1) = 2; for(i = 0; i < n; i++) printf("%dn",ptr[i]); n = 5; ptr = realloc(ptr, n * sizeof(int)); *(ptr + 2) = 3; *(ptr + 3) = 4; *(ptr + 4) = 5; for(i = 0; i < size; i++) printf("%dn",ptr[i]);