Module 3
Syllabus:
Functions - Function definition, Function call, Function prototype, Parameter passing;
Recursion; Passing array to function; Macros – Defining and calling macros; Command line
Arguments.
Structures - Defining a Structure variable, Accessing members, Array of structures, Passing
structure to function; Union.
Storage Class - Storage Classes associated with variables: automatic, static, external and
register.
Functions in C
● A function in C programming language is a self-contained block of code that
performs a specific task. Functions help divide a large program into smaller,
manageable parts.
● A function is a group of statements that are executed whenever the function is called.
Example:
Instead of writing the same code many times, we place it in a function and call it whenever
needed.
Structure of a Function
return_type function_name (parameter_list)
{
// body of the function
}
Components
Return type – Data type of value returned (int, float, void etc.)
Function name – Identifier of the function
Parameters – Inputs to the function
Function body – Statements that perform the task
Return statement – Sends value back to the caller
In C programming language, functions are mainly associated with three important
concepts:
1. Function Prototype
2. Function Definition
3. Function Call
1. Function Prototype/ Function Declaration
A function prototype declares the function to the compiler before the function is used.
It tells the compiler:
● Function name
● Return type
● Number and type of arguments
Syntax
return_type function_name(parameter_list);
Example
int add(int, int);
Here:
● int → return type
● add → function name
● (int, int) → parameters
Purpose:
It informs the compiler that the function exists somewhere in the program.
2. Function Definition
The function definition contains the actual body of the function where the task is
performed.
Syntax:
return_type function_name(parameters)
{
// statements
}
Example
int add(int a, int b)
{
int sum;
sum = a + b;
return sum;
}
Here:
● a and b are formal parameters
● The function calculates and returns the sum
3. Function Call
A function call is used to execute the function.
Syntax:
function_name(arguments);
Example
result = add(5,3);
Here:
● 5 and 3 are actual parameters
● The function executes and returns the value.
Example Program
#include <stdio.h>
int add(int, int); // Function Prototype
int main()
{
int result;
result = add(4,5); // Function Call
printf("Sum = %d", result);
return 0;
}
int add(int a, int b) // Function Definition
{
return a+b;
}
Output
Sum = 9
Actual parameters and Formal parameters
In C programming language, parameters are values passed to a function. They are of two
types:
● Actual Parameters (Actual Arguments)
● Formal Parameters
1. Actual Parameters
Actual parameters are the values or variables passed to a function when it is called.
They appear in the function call statement.
Example
sum = add(5, 3);
Here:
● 5 and 3 are actual parameters.
2. Formal Parameters
Formal parameters are the variables defined in the function definition that receive the values
from the actual parameters.
They appear in the function definition.
Example
int add(int a, int b)
{
return a + b;
}
Here:
● a and b are formal parameters.
Example:
#include <stdio.h>
int add(int a, int b); // Function prototype
int main()
{
int num1, num2, result;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
result = add(num1, num2); // Function call (actual parameters)
printf("Sum = %d", result);
return 0;
}
int add(int a, int b) // Function definition (formal parameters)
{
return a + b;
}
Write a program to find Square of a Number
#include <stdio.h>
int square(int n);
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Square = %d", square(num));
return 0;
}
int square(int n)
{
return n * n;
}
Write a program to find Area of Circle, Rectangle and Square Using Functions
#include <stdio.h>
float areaCircle(float r);
float areaRectangle(float l, float b);
float areaSquare(float s);
int main()
{
float r, l, b, s;
printf("Enter radius of circle: ");
scanf("%f", &r);
printf("Area of Circle = %.2f\n", areaCircle(r));
printf("Enter length and breadth of rectangle: ");
scanf("%f %f", &l, &b);
printf("Area of Rectangle = %.2f\n", areaRectangle(l, b));
printf("Enter side of square: ");
scanf("%f", &s);
printf("Area of Square = %.2f\n", areaSquare(s));
return 0;
}
float areaCircle(float r)
{
return 3.14 * r * r;
}
float areaRectangle(float l, float b)
{
return l * b;
}
float areaSquare(float s)
{
return s * s;
}
Menu driven program for addition,subtraction and multiplication using function
Output:
Parameter passing Methods
Based on parameters passed between caller program and the function, functions are
differentiated as “call by value” and “call by reference”
Call by Value
When a function call is made, only a copy of the values of the actual arguments is passed into
the called function. The value of the formal argument can be altered within the function but
the value of the actual argument does not change. This procedure for passing the value of an
argument to a function is known as call by value.
Swapping using Call by value(Pass by value)
#include <stdio.h>
void swap(int , int );
int main()
{
int x = 10, y = 20;
swap(x, y);
printf("In main after function call:\n");
printf("x = %d, y = %d\n", x, y);
return 0;
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf("Inside function after swap:\n");
printf("a = %d, b = %d\n", a, b);
}
Output:
Inside function after swap:
a = 20, b = 10
In main after function call:
x = 10, y = 20
Call by Reference(Pass by Reference)
The address of the argument is passed to the formal argument of the function. The parameters
receiving the address should be pointers. The process of calling a function using pointers to
pass the addresses of variables is known as “call by reference”.
Swapping using Call by reference
#include <stdio.h>
void swap(int *, int *);
int main()
{
int x = 10, y = 20;
swap(&x, &y); // passing addresses
printf("In main after function call:\n");
printf("x = %d, y = %d\n", x, y);
return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
printf("Inside function after swap:\n");
printf("a = %d, b = %d\n", *a, *b);
}
Output:
Inside function after swap:
a = 20, b = 10
In main after function call:
x = 20, y = 10
Passing arrays to functions (Arrays as function parameters)
To pass a one dimensional array to a function, it is sufficient to list the name of the array,
without any subscripts, and the size of the array as arguments.
For example, the call,
largest(a,n);
will pass the whole array a to the called function. The called function must be appropriately
defined.
The largest function header can be defined as:
float largest(float array[], int size)
The function is defined to take two arguments, the array name and the size of the array. The
declaration of the formal argument array is made as follows:
float array[];
The pair of brackets informs the compiler that the argument array is an array of numbers. It is
not necessary to specify the size of the array here.
In C, the name of the array represents the address of its first element. By passing the array
name, we are passing the address of the array to the called function. The array in the called
function refers to the same array stored in memory. Therefore, any changes to the array in the
called function will be reflected in the original way.
Recursion
Recursion is a process by which a function calls itself repeatedly, until some specified
condition has been satisfied.
In order to solve a problem recursively, two conditions must be satisfied. First, the problem
must be written in recursive form and second, the problem statement must include a stopping
condition.
For example, the function to evaluate factorial of n is as follows:
int find_factorial (int n)
{
int fact;
if (n==1)
return (1);
else
fact = n*factorial(n-1);
return (fact);
}
If n is taken as 3, the statement fact = n*factorial(n-1) will be executed with n=3.
Hence, fact = 3*factorial(2) will be evaluated. This includes a call to factorial(2), which will
return the following value 2*factorial(1)
Again factorial is called with n=1. This time, the function returns 1. Hence sequence of
operations are:
fact = 3* factorial(2)
= 3 * 2* factorial(1)
= 3* 2 *1
=6
Factorial of a number using recursion
#include <stdio.h>
int factorial(int n)
{
if (n == 0 || n == 1) // Base case
return 1;
else
return n * factorial(n - 1); // Recursive call
}
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial = %d", factorial(num));
return 0;
}
Output:
Enter a number: 5
Factorial = 120
Fibonacci Series using recursion
#include <stdio.h>
int fib(int);
int main()
{
int n, i;
printf("Enter number of terms: ");
scanf("%d", &n);
for(i = 0; i < n; i++)
{
printf("%d ", fib(i));
}
return 0;
}
int fib(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fib(n-1) + fib(n-2); // Recursive call
}
Output:
Enter number of terms: 5
01123
Macros in C
• The macro in C language is known as the piece of code which can be replaced by the macro
value.
• The macro is defined with the help of #define preprocessor directive and the macro
doesn’t end with a semicolon(;).
• Macro is just a name given to certain values or expressions it doesn't point to any memory
location.
• Whenever the compiler encounters the macro, it replaces the macro name with the macro
value. Two macros could not have the same name.
• The syntax of the macro is as shown in the following figure. Here, we will have the
three components:
1. #define - Preprocessor Directive
2. PI - Macro Name
3. 3.14 - Macro Value
Syntax : #define macro_name macro_value
Example : #define pi 3.14
Example Program:
#include <stdio.h>
#define a 10 //macro definition
int main()
{
printf("the value of a is: %d", a);
return 0;
}
Output : The value of a is: 10
From the above code, “a” is a macro name and 10 is the value. Whenever the compiler
encounters a macro name, it will replace it with the macro value.
Example Program 2 :
#include <stdio.h>
#define date 21 //macro definition
int main()
{
printf("Today's date is: %d/JULY/2025", date);
return 0;
}
Output:
Today’s date is: 21/JULY/2025
Types of Macros in C
• Object Like Macros
• Function Like Macros
Object Like Macros
A macro is replaced by the value in object-like macros. Generally, a defined value can be a
constant numerical value.
Let’s look at the examples of how object-like macros are used in c.
Example:
#include <stdio.h>
#define pi 3.14 //macro definition
int main()
{
int r = 4, area, circum;
circum = 2*pi*r;
area =pi*r*r;
printf("circumference of a circle is: %d \n", circum);
printf("area a circle is: %d", area);
return 0;
}
From the above-given code, pi is repeated two times in a program. First, it Calculates the
circumference of the circle and then calculates the area of the circle. So whenever a compiler
encounters the macro, it will replace it with the value 3.14, which is how an object like macros
works in c programming.
Output: circumference of a circle is:25
area a circle is:50
Function Like Macros
The way function call happen in C programs. Similarly, the function is defined in functions like
macros, and arguments are passed by the #define directive.
We will use the examples to help you understand how to use functions like macros in c.
Example Program:
#include <stdio.h>
#define add(a, b) (a + b) //macro definition
int main()
{
int a = 10, b = 15, result;
result = add(a, b);
printf("Addition of two numbers is: %d",result);
return 0;
}
OUTPUT : Addition of two numbers is: 25
Once the compiler finds the add (a,b) function, it will replace it with (a+b) and perform the
operation.
Command line arguments in C
Command line arguments are values supplied to a program when it is executed from the command
line or terminal. These arguments allow the user to pass input directly while running the program,
instead of entering input during execution.
In C, command line arguments are handled using the parameters of the main() function.
Syntax:
int main(int argc, char *argv[])
1. argc (Argument Count)
• argc stands for Argument Count.
• It stores the total number of arguments passed to the program.
• It is an integer variable.
• The program name itself is counted as the first argument.
Example:
./program 10 20 à argc=3
Because:
• argv[0] → program name (./program)
• argv[1] → 10
• argv[2] → 20
2. argv (Argument Vector)
• argv stands for Argument Vector.
• It is an array of pointers to characters.
• Each element of argv stores one command line argument as a string.
argv[0] → program name
argv[1] → first argument
argv[2] → second argument
argv[3] → third argument
Command:
./program apple mango orange
Memory:
argv[0] → "./program"
argv[1] → "apple"
argv[2] → "mango"
argv[3] → "orange"
Example program:
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
printf("Number of arguments = %d\n", argc);
for(i = 0; i < argc; i++)
{
printf("Argument %d = %s\n", i, argv[i]);
}
return 0;
}
Compile:
gcc test.c
Run Program
./[Link] one two three
Output:
Number of arguments = 4
Argument 0 = ./[Link]
Argument 1 = one
Argument 2 = two
Argument 3 = three
Structures
A structure is a user-defined data type in C that allows you to store different types of data
together.
Example:
● A student has: ID (int), Name (string), Marks (float)
● Instead of separate variables, we group them into one structure.
Defining a Structure
struct structure_name
{
data_type member1;
data_type member2;
...
};
Example:
struct Student
{
int id;
char name[50];
float marks;
};
Declaring Structure Variables
A structure variable declaration includes the following elements:
1. The keyword struct
2. The structure tag name
3. List of variable names separated by commas
4. A terminating semicolon
For example, the statement:
struct book_bank book1, book2, book3;
The above statement declares book1, book2 and book3 as variables of type struct book_
bank.
The complete declaration is given by:
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
struct book_bank book1, book2, book3;
Memory Allocation of Structure
● The memory allocated to a structure is equal to the sum of the sizes of all its
members.
● Total size = Sum of sizes of all members
Eg:
Array v/s Structures
Feature Array Structure
Data Type Homogeneous (same type) Heterogeneous (different types)
Purpose Store similar data Store related different data
Access Using index (arr[i]) Using member name ([Link])
Memory Continuous same-type memory Combined memory of all members
User-defined No Yes
Complexity Simple More flexible
Accessing members
● After defining and declaring a structure, you can access its members using Dot
Operator (.)
● Used when you have a structure variable
Syntax:
structure_variable.member_name
Example:
#include <stdio.h>
struct Student
{
int id;
float marks;
};
int main()
{
struct Student s1;
printf("Enter ID: ");
scanf("%d", &[Link]);
printf("Enter Marks: ");
scanf("%f", &[Link]);
printf("\n--- Student Details ---\n");
printf("ID: %d\n", [Link]);
printf("Marks: %.2f\n", [Link]);
return 0;
}
Array of structures
An array of structures is a collection of structure variables of the same type stored in
contiguous memory locations.
Use when you need to store multiple records of the same type.
Example:
● Many students (ID, Name, Marks)
● Many employees
Syntax:
struct structure_name array_name[size];
Example:
struct Student
{
int id;
float marks;
};
struct Student s[3];
Write a C program using structure, read and print data of n employees (Name,
Employee Id and Salary)
Passing a structure to a function
Passing a structure to a function means providing the structure variable to a function so
that the function can access the structure’s members.
Syntax:
void functionName(struct StructName s);
Example:
#include <stdio.h>
struct Student
{
int id;
float marks;
};
void display(struct Student s)
{
printf("\nInside Function:\n");
printf("ID: %d\n", [Link]);
printf("Marks: %.2f\n", [Link]);
}
int main()
{
struct Student s1;
printf("Enter ID: ");
scanf("%d", &[Link]);
printf("Enter Marks: ");
scanf("%f", &[Link]);
display(s1);
return 0;
}
Output:
Enter ID: 101
Enter Marks: 95.5
Inside Function:
ID: 101
Marks: 95.50
Write a c program to define a structure Book(title, author,price). Write a function
to accept and display a book's details
#include <stdio.h>
struct Book
{
char title[50];
char author[50];
float price;
};
void displayBook(struct Book b)
{
printf("\n--- Book Details ---\n");
printf("Title : %s\n", [Link]);
printf("Author: %s\n", [Link]);
printf("Price : %.2f\n", [Link]);
}
int main()
{
struct Book b1;
printf("Enter Title: ");
scanf(" %[^\n]", [Link]); // %[^\n] reads string with spaces
printf("Enter Author: ");
scanf(" %[^\n]", [Link]);
printf("Enter Price: ");
scanf("%f", &[Link]);
displayBook(b1);
return 0;
}
Union
Union is a user-defined data type, similar to a structure, but all members share the same
memory location.
Only one member can hold a value at a time.
Syntax:
union UnionName
{
data_type1 member1;
data_type2 member2;
...
};
Memory Allocation
● The size of a union = size of its largest member.
● Example:
●
● union Data
● {
● int i; // 4 bytes
● double d; // 8 bytes
● char c; // 1 byte
● };
● Size of union = 8 bytes (largest member: double)
Accessing Union Members
● Use dot operator for variables.
● Only one member can store a value at a time.
Example:
union Data d;
d.i = 5;
printf("%d\n", d.i);
d.f = 2.5; // overwrites d.i
printf("%.2f\n", d.f);
Explain with an example how a union saves memory compared to a structure
Structure: Memory is allocated for all members separately.
● Total size = sum of sizes of all members
Union: Memory is allocated only once for the largest member.
● All members share the same memory location.
Example
Suppose we want to store an int, a float, and a char:
#include <stdio.h>
// Structure
struct MyStruct
{
int i; // 4 bytes
float f; // 4 bytes
char c; // 1 byte
};
// Union
union MyUnion
{
int i; // 4 bytes
float f; // 4 bytes
char c; // 1 byte
};
int main()
{
struct MyStruct s;
union MyUnion u;
printf("Size of structure: %d bytes\n", sizeof(s));
printf("Size of union: %d bytes\n", sizeof(u));
return 0;
}
Output:
Size of structure: 12 bytes
Size of union: 4 bytes
Structure allocates memory for all members individually.
Union allocates memory for only the largest member, saving memory.
Declare a union containing 5 string variables (Name, House Name, City Name, State
and Pin code) each with a length of C_SIZE (user defined constant). Then, read and
display the address of a person using a variable of the union.
Storage classes
In C, a storage class defines where a variable is stored, its lifetime, scope, and
visibility in a program.
1. Scope
Scope is the region of the program where a variable can be accessed.
Types of Scope
1. Local Scope
o Variable declared inside a function or block.
o Accessible only within that block.
Example
#include <stdio.h>
int main()
{
int a = 10; // local variable
printf("%d", a);
}
2. Global Scope
o Variable declared outside all functions.
o Accessible by all functions in the program.
Example
#include <stdio.h>
int a = 20; // global variable
int main()
{
printf("%d", a);
}
2. Lifetime
Lifetime is the time during program execution when a variable exists in memory.
Types
• Automatic lifetime
o Created when a function starts.
o Destroyed when the function ends.
• Static lifetime
o Exists from the start to the end of the program.
Example
void fun()
{
int x = 5; // lifetime only during function execution
}
3. Visibility
Visibility means where the variable can be seen or used in the program.
• A local variable is visible only inside its function or block.
• A global variable is visible to all functions unless restricted.
Example
int x = 10; // visible to all functions
void fun()
{
printf("%d", x);
}
Types of Storage Classes in C
auto
register
static
extern
Storage Default
Scope Lifetime Storage
Class Value
Local (inside Till block Garbage
auto Stack
function/block) execution value
Till block Garbage CPU register (if
register Local
execution value possible)
Entire program
static Local/Global 0 Data segment
execution
Entire program
extern Global 0 Data segment
execution
1. auto Storage Class
• Default storage class for local variables.
• Declared inside functions.
Example:
#include <stdio.h>
int main()
{
auto int x = 10;
printf("%d", x);
return 0;
}
Characteristics
• Scope: Inside the function/block.
• Lifetime: Exists only during function execution.
2. register Storage Class
• Requests the compiler to store variable in CPU register for faster access.
Example:
#include <stdio.h>
int main()
{
register int i;
for(i=0;i<5;i++)
printf("%d ",i);
return 0;
}
Characteristics
• Faster access.
• Address (&) of register variable cannot be taken.
3. static Storage Class
• Variable retains its value between function calls.
Example:
#include <stdio.h>
void fun()
{
static int x = 0;
x++;
printf("%d ",x);
}
int main()
{
fun();
fun();
fun();
}
Output
123
Characteristics
• Lifetime: Entire program.
• Scope: Only inside the function.
4. extern Storage Class
• Used to declare a global variable defined in another file or location.
Example:
#include <stdio.h>
extern int x;
int x = 20;
int main()
{
printf("%d", x);
}
Characteristics
• Used for global variables.
• Lifetime: Entire program execution.