PRINCIPLES OF
PROGRAMMING IN C
22CS2ESPOP - UNIT 3 PART 1
Prof. SNEHA S BAGALKOT
Assistant Professor, Dept. of CSE
UNIT – 3: Functions and Arrays
▪ Introduction
▪ Using Functions
▪ Components of Functions (Function Declaration, Function Definition,
Function Call)
▪ Passing Parameters to Functions
▪ Example Programs
Introduction to Functions
• Every C program should consist of one or more functions. Among
these functions main() function is compulsory. All programs start
execution from main function.
Functions
• A function is a block of code to perform a specific task.
• Every c program has at least one function main(). Without main() function, there is
technically no c program.
• In modular programming, the program is divided into separate small programs
called modules.
• Each module is designed to perform a specific task.
• Modules make our actual program shorter. Hence easier to read and write.
Introduction
• C enables its programmers to break up a program into segments
commonly known as functions, each of which can be written more or less
independently of the others.
• Every function in the program is supposed to perform a well defined task.
Therefore, the program code of one function is completely insulated from
that of other functions.
• Every function has a name which acts as an interface to the outside world
in terms of how information is transferred to it and how results generated
by the function are transmitted back from it. This interface is specified by
the function name.
Introduction (Contd..)
• In the fig, main() calls another function, func1() to perform a well defined
task.
• main() is known as the calling function and func1() is known as the called
function.
• When the compiler encounters a function call, instead of executing the next
statement in the calling function, the control jumps to the statements that
are a part of the called function.
• After the called function is executed, the control is returned back to the
calling program. main() func1()
{ {
………….. Statement Block;
………….. }
func1();
…………
………..
return 0;
}
Introduction (Contd..)
● It is not necessary that the main() can call only one function, it can call as many
functions as it wants and as many times as it wants. For example, a function call
placed within a for loop, while loop or do-while loop may call the same function
multiple times until the condition holds true.
● It is not that only the main() can call another functions. Any function can call any
other function. In the fig. one function calls another, and the other function in turn
calls some other function.
main() func1() func2() func3()
{ { { {
………….. ……….. ……….. ………..
………….. ………… ………. ……….
func1(); func2(); func3(); ………..
………… ……….. ……….. return;
……….. ………. ………. }
return 0; return; return;
} } }
Top-down modular programming using functions
Advantages of Functions
Functions based modular programming is advantageous in many ways:
• Managing huge programs and software packages is easier by dividing them into
functions/modules—Maintenance is easier
• Error detection is easier—Debugging is easier
• Functions once written can be re-used in any other applications – Reusability is
enhanced
• We can protect our data from illegal users—Data protection becomes easier
Modular programming
• Modular programming is defined as organizing a large program into small,
independent program segments called modules that are separately named and
individually callable program units.
• It is basically a “divide-and-conquer” approach to problem solving.
Characteristics of Modular programming:
1. Each module should do only one thing.
2. Communication between modules is allowed only by calling module.
3. No communication can take place directly between modules that do not have
calling-called relationship.
4. All modules are designed as single-entry, single-exit systems using control
structures.
5. A module can be called by one and only higher module.
Function types
1. Built-in (Library/ Pre-defined) function
2. User defined function
Why Do We Need Functions?
• Dividing the program into separate well defined functions facilitates
each function to be written and tested separately. This simplifies the
process of getting the total program to work.
• Understanding, coding and testing multiple separate functions are far
easier than doing the same for one huge function.
• If a big program has to be developed without the use of any function
(except main()), then there will be countless lines in the main() .
• All the libraries in C contain a set of functions that the programmers
are free to use in their programs. These functions have been prewritten
and pre-tested, so the programmers use them without worrying about
their code details. This speeds up program development.
Advantages of user defined functions
• Decompose the large program into small segments which makes the programmer
easier to understand, maintain and debug.
• If repeated code occurs in a program, then function can include those codes and
execute when needed by calling that function.
• Programmer working on large project can divide the workload by making different
functions.
Terminology of Functions
• A function, f that uses another function g, is known as the calling function
and g is known as the called function.
• The inputs that the function takes are known as arguments.
• When a called function returns some result back to the calling function, it is
said to return that result.
• The calling function may or may not pass parameters to the called function. If
the called function accepts arguments, the calling function will pass
parameters, else not.
• Main() is the function that is called by the operating system and therefore, it is
supposed to return the result of its processing to the operating system.
Components of Functions
▪ Function Declaration
▪ Function Definition
▪ Function Call
Function Declaration
• Function declaration is a declaration statement that identifies a function with its
name, a list of arguments that it accepts and the type of data it returns.
• The general format for declaring a function that accepts some arguments and
returns some value as result can be given as:
return_data_type function_name(data_type variable1,
data_type variable2,..);
• No function can be declared within the body of another function.
Example, float avg ( int a, int b);
Function Definition
• Function definition consists of a function header that identifies the function, followed
by the body of the function containing the executable code for that function.
• When a function defined, space is allocated for that function in the memory.
• The syntax of a function definition can be given as:
return_data_type function_name(data_type var1, data_type var2,..)
{ ………….
statements
………….
return( variable);
}
• The no. and the order of arguments in the function header must be same as that given
in function declaration statement.
Function Call
• The function call statement invokes the function.
• When a function is invoked the compiler jumps to the called function to execute
the statements that are a part of that function.
• Once the called function is executed, the program control passes back to the
calling function.
• Function call statement has the following syntax.
function_name(variable1, variable2, …);
Function Call
Points to remember while calling the function:
• Function name and the number and type of arguments in the function call must be
same as that given in the function declaration and function header of the function
definition.
• Names (and not the types) of variables in function declaration, function call and
header of function definition may vary.
• Arguments may be passed in the form of expressions to the called function. In
such a case, arguments are first evaluated and converted to the type of formal
parameter and then the body of the function gets executed.
• If the return type of the function is not void, then the value returned by the called
function may be assigned to some variable as given below.
variable_name = function_name(variable1, variable2, …);
Return Statement
● The return statement is used to terminate the execution of a function and return control
to the calling function. Programming Tip: It is an error to use a return statement in a
function that has void as its return type.
● A return statement may or may not return a value to the calling function. Syntax: return
<expression> ;
● Expression is placed in between angular brackets because specifying an expression is
optional. The value of expression, if present, is returned to the calling function.
However, in case expression is omitted, the return value of the function is undefined.
● Programmer may or may not place the expression within parentheses. By default, the
return type of a function is int.
● For functions that has no return statement, the control automatically returns to the
calling function after the last statement of the called function is executed.
Program That Uses Function
#include<stdio.h>
int sum(int a, int b); // FUNCTION DECLARATION
int main()
{
int num1, num2, total = 0;
printf(“\n Enter the first number : “);
scanf(“%d”, &num1);
printf(“\n Enter the second number : “);
scanf(“%d”, &num2);
total = sum(num1, num2); // FUNCTION CALL
printf(“\n Total = %d”, total);
return 0;
}
// FUNCTION DEFINITION
int sum ( int a, int b) // FUNCTION HEADER
{ // FUNCTION BODY
return (a + b);
}
Basic structure of C program with functions
Actual and Formal parameters/arguments
• Arguments refer to data that is passed to function(function definition)
while calling
• Arguments listed in function call are referred to as actual arguments.
• The arguments used in function declaration are called formal
parameters/arguments. They receive values from actual parameters
• The number of actual and formal arguments and their datatypes
should always be same.
Function Call Example
• A function call is a statement that instructs the compiler to execute the function. We use the
function name and parameters in the function call.
• In the below example, the first sum function is called and 10,30 are passed to the sum
function. After the function call sum of a and b is returned and control is also returned back to
the main function of the program.
Types of User-defined Functions in C Programming
• In C programming language, functions can be called either with or without arguments
and might return values. They may or might not return values to the calling functions.
• Function with no arguments and with no return value
• Function with no arguments and with return value
• Function with argument and with no return value
• Function with arguments and with return value
Void Functions without parameters – No arguments and no return values
• When a function has no arguments, it does not receive any data from
the calling function.
• Similarly, when it does not return a value, the calling function does
not receive any data from the called function.
Example 1: function with no argument and
with no return type
#include<stdio.h>
void sum()
{
int a, b, c;
printf("Enter two numbers:\n");
scanf("%d%d", &a, &b);
c = a + b;
printf("The sum of %d and %d = %d\n", a, b, c);
}
void main()
{
sum(); // function with no argument and with no return type
}
Functions without parameters and with return
values – No arguments but returns values
• The calling function does not send any data to called function and
but, accepts the return values from called function
Example 2: function with no argument and with
return type
#include<stdio.h>
int sum()
{
int x, y;
printf("Enter two numbers:\n");
scanf("%d%d", &x, &y);
return (x + y);
}
void main()
{
int result;
result = sum(); // function with no argument and with return type
printf("Sum = %d\n", result);
}
Void Functions with parameters – Arguments but no return values
• The calling function accepts the input, checks its validity and pass it
on to the called function.
• The called function does not return any values back to calling
function.
• The actual and formal arguments should match in number, type and
order.
Example 3: function with argument and with
no return type
#include<stdio.h>
void sum(int x, int y)
{
int result;
result = x + y;
printf("sum = %d\n", result);
}
void main()
{
int a, b;
printf("Enter two numbers:\n");
scanf("%d%d", &a, &b);
sum(a, b); // function with argument and with no return type
}
Functions with parameters and return values –
Arguments with return values
• The calling function sends the data to called function and also accepts
the return values from called function.
• Actual Parameters: When a function is called, the values that are
passed in the call are called actual parameters.
• Formal Parameters: The values which are received by the function,
and are assigned to formal parameters.
Example 4: function with argument and
with return type
#include<stdio.h>
int sum(int x, int y)
{
return ( x + y );
}
void main()
{
int a, b, result;
printf("Enter two numbers:\n");
scanf("%d%d", &a, &b);
result = sum( a , b ); // function with argument and with return type
printf("Sum = %d\n", result);
}
Swapping two values-call by value
Swapping two values-call by reference
Passing Parameters to Functions
• In C, there are two types of parameters and they are as follows...
• Actual Parameters
• Formal Parameters
• The actual parameters are the parameters that are specified in calling function.
• The formal parameters are the parameters that are declared at called function. When a
function gets executed, the copy of actual parameter values are copied into formal parameters.
In C Programming Language, there are two methods to pass parameters from calling function to
called function and they are as follows...
• Call by Value
• Call by Reference
Passing Parameters to the Function
• There are two ways in which arguments or parameters can be passed to the
called function.
• Call by value in which values of the variables are passed by the calling function to
the called function.
• Call by reference in which address of the variables are passed by the calling
function to the called function.
Passing parameters to function
Call by value Call by reference
Inter-Function Communication
•Two functions can communicate with each other by
two methods:
•By Passing parameters as values (Pass by value)
•By passing parameters as address (Pass by address)
Swapping two values-call by value
Call By Value
● In the Call by Value method, the called function creates new variables to
store the value of the arguments passed to it.
● Therefore, the called function uses a copy of the actual arguments to
perform its intended task.
● If the called function is supposed to modify the value of the parameters
passed to it, then the change will be reflected only in the called function.
● In the calling function no change will be made to the value of the variables.
Call by Value
• In call by value parameter passing method, the copy of actual parameter values are copied to
formal parameters and these formal parameters are used in called function. The changes made
on the formal parameters does not effect the values of actual parameters. That means, after
the execution control comes back to the calling function, the actual parameter values remains
same.
• Example Program:
Call By Value (Contd..)
#include<stdio.h>
void add( int n);
int main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
void add(int n)
{
n = n + 10;
printf("\n The value of num in the called function = %d", n);
}
The output of this program is:
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 2
Call By Value (Contd..)
The following points are to be noted while passing arguments to a function using the
call-by-value method.
∙ When arguments are passed by value, the called function creates new variables of
the same data type as the arguments passed to it.
∙ The values of the arguments passed by the function are copied into the newly
created variables.
∙ Arguments are called by value when the called function does not need to modify the
values of the original variables in the calling function.
∙ Values of the variables in the calling function remain unaffected when the arguments
are passed by using call-by-value technique.
Call By Value (Contd..)
∙ Therefore, call-by-value method of passing arguments to a function must be
used only in two cases:
o When the called function does not need to modify the value of the actual
parameter. It simply uses the value of the parameter to perform its task.
o When we want the called function should only temporarily modify the
value of the variables and not permanently. So although the called
function may modify the value of the variables, these variables remain
unchanged in the calling function.
Ex 2: By Passing parameters as values (Pass by
value):
• In pass by value calling function sends the copy of parameters( Actual
Parameters) to the called function (Formal Parameters).
• The change does not affect the actual value.
Call By Reference
● When the calling function passes arguments to the called function using
call by value method, the only way to return the modified value of the
argument to the caller is explicitly using the return statement. The better
option when a function can modify the value of the argument is to pass
arguments using call by reference technique.
● In call by reference, we declare the function parameters as references
rather than normal variables. When this is done any changes made by the
function to the arguments it received are visible by the calling program.
● To indicate that an argument is passed using call by reference, an
ampersand sign (&) is placed after the type in the parameter list. This way,
changes made to that parameter in the called function body will then be
reflected in its value in the calling program.
Call by Reference
• In Call by Reference parameter passing method, the memory location address of the
actual parameters is copied to formal parameters. This address is used to access the
memory locations of the actual parameters in called function.
• In this method of parameter passing, the formal parameters must be pointer variables.
• That means in call by reference parameter passing method, the address of the actual
parameters is passed to the called function and is received by the formal parameters
(pointers).
• Whenever we use these formal parameters in called function, they directly access the
memory locations of actual parameters. So the changes made on the formal parameters
effects the values of actual parameters.
Swapping two values-call by reference
Program Illustrating Call By Reference Technique
#include<stdio.h>
void add( int *n);
int main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(&num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}
void add( int *n)
{
*n = *n + 10;
printf("\n The value of num in the called function = %d", *n);
}
The output of this program is:
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 12
Functions with parameters and return values – Arguments with return values
• The calling function sends the data to called function and also accepts
the return values from called function.
• Actual Parameters: When a function is called, the values that are
passed in the call are called actual parameters.
• Formal Parameters:The values which are received by the function,
and are assigned to formal parameters.
Ex 2: By Passing parameters as address (Pass
by address)
• In pass-by-reference the calling function sends the address of
parameters (Actual Parameters) to the called function (Formal
Parameters).
• The change affects the actual value.
Nesting of Functions
• A function within a function is called as nesting of functions.
Example Programs
Write a C program to find factorial of a number
using functions.
#include<stdio.h> int fact()
#include<math.h> {
int main() int i, fact=1,n;
{ scanf("%d", &n);
for(i = 1; i <= n; i ++)
printf("Enter a Number to Find Factorial: ");
{
printf("\n Factorial of a Given Number is: %d ",fact());
fact = fact * i;
return 0;
}
} return fact;
}
C Program To Find Biggest of Three Numbers using
Function
#include<stdio.h> // function definition
int biggest(int x, int y, int z)
int biggest(int, int, int); // function prototype
{
int main() if(x > y && x > z)
{ {
int a, b, c; return x;
printf("Enter 3 integer numbers\n"); }
else
scanf("%d%d%d", &a, &b, &c);
{
//function call biggest(a, b, c) if(y > z)
printf("Biggest of %d, %d and %d is %d\n", return y;
a, b, c, biggest(a, b, c)); else
return 0; return z;
} }
}
C Program using function to find the area of circle
# include < stdio.h >
# include < conio.h > float area(float r)
{
float area(float) ;
int main( ) float ar ;
{ ar = 3.14 * r * r ;
return ar ;
float r, ar = 0.0 ;
printf(" Enter the radius of circle : ") ; }
scanf("%f", &r) ;
ar = area(r) ;
printf("\n Area of circle : %f ", ar) ;
return (0);
}
C Program using function to find the area of square,
rectangle and triangle
C Program to check even or odd number
#include <stdio.h> /* If isEven() function returns 0 then the
int isEven(int num) number is even */
{ if(isEven(num))
return !(num & 1); {
} printf("The number is even.");
int main() }
{ else
int num; {
printf("The number is odd.");
/* Input number from user */ }
printf("Enter any number: ");
scanf("%d", &num); return 0;
}
Program to generate all prime numbers till the
number n using functions
void genprime(int n)
#include<stdio.h> {
void genprime(int n); int i, j, flag;
void main() for(i=1; i <= n; i++)
{ {
flag=0;
int n; for(j = 2; j <= i/2; j++)
printf("\n Enter the value of n: "); {
scanf("%d", &n); if(i % j == 0)
{
flag = 1;
genprime(n); break;
} }
}
if(flag == 0)
/* Output printf("%d ", i);
}
Enter the value of n: 25 }
1 2 3 5 7 11 13 17 19 23
*/
Write a C program to find using functions the
sum of series (1/1!+1/2!+1/3!+… +1/n!)
Write a C program to find nCr using functions
int main ( )
#include<stdio.h> {
int fact ( int n ) int i, n, r, ncr, fact1, fact2, fact3 ;
{ printf ( “Enter the value of n and r\n" ) ;
int res, i ; scanf ( "%d%d", &n, &r ) ;
res = 1 ; if ( n < r )
for ( i = 1 ; i <= n ; i++ ) printf ( "Cant compute nCr\n" ) ;
res = res * i ; else if ( n == r )
return res; printf ( "The value of nCr is 1\n" ) ;
} else
{
fact1 = fact(n);
fact2 = fact(r);
fact3 = fact(n-r);
Output:
ncr = fact1 / (fact2 * fact3);
Enter the value of n and r
printf ( "The ncr value is %d\n", ncr ) ;
53
}
The ncr value is 10
}
Recursion
• A function that calls itself is known as a recursive function. And, this technique is
known as recursion.
Sum of Natural Numbers Using Recursion
Example Programs on functions
• Convert decimal to Binary
Convert Binary to decimal
Example Programs on functions
• Write a program in C to find the square of any number using the
function.
• Write a program in C to swap two numbers using a function.
• Write a program in C to check if a given number is even or odd
using the function.
• Write a program in C to check if a given number is a palindrome
using function.
• Program to find maximum and minimum between two numbers
using functions (use ternary operator to check the min and max).
Location of Functions
THANK
YOU