SlideShare a Scribd company logo
1 of 20
Download to read offline
Computing Fundamentals
Dr. Muhammad Yousaf Hamza
Deputy Chief Engineer, PIEAS
Automatic Versus Static Variables
Dr. Yousaf, PIEAS
// Auto Variables
#include <stdio.h>
void func1(void);
int main()
{
int count;
for (count = 0; count < 20; count++)
{
printf("At iteration %d: ", count);
func1();
}
getchar(); return 0;
}
void func1(void)
{
int x = 0;
int y = 0;
printf("x = %d, y = %dn", x, y);
x++;
Y++;
} Dr. Yousaf, PIEAS
• At iteration 0: x = 0, y = 0
• At iteration 1: x = 0, y = 0
• At iteration 2: x = 0, y = 0
• At iteration 3: x = 0, y = 0
• At iteration 4: x = 0, y = 0
• At iteration 5: x = 0, y = 0
• At iteration 6: x = 0, y = 0
• At iteration 7: x = 0, y = 0
• At iteration 8: x = 0, y = 0
• At iteration 9: x = 0, y = 0
• and so on
//Automatic versus Static Variables, pages 209-211
// Example Page 211 Static Variables
#include <stdio.h>
void func1(void);
int main()
{
int count;
for (count = 0; count < 20; count++)
{
printf("At iteration %d: ", count);
func1();
}
getchar(); return 0;
}
void func1(void)
{
static int x = 0;
int y = 0;
printf("x = %d, y = %dn", x, y);
x++;
y++; }
Dr. Yousaf, PIEAS
• At iteration 0: x = 0, y = 0
• At iteration 1: x = 1, y = 0
• At iteration 2: x = 2, y = 0
• At iteration 3: x = 3, y = 0
• At iteration 4: x = 4, y = 0
• At iteration 5: x = 5, y = 0
• At iteration 6: x = 6, y = 0
• At iteration 7: x = 7, y = 0
• At iteration 8: x = 8, y = 0
• At iteration 9: x = 9, y = 0
• and so on
Dr. Yousaf, PIEAS
// static.c
// demonstrates static variables
#include <stdio.h>
float getavg(float); //declaration
int main()
{
float data=1, avg;
while( data != 0 )
{
printf("Enter a number: ");
scanf("%f",&data);
avg = getavg(data);
printf("New average is %fn",avg);
}
return 0;
}
// finds average of old plus
new data
float getavg(float newdata)
{
static float total = 0;
/*static variables are
initialized*/
static int count = 0;
count++; //increment count
total += newdata; /*add
new data to total*/
return total / count;
//return the new average
}
Automatic Storage
• Storage class specifiers (auto or static) decide
Storage duration which means how long an object
exists in memory
• Automatic storage
– Object created and destroyed within its block
– auto: default for local variables
auto double x, y;
Variables that are automatically created and
automatically destroyed are called automatic or auto
variables. Non‐static variables that are declared inside a
function are automatically created and destroyed so
non‐static local variables are auto variables
Dr. Yousaf, PIEAS
Static Storage
• Static storage
– Variables exist for entire program execution
– Default value of zero
static: local variables defined in functions.
• Keep value after function ends
• Only known in their own function
Dr. Yousaf, PIEAS
exit() function
Dr. Yousaf, PIEAS
exit()
// About exit() function. Page 236
#include<stdio.h>
#include<stdlib.h> // to use exit() function.
int main()
{
int i, j, k;
for (i = 0; i<5; i++)
printf("%dn", i);
getchar();
exit(0); // it will exit the program
j = 23;
printf("j = %dn", j);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
// Following program without exit()
// In the next slide, we will use exit() within a function
#include<stdio.h>
#include<stdlib.h>
int add(int x, int y);
int main()
{
int i = 10, j, k;
printf ("i = %dn", i);
j = add(10,20);
printf ("j = %dn", j);
getchar(); return 0;
}
int add(int x, int y)
{
int z;
z = x+y;
return z;
} Dr. Yousaf, PIEAS
exit()
// Use of exit() within a function
#include<stdio.h>
#include<stdlib.h> // to use exit function
int add(int x, int y);
int main()
{
int i = 10, j, k;
printf ("i = %dn", i);
getchar();
j = add(10,20);
printf ("j = %dn", j);
getchar(); return 0;
}
int add(int x, int y)
{
int z;
z = x+y;
exit(0); // It will exit the entire program (not the function only).
return z;
}
Dr. Yousaf, PIEAS
exit()
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:
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

More Related Content

What's hot

openFrameworks、サウンド機能・音響合成、ofxMaxim, ofxOsc, ofxPd, ofxSuperCollider
openFrameworks、サウンド機能・音響合成、ofxMaxim, ofxOsc, ofxPd, ofxSuperCollideropenFrameworks、サウンド機能・音響合成、ofxMaxim, ofxOsc, ofxPd, ofxSuperCollider
openFrameworks、サウンド機能・音響合成、ofxMaxim, ofxOsc, ofxPd, ofxSuperCollider
Atsushi Tadokoro
 
ภาษาซี
ภาษาซีภาษาซี
ภาษาซี
kramsri
 
ภาษาซี
ภาษาซีภาษาซี
ภาษาซี
kramsri
 
Reverse Engineering: C++ "for" operator
Reverse Engineering: C++ "for" operatorReverse Engineering: C++ "for" operator
Reverse Engineering: C++ "for" operator
erithion
 
Tarea De Scilab By Sebastian Vasquez
Tarea De Scilab By Sebastian VasquezTarea De Scilab By Sebastian Vasquez
Tarea De Scilab By Sebastian Vasquez
Sebastian Vasquez
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnit
ferca_sl
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io
웅식 전
 

What's hot (20)

openFrameworks、サウンド機能・音響合成、ofxMaxim, ofxOsc, ofxPd, ofxSuperCollider
openFrameworks、サウンド機能・音響合成、ofxMaxim, ofxOsc, ofxPd, ofxSuperCollideropenFrameworks、サウンド機能・音響合成、ofxMaxim, ofxOsc, ofxPd, ofxSuperCollider
openFrameworks、サウンド機能・音響合成、ofxMaxim, ofxOsc, ofxPd, ofxSuperCollider
 
Intro to c programming
Intro to c programmingIntro to c programming
Intro to c programming
 
week-16x
week-16xweek-16x
week-16x
 
ภาษาซี
ภาษาซีภาษาซี
ภาษาซี
 
ภาษาซี
ภาษาซีภาษาซี
ภาษาซี
 
What is recursion?
What is recursion? What is recursion?
What is recursion?
 
DataStructures notes
DataStructures notesDataStructures notes
DataStructures notes
 
ADA FILE
ADA FILEADA FILE
ADA FILE
 
Operating system labs
Operating system labsOperating system labs
Operating system labs
 
Reverse Engineering: C++ "for" operator
Reverse Engineering: C++ "for" operatorReverse Engineering: C++ "for" operator
Reverse Engineering: C++ "for" operator
 
Tarea De Scilab By Sebastian Vasquez
Tarea De Scilab By Sebastian VasquezTarea De Scilab By Sebastian Vasquez
Tarea De Scilab By Sebastian Vasquez
 
Data Structure using C
Data Structure using CData Structure using C
Data Structure using C
 
Hangman Game Programming in C (coding)
Hangman Game Programming in C (coding)Hangman Game Programming in C (coding)
Hangman Game Programming in C (coding)
 
Unit testing with PHPUnit
Unit testing with PHPUnitUnit testing with PHPUnit
Unit testing with PHPUnit
 
An introduction to functional programming with go
An introduction to functional programming with goAn introduction to functional programming with go
An introduction to functional programming with go
 
Ping pong game
Ping pong  gamePing pong  game
Ping pong game
 
Binary tree
Binary treeBinary tree
Binary tree
 
Vcs16
Vcs16Vcs16
Vcs16
 
Python program
Python programPython program
Python program
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io
 

Similar to C Language Lecture 18

openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートIIopenFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
Atsushi Tadokoro
 

Similar to C Language Lecture 18 (20)

C Language Lecture 5
C Language Lecture  5C Language Lecture  5
C Language Lecture 5
 
C Language Lecture 19
C Language Lecture 19C Language Lecture 19
C Language Lecture 19
 
C Language Lecture 16
C Language Lecture 16C Language Lecture 16
C Language Lecture 16
 
C Language Lecture 22
C Language Lecture 22C Language Lecture 22
C Language Lecture 22
 
C Language Lecture 8
C Language Lecture 8C Language Lecture 8
C Language Lecture 8
 
Let us C (by yashvant Kanetkar) chapter 3 Solution
Let us C   (by yashvant Kanetkar) chapter 3 SolutionLet us C   (by yashvant Kanetkar) chapter 3 Solution
Let us C (by yashvant Kanetkar) chapter 3 Solution
 
C Language Lecture 6
C Language Lecture 6C Language Lecture 6
C Language Lecture 6
 
6. function
6. function6. function
6. function
 
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...
Flink Forward Berlin 2017: David Rodriguez - The Approximate Filter, Join, an...
 
Python
PythonPython
Python
 
Lab manual operating system [cs 502 rgpv] (usefulsearch.org) (useful search)
Lab manual operating system [cs 502 rgpv] (usefulsearch.org)  (useful search)Lab manual operating system [cs 502 rgpv] (usefulsearch.org)  (useful search)
Lab manual operating system [cs 502 rgpv] (usefulsearch.org) (useful search)
 
Assignment on Numerical Method C Code
Assignment on Numerical Method C CodeAssignment on Numerical Method C Code
Assignment on Numerical Method C Code
 
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートIIopenFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
 
C programming
C programmingC programming
C programming
 
C Language Lecture 15
C Language Lecture 15C Language Lecture 15
C Language Lecture 15
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
 
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
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)
 
Week3
Week3Week3
Week3
 

More from Shahzaib Ajmal (9)

C Language Lecture 21
C Language Lecture 21C Language Lecture 21
C Language Lecture 21
 
C Language Lecture 20
C Language Lecture 20C Language Lecture 20
C Language Lecture 20
 
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 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

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 

Recently uploaded (20)

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
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

C Language Lecture 18

  • 1. Computing Fundamentals Dr. Muhammad Yousaf Hamza Deputy Chief Engineer, PIEAS
  • 2. Automatic Versus Static Variables Dr. Yousaf, PIEAS
  • 3. // Auto Variables #include <stdio.h> void func1(void); int main() { int count; for (count = 0; count < 20; count++) { printf("At iteration %d: ", count); func1(); } getchar(); return 0; } void func1(void) { int x = 0; int y = 0; printf("x = %d, y = %dn", x, y); x++; Y++; } Dr. Yousaf, PIEAS • At iteration 0: x = 0, y = 0 • At iteration 1: x = 0, y = 0 • At iteration 2: x = 0, y = 0 • At iteration 3: x = 0, y = 0 • At iteration 4: x = 0, y = 0 • At iteration 5: x = 0, y = 0 • At iteration 6: x = 0, y = 0 • At iteration 7: x = 0, y = 0 • At iteration 8: x = 0, y = 0 • At iteration 9: x = 0, y = 0 • and so on
  • 4. //Automatic versus Static Variables, pages 209-211 // Example Page 211 Static Variables #include <stdio.h> void func1(void); int main() { int count; for (count = 0; count < 20; count++) { printf("At iteration %d: ", count); func1(); } getchar(); return 0; } void func1(void) { static int x = 0; int y = 0; printf("x = %d, y = %dn", x, y); x++; y++; } Dr. Yousaf, PIEAS • At iteration 0: x = 0, y = 0 • At iteration 1: x = 1, y = 0 • At iteration 2: x = 2, y = 0 • At iteration 3: x = 3, y = 0 • At iteration 4: x = 4, y = 0 • At iteration 5: x = 5, y = 0 • At iteration 6: x = 6, y = 0 • At iteration 7: x = 7, y = 0 • At iteration 8: x = 8, y = 0 • At iteration 9: x = 9, y = 0 • and so on
  • 5. Dr. Yousaf, PIEAS // static.c // demonstrates static variables #include <stdio.h> float getavg(float); //declaration int main() { float data=1, avg; while( data != 0 ) { printf("Enter a number: "); scanf("%f",&data); avg = getavg(data); printf("New average is %fn",avg); } return 0; } // finds average of old plus new data float getavg(float newdata) { static float total = 0; /*static variables are initialized*/ static int count = 0; count++; //increment count total += newdata; /*add new data to total*/ return total / count; //return the new average }
  • 6. Automatic Storage • Storage class specifiers (auto or static) decide Storage duration which means how long an object exists in memory • Automatic storage – Object created and destroyed within its block – auto: default for local variables auto double x, y; Variables that are automatically created and automatically destroyed are called automatic or auto variables. Non‐static variables that are declared inside a function are automatically created and destroyed so non‐static local variables are auto variables Dr. Yousaf, PIEAS
  • 7. Static Storage • Static storage – Variables exist for entire program execution – Default value of zero static: local variables defined in functions. • Keep value after function ends • Only known in their own function Dr. Yousaf, PIEAS
  • 9. exit() // About exit() function. Page 236 #include<stdio.h> #include<stdlib.h> // to use exit() function. int main() { int i, j, k; for (i = 0; i<5; i++) printf("%dn", i); getchar(); exit(0); // it will exit the program j = 23; printf("j = %dn", j); getchar(); return 0; } Dr. Yousaf, PIEAS
  • 10. // Following program without exit() // In the next slide, we will use exit() within a function #include<stdio.h> #include<stdlib.h> int add(int x, int y); int main() { int i = 10, j, k; printf ("i = %dn", i); j = add(10,20); printf ("j = %dn", j); getchar(); return 0; } int add(int x, int y) { int z; z = x+y; return z; } Dr. Yousaf, PIEAS exit()
  • 11. // Use of exit() within a function #include<stdio.h> #include<stdlib.h> // to use exit function int add(int x, int y); int main() { int i = 10, j, k; printf ("i = %dn", i); getchar(); j = add(10,20); printf ("j = %dn", j); getchar(); return 0; } int add(int x, int y) { int z; z = x+y; exit(0); // It will exit the entire program (not the function only). return z; } Dr. Yousaf, PIEAS exit()
  • 13. 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
  • 14. 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; } }
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. 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 ); }
  • 20. Recursion vs. Iteration • Repetition – Iteration: explicit loop – Recursion: repeated function calls • Termination – Iteration: loop condition fails – Recursion: base case recognized Dr. Yousaf, PIEAS