0% found this document useful (0 votes)
9 views40 pages

C Programming Functions Explained

The document provides an overview of functions in C programming, explaining their definition, types (library and user-defined), and rules for usage. It covers function declaration, calling, and the concepts of call by value and call by reference, along with examples. Additionally, it introduces recursion, detailing how functions can call themselves to solve problems.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views40 pages

C Programming Functions Explained

The document provides an overview of functions in C programming, explaining their definition, types (library and user-defined), and rules for usage. It covers function declaration, calling, and the concepts of call by value and call by reference, along with examples. Additionally, it introduces recursion, detailing how functions can call themselves to solve problems.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 3

Functions

By Prof. Prerna Solanke


Introduction A function is a self-contained block of
statements that perform a coherent task
of some kind.
Using a function is something like hiring a
person to do a specific job for you.
void main( )
{
message( ) ; here, main()
printf(" Study hard, and success will follow! "); becomes the
} ‘calling’ function,
message( ) whereas
{ message()
printf("\nWake up early, and make your day better..."); becomes the
} ‘called’ function.
Types:

There are basically two types of functions:


● Library functions: the in-built function in C programming
Ex. printf( ), scanf( ) etc.
● User-defined functions Ex. message( ), greet( ) etc.
Call to more than 1 // function definitions
void greet()
one function : {
printf("Hello!\n");
}
void display()
2 {
printf("Welcome to VESIT\n");
int main() }
{ void goodbye()
greet(); // call first function {
display(); // call second function printf("See you again soon.\n");
goodbye(); // call third function }
return 0;
}
Call to more than // function definitions
one function : void greet()
{
// function declarations printf("Hello!\n");
void greet(); }
void display(); void display()
void goodbye(); {
int main() printf("Welcome to VESIT\n");
{ }
greet(); // call first function void goodbye()
display(); // call second function {
goodbye(); // call third function printf("See you again soon.\n");
return 0; }
}
Rules:
● Any C program contains at least one function. If a program contains only
one function, it must be main( ).
● If a C program contains more than one function, then one of these
functions must be main( ), because program execution always begins with
main( ).
● There is no limit on the number of functions that might be present in a C
program.
● Each function in a program is called in the sequence specified
by the function calls in main( ).
● After each function has done its thing, control returns to main( ).
Rules:
void main( )
{ Here, even though message1( ) is
message1( ) ; getting called before message2( ),
message2( ) ; still, message1( ) has been defined
} after message2( ).
message2( ) However, it is advisable to define
{ the functions in the same order in
printf ( "Butter was bitter" ) ; which they are called. This makes
} the program easier to understand.
message1( )
{
printf ( "Mary bought some butter" ) ;
}
Rules:
main( )
A function can be called from other
{
function, but a function cannot be
printf ( "I am in main" ) ;
defined in another function.
argentina( )
Thus, this program code would be
{
wrong, since argentina( ) is being
printf ( "I am in argentina" ) ;
defined inside another function,
}
main( ).
}

A function can call itself. Such a


process is called ‘recursion’. ….. Will be covered in later slides
Rules: This is an example of infinite recursion — a
function keeps calling itself (directly or
Any function can be called from any indirectly) without a stopping condition.
other function. Even main() can be ● The program starts with main().
called from other functions. ● main() calls greet().
● Inside greet(), you print "Hello" and then call
void main() main() again.
{ ● That new main() again calls greet(), and the
greet(); cycle repeats forever:
} main() → greet() → main() → greet() → ...
void greet() ● Each time this happens, "Hello" gets printed
{ — leading to infinite output until your
printf("Hello!\n"); system crashes or you stop the program.
main();
}
Rules:
main( )
{ A function can be called from other
printf ( "\nI am in main" ) ; function, but a function cannot be
argentina( ) defined in another function.
{ Thus, this program code would be
printf ( "\nI am in argentina" ) ; wrong, since argentina( ) is being
} defined inside another function,
} main( ).
Elements of Function:

The Three Elements of User Defined function structure


consists of :
1. Function Definition
2. Function Declaration
3. Function calling
Elements of Function:
Function Definition: A program Module written to achieve a specific task
is called as function definition.
Syntax: Example:
Datatype functionname(parameters) void add()
{ {
declaration part; int sum,a,b;
executable part; printf(“enter a and b\n”);
return statement; scanf(“%d%d”,&a,&b);
} sum=a+b;
printf(“sum is %d”,sum);
}
Elements of Function:
Function Declaration: The process of declaring the function before they
are used is called as function declaration or function prototype.
Syntax:
Datatype functionname(type p1,type p2,………type pn);
Example:
int add(int a, int b);
void add(int a, int b);
Note: The function declaration should end with a semicolon ;
Elements of Function:
Function Calling: A function call is defined as function name followed by
semicolon. It is nothing but invoking a function at the required place in the
program to achieve a specific task.
Syntax:
Example:
void main()
{
add( ); // function call without parameter
}
Example:
#include <stdio.h>
#include <stdio.h> void greet(); //Function declaration
(prototype)
void greet() //Function define int main()
{ {
printf("Hello, welcome!"); greet(); // Function call
OR return 0;
}
}
int main() void greet() // Function def after main
{ {
greet(); // Function call printf("Hello, welcome!");
return 0; }
}
Example:
void swap(int, int ); // function declaration
void main( )
{
int a=10, b=20;
swap(a, b); // function calling
printf(“ %d %d \n”, a, b);
}
void swap (int x, int y) // function definition
{
int temp = x;
x= y;
y=temp;
}
Practice programs:
#include <stdio.h>

int square(int n)
Function to find the square of {
a number return n * n;
}

int main()
{
printf("Square = %d\n", square(4));
return 0;
}
Practice programs:
void checkEven(int n)
{
if(n % 2 == 0)
Function to check if a number printf("%d is even\n", n);
is even else
printf("%d is odd\n", n);
}
int main()
{
checkEven(7);
checkEven(10);
return 0;
}
The variables defined in the function header of function definition are called
formal parameters.
The variables that are used when a function is invoked in function call are
called actual parameters.
Call by Value and Call by Reference
Call by Value #include <stdio.h>
void change(int x) {
In call by value method, we can x = 10; // only local copy is changed
not modify the value of the }
actual parameter by the formal int main() {
parameter. int a = 5;
In this, different memory is printf("Before function call: %d\n", a);
allocated for actual and formal change(a); // call by value
parameters. printf("After function call: %d\n", a);
return 0;
}
Call by Value
Call by Value Example

void fun(int x, int y) // formal parameter


{
x = 20;
y = 10;
}
int main()
{
int x = 10, y = 20;
fun(x, y); // actual parameter
printf("x = %d and y = %d\n", x, y);
return 0;
}
Practice Example
void square(int n)
{
n = n * n;
printf("Inside function: n = %d\n", n);
}
int main()
{
int num = 4;
printf("Before function call: num = %d\n", num);
square(num); // call by value
printf("After function call: num = %d\n", num);
return 0;
}
Practice Example Function to calculate square using Call by Value

int square(int n)
{
n = n * n;
return n; // returning the square value
}
int main() {
int num=5,sq;
sq=square(num);
printf("Square is %d", sq);
return 0;
}
Practice Example Swapping of two numbers using Call by Value

void swap(int a, int b) {


int temp;
temp = a;
a = b;
b = temp;
printf("Inside function (after swapping): a = %d, b = %d\n", a, b);
}
int main() {
int a = 10, b = 20;
printf("Before function call: a = %d, b = %d\n", a, b);
swap(a, b);
printf("After function call: a = %d, b = %d\n", a, b);
return 0;
}
Concept of Pointer Note that printing the value of *( &i ) is same as
printing the value of i.

A pointer is a variable that stores the memory address of #include <stdio.h>


another variable. int main() {
Instead of holding a direct value like an int or char, a
int x=100;
pointer holds the location where that value is stored in
the computer's memory.
int *y=&x;
A pointer variable is declared by placing an asterisk (*) printf("%d\n",x);
before the variable name. printf("%d\n",&x);
Syntax: printf("%d\n",y);
data_type *pointer_name;
printf("%d",*y);
Example:
int i = 3; return 0;
int *ptr = &i; }
Call by Reference Instead of passing values, we pass addresses.

In call by reference, the void set(int *ptr)


address of the variable is {
passed into the function *ptr = 10; // value at the address is changed
call as the actual }
parameter. int main()
In this, the memory {
allocation is same for both int a = 5;
formal parameters and printf("Before function call: %d\n", a);
actual parameters. set(&a); // call by reference using address
printf("After function call: %d\n", a);
return 0;
}
Call by Reference example:

void fun(int *ptr1, int *ptr2)


{
*ptr1 = 20;
*ptr2 = 10;
}
int main()
{
int x = 10, y = 20;
fun(&x, &y);
printf("x = %d and y = %d\n", x, y);
return 0;
}
Practice example:
void swap(int *a, int *b) { Swapping of two
int temp; numbers using Call by
temp = *a; Reference
*a = *b;
*b = temp;
}
int main() {
int a = 10, b = 20;
printf("Before swapping: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
Practice example:
void square(int *n)
{
*n = (*n) * (*n);
printf("Inside function: n = %d\n", *n);
}
int main()
{
int num = 4;
printf("Before function call: num = %d\n", num);
square(&num); // call by reference
printf("After function call: num = %d\n", num);
return 0;
}
Recursion:

Recursion is a process in which a function calls itself


directly or indirectly to solve a problem.
In C programming, recursion is often used when a
problem can be broken down into smaller, similar
subproblems.
Each time the function calls itself, a new copy of that
function is created in the memory stack with new local
variables.
Recursion:
Syntax:
return_type function_name(parameters)
{
if (base_condition)
return value; // stopping condition
else
return function_name(modified_parameters); // recursive call
}

Base condition: The condition that stops recursion. Without it, the recursion
continues forever (infinite loop).
Recursive call: The function calls itself with modified parameters to move toward
the base condition.
Recursion:

void show()
{
printf("Hello\n");
show(); // function calling itself again This program will print "Hello"
} infinite times because there’s
int main() no stopping condition (no if
{ statement to stop recursion).
show(); It keeps calling itself forever
return 0; until the program crashes due
to stack overflow.
}
Recursion:
void show(int n)
{
if (n == 0)
return; // stop recursion
printf("Hello\n");
show(n - 1); // call itself again
} ● show(3) prints once and
int main() calls show(2)
{ ● then show(1)
show(3); // prints "Hello" 3 times ● stops when n becomes 0.
return 0;
} So it’s a safe recursion example
Recursion: Find the sum of first N natural numbers using
recursion.
// Function declaration
int sum(int n);
int main() {
int num;
printf("Enter a positive number: ");
scanf("%d", &num);
printf("Sum of first %d natural numbers is: %d\n", num, sum(num));
return 0;
How It Works (for n = 5)
}
sum(5)
// Recursive function definition = 5 + sum(4)
int sum(int n) { = 5 + (4 + sum(3))
if (n == 0) // base condition = 5 + (4 + (3 + sum(2)))
return 0; = 5 + (4 + (3 + (2 + sum(1))))
else = 5 + 4 + 3 + 2 + 1 + sum(0)
return n + sum(n - 1); // recursive call = 15
}
Thank You
Questions?

You might also like