North South University
Department of Electrical and Computer Engineering
CSE 115L (Programming Language I Lab)
Lab 6: User- Defined Functions in C
Objective:
● Functions: Learn what functions are in c.
● User-Defined Functions: Learn how to create user-defined functions im c.
User-Defined Function in C
A user-defined function in C is a function that is created by the programmer to perform a
specific task, as opposed to pre-defined library functions like printf() or scanf(). These functions
allow for more modular and reusable code.
Structure of a User-Defined Function
A user-defined function in C has the following components:
1. Function Declaration (Prototype): This tells the compiler about the function's name,
return type, and parameters (if any).
2. Function Definition: This is where the actual logic of the function is written.
3. Function Call: This is where the function is invoked in the main() function (or any other
function).
Practice :
Create a user-defined function to calculate the Write a program in C to find the square of any
area of a rectangle. number using the function.
#include <stdio.h> #include <stdio.h>
// Function Declaration // Function to calculate the square of a number
float calculateArea(float length, float width); float square(float num) {
return num * num;
int main(void) { }
float length, width, area;
int main(void) {
// Taking user input float num, result;
printf("Enter the length of the rectangle: ");
scanf("%f", &length); // Taking user input
printf("Enter a number: ");
printf("Enter the width of the rectangle: "); scanf("%f", &num);
scanf("%f", &width);
// Calling the square function
// Function Call result = square(num);
area = calculateArea(length, width);
// Displaying the result
// Output the area printf("The square of %.2f is %.2f\n", num,
printf("Area of the rectangle: %.2f\n", result);
area);
return 0;
return 0; }
}
// Function Definition
float calculateArea(float length, float width) {
return length * width;
}
Classwork :
1. Using the function, write a program in C that will take your age and will return
your birth year.
2. Write a C program that takes a double value as input and computes both its square
and cube. The program should have two separate functions:
● calculateSquare(double num): This function should take a number as input and
return its square.
● calculateCube(double num): This function should take a number as input and
return its cube.