0% found this document useful (0 votes)
24 views

Chapter 13 Functions

Jj

Uploaded by

hassanishfaq142
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Chapter 13 Functions

Jj

Uploaded by

hassanishfaq142
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Learn C programming with Prof.

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:

return_type function_name (parameter_type1 parameter1, parameter_type2 parameter2, ...)

// function body

// return statement (if return_type is not void)

• 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

Function: Preparing a dish.

• Parameters: Ingredients (e.g., flour, sugar, eggs).


• Function Behavior: Depending on the ingredients you use, the outcome (the dish) will
vary.
• Example: If you change the amount of sugar, the dish might be sweeter or less sweet.

Email:[email protected]
Learn C programming with Prof. Shahzeb Malik

2. Booking a Flight

Function: Making a flight reservation.

• Parameters: Departure city, destination city, date of travel, number of passengers.


• Function Behavior: The details you provide will determine the available flights and
prices.
• Example: Changing the destination will yield different flight options and costs.

3. Sending a Package

Function: Shipping a package.

• Parameters: Destination address, package weight, delivery speed (e.g., standard,


express).
• Function Behavior: The parameters will influence the shipping cost and delivery time.
• Example: A heavier package may cost more to ship.

4. Creating a Profile on a Social Media Platform

Function: Setting up a user profile.

• Parameters: Username, password, profile picture, bio.


• Function Behavior: The values of these parameters determine how your profile appears
and functions.
• Example: A catchy username might attract more followers.

5. Personal Trainer Session

Function: Designing a workout plan.

• 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

Here’s a simple example demonstrating functions in C.

#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.

1. Include Header File

#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

float calculateArea(float width, float height) {


return width * height;
}

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

float width, height, area;

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

printf("Enter width of the rectangle: ");


scanf("%f", &width);

o printf displays a message asking the user to enter the width.


o scanf reads the user’s input and stores it in the width variable. The %f format
specifier indicates that we expect a floating-point number.
6. User Input for Height

printf("Enter height of the rectangle: ");


scanf("%f", &height);

o Similar to the previous step, this asks the user for the height and stores the input
in the height variable.
7. Calculate Area

area = calculateArea(width, height);

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

printf("Area of the rectangle: %.2f\n", area);

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.

1. Calculate the Circumference of a Circle


#include <stdio.h>

#define PI 3.14

// Function to calculate the circumference of a circle


float calculateCircumference(float radius) {
return 2 * PI * radius;
}

int main() {
float radius, circumference;

// User input for radius


printf("Enter radius of the circle: ");
scanf("%f", &radius);

// Calling the function to calculate circumference


circumference = calculateCircumference(radius);

// Displaying the circumference


printf("Circumference of the circle: %.2f\n", circumference);

return 0;
}

Overview

This program calculates the circumference of a circle based on the radius provided by the user.

Breakdown

1. Include Header and Define Constant


o #include <stdio.h>: Allows for input and output functions.
o #define PI 3.14: Defines a constant value for π (Pi).
2. Function Definition
o float calculateCircumference(float radius): Calculates circumference
using the formula 2×π×radius2 \times \pi \times \text{radius}2×π×radius.
3. Main Function
o Declares radius and circumference as float variables.
4. User Input for Radius
o Prompts the user to enter the radius and stores it.
5. Calculate Circumference
o Calls calculateCircumference to compute the circumference.
6. Display the Result
o Prints the calculated circumference with two decimal places.

Email:[email protected]
Learn C programming with Prof. Shahzeb Malik

2. Convert Celsius to Fahrenheit


#include <stdio.h>

// Function to convert Celsius to Fahrenheit


float celsiusToFahrenheit(float celsius) {
return (celsius * 9 / 5) + 32;
}

int main() {
float celsius, fahrenheit;

// User input for temperature in Celsius


printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);

// Calling the function to convert to Fahrenheit


fahrenheit = celsiusToFahrenheit(celsius);

// Displaying the temperature in Fahrenheit


printf("Temperature in Fahrenheit: %.2f\n", fahrenheit);

return 0;
}

Overview

This program converts a temperature from Celsius to Fahrenheit.

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

3. Find the Maximum of Two Numbers


#include <stdio.h>

// Function to find the maximum of two numbers


float findMax(float num1, float num2)
{
return (num1 > num2) ? num1 : num2;
}

int main() {
float num1, num2, max;

// User input for two numbers


printf("Enter two numbers: ");
scanf("%f %f", &num1, &num2);

// Calling the function to find the maximum


max = findMax(num1, num2);

// Displaying the maximum number


printf("Maximum number: %.2f\n", 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.

Example of a Global Variable


#include <stdio.h>

int globalVar = 10; // Global variable

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.

Example of a Local Variable


#include <stdio.h>

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

Feature Global Variables Local Variables


Declaration Outside any function Inside a function or block
Scope Accessible from any function Accessible only within its function
Lifetime Throughout the program's execution Limited to the function's execution
Initialization Automatically initialized to zero Uninitialized (contains garbage values)
Usage Shared across multiple functions Temporary data within a function

Email:[email protected]
Learn C programming with Prof. Shahzeb Malik

Important Concepts/Questions regarding functions

Here are some important definitions regarding functions in C programming:

1. Function

A block of code that performs a specific task.

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:

float calculateArea(float width, float height)


{
return width * height;
}

Real-Life Example: A complete recipe that includes the dish name, ingredients, and cooking
instructions.

3. Function Declaration (Prototype)

A statement that specifies the function's name, return type, and parameters without the body.

Example:

float calculateArea(float width, float height);

Real-Life Example: A list of recipes with names and preparation times but without the actual
cooking steps.

4. Return Type

The data type of the value that a function returns.

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)

Values passed to a function when it is called.

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

The statement that executes the function, providing necessary arguments.

Example:

float area = calculateArea(5.0, 10.0);

Real-Life Example: Telling the waiter your order (calling the function with parameters).

7. Local Variable

A variable declared within a function, only accessible within that function.

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

A function that does not return a value.

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

10. Recursive Function

A function that calls itself to solve a problem.

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).

11. Library Function

Pre-defined functions provided by libraries that can be used in a program.

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.

12. Function Overloading

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).

13. Function Pointer

A variable that stores the address of a function.

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]

You might also like