PF Lab 10
PF Lab 10
● Explore recursive functions and understand the process of function self-calling for solving
complex problems.
● Understand the use of constants and static variables to manage variable scope and
immutability.
● Learn how to define and use structures to store and manage complex data types.
Introduction
Recursion is a powerful programming technique where a function calls itself to solve smaller
instances of a problem until it reaches a base case. In recursion, a base case is a condition that
stops the recursion from continuing indefinitely. Recursion may be a bit difficult to understand
and write but problems like factorials, Fibonacci sequences, and others that have naturally
recursive characteristics which often easily to implement.
Constants in C are values that do not change during program execution. They provide stability
and are defined using the const keyword. Static variables retain their value across function calls,
with scope confined to the function they’re declared in, helping manage data that should
persist through multiple function executions.
In C programming, structures provide a way to combine multiple data types into a single unit,
allowing complex data handling beyond primitive types. Structures are used to represent
real-world entities with multiple attributes, such as storing details for a student (name, ID,
grades).
Section 1: Recursion
Recursion is the process by which a function calls itself. C language allows writing of such
functions which call itself to solve complicated problems by breaking them down into simple
and easy problems. These functions are known as recursive functions. In other words, inside
Lab 09 Page 2 of 11
Nested if else, nested structures, Operators Programming Fundamentals Lab
the body of a recursive function there is a call to that same function. There are 2 parts of a
recursive function.
1. Base Case (Stopping Condition) - In base case, there is no call to the same function
directly or indirectly. It must return something.
2. Recursive Case - Here the recursion occurs. A call is made to the same function.
Functions in C are recursive, which means that they can call themselves. Recursion tends to be
less efficient than iterative code (i.e., code that uses loop-constructs), but in some cases may
facilitate more elegant, easier to read code.
Syntax of Recursion:
01 void recursive_function(){
02 recursion(); // function calls itself
03 }
04
05 int main(){
06 recursive_function();
07 }
Types of Recursion:
Lab 09 Page 3 of 11
Nested if else, nested structures, Operators Programming Fundamentals Lab
function name (same name) gets placed on the stack until the base case is reached. Upon which
the functions keep getting popped out from the stack. The calls go all the way to the stopping
case i.e., n = 1.
In other words, each recursive function call is added to the stack, which maintains the execution
of program. The stack allows the program to “remember” each state of the function’s variables
before the next recursive call. The base case pops all calls off the stack, unwinding back through
the stored contexts.
Example 1: Factorial Using Recursion.
#include <stdio.h>
int factorial(int n) {
if (n <= 1) {
return 1;
} else {
int main() {
int num = 5;
return 0;
Lab 09 Page 4 of 11
Nested if else, nested structures, Operators Programming Fundamentals Lab
#include <stdio.h>
int sum(int n) {
if (n == 0) return 0;
int main() {
int num = 5;
return 0;}
int fibonacci(int n) {
if (n <= 1) return n;
int main() {
int n = 5;
return 0; }
Output: 0 1 1 2 3
Lab 09 Page 5 of 11
Nested if else, nested structures, Operators Programming Fundamentals Lab
Section 2: Structures
The structure in C is a user-defined data type that can be used to group items of possibly
different types into a single type. The struct keyword is used to define the structure in the C
programming language. The items in the structure are called its member and they can be of any
valid data type. Additionally, the values of a structure are stored in contiguous memory
locations like arrays. The difference between an array and a structure is that an array is a
homogenous collection of similar types, whereas a structure can have elements of different
types stored adjacently and identified by a name.
Defining a Structure:
To define a structure, we use the struct keyword, followed by the structure name and the
members enclosed in curly braces.
01 struct structure_name {
02 data_type member1;
03 data_type member2;
04 ...
05 };
01 struct Student {
02 int id;
03 char name[50];
04 float marks;
05 }student1, student2;
----------------OR------------------
Lab 09 Page 6 of 11
Nested if else, nested structures, Operators Programming Fundamentals Lab
Initialization of Structures:
We can access the members of a structure using the dot (.) operator.
01 student1.id = 1;
02 strcpy(student1.name, "Haseeb Ahmed");
03 student1.marks = 85.5;
struct Student {
int id;
char name[50];
float marks;
};
int main() {
Lab 09 Page 7 of 11
Nested if else, nested structures, Operators Programming Fundamentals Lab
printStudent(student1);
return 0;
A static variable in a function retains its value between calls. Static variables have scope limited
to the function but lifetime for the program’s duration. They retain their value between function
calls. They are initialized only once and remain in memory for the program's life.
Example 2: A Chocolate structure to collect and display details (name, weight, calories, price,
expiry date) for three chocolates entered by the user.
Lab 09 Page 8 of 11
Nested if else, nested structures, Operators Programming Fundamentals Lab
#include <stdio.h>
struct Chocolate {
char Name[50];
float Weight;
int Calories;
float Price;
char ExpiryDate[20];
};
int main() {
scanf("%s", myFavChocolates[i].Name);
scanf("%f", &myFavChocolates[i].Weight);
scanf("%d", &myFavChocolates[i].Calories);
scanf("%f", &myFavChocolates[i].Price);
scanf("%s", myFavChocolates[i].ExpiryDate); }
Lab 09 Page 9 of 11
Nested if else, nested structures, Operators Programming Fundamentals Lab
} return 0; }
Lab Task
1. Write a recursive function that takes an array and its size as input and prints all the
elements.
3. Create a program with a constant that defines the maximum allowable temperature (in
Celsius). Write a function to compare input temperatures and use a static variable to
count how many times temperatures exceeded the limit.
Lab 09 Page 10 of 11
Nested if else, nested structures, Operators Programming Fundamentals Lab
4. Create a structure to store details about cars in a dealership, including make, model,
year, price, and mileage. Write a program that allows users to add new cars, display a list
of available cars, and search for cars by make or model.
5. Write a recursive function bubbleSort that takes an array and its size. It performs the
bubble sort algorithm by repeatedly comparing adjacent elements and swapping them if
they are in the wrong order.
6. Design a structure to store information about travel packages, including package name,
destination, duration, cost, and number of seats available. Write a program that allows
users to book a travel package and display available packages.
7. Create a C program that defines a constant for the conversion factor of meters to
kilometers. Use a static variable in a function to count how many times the function is
called.
8. Write a recursive function linearSearch that takes an array, its size, the target element to
search for, and the current index. It checks if the target is at the current index and
continues searching in the subsequent indices until it either finds the target or exhausts
the array.
9. Write a recursive function that calculates the sum of digits of a number. For example, if
the input is 123, the output should be 6.
10. Write a recursive function that takes a string as input and returns the reversed string.
11. Write a program that uses structures to manage flight information, including flight
number, departure city, destination city, date, and available seats. Create functionalities
to book a seat and display flight details.
12. Write a program that use a structure to hold information about movies, such as title,
genre, director, release year, and rating. Write a program that allows users to add new
movies, search for movies by genre, and display all movie details.
Lab 09 Page 11 of 11