SlideShare a Scribd company logo
1 of 33
Download to read offline
Computing Fundamentals
Dr. Muhammad Yousaf Hamza
Deputy Chief Engineer, PIEAS
Recursion
Dr. Yousaf, PIEAS
Recursion
Example: factorials
– 5! = 5 * 4 * 3 * 2 * 1
– Notice that
• 5! = 5 * 4!
• 4! = 4 * 3! ...
– Can compute factorials recursively
– Solve base case (1! = 0! = 1) then plug in
• 2! = 2 * 1! = 2 * 1 = 2;
• 3! = 3 * 2! = 3 * 2 = 6;
Write a recursive function int fact(int num) that should return
the factorial of given number num
Dr. Yousaf, PIEAS
Dr. Yousaf, PIEAS
//Calculate Factorial using Recursion
# include<stdio.h>
int factorial(int num);
int main ()
{
int f,x;
printf("Enter integer value in the range 1
to 10: ");
scanf("%d", &x);
if (x > 10 || x < 1)
printf ("Illegal input!n");
else
{
f = factorial(x);
printf ("%d factorial equals %dn", x,f);
}
getchar(); return 0; }
int factorial (int a)
{
if (a==1) // base case
return 1;
else
{
a *= factorial(a-1);
return a;
}
}
Recursion
• Recursive functions
• A function that calls itself inside its body is called a
recursive function
• Can only solve a base case
– Divide a problem into
• What it can do
• What it cannot do
– What it cannot do resembles original problem
– The function launches a new copy of itself (recursion
step) to solve what it cannot do
– Eventually base case gets solved
• Gets plugged in, works its way up and solves whole problem
Dr. Yousaf, PIEAS
Example Using Recursion
/*This function prints all the number between zero and a given number that is
greater than zero. */
#include <stdio.h>
void printSeries(int num);
int main()
{
printSeries(6);
getchar(); return 0;
}
void printSeries(int num)
{
if(num<=0)
return;
printf("%d", num);
printSeries(num-1);
}
Dr. Yousaf, PIEAS
Example Using Recursion
/*This function prints all the number between zero and a given number that is
greater than zero. */
#include <stdio.h>
void printSeries(int num);
int main()
{
printSeries(6);
getchar(); return 0;
}
void printSeries(int num)
{
if(num<=0)
return;
printf("%d", num);
printSeries(num-1);
}
Dr. Yousaf, PIEAS
Example Using Recursion:
The Fibonacci Series
• Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, ...
– Each number is the sum of the previous two
– fib( n ) = fib( n - 1 ) + fib( n – 2 )
– Write a recursive function that can print first N terms of
Fibonacci series ,
– Can be solved recursively:
Code for the fibaonacci function
int fibonacci(int n )
{
if (n == 0 || n == 1) // base case
return n;
else
return fibonacci(n - 1)+ fibonacci(n – 2);
}
Dr. Yousaf, PIEAS
Example Using Recursion:
The Fibonacci Series
• Set of recursive calls to function fibonacci
f( 3 )
f( 1 )f( 2 )
f( 1 ) f( 0 ) return 1
return 1 return 0
return +
+return
Dr. Yousaf, PIEAS
Dr. Yousaf, PIEAS
// To generate Fibonacci series
using Recursion
#include<stdio.h>
int fibonacci(int n);
int main()
{
int i, terms, result;
printf("Please enter the number of
terms from 1 to 20: ");
scanf("%d",&terms);
for ( i = 0; i<= terms; i++)
{
result = fibonacci(i);
printf("%d, ", result);
}
getchar(); return 0; }
// Function Definition
int fibonacci(int n)
{
if ( n == 0 || n == 1 )
return n;
else
return fibonacci( n - 1 ) +
fibonacci( n - 2 );
}
Recursion vs. Iteration
• Repetition
– Iteration: explicit loop
– Recursion: repeated function calls
• Termination
– Iteration: loop condition fails
– Recursion: base case recognized
Dr. Yousaf, PIEAS
POINTERS
Dr. Yousaf, PIEAS
/* Demonstration on Pointers
A very simple program to print a value of a variable
without using pointer */
#include<stdio.h>
int main()
{
int x = 20;
printf("n x = %d", x);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
// A very simple program to print the address and value of
a variable using pointer
#include<stdio.h>
int main()
{
int x = 20;
int *ptrx; //Pointer is declared. Select any name instead of ptrx.
ptrx = &x; // Initialization of the pointer
printf("n address of x = %d", ptrx);
// It would print the address value
printf("n Value of x = %d",*ptrx);
/* It would print the value of the variable stored at the
address value of the pointer */
getchar(); return 0;
}
Dr. Yousaf, PIEAS
Dr. Yousaf, PIEAS
• Pointers are powerful and very useful tools
• With pointers we can effectively return more than one
value from a function
• Arrays are a form of pointer REALLY
• Pass by reference is also possible
Dr. Yousaf, PIEAS
The Importance of Pointers
The Importance of Pointers
• Pointers can be used for advanced data structures.
• Pointers can be "cheaper" to pass around a
program.
• You could program without using them but you
would be making life more difficult for yourself.
• Some things simply can't be done sensibly in C
without them.
Dr. Yousaf, PIEAS
What are pointers?
• Pointers are considered as one of the most
difficult topics to understand in C.
• Pointers "point at" areas of your computer's
memory (address of the memory)
• int *p; says p is a pointer to an int
• Imagine your computer's memory as a series of
boxes which all hold ints
56 71 12 3 21 7
p points at one of the ints
Dr. Yousaf, PIEAS
& means "address of" or "point at
me"
* means value or "what am I
pointing at?"
int *p; // p is a pointer to an int
int q= 5; // q is an int
p= &q; // p now points at q
printf (“The value stored at p location is
%dn",*p); // 5
/*We use *p to mean "the value in the memory where pointer p is pointing
at*/
q=5
p
Dr. Yousaf, PIEAS
& means "address of" or "point at
me"
* means value or "what am I
pointing at?"
int *p; // p is a pointer to an int
int q= 5; // q is an int
p= &q; // p now points at q
printf (“The value stored at p location is
%dn",*p); // 5
*p= 9;
printf (“%dn",q); // 9
printf (“The value stored at p location is
%dn",*p); // 9
Dr. Yousaf, PIEAS
p= &q; // p now points at q
This is what was going on when we use & in scanf
int x;
scanf(“%d”, &x);
Dr. Yousaf, PIEAS
& means "address of" or "point at
Pointer Variable Declarations and
Initialization
• Pointer variables
– Normal variables contain a specific value (direct reference)
– int count = 7;
– Pointer contains address of a variable that has a specific value
(indirect reference)
– Indirection – referencing a pointer value
– int *countPtr
– countPtr = &count
count
7
count
7
countPtr
Dr. Yousaf, PIEAS
Pointer Variable Declarations and
Initialization
• Pointer declarations
– * used with pointer variables
int *myPtr;
– Declares a pointer to an int (pointer of type int *)
– Multiple pointers require using a * before each variable
declaration
int *myPtr1, *myPtr2;
– Can declare pointers to any data type
Dr. Yousaf, PIEAS
Pointer Variables
• Pointer variables are variables that store memory
addresses.
• Pointer Declaration:
– int x, y = 5;
– int *ptr;
– /*ptr is a POINTER to an integer variable*/
• Reference operator &:
– ptr = &y;
– /*assign ptr to the MEMORY ADDRESS of y.*/
• Dereference operator *:
– x = *ptr;
– /*assign x to the int that is pointed to by ptr */
Dr. Yousaf, PIEAS
Pointer Variables
int x;
int y = 5;
int *ptry;
ptr = &y;
x = *ptry;
printf(“%d”, x); //5 ptry
Dr. Yousaf, PIEAS
Pointer Variables
Dr. Yousaf, PIEAS
#include<stdio.h>
int main()
{
int x = 9;
int *ptrx = 0;
ptrx = &x;
printf("address of x = %dn",ptrx);
printf("Value in ptrx is %d", *ptrx);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
Dr. Yousaf, PIEAS
#include<stdio.h>
int main()
{
double x = 7.8;
double *ptrx = 0;
ptrx = &x;
printf("address of x = %dn",ptrx);
printf("Value in ptrx is %lf", *ptrx);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
Dr. Yousaf, PIEAS
Pointer Operators
• & (address operator)
– Returns address of operand
int y = 5;
int *yPtr;
yPtr = &y; // yPtr gets address of y
yPtr “points to” y
yPtr
y
5
yptr
500000 600000
y
600000 5
Address of y
is value of
yptr
Dr. Yousaf, PIEAS
Pointer Operators
• * (indirection/dereferencing operator)
– Returns a synonym/alias of what its operand points to
– *yptr returns y (because yptr points to y)
– * can be used for assignment
• Returns alias to an object
int y = 5;
int *yPtr;
yPtr = &y;
*yptr = 7; // changes y to 7
Dr. Yousaf, PIEAS
Revision
• We declare a pointer with a *
• We use an & to get the "address of" and save this
address in a pointer variable
• We use a * to get the value "pointed at“
int *p;
int q = 5;
printf ("q is %dn",q); // 5
p= &q;
printf (“%dn",*p); //5
*p= 6;
printf ("q is now %dn",q); // 6
printf (“%dn",*p); //6
Dr. Yousaf, PIEAS

More Related Content

What's hot

Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsP3 InfoTech Solutions Pvt. Ltd.
 
Unit2 control statements
Unit2 control statementsUnit2 control statements
Unit2 control statementsdeepak kumbhar
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string libraryMomenMostafa
 
C tech questions
C tech questionsC tech questions
C tech questionsvijay00791
 
8 arrays and pointers
8  arrays and pointers8  arrays and pointers
8 arrays and pointersMomenMostafa
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statementsMomenMostafa
 
Python iteration
Python iterationPython iteration
Python iterationdietbuddha
 
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Kevlin Henney
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, pythonRobert Lujo
 
Implementing Virtual Machines in Go & C
Implementing Virtual Machines in Go & CImplementing Virtual Machines in Go & C
Implementing Virtual Machines in Go & CEleanor McHugh
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationMohammad Usman
 
TensorFlow 深度學習快速上手班--自然語言處理應用
TensorFlow 深度學習快速上手班--自然語言處理應用TensorFlow 深度學習快速上手班--自然語言處理應用
TensorFlow 深度學習快速上手班--自然語言處理應用Mark Chang
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statementnarmadhakin
 
Pratt Parser in Python
Pratt Parser in PythonPratt Parser in Python
Pratt Parser in PythonPercolate
 

What's hot (20)

Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
 
Unit2 control statements
Unit2 control statementsUnit2 control statements
Unit2 control statements
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string library
 
C tech questions
C tech questionsC tech questions
C tech questions
 
8 arrays and pointers
8  arrays and pointers8  arrays and pointers
8 arrays and pointers
 
4 operators, expressions &amp; statements
4  operators, expressions &amp; statements4  operators, expressions &amp; statements
4 operators, expressions &amp; statements
 
Buffer OverFlow
Buffer OverFlowBuffer OverFlow
Buffer OverFlow
 
Python iteration
Python iterationPython iteration
Python iteration
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
7 functions
7  functions7  functions
7 functions
 
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
 
Unit 3
Unit 3 Unit 3
Unit 3
 
Implementing Virtual Machines in Go & C
Implementing Virtual Machines in Go & CImplementing Virtual Machines in Go & C
Implementing Virtual Machines in Go & C
 
C programming slide c04
C programming slide c04C programming slide c04
C programming slide c04
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Get Kata
Get KataGet Kata
Get Kata
 
TensorFlow 深度學習快速上手班--自然語言處理應用
TensorFlow 深度學習快速上手班--自然語言處理應用TensorFlow 深度學習快速上手班--自然語言處理應用
TensorFlow 深度學習快速上手班--自然語言處理應用
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Pratt Parser in Python
Pratt Parser in PythonPratt Parser in Python
Pratt Parser in Python
 

Similar to C Language Lecture 19

Similar to C Language Lecture 19 (20)

C Language Lecture 20
C Language Lecture 20C Language Lecture 20
C Language Lecture 20
 
C Language Lecture 18
C Language Lecture 18C Language Lecture 18
C Language Lecture 18
 
C Language Lecture 17
C Language Lecture 17C Language Lecture 17
C Language Lecture 17
 
C Language Lecture 3
C Language Lecture  3C Language Lecture  3
C Language Lecture 3
 
Pointer
PointerPointer
Pointer
 
C Language Lecture 8
C Language Lecture 8C Language Lecture 8
C Language Lecture 8
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 
C Language Lecture 16
C Language Lecture 16C Language Lecture 16
C Language Lecture 16
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
 
Chapter5.pptx
Chapter5.pptxChapter5.pptx
Chapter5.pptx
 
C Language Lecture 22
C Language Lecture 22C Language Lecture 22
C Language Lecture 22
 
C Language Lecture 15
C Language Lecture 15C Language Lecture 15
C Language Lecture 15
 
Unit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptxUnit-I Pointer Data structure.pptx
Unit-I Pointer Data structure.pptx
 
Pointers [compatibility mode]
Pointers [compatibility mode]Pointers [compatibility mode]
Pointers [compatibility mode]
 
C Language Lecture 6
C Language Lecture 6C Language Lecture 6
C Language Lecture 6
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
C Language Lecture 7
C Language Lecture 7C Language Lecture 7
C Language Lecture 7
 
C Language Lecture 21
C Language Lecture 21C Language Lecture 21
C Language Lecture 21
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
CSE240 Pointers
CSE240 PointersCSE240 Pointers
CSE240 Pointers
 

More from Shahzaib Ajmal

More from Shahzaib Ajmal (9)

C Language Lecture 14
C Language Lecture 14C Language Lecture 14
C Language Lecture 14
 
C Language Lecture 13
C Language Lecture 13C Language Lecture 13
C Language Lecture 13
 
C Language Lecture 12
C Language Lecture 12C Language Lecture 12
C Language Lecture 12
 
C Language Lecture 11
C Language Lecture  11C Language Lecture  11
C Language Lecture 11
 
C Language Lecture 10
C Language Lecture 10C Language Lecture 10
C Language Lecture 10
 
C Language Lecture 9
C Language Lecture 9C Language Lecture 9
C Language Lecture 9
 
C Language Lecture 4
C Language Lecture  4C Language Lecture  4
C Language Lecture 4
 
C Language Lecture 2
C Language Lecture  2C Language Lecture  2
C Language Lecture 2
 
C Language Lecture 1
C Language Lecture  1C Language Lecture  1
C Language Lecture 1
 

Recently uploaded

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 

Recently uploaded (20)

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 

C Language Lecture 19

  • 1. Computing Fundamentals Dr. Muhammad Yousaf Hamza Deputy Chief Engineer, PIEAS
  • 3. Recursion Example: factorials – 5! = 5 * 4 * 3 * 2 * 1 – Notice that • 5! = 5 * 4! • 4! = 4 * 3! ... – Can compute factorials recursively – Solve base case (1! = 0! = 1) then plug in • 2! = 2 * 1! = 2 * 1 = 2; • 3! = 3 * 2! = 3 * 2 = 6; Write a recursive function int fact(int num) that should return the factorial of given number num Dr. Yousaf, PIEAS
  • 4. Dr. Yousaf, PIEAS //Calculate Factorial using Recursion # include<stdio.h> int factorial(int num); int main () { int f,x; printf("Enter integer value in the range 1 to 10: "); scanf("%d", &x); if (x > 10 || x < 1) printf ("Illegal input!n"); else { f = factorial(x); printf ("%d factorial equals %dn", x,f); } getchar(); return 0; } int factorial (int a) { if (a==1) // base case return 1; else { a *= factorial(a-1); return a; } }
  • 5. Recursion • Recursive functions • A function that calls itself inside its body is called a recursive function • Can only solve a base case – Divide a problem into • What it can do • What it cannot do – What it cannot do resembles original problem – The function launches a new copy of itself (recursion step) to solve what it cannot do – Eventually base case gets solved • Gets plugged in, works its way up and solves whole problem Dr. Yousaf, PIEAS
  • 6. Example Using Recursion /*This function prints all the number between zero and a given number that is greater than zero. */ #include <stdio.h> void printSeries(int num); int main() { printSeries(6); getchar(); return 0; } void printSeries(int num) { if(num<=0) return; printf("%d", num); printSeries(num-1); } Dr. Yousaf, PIEAS
  • 7. Example Using Recursion /*This function prints all the number between zero and a given number that is greater than zero. */ #include <stdio.h> void printSeries(int num); int main() { printSeries(6); getchar(); return 0; } void printSeries(int num) { if(num<=0) return; printf("%d", num); printSeries(num-1); } Dr. Yousaf, PIEAS
  • 8. Example Using Recursion: The Fibonacci Series • Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, ... – Each number is the sum of the previous two – fib( n ) = fib( n - 1 ) + fib( n – 2 ) – Write a recursive function that can print first N terms of Fibonacci series , – Can be solved recursively: Code for the fibaonacci function int fibonacci(int n ) { if (n == 0 || n == 1) // base case return n; else return fibonacci(n - 1)+ fibonacci(n – 2); } Dr. Yousaf, PIEAS
  • 9. Example Using Recursion: The Fibonacci Series • Set of recursive calls to function fibonacci f( 3 ) f( 1 )f( 2 ) f( 1 ) f( 0 ) return 1 return 1 return 0 return + +return Dr. Yousaf, PIEAS
  • 10. Dr. Yousaf, PIEAS // To generate Fibonacci series using Recursion #include<stdio.h> int fibonacci(int n); int main() { int i, terms, result; printf("Please enter the number of terms from 1 to 20: "); scanf("%d",&terms); for ( i = 0; i<= terms; i++) { result = fibonacci(i); printf("%d, ", result); } getchar(); return 0; } // Function Definition int fibonacci(int n) { if ( n == 0 || n == 1 ) return n; else return fibonacci( n - 1 ) + fibonacci( n - 2 ); }
  • 11. Recursion vs. Iteration • Repetition – Iteration: explicit loop – Recursion: repeated function calls • Termination – Iteration: loop condition fails – Recursion: base case recognized Dr. Yousaf, PIEAS
  • 13. /* Demonstration on Pointers A very simple program to print a value of a variable without using pointer */ #include<stdio.h> int main() { int x = 20; printf("n x = %d", x); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 14. // A very simple program to print the address and value of a variable using pointer #include<stdio.h> int main() { int x = 20; int *ptrx; //Pointer is declared. Select any name instead of ptrx. ptrx = &x; // Initialization of the pointer printf("n address of x = %d", ptrx); // It would print the address value printf("n Value of x = %d",*ptrx); /* It would print the value of the variable stored at the address value of the pointer */ getchar(); return 0; } Dr. Yousaf, PIEAS
  • 16. • Pointers are powerful and very useful tools • With pointers we can effectively return more than one value from a function • Arrays are a form of pointer REALLY • Pass by reference is also possible Dr. Yousaf, PIEAS The Importance of Pointers
  • 17. The Importance of Pointers • Pointers can be used for advanced data structures. • Pointers can be "cheaper" to pass around a program. • You could program without using them but you would be making life more difficult for yourself. • Some things simply can't be done sensibly in C without them. Dr. Yousaf, PIEAS
  • 18. What are pointers? • Pointers are considered as one of the most difficult topics to understand in C. • Pointers "point at" areas of your computer's memory (address of the memory) • int *p; says p is a pointer to an int • Imagine your computer's memory as a series of boxes which all hold ints 56 71 12 3 21 7 p points at one of the ints Dr. Yousaf, PIEAS
  • 19. & means "address of" or "point at me" * means value or "what am I pointing at?" int *p; // p is a pointer to an int int q= 5; // q is an int p= &q; // p now points at q printf (“The value stored at p location is %dn",*p); // 5 /*We use *p to mean "the value in the memory where pointer p is pointing at*/ q=5 p Dr. Yousaf, PIEAS
  • 20. & means "address of" or "point at me" * means value or "what am I pointing at?" int *p; // p is a pointer to an int int q= 5; // q is an int p= &q; // p now points at q printf (“The value stored at p location is %dn",*p); // 5 *p= 9; printf (“%dn",q); // 9 printf (“The value stored at p location is %dn",*p); // 9 Dr. Yousaf, PIEAS
  • 21. p= &q; // p now points at q This is what was going on when we use & in scanf int x; scanf(“%d”, &x); Dr. Yousaf, PIEAS & means "address of" or "point at
  • 22. Pointer Variable Declarations and Initialization • Pointer variables – Normal variables contain a specific value (direct reference) – int count = 7; – Pointer contains address of a variable that has a specific value (indirect reference) – Indirection – referencing a pointer value – int *countPtr – countPtr = &count count 7 count 7 countPtr Dr. Yousaf, PIEAS
  • 23. Pointer Variable Declarations and Initialization • Pointer declarations – * used with pointer variables int *myPtr; – Declares a pointer to an int (pointer of type int *) – Multiple pointers require using a * before each variable declaration int *myPtr1, *myPtr2; – Can declare pointers to any data type Dr. Yousaf, PIEAS
  • 24. Pointer Variables • Pointer variables are variables that store memory addresses. • Pointer Declaration: – int x, y = 5; – int *ptr; – /*ptr is a POINTER to an integer variable*/ • Reference operator &: – ptr = &y; – /*assign ptr to the MEMORY ADDRESS of y.*/ • Dereference operator *: – x = *ptr; – /*assign x to the int that is pointed to by ptr */ Dr. Yousaf, PIEAS
  • 25. Pointer Variables int x; int y = 5; int *ptry; ptr = &y; x = *ptry; printf(“%d”, x); //5 ptry Dr. Yousaf, PIEAS
  • 27. #include<stdio.h> int main() { int x = 9; int *ptrx = 0; ptrx = &x; printf("address of x = %dn",ptrx); printf("Value in ptrx is %d", *ptrx); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 29. #include<stdio.h> int main() { double x = 7.8; double *ptrx = 0; ptrx = &x; printf("address of x = %dn",ptrx); printf("Value in ptrx is %lf", *ptrx); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 31. Pointer Operators • & (address operator) – Returns address of operand int y = 5; int *yPtr; yPtr = &y; // yPtr gets address of y yPtr “points to” y yPtr y 5 yptr 500000 600000 y 600000 5 Address of y is value of yptr Dr. Yousaf, PIEAS
  • 32. Pointer Operators • * (indirection/dereferencing operator) – Returns a synonym/alias of what its operand points to – *yptr returns y (because yptr points to y) – * can be used for assignment • Returns alias to an object int y = 5; int *yPtr; yPtr = &y; *yptr = 7; // changes y to 7 Dr. Yousaf, PIEAS
  • 33. Revision • We declare a pointer with a * • We use an & to get the "address of" and save this address in a pointer variable • We use a * to get the value "pointed at“ int *p; int q = 5; printf ("q is %dn",q); // 5 p= &q; printf (“%dn",*p); //5 *p= 6; printf ("q is now %dn",q); // 6 printf (“%dn",*p); //6 Dr. Yousaf, PIEAS