User-Defined Functions in C Programming
User-Defined Functions in C Programming
Chapter-5
User-Defined Functions, Structure and Unions
Functions
In Functions, you will learn about
• Introduction to function
• Concepts of User define function
Function prototype (declaration)
Function definition
Function call and return
• Parameters
Actual and Formal
• Parameter Passing
• Calling a function
• Recursive function
• Macros
• Pre-Processing
Introduction to Function
• A function is a block of code which is used to perform a
specific task.
• It can be written in one program and used by another
program without having to rewrite that piece of code.
Hence, it promotes usability!!!
• Functions can be put in a library. If another program
would like to use them, it will just need to include the
appropriate header file at the beginning of the program
and link to the correct library while compiling.
Introduction to Function
Functions can be divided into two categories :
• Predefined functions (standard functions)
Built-in functions provided by C that are used by
programmers without having to write any code for
them. i.e: printf( ), scanf( ), etc
• User-Defined functions
Functions that are written by the programmers
themselves to carry out various individual tasks.
Predefined (Standard) Functions
• Standard functions are functions pre-defined by C and
put into standard C libraries.
Example: printf(), scanf(), pow(), ceil(), rand(), etc.
• We need to include the appropriate header files.
Example: #include <stdio.h>, #include <math.h>
• What contained in the header files are the prototypes of
the standard functions. The function definitions (the
body of the functions) has been compiled and put into a
standard C library which will be linked by the compiler
during compilation.
User defined functions
• A programmer can create his/her own function(s).
• It is easier to plan and write our program if we divide it into several
functions instead of writing a long piece of code inside the main
function.
• A function is reusable and therefore prevents us (programmers)
from having to unnecessarily rewrite what we have written before.
• In order to write and use our own function, we need to do the
following:
create a function prototype (declare the function)
define the function somewhere in the program (implementation)
call the function whenever it needs to be used
Function Prototype (Declare the function)
• A function prototype will tell the compiler that there
exist a function with this name defined somewhere in
the program and therefore it can be used even though
the function has not yet been defined at that point.
• Function prototypes need to be written at the beginning
of the program.
• If the function receives some arguments, the variable
names for the arguments are not needed. State only the
data types
Function Prototype (Declare the function)
• Function prototypes can also be put in a header file. Header
files are files that have a .h extension.
• The header file can then be included at the beginning of our
program.
• To include a user defined header file, type:
• #include “header_file.h”
• Notice that instead of using < > as in the case of standard
header files, we need to use “ ”. This will tell the compiler to
search for the header file in the same directory as the
program file instead of searching it in the directory where
the standard library header files are stored.
Function Prototype (Declare the function) Example
• A function prototype Consists of the following elements:
• function’s name
• Parameters
• Return type.
• It must appear before the function is called.
Example:
int add(int, int); // function prototype
Function Definitions
• Is also called as function implementation
• A function definition is where the actual code for the
function is written. This code will determine what the
function will do when it is called.
• A function definition consists of the following elements:
A function name
An optional list of formal parameters enclosed in
parentheses (function arguments)
A function return data type (return value)
A compound statement ( function body)
Function Definition
• A function definition has this format:
return_data_type FunctionName(data_type variable1, data_type
variable2, data_type variable3, …..)
{
local variable declarations;
statements;
}
• The return data type is the type of data that will be returned to the
calling function. There can be only one return value.
• Any function not returning anything must be of type ‘void’.
• If the function does not receive any arguments from the calling
function, ‘void’ is used in the place of the arguments.
Function Definition Example 1
This is where the actual code of the function is written.
The definition must match the prototype.
Example:
int add(int a, int b) {
return a + b;
}
Function Definition Example 2
• A simple function is :
void print_message (void)
{
printf(“Hello, are you having fun?\n”);
}
• Note the function name is print_message. No arguments are
accepted by the function, this is indicated by the keyword void
enclosed in the parentheses. The return_value is void, thus data is
not returned by the function.
• So, when this function is called in the program, it will simply
perform its intended task which is to print Hello, are you having
fun?
Function Definition Example 3
• Consider the following example:
int calculate (int num1, int num2)
{
int sum;
sum = num1 + num2;
return sum;
}
• The above code segments is a function named calculate. This function accepts
two arguments i.e. num 1 and num2 of the type int. The return_value is int,
thus this function will return an integer value.
• So, when this function is called in the program, it will perform its task which is to
calculate the sum of any two numbers and return the result of the summation.
• Note that if the function is returning a value, it needs to use the keyword
‘return’.
Function Call and Return
Any function (including main) could utilize any other
function definition that exist in a program – hence it is said
to call the function (function call).
To call a function (i.e. to ask another function to do
something for the calling function), it requires the
FunctionName followed by a list of actual parameters (or
arguments), if any, enclosed in parenthesis.
Function Call and Return: Example
If the function requires some arguments to be passed along,
then the arguments need to be listed in the bracket ( )
according to the specified order.
For example:
void Calc(int, double, char, int);
void main(void) {
int a, b;
double c;
char d; Function Call
…
Calc(a, c, d, b);
}
Function Call and Return: Example
If the function returns a value, then the returned value need to be
assigned to a variable so that it can be stored. For example:
int GetUserInput (void); /* function prototype*/
void main(void) {
int input;
input = GetUserInput( );
}
However, it is perfectly okay (syntax wise) to just call the function
without assigning it to any variable if we want to ignore the returned
value.
We can also call a function inside another function. For example:
printf(“User input is: %d”, GetUserInput( ));
Basic Skeleton
#include <stdio.h>
void fn1(void)
//function prototype {
//global variable declaration local variable declaration;
statements;
void main(void) }
{
void fn2(void)
local variable declaration; {
local variable declaration;
statements;
statements;
fn1( ); }
fn2( );
}
Examples
A function may
Receive no input parameter and return nothing
Receive no input parameter but return a value
Receive input parameter(s) and return nothing Receive
input parameters(s) and return a value
Example 1: Receive nothing and Return nothing
#include <stdio.h>
void greeting(void); /* function
In this example, function
prototype */ greeting does not receive any
arguments from the calling
void main(void) function (main), and does not
{ return any value to the calling
greeting( ); function, hence type ‘void’ is
greeting( );
used for both the input
}
arguments and return data type.
void greeting(void) The output of this program is:
{
printf("Have fun!! \n"); Have fun!!
} Have fun!!
Example 2: Receive nothing and Return a value
#include <stdio.h> int getInput(void)
int getInput(void); {
int number;
printf("Enter a number:");
void main(void) scanf("%d",&number);
{
return number;
int num1, num2, sum;
}
num1 = getInput( );
num2 = getInput( ); Sample Output:
Enter a number: 3
sum = num1 + num2; Enter a number: 5
printf("Sum is %d\n",sum); Sum is 8
}
Example 3: Receive parameters and Return nothing
#include <stdio.h> int getInput(void)
int getInput(void); {
void displayOutput(int); int number;
void main(void) printf("Enter a number:");
{ scanf("%d",&number);
int num1, num2, sum; return number;
}
num1 = getInput();
num2 = getInput(); void displayOutput(int sum)
{
printf("Sum is %d \n",sum);
sum = num1 + num2;
}
Sample Output:
displayOutput(sum); Enter a number: 3
} Enter a number: 5
Sum is 8
Example 4: Receive parameters and Return a value
#include <stdio.h> int calSum(int val1, int val2)
int calSum(int,int); /*function protototype*/ /*function definition*/
{
void main(void) int sum;
{ sum = val1 + val2;
int sum, num1, num2;
return sum;
printf("Enter two numbers to calculate its sum:\n"); }
void greet() {
printf("Hello from the greet function!\n");
}
Output:
int main() { Hello from the greet function!
// base case
if (base condition) {
return base value;
}
// recursive case
return recursive expression involving function(modified
parameters);
}
Recursive Function: Example
#include <stdio.h>
void rec(int n) {
// Base Case Output:
if (n == 6) return; Recursion Level 1
Recursion Level 2
printf("Recursion Level %d\n", n); Recursion Level 3
rec(n + 1); Recursion Level 4
} Recursion Level 5
int main() {
rec(1);
return 0;
}
Recursive Function: Factorial Example
#include <stdio.h> int main() {
// Recursive function to calculate factorial int num;
// Prompt user to enter a non-negative integer
long long int factorial(int n) printf("Enter a non-negative integer: ");
{ scanf("%d", &num);
// Base case: factorial of 0 is 1 // Validate input
if (n == 0) { if (num < 0) {
return 1; printf("Factorial is not defined for negative numbers.\n");
} else
} else {
{
// Recursive case: n * factorial of (n-1) // Calculate and print the factorial
return n * factorial(n - 1); printf("Factorial of %d is %lld\n", num, factorial(num));
} }
} return 0;
} Enter a non-negative integer: 5
Factorial of 5 is 120
Macros
• In C programming, a macro is a segment of code that is
assigned a name and processed by the preprocessor
before the actual compilation.
• Macros are defined using the #define directive.
• When the preprocessor encounters a macro name in the
code, it replaces it with the corresponding code segment,
a process known as macro expansion.
Macros: Object-Like
There are primarily two types of macros:
Object-like Macros:
• These macros are used to define constants or simple values.
• They don't take any arguments.
Example: Output:
#include <stdio.h> Value of PI: 3.141590
#define PI 3.14159 // Defining a constant PI
int main() {
printf("Value of PI: %f\n", PI);
return 0;
}
In this example PI will be replaced by 3.14159 during preprocessing
Macros: Function-Like
Function-like Macros:
• These macros resemble functions and can take
arguments.
• They are often used for code reusability or to
create inline functions for performance
optimization.
Macros: Function-Like
Example In this example,
#include <stdio.h> SQUARE(num) expands to
#define SQUARE(x) ((x) * (x)) // Defining a macro to calculate square ((num) * (num)), and
int main() {
MAX(a, b) expands to ((a)
int num = 5;
int result = SQUARE(num); // Macro expansion: ((num) * (num))
> (b) ? (a) : (b)) during
printf("Square of %d is %d\n", num, result); preprocessing.
int a = 3, b = 7; The parentheses in
#define MAX(a, b) ((a) > (b) ? (a) : (b)) // Macro to find maximum of function-like macros are
two numbers
int main() {
float radius;
float area; Output:
printf("Enter the radius of the circle: "); Enter the radius of the circle: 5
scanf("%f", &radius); The area of the circle is: 78.54
// Calculate area using the defined macro
area = CIRCLE_AREA(radius);
printf("The area of the circle is: %.2f\n", area);
return 0;
}
Local and Global Variables
Local variables only exist within a function. After leaving the
function, they are ‘destroyed’. When the function is called
again, they will be created (reassigned).
Global variables can be accessed by any function within the
program. While loading the program, memory locations are
reserved for these variables and any function can access these
variables for read and write (overwrite).
If there exist a local variable and a global variable with the
same name, the compiler will refer to the local variable.
Local Variables: Example
#include <stdio.h>
int main() {
void displaySum() //function prototype and definition displaySum(); // Function call
{ return 0;
int a, b, sum; // Local variables }
void calSum(void);
} 3
void getInputs(void) Sum is 0
int sum, num1, num2; // Global Variables {
void main(void) printf("Enter num1 and num2:\n");
scanf("%d%d",&num1,&num2);
{ }
/* initialise sum to 0 */ void calSum(void)
initialise( ); {
sum = num1 + num2;
/* read num1 and num2 */
initialise( );
getInputs( );
calSum( ); } Imagine what would be the output of this
program if someone ‘accidently’ write the
printf("Sum is %d\n",sum); following function call inside calSum?
}
Structures and Unions
• Structures
Introduction to Structures
Structure Definition
Declaring and Initializing Structure variables
Accessing Structure members
Copying and comparison of Structures
Array of Structures
Arrays within Structures
Structures within structures
Structures and functions
• Unions
Introduction to Structure
What is a Structure?
• A structure in C is a user-defined data type that allows you to
group different types of data together under one name.
• It is used when you want to store information about a single
entity that has multiple attributes of different data types.
Introduction to Structures:
• Heterogeneous data to be stored together e.g student’s result
data
• Group logically related items to make the complex design more
meaningful
• Structure and unions are two different data types which hold
other data types in turn
Example Situation
Suppose you want to store information
about a student:
• Roll number (integer)
• Name (string)
• Marks (float)
You could use a structure to group these
together instead of using separate variables.
Structure Syntax (Definition)
struct structure_name {
data_type member1;
data_type member2;
...
data_type memberN;
};
Declaring and initializing Structure Variables
You can declare variables in two ways:
s1.roll_no = 101;
strcpy([Link], "Alice");
[Link] = 89.5;
return 0;
}
Copying and Comparison of Structures
Book Details:
Book 1: Name: Anil, Price: 20.50, Pages: 10
Book 2: Name: Shail, Price: 41.00, Pages: 20
Book 3: Name: Hinal, Price: 10.25, Pages: 5
Arrays within Structures
#include <stdio.h> // Assign values to the array of marks
#include <string.h> [Link][0] = 95;
[Link][1] = 88;
// Define a structure named Student [Link][2] = 92;
struct Student {
int roll_number; // --- Calculating and assigning the average ---
char name[50]; for (int i = 0; i < 3; i++) {
int marks[3]; // An array of integers to store marks for 3 subjects total_marks += [Link][i];
float average; }
}; [Link] = (float)total_marks / 3;
int main() { // --- Printing the data ---
// Declare a single variable of type struct Student printf("--- Student Information ---\n");
struct Student s1; printf("Roll Number: %d\n", s1.roll_number);
int total_marks = 0; printf("Name: %s\n", [Link]);
printf("Marks in 3 subjects: %d, %d, %d\n", [Link][0],
// --- Assigning values to the structure members --- [Link][1], [Link][2]);
printf("Average Marks: %.2f\n", [Link]);
// Assign a roll number
s1.roll_number = 101; return 0;
}
// Use strcpy to assign a string to the character array 'name'
strcpy([Link], "Alice");
Arrays within Structures
Output: