Unit 2 Functions
Unit 2 Functions
2
Introduction
• A function is a self-contained block of statements that perform a
coherent task of some kind.
• Every C program can be thought of as a collection of these functions.
• They help you divide bigger problems into smaller, more manageable
chunks of code, making it simpler to create and run programs.
• Like hiring a person to perform some task.
3
Introduction
• Types of Function
• Library Function
• User-defined Function
• User-defined function
• C allows Programmers to define their own functions for carrying out
various individual tasks
• Allows a large program to be broken down into a number of smaller, self-
contained components
➢ Each of which has some unique, identifiable purpose
• C program can be modularized through the intelligent use of such functions
4
Why function needed?
• Writing functions avoids rewriting the same code over and over.
• Using functions it becomes easier to write programs and keep track
of what they are doing.
• If the operation of a program can be divided into separate activities,
and each activity placed in a different function,
• then each could be written and checked more or less independently.
• Separating the code into modular functions also makes the program
easier to design and understand.
5
Advantages of function
• The use of a function avoids the need for redundant (repeated)
programming of the same instructions
• Logical clarity resulting from the decomposition of a program into
several concise functions
• Programs are easier to write and easier to debug
• Enables the programmer to build a customized library of
frequently used routines or of routines containing system
dependent features.
6
Functions overview
• A function is a self-contained program segment that carries out some
specific, well-defined tasks.
• Every C program consists of one or more functions
• One of these functions must be called main
• Execution of the program will always begin by carrying out the instructions in
main
• Additional functions will be subordinate to main, and perhaps to one
another
7
Function Overview
• Definition of functions can appear in any order
• One function cannot embed another function
• function will carry out its intended action whenever it is accessed /
called
• Once accessed, control will be returned to the point from which the
function was accessed
8
Function Overview
• Generally, function will process information that is passed to it from
the calling portion of the program, and return a single value
• Information is passed to the function via special identifiers called
arguments/parameters
The mechanism used to convey information to the function is the
‘argument’.
• returned via the return statement
9
#include<stdio.h>
Example-1
main( )
{
int a, b, c, sum ;
printf ( "\nEnter any three numbers " ) ;
scanf ( "%d %d %d", &a, &b, &c ) ;
sum = calsum ( a, b, c ) ;
printf ( "\nSum = %d", sum ) ;
}
calsum ( x, y, z )
int x, y, z ;
{
int d ;
d=x+y+z;
return ( d ) ;
} 10
Example-2
#include <stdio.h>
char lower_to_upper(char c 1){ a-z-> 97-122;
char c2;
c2 = ( c1 >= 'a' && c1 <= ‘z' ) ? ( 'A' + c1 - 'a' ) : c1 ;
A-Z-> 65-90;
return(c2); c=99;
} 65+99-97;
main() 65+2=67;
{
char lower, upper;
printf("P1ease enter a lowercase character: " ) ;
scanf( “%c" &lower) ;
upper = lower_to_upper(lower) ;
printf ( \nThe uppercase equivalent is %c", upper);
}
11
Defining Function
• has two principal components:
• the first line (including the argument declarations)
• the body of the function. (Normally a compound Statement)
• The first line
• contains the type specification of the value returned by the function,
• followed by the function name,
• a set of arguments (optional), separated by commas and enclosed in
parentheses
• Each argument is preceded by its associated type declaration
• empty pair of parentheses must follow the function name if the function
definition does not include any arguments
12
General syntax
13
Return type Function name Formal Parameters /
Arguments
15
Multiple return statement
16
Multiple return statement
• Valid return statements
return ( a ) ;
return ( 23 ) ;
return ( 12.34 ) ;
return ;
• A function can return only one value at a time. Thus, the
following statements are invalid.
return ( a, b ) ;
return ( x, 12 ) ;
17
#include <stdio.h>
char lower_to_upper(char c 1){
char c2;
c2 = ( c1 >= 'a' && c1 <= ‘z' ) ? ( 'A' + c1 - 'a' ) : c1 ;
return(c2);
}
main(){
char lower, upper; Function Call /
printf("P1ease enter a lowercase character: " ) ;
scanf( “%c" &lower) ;
Function Access
upper = lower_to_upper(lower) ;
printf ( \nThe uppercase equivalent is %c", upper) ;
}
18
Accessing a Function
• accessed (i.e., called) by specifing its name, followed by a list of
arguments enclosed in parentheses and separated by commas
• function call does not require any arguments, an empty pair of
parentheses must follow the name of the function
• arguments appearing in the function call are referred to as actual
arguments
• actual arguments may be expressed as constants, single variables, or
more complex expressions
19
Function Call
#include <stdio.h> Actual
char lower_to_upper(char c 1){ Parameter
char c2;
c2 = ( c1 >= 'a' && c1 <= ‘z' ) ? ( 'A' + c1 - 'a' ) : c1 ; Function
return(c2); name
}
main(){
char lower, upper;
printf("P1ease enter a lowercase character: " ) ;
scanf( “%c" &lower) ;
upper = lower_to_upper(lower) ;
printf ( \nThe uppercase equivalent is %c", upper) ; upper = lower_to_upper( lower ) ;
}
20
Function call
• There may be several different calls to the same function
• Actual arguments may differ from one function call to another
• the actual arguments must correspond to the formal arguments in
the function definition
• the number of actual arguments must be the same as the number of formal
arguments
• each actual argument must be of the same data type as its corresponding
formal argument
21
Function Prototype
• The C function prototype is a statement that tells the compiler about the
function’s name, its return type, numbers and data types of its
parameters.
• By using this information, the compiler cross-checks function parameters
and their data type with function definition and function call.
• Function prototype works like a function declaration where it is
necessary where the function reference or call is present before the
function definition but optional if the function definition is present
before the function call in the program.
• Function prototypes are usually written at the beginning of the program
22
Function Prototype
• Syntax
return_type function_name (parameter_list);
• return_type: It is the data type of the value that the function returns. It
can be any data type int, float, void, etc. If the function does not return
anything, void is used as the return type.
• function_name: It is the identifier of the function. Use appropriate names
for the functions that specify the purpose of the function.
• parameter_list: It is the list of parameters that a function expects in
parentheses. A parameter consists of its data type and name. If we don’t
want to pass any parameter, we can leave the parentheses empty.
23
Example
Program to calculate area of rectangle // Function definition
#include <stdio.h> float calculateRectangleArea(float length, float width)
// Function prototype {
float calculateRectangleArea(float length, float width); return length * width;
}
int main()
{
float length = 5.0;
float width = 3.0;
// Function call
float area = calculateRectangleArea(length, width);
return 0;
}
24
Function Prototype Function Prototype
#include <stdio.h>
#include <stdio.h>
char lower_to_upper(char c 1);
char lower_to_upper(char c 1){
main(){
char c2;
char lower, upper;
c2 = ( c1 >= 'a' && c1 <= ‘z' ) ? ( 'A' + c1 - 'a' ) : c1 ;
printf("P1ease enter a lowercase character: " ) ;
return(c2);
scanf( “%c" &lower) ; Function call
} upper = lower_to_upper(lower) ;
main(){ printf ( \nThe uppercase equivalent is %c", upper) ;
char lower, upper; }
printf("P1ease enter a lowercase character: " ) ; char lower_to_upper(char c 1){
scanf( “%c" &lower) ; char c2;
upper = lower_to_upper(lower) ; c2 = ( c1 >= 'a' && c1 <= ‘z' ) ? ( 'A' + c1 - 'a' ) : c1 ;
printf ( \nThe uppercase equivalent is %c", upper) ; return(c2);
} }
Function definition
25
Passing Argument to a Function
26
Passing argument to a function
• the value of the actual argument is copied into the function
• the value of the corresponding formal argument can be altered within the
function
• the value of the actual argument within the calling routine will not change
• This procedure for passing the value of an argument to a function is
known as passing by value
27
Passing argument to a function
#include <stdio.h>
void modify (int a);
• The original value of a (i.e., a = 2) is
displayed when main begins main(){
execution int a=2
• In, modify function a is modified by printf(“”a=%d from main, before calling modify \n”,a) ;
multiplying 3 to it modify(a);
• Altered value of the formal argument printf(“”a=%d from main, after calling modify \n”,a) ;
displayed in function }
void modify (int a){
• Finally, the value of a within main
(i.e., the actual argument) is again a*=3;
displayed, after control is transferred printf(“”a=%d from the function, after modified \n”,a) ;
back to main from modify return;
}
28
• Functions can be invoked in two ways:
• Call by Value or Call by Reference.
• These two ways are generally differentiated by the type of values
passed to them as parameters.
• The parameters passed to the function are called actual parameters
• whereas the parameters received by the function are called formal
parameters.
29
Call by value
• In call by value method of parameter passing, the values of actual
parameters are copied to the function’s formal parameters.
30
Call by value-example
Swapping of 2 numbers
#include <stdio.h> // Swap functions that swaps two values
void swapx(int x, int y) // Formal Parameters
// Function Prototype {
void swapx(int x, int y); int t;
// Main function t = x;
int main() x = y;
{ y = t;
int a = 10, b = 20;
printf("Inside Function:\nx = %d y = %d\n", x, y);
// Pass by Values }
swapx(a, b); // Actual Parameters
return 0;
}
31
Call by reference
• In call by reference method of parameter passing, the address of
the actual parameters is passed to the function as the formal
parameters.
❖ Both the actual and formal parameters refer to the same locations.
❖ Any changes made inside the function are actually reflected in the
actual parameters of the caller.
32
Call by reference-example
Swapping of 2 numbers
#include <stdio.h>
// Function Prototype
void swapx(int*, int*);
// Main function
int main()
{
int a = 10, b = 20;
// Pass reference
swapx(&a, &b); // Actual Parameters
return 0;
}
33
Call by reference-example
// Function to swap two variables by references
void swapx(int* x, int* y) // Formal Parameters
{
int t;
t = *x;
*x = *y;
*y = t;
34
Writing Program using Functions
35
#include <stdio.h>
int main() { Declaration
int i,fact=1,n;
scanf("%d",&n); Input
for(i=1;i<=n;i=i++) {
fact=fact*i;
Process
}
printf("%d\t",fact); Output
} • Move the process to the function
return 0; • While moving the process, the required data should be passed
as parameter to the function
}
• Return the value from the function after processing
• Instead of process, a function call will be present in the main
36
#include <stdio.h>
int factorial( int n1);
int factorial(int n1) {
int main() {
Declaration int i,fact=1;
int fact, n; for(i=1;i<=n1;i++) {
Input
scanf("%d",&n);
fact=fact*i;
fact=factorial(n); Function call
}
printf(“factorial=%d",fact);
return fact;
return 0;
}
} Output
37
Write a Program to find sine value of a given
angle
3 5 7
𝑥 𝑥 𝑥 𝑥
• sin 𝑥 = − + − ……
1! 3! 5! 7!
• To solve break the problem in to small problems
• Try to generate 1!, 3!, 5!, ……..
• Try to generate 𝑥, 𝑥 3 , 𝑥 5 , … …
• Try changing sign alternatively (1, -1, 1, -1, …….)
• Lets write the algorithm 1!, 3!, 5!, ……..
• So the expected output is 1, 6, 120, …….
• I/p is no. of terms
38
Step 1: Start the process
Step 2: Initialize fact1, i1 #include <stdio.h>
int main() {
Step 3: Input value of n
int i,j,fact=1,n;
Step 4: Repeat the steps until i=n scanf("%d",&n);
4.1 fact1, j1 for(i=1;i<=2*n;i=i+2) {
fact=1;
1. Repeat steps until j=i
for(j=1;j<=i;j++) {
1. fact fact * j
fact=fact*j;
4.1.2 j j+1 }
4.3 print the value of fact printf("%d\t",fact);
4.2 i i+2 }
return 0;
Step 6: Stop the process
} 39
Step 1: Start the process
Step 2: Initialize result1, i1 #include <stdio.h>
int main() {
Step 3: Input value of x, n
int i,j,result=1,n,x;
Step 4: Repeat the steps until i=n scanf("%d %d",&x,&n);
4.1 result1 for(i=1;i<=2*n;i=i+2) {
1. Repeat steps until j=i result=1;
for(j=1;j<=i;j++) {
1. result result * x
result=result*x;
4.1.2 j j+1
}
4.3 print the value of result printf("%d\t",result);
4.2 i i+2 }
Step 6: Stop the process return 0;
} 40
Step 1: Start the process
#include <stdio.h>
Step 2: Initialize sign1 int main() {
Step 3: Input n int sign=1,n
scanf("%d”,&n);
Step 4: Repeat the steps until i=n
for(i=1;i<=2*n;i=i+2) {
1. print the value of sign printf("%d\t",sign);
2. sign -sign sign= -sign;
}
Step 5: Stop the process
return 0;
}
41
#include <stdio.h>
int main() {
int i, j, n, fact=1,sign=1;
float x,sum=0, result=1;
scanf("%f %d",&x,&n);
for(i=1;i<=2*n;i=i+2) {
fact=1;
result=1;
for(j=1;j<=i;j++) {
fact=fact*j;
result=result*x;
}
sum=sum+sign*result/fact;
sign= -sign;
}
printf(“\nsum=%f”,sum);
return 0;
}
42
To find sin(x) using recursive statement
𝑥 𝑥3 𝑥5 𝑥7
• sin 𝑥 = − + − …… • In general every term is varies by
1! 3! 5! 7!
43
Iterative method
• To generate consecutive terms of sine
44
Step 1: Start the process
Step 3: Input value of x, n
Step 4: Initialize tsin x, term x, i 1
Step 4: Repeat the steps until i=n
1. term -term * x*x/ (i*(i-1))
2. tsin tsin+term
4.3 i i+2
Step 5: display tsin
Step 6: End the process
45
Write a Program to find sine value of a given
angle
3 5 7
𝑥 𝑥 𝑥 𝑥
• sin 𝑥 = − + − ……
1! 3! 5! 7!
• To solve break the problem in to small problems
• Function to find 1!, 3!, 5!, ……..
• Function to 𝑥, 𝑥 3 , 𝑥 5 , … …
• Finally a main() to calculate sine value using factorial and power
function
46
#include <stdio.h>
int factorial(int); int factorial(int i) {
int power(int,int); int j, fact=1;
int main() { for(j=1;j<=i;j++) {
int i, n, fact,sign=1; fact=fact*j;
float x,sum=0, result; }
scanf("%f %d",&x,&n); return fact;
for(i=1;i<=2*n;i=i+2) { }
fact=factorial(i);
int power(int x, int i) {
result=power(x,i); int j, result=1;
sum=sum+sign*result/fact; for(j=1;j<=i;j++) {
sign= -sign; result=result*x;
} }
printf(“\nsum=%f”,sum); return result;
return 0; }
}06-12-2022 Ref: Programming with C, Byron S. Gottfried. 47
37
Recursion
48
Recursion
• A process by which a function calls itself repeatedly, until some
specified condition has been satisfied
• Used for repetitive computations in which each action is stated in
terms of a previous result
• Many iterative (i.e., repetitive) problems can be written in this form.
• To solve a problem recursively, two conditions must be satisfied
• the problem must be written in a recursive form
• the problem statement must include a stopping condition
49
Factorial using Recursion
• Consider finding n!
• n! = 1 x 2 x 3 x . . . . x n
• Can also express this problem in another way, by writing
• n!= n x (n-1) x ……..x 2 x 1
• n! = n x (n - 1)!
• This is a recursive statement
• The desired action (the calculation of n!) is expressed in terms of a
previous result the value of (n - 1)!
• Also, 1! = 1 by definition
• provides a stopping condition (base condition) for the recursion.
50
Example
5! 5*4! 5*24
• Lets find 5!
4! 4*3! 4*6
3! 3*2! 3*2
2! 2*1! 2*1
1! 1
51
#include <stdio.h>
int factorial(int); int factorial(int i){
int main() { if(i<=1)
int n, fact; scanf("%d",&n); return 1;
fact=factorial(n); else
printf(“\nfactorial=%d”,fact); return i*factorial(i-1)
return 0; }
}
52
• Lets find 5!
• From main(), Factorial(5) is called
factorial(1) 1
53
Sum of N natural numbers using recursion
#include <stdio.h>
int nSum(int n);
int main()
{
int n = 5;
return res;
}
55
56
Write a program to find the sum of digits in the odd or
even positions of a given number separately
#include<stdio.h>
void getsum(int); //function prototype
int main()
{
int n;
printf(“enter the number”);
scanf(“%d”, &n);
getsum(n); //function call
return 0;
}
57
void getsum(int n)
{
int sum1=0, sum2=0, rem, c=1; n = n/10;
while(n!=0) n++;
{ }
if(c%2==0) printf(“The sum1 = %d”, sum1);
{ printf(“The sum2 = %d”, sum1);
rem = n%10; }
sum1 = sum1 + rem;
}
else
{
rem = n%10;
sum2 = sum2 + rem;
} 58
GCD using Recursion
18 24
a= 18 b= 24 a%b= 18
a= 24 b= 18 a%b= 6
a= 18 b= 6 a%b= 0
a= 6 b= 0
GCD of 18 and 24 = 6 =a
59
#include <stdio.h>
int gcd(int,int); int gcd(int a, int b){
int main() { if(b==0)
int x, y, result; return a;
scanf("%d %d", &x, &y); else
result=gcd(x,y); return
printf(“\ngcd=%f”,result); gcd(b,a%b);
return 0; }
}
60
Write a loop that will generate every 3rd integer,
beginning with i=2 and continuing for all integers that
are less than 100. Calculate the sum of these integers
that are evenly divisible by 5. Use 2 different methods
to carry out the test.
* conditional operator
* use an if-else statement
61
Using conditional operator
#include<stdio.h>
main()
{
int i=2, val, sum=0;
for(i=2;i<100;i=i+3)
{
val = (i%5==0) ? i : 0
sum=sum+val;
}
printf(“%d”, sum);
}
62
Using an if-else statement
#include<stdio.h>
main()
{
int i=2, sum=0;
for(i=2;i<100;i=i+3)
{
if(i%5==0)
{
sum=sum+i;
}
}
printf(“%d”, sum);
}
63
Write a loop that will calculate and print the sum of an
integer which is divisible by 2 and 6, beginning with
i=2, (i.e. 6+12+18……) for all values less than 100.
write in 3 different ways
(i) for loop
(ii) while loop
(iii) do-while
64
Using for loop
#include<stdio.h>
main()
{
int i, sum=0;
for(i=2;i<100;i++)
{
if(i%2==0 && i%6==0)
{
sum+=i;
}
}
printf(“The sum=%d”, sum);
}
65
Write a c program to get ‘N’ number of non-negative
values. The program should show an error message
for negative values. Find how many values are even
and odd.
66
#include<stdio.h> else
int main() {
{ oddcount+=1;
int i, n, x, oddcount=0, evencount=0; }
printf(“Enter n value:\n”); scanf(“%d”, &n); }
for(i=1;i<n;i++) }
{ printf(“The even number count=%d”, evencount);
printf(“Enter the value=”); printf(“The odd number count=%d”, oddcount);
scanf(“%d”, &x);
if(x<0) }
{
printf(“Error”);
}
else
{
if(x%2==0)
{
evencount+=1;} 67
Write a c program to check whether the given number is
Adam or not.
• Adam number is a number when reversed, the square of the number and the
square of the reversed number should be numbers which are reverse of each
other.
• Adam numbers up to 1000 are:
0, 1, 2, 3, 11, 12, 13, 21, 22, 31, 101, 102, 103, 111, 112 , 113, 121, 122,
201, 202, 211, 212, 221, 301, 311.
• For example,
Input, n = 12
Output = to check adam or not
Explanation:
➢ Square of 12 = 144
➢ Reverse of 12 = 21
➢ Square of 21 = 441
➢ Now, square of 12 and square of reverse of 12 are reverse of each other 68
Steps to find Adam number.
STEP-1: Find square of a number
STEP-2: Find reverse of a number
STEP-3: Find square of number in step-2
STEP-4: Find reverse of number in step-3
STEP-5: Find whether number obtained in step-4 and step-1
are equal or not
69
Source code.
#include <stdio.h> int isAdamNumber(int num)
#include <math.h> {
int sq = num * num;
int reverse(int num) int rev = reverse(num);
{ int rev_sq = rev * rev;
int rev = 0; int rev_rev_sq = reverse(rev_sq);
while(num > 0) if(sq == rev_rev_sq)
{ return 1;
rev = rev * 10 + num % 10; else
num = num / 10; return 0;
} }
return rev;
}
70
int main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(isAdamNumber(num))
printf("%d is an Adam number\n", num);
else
printf("%d is not an Adam number\n", num);
return 0;
}
71