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

C Language Lecture 19

  • 1.
    Computing Fundamentals Dr. MuhammadYousaf Hamza Deputy Chief Engineer, PIEAS
  • 2.
  • 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 //CalculateFactorial 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 /*Thisfunction 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 /*Thisfunction 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: TheFibonacci 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: TheFibonacci 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
  • 12.
  • 13.
    /* Demonstration onPointers 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 verysimple 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
  • 15.
  • 16.
    • Pointers arepowerful 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 ofPointers • 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 "addressof" 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 "addressof" 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 Declarationsand 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 Declarationsand 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 • Pointervariables 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; inty = 5; int *ptry; ptr = &y; x = *ptry; printf(“%d”, x); //5 ptry Dr. Yousaf, PIEAS
  • 26.
  • 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
  • 28.
  • 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
  • 30.
  • 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 declarea 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