Computer Programming in C - Pratiksha A.
FUNCTIONS
Introduction to Functions:
- A function is a set of statements that takes input, performs some computations and
produces an output.
- Functions are classified as derived datatypes in C, therefore are used as variables in C.
- They help in organizing code, promote reusability and simplify complex tasks.
- Functions, just like main(), are independent sub-programs which make it easier to
perform complex tasks by keeping them modularized (in modules) hence simplifying
coding them, understanding them and debugging them.
A.
Advantages of Functions:
- Functions in C help in organizing code by grouping related tasks together and improves
readability and makes it easier to navigate them.
- They also allow breaking down a program into smaller, manageable modules where
each function focuses on a specific task.
a
- The length of the source program can be reduced by using functions at appropriate
places. This is useful when there is limited memory space.
- Once a function is defined, it can be called multiple times from different parts of the
sh
program and saves development time.
Types of Function:
- Standard Library Functions: These are built-in functions provided by the C standard
library, such as printf(), scanf(), Math functions like sqrt(), pow(), etc.
ik
- User-defined Functions: These are functions created by the programmer to perform
specific tasks. They can be called from other parts of the program to execute the defined
functionality.
- Recursive Functions: These are functions that call themselves either directly or
at
indirectly in order to solve a problem. Recursive functions are useful for tasks like
factorial calculation, Fibonacci series generation, etc.
Standard Library / Inbuilt Functions and their Uses:
Pr
Function Name Standard Library Description
printf() <stdio.h> printf() is used to print
formatted output to the
standard output stream
(usually the console). It
allows printing various types
of data, such as integers,
floating-point numbers,
characters, strings, etc., with
formatting options like
1
Computer Programming in C - Pratiksha A.
placeholders (%d, %f, %s)
and escape sequences (\n for
newline, \t for tab, etc.).
scanf() <stdio.h> scanf() is used to read
formatted input from the
standard input stream
(usually the keyboard). It
allows reading data into
variables of different types,
such as integers,
floating-point numbers,
characters, etc., based on the
A.
specified format string. Input
values are typically separated
by whitespace.
getch() <conio.h> getch() is used to read a
character directly from the
a
console without echoing it on
the screen. It is commonly
used in scenarios where
character input is required
sh
without waiting for the user to
press Enter.
clrscr() <conio.h> clrscr() is used to clear
the console screen by
removing all previously
ik
printed text and resetting the
cursor position to the top-left
corner of the screen.
at
sqrt() <math.h> sqrt() is used to calculate
the square root of a given
number. It takes a single
argument (a non-negative
Pr
value) and returns its square
root as a double-precision
floating-point number. If the
argument is negative, sqrt()
returns NaN (Not a Number).
pow() <math.h> pow() is used to calculate
the power of a given base
raised to a specified
exponent. It takes two
arguments: the base (a
double) and the exponent (a
double), and returns the
2
Computer Programming in C - Pratiksha A.
result as a double. It can
handle both integer and
fractional exponents.
User Defined Functions, Function Prototype, Definition, Syntax and Example:
- These are functions created by the programmer to perform specific tasks. They can be
called from other parts of the program to execute the defined functionality.
Elements of a User-Defined Function:
A.
1. Function prototype / declaration.
2. Function call.
3. Function definition.
- In order to use a function in a program, the function is to be invoked at the required
place in the program and this is known as function call.
a
- The program or the function that calls the function is referred to as the calling program or
calling function.
- The calling program should declare any function like a declaration of a variable that is to
sh
be used in the program and this is known as function declaration or function prototype.
Function Prototype / Declaration:
- Like variables, functions in a C program are to be declared before they are called /
ik
invoked.
- A function prototype or declaration consists of 4 parts:
- Function type (return type).
at
- Function name.
- Parameter list.
- Terminating semicolon.
-
Pr
Syntax of User-Defined Function Prototype
return_type function_name (set_of_arguments);
type of output returned by name of the function inputs or arguments
the function provided to the function.
{optional}.
int, char, float add,sub,store, etc. int i, int i1, char
c, float f
Example of User-Defined Function:
3
Computer Programming in C - Pratiksha A.
#include<stdio.h>
#include<conio.h>
char alphabet(); //function prototype
int main()
{
char a = alphabet(); //function call
printf(“Character is: %c”, a);
return 0;
}
char alphabet() //function definition
{
A.
return ‘p’;
}
Function call:
- A function call in C is a statement that invokes (or “calls”) a function to perform a specific
a
task.
- It consists of the function name followed by parentheses containing any necessary
sh
arguments or parameters.
Syntax for Function Call:
function_name(arguments);
ik
Example:
char a = alphabet();
at
Function Definition:
- A function definition must include the following elements:
Pr
1. function_type / return_type.
2. function_name.
3. list of parameters / set of arguments.
4. local variable declarations.
5. function statements.
6. return statement.
- The first three elements are known as function header and the second three elements
are known as function body.
4
Computer Programming in C - Pratiksha A.
Syntax for Function Definition:
function_type - function header:
function_name(parameter_list) ● The type and name are explained in
{ the above syntax for user defined
local variable declaration; functions.
executable statements;
.. ● Formal and Actual Parameter List:
… The parameters used in prototype and
return statement; definitions are known as formal
} parameters and those used in function
calls are known as actual parameters.
A.
- function body:
● This contains the declarations and
statements necessary for performing
the required task.
Example of Function Definition:
a
char alphabet() //function definition
sh
return ‘p’;
}
Accessing Function and Parameter Passing:
ik
- The functions inside C are accessed by using their name followed with a pair of
parentheses {()} and the list of parameters that function contains.
at
- The parameters for a function can be passed using the following 2 methods:
- Call By Value: Here values of actual parameters will be copied to the formal
parameters and they will store values in 2 different locations. Any modifications
Pr
made to the parameter inside the function do not affect the original value of the
argument. This is the default method of passing arguments in C. Primitive data
types (such as int, float, char) are typically passed by value.
Example of Call By Value:
#include <stdio.h>
// Function to change the value of a parameter (call by value)
void changeValue(int x) {
x = 20; // Modifying the value of the parameter
5
Computer Programming in C - Pratiksha A.
int main() {
int num = 10;
printf("Before calling changeValue: %d\n", num); // Output:
Before calling changeValue: 10
// Call the function with num as argument (call by value)
changeValue(num);
printf("After calling changeValue: %d\n", num); // Output: After
calling changeValue: 10
A.
return 0;
}
- Call By Reference: Here both actual and formal parameters refer to the same
a
memory location and the address of the actual argument is passed to the
function. Any modifications made to the parameter inside the function affect the
sh original value of the argument because the function operates directly on the
memory location of the argument. Pointers are typically used to implement call by
reference in C.
[Note: will be doing this type of function in chapter 6]
ik
Recursion:
- It is the process of a function calling itself repeatedly till the given condition is satisfied.
at
- These are functions that call themselves either directly or indirectly in order to solve a
problem.
- Recursive functions are useful for tasks like factorial calculation, Fibonacci series
generation, etc.
Pr
-
Syntax for Recursive Function:
function_type
function_name(parameters)
{ - execution statements for that function.
execution statements;
- this is an important element to define
base condition; while writing recursive functions.
- this is the recursive call in the function.
recursion case(call);
6
Computer Programming in C - Pratiksha A.
Example for Recursive Function:
#include<stdio.h>
int fun(int n)
{
if(n == 0) //base condition or breaking point
return 1;
else
return 1 + fun(n - 2); //recursive call
A.
}
int main()
{
printf(“%d”, fun(4));
return 0;
}
a
Elements of a Recursive Functions:
sh
- Recursion Call: it refers to the recursive call present in the recursive function. It decides
what type of recursion will occur and how the problem will be divided into smaller
subproblems.
- Base Condition / Breaking Point: It specifies when the recursion is going to terminate.
ik
It is the condition that determines the exit point of the recursion.
- It is important to define the base condition before the recursive case otherwise,
the base condition may never be encountered and recursion might continue till
infinity.
at
Pr
7
Computer Programming in C - Pratiksha A.
Note for Prototypes & Parameters:
Prototypes: Prototype declarations are not essential. If a function has not been declared
before it is used, C will assume that its details are available at the time of linking. Since the
prototype is not available, C will assume that the return type is an integer and that the types
of parameters match the formal definitions.
If these assumptions are wrong, the linker will fail and we will have to change the program.
The moral is that we must always include prototype declarations, preferably in the global
declaration section.
Parameters: Parameters (also known as arguments) are used in three places:
A.
1. in declaration (prototypes),
2. in function call, and
3. in function definition.
The formal and actual parameters must match exactly in type, order and number. Their
names, however, do not need to match.
a
sh
ik
at
Pr
8
Computer Programming in C - Pratiksha A.
Practical Questions:
1. Write a program for Factorial of a Number using all Function Types.
2. Use a call by Reference method for swapping two numbers.
3. Use a call by Reference method for adding 10 to two numbers to understand multiple
return statements.
4. Use Recursive Method to write a program to calculate Factorial of a number.
5. Use Recursive Method to write a program to calculate Fibonacci series upto a given
number.
A.
University Asked Questions:
Question & Question Paper Marks
May’2018:
a
Q.1. b) State whether True or False:
vi) A function can have any number of return statements 1
sh
Q.4. a) What is recursion? WAP using recursion to find 10
the sum of arrays of size n.
Dec’2018:
Q.1. a) What is recursion? Write a program to find xy 4
using recursion.
ik
Q.6. b) Explain call by value and call by reference with 10
example.
at
May’2019: 8
Q.2. a) What is recursion? Write a program using
recursion to calculate the value of Z=XY.
Pr
Q.2. b) Write a function to reverse a 3 digit number 6
Q.4. b) Differentiate between call by value and call by 10
reference. Write a program to calculate
Factorial of a number using call by reference.
Dec’2019:
Q.1. a) MCQ
ii) Which keyword can be used for coming out of 1
recursion?
(a) break (b) exit (c) return (d)all of above
9
Computer Programming in C - Pratiksha A.
Q.4. b) Explain recursion and its advantages? Write a 10
recursive c program to find the factorial
of a given number.
May’2022:
Q.1. MCQ:
5. The value obtained in the function is given back to the 2
main program by using which keyword?
(a) new (b) return (c) volatile (d) static
Q.2. D) Define recursion. Write a program using 4
recursive function ‘power’ to compute x raised
A.
to n i.e. xn which can be defined as given below:
power (x, n)=1 if n=0
power(x, n)=x if n=1
power(x, n)=x*power(x,n-1) otherwise
a
Q.3.C) Write a program to find factorial of a given number 4
using function.
sh
Q.4. E) Explain the advantages of Function. 4
Dec’2022:
Q.2. A) What is recursion? Write a program to find GCD 6
of two numbers using recursive function.
ik
Q.5. C) Explain the need of Function Prototype with an 4
example.
at
May’2023:
Q.1. C) Explain the need of Function Prototype with an 5
example.
Pr
Q.5. A) Write a program using function to check if the 5
entered number is prime or not.
Q.5. B) Define recursion and Write a program to calculate 5
power of a given number
using recursive function.
10