Chapter 13 Functions
Chapter 13 Functions
Shahzeb Malik
Functions
Definition:
Functions in C are a way to organize code into reusable blocks. They allow for modular
programming, making the code easier to read, maintain, and debug. Each function can perform a
specific task and can be called multiple times within a program.
Real-Life Analogy:
Think of a function like a coffee machine. You input your choice (e.g., espresso or cappuccino)
and press a button (call the function). The machine processes your request and gives you your
coffee (the return value). You can use the coffee machine repeatedly for different types of coffee
without needing to know the intricate details of how it works inside.
Syntax:
// function body
• return_type: Type of value the function returns (e.g., int, float, void).
• function_name: Name of the function.
• parameters: Input values (arguments) that the function takes. These are optional.
Some Real life example to understand logic of parameters:
Parameters in functions can be thought of as the inputs that determine how the function behaves
or what it produces. Let’s explore some real-life examples to illustrate the concept of parameters
more clearly.
1. Cooking a Recipe
Email:[email protected]
Learn C programming with Prof. Shahzeb Malik
2. Booking a Flight
3. Sending a Package
• Parameters: Fitness goals (e.g., weight loss, muscle gain), duration of training, preferred
exercises.
• Function Behavior: The trainer tailors the session based on your inputs.
• Example: If your goal is muscle gain, the workout plan will focus on strength training.
• Summary
• In these examples, parameters serve as inputs that influence the output or behavior of a
function. Understanding how parameters work in both programming and real life helps
clarify how we can manipulate and control outcomes based on the values we provide.
Email:[email protected]
Learn C programming with Prof. Shahzeb Malik
Example Program
#include <stdio.h>
// Function to calculate the area of a rectangle
float calculateArea(float width, float height) {
return width * height;
}
int main() {
float width, height, area;
// User input for width and height
printf("Enter width of the rectangle: ");
scanf("%f", &width);
printf("Enter height of the rectangle: ");
scanf("%f", &height);
// Calling the function to calculate area
area = calculateArea(width, height);
// Displaying the area
printf("Area of the rectangle: %.2f\n", area);
return 0;
}
Code Overview
This program calculates the area of a rectangle based on user input for width and height.
#include <stdio.h>
o This line includes the standard input-output library, which allows us to use
functions like printf and scanf for displaying output and getting user input.
Email:[email protected]
Learn C programming with Prof. Shahzeb Malik
2. Function Definition
o This defines a function called calculateArea that takes two parameters: width
and height, both of type float.
o Inside the function, it calculates the area by multiplying width and height and
returns the result.
3. Main Function
int main() {
4. Variable Declarations
o Here, we declare three variables: width, height, and area, all of type float.
These will store the dimensions of the rectangle and the calculated area.
5. User Input for Width
o Similar to the previous step, this asks the user for the height and stores the input
in the height variable.
7. Calculate Area
o This line calls the calculateArea function with the width and height provided
by the user. The result (area) is stored in the area variable.
8. Display the Result
o Finally, this line prints the calculated area to the screen. The %.2f format specifier
ensures the area is displayed with two decimal places.
Email:[email protected]
Learn C programming with Prof. Shahzeb Malik
Sure! Here are a few more simple C programs, each with an overview and step-by-step
explanations.
#define PI 3.14
int main() {
float radius, circumference;
return 0;
}
Overview
This program calculates the circumference of a circle based on the radius provided by the user.
Breakdown
Email:[email protected]
Learn C programming with Prof. Shahzeb Malik
int main() {
float celsius, fahrenheit;
return 0;
}
Overview
Breakdown
1. Include Header
o #include <stdio.h>: For input and output functions.
2. Function Definition
o float celsiusToFahrenheit(float celsius): Converts Celsius to Fahrenheit
using the formula (C×95)+32(C \times \frac{9}{5}) + 32(C×59)+32.
3. Main Function
o Declares celsius and fahrenheit as float variables.
4. User Input for Celsius
o Prompts the user to enter a temperature in Celsius.
5. Convert Temperature
o Calls celsiusToFahrenheit to compute the Fahrenheit value.
6. Display the Result
o Prints the temperature in Fahrenheit with two decimal places.
Email:[email protected]
Learn C programming with Prof. Shahzeb Malik
int main() {
float num1, num2, max;
return 0;
}
Overview
This program finds the maximum of two numbers provided by the user.
1. Include Header
o #include <stdio.h>: For input and output functions.
2. Function Definition
o float findMax(float num1, float num2): Uses a ternary operator to return
the larger of the two numbers.
3. Main Function
o Declares num1, num2, and max as float variables.
4. User Input for Numbers
o Prompts the user to enter two numbers.
5. Find Maximum
o Calls findMax to determine the larger number.
6. Display the Result
o Prints the maximum number with two decimal places.
Summary
These programs follow a similar structure: they include necessary headers, define functions for
specific tasks, gather user input, process that input using functions, and finally display the
results. This organization makes the code clear and easy to understand!
Email:[email protected]
Learn C programming with Prof. Shahzeb Malik
In C programming, variables can be categorized into two main types based on their scope: global
variables and local variables. Here’s a breakdown of the differences between them:
Global Variables
1. Definition:
o A global variable is declared outside of any function, usually at the top of the file.
2. Scope:
o Accessible from any function within the same file (and potentially other files if
declared with extern).
3. Lifetime:
o Exists for the entire duration of the program. It is allocated when the program
starts and deallocated when it ends.
4. Initialization:
o If not explicitly initialized, global variables are automatically initialized to zero
(or equivalent for their data type).
5. Usage:
o Suitable for data that needs to be shared across multiple functions.
void display() {
printf("Global variable: %d\n", globalVar);
}
int main() {
display();
globalVar = 20; // Modify global variable
display();
return 0;
}
Local Variables
1. Definition:
o A local variable is declared within a function or a block (e.g., inside {}).
2. Scope:
o Accessible only within the function or block where it is declared. It cannot be
accessed outside of that context.
3. Lifetime:
o Exists only while the function is executing. It is created when the function is
called and destroyed when it exits.
Email:[email protected]
Learn C programming with Prof. Shahzeb Malik
4. Initialization:
o If not explicitly initialized, local variables contain garbage values (indeterminate
values).
5. Usage:
o Suitable for temporary data needed only within a specific function.
void display() {
int localVar = 5; // Local variable
printf("Local variable: %d\n", localVar);
}
int main() {
display();
// printf("%d", localVar); // This would cause an error because localVar
is not accessible here
return 0;
}
Summary of Differences
Email:[email protected]
Learn C programming with Prof. Shahzeb Malik
1. Function
Real-Life Example: Think of a function as a recipe in a cookbook. Each recipe (function) tells
you how to prepare a specific dish (task) using certain ingredients (parameters).
2. Function Definition
The complete specification of a function, including its return type, name, parameters, and body.
Example:
Real-Life Example: A complete recipe that includes the dish name, ingredients, and cooking
instructions.
A statement that specifies the function's name, return type, and parameters without the body.
Example:
Real-Life Example: A list of recipes with names and preparation times but without the actual
cooking steps.
4. Return Type
Real-Life Example: When you order a dish, the restaurant brings it to you (returning a value). If
they bring a drink, it might be a soda (specific type), but if you don’t order anything, you get
nothing (void).
Email:[email protected]
Learn C programming with Prof. Shahzeb Malik
5. Parameters (Arguments)
Real-Life Example: When you place an order at a restaurant, the specifics (like size, flavor, or
ingredients) are the parameters you give to the chef (function).
6. Function Call
Example:
Real-Life Example: Telling the waiter your order (calling the function with parameters).
7. Local Variable
Real-Life Example: When you’re cooking, any temporary ingredients (like spices added just for
that dish) are only used in that recipe (function) and not stored for future use.
8. Global Variable
A variable declared outside any function, accessible from any function within the same file.
Real-Life Example: A common ingredient that is available in the kitchen and can be used in
multiple recipes (functions) throughout the cooking process.
9. Void Function
Example:
void printMessage()
{
printf("Hello, World!\n");
}
Real-Life Example: A cooking class demonstration where the instructor shows how to cook
without giving you a dish to take home (no return value).
Email:[email protected]
Learn C programming with Prof. Shahzeb Malik
Example:
int factorial(int n) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1); // Recursive call
}
Real-Life Example: A set of Russian nesting dolls, where each doll contains a smaller one,
continuing until you reach the smallest doll (base case).
Real-Life Example: Using an appliance in the kitchen, like a blender, that already has built-in
functions (like mixing or chopping) that you can use without knowing how they work internally.
Defining multiple functions with the same name but different parameters (not applicable in C).
Real-Life Example: Having a universal remote control that can operate different devices (TV,
DVD player) based on the mode selected (function name remains the same, but the function's
parameters differ).
Real-Life Example: Think of a contact list on your phone where you can point to different
contacts (function addresses) to call them, depending on whom you want to reach.
Email:[email protected]