3 1 Functions
3 1 Functions
1
Functions in C
✧ What is a function in C?
✧ A program segment that carries out some specific,
well-defined task
✧ Example:
✧ A function to add two numbers
✧ A function to find the largest of n numbers
CP - Functions - Basics -
01/02/2021 2
IIIT Sri City
Functions – Characteristics
✧ Every C program consists of one or more functions
✧ Function Declaration:
✧ Tells the compiler about a function's name, return
type, and parameters
✧ A function definition provides the actual body of the
function
CP - Functions - Basics -
01/02/2021 4
IIIT Sri City
Functions - Components
✧ Return Type:
✧ A function may return a value
✧ The return_type is the data type of the value the
function returns.
✧ Some functions perform the desired operations
without returning a value.
✧ In this case, the return_type is the keyword void.
✧ Function Name:
✧ Actual name of the function
✧ The function name and the parameter list together
constitute the function signature.
CP - Functions - Basics -
01/02/2021 5
IIIT Sri City
Functions – Components (contd)
✧ Parameters:
✧ A parameter is like a placeholder.
✧ When a function is invoked, you pass a value to the
parameter.
✧ This value is referred to as actual parameter or
argument.
✧ The parameter list refers to the type, order, and
number of the parameters of a function.
✧ Parameters are optional; this means that a function
may contain no parameters as well
✧ Formal parameters vs Actual parameters
✧ Function Body:
✧ The function body contains a collection of statements
that define what
01/02/2021
CP the function
- Functions does.
- Basics - 6
IIIT Sri City
7
Parameter passed
Returning value
Calling/Invoking the cent2fahr function
Functions – An example
✧ The following function returns the max between
two numbers Function Paramerters
Function
(formal parameters)
Name
CP - Functions - Basics -
01/02/2021 9
IIIT Sri City
Functions – A Simplified Example
✧ A simplified version of the same function that finds
the maximum of two integers: m, n
CP - Functions - Basics -
01/02/2021 10
IIIT Sri City
Functions – main()
✧ How do we call getMax function from main()?
int main(void) {
int m = 10, n = 27;
printf("\nm = %d, n = %d\n", m, n);
return 0;
}
CP - Functions - Basics -
01/02/2021 11
IIIT Sri City
Function that finds max(m,n)
/* The complete Program – finding max of m and n */
#include <stdio.h>
int main(void) {
Function
int m = 10, n = 27; getMax() is
printf("\nm = %d, n = %d\n", m, n); defined before
main(). So
int max = getMax(m,n); function
printf("\nMax = %d\n", max); declaration is
return 0; implicit
}
CP - Functions - Basics -
01/02/2021 12
IIIT Sri City
Where is the function defined?
/* The complete Program – finding max of m and n */
#include <stdio.h>
Function Prototypes
• Function prototypes are usually written at the
beginning of a program, ahead of any functions
(including main())
• Prototypes can specify parameter names or just
types (more common)
• Examples:
int gcd (int , int );
void div7 (int number);
• Note the semicolon at the end of the line.
• The parameter name, if specifed, can be
anything; but it is a good practice to use the
same names as in the function definition
Function Arguments
✧ Formal Parameters:
✧ If a function is to use arguments, it must declare
variables that accept the values of the
arguments
✧ These variables are called the formal parameters
of the function.
✧ Formal parameters behave like local variables
inside the function and are created upon entry
into the function and destroyed upon exit
✧ Two ways to call a function:
✧ Call by Value
✧ Call by Reference
void PrintGreetings() {
printf(“\nWelcome”);
printf(“\n This is Anna Univ\n”);
}
CP - Functions - Basics -
01/02/2021 16
IIIT Sri City
Function with one argument
✧ Compute and print the sum of the first N natural Numbers
✧ This function does not need to return any value.
#include <stdio.h>
/* Method 1 – Using FOR loop */
void printSumN( int n ) {
int i = 0, sum = 0;
for (i = 0; i < n + 1; i++) {
sum += i;
}
printf("\nMethod - 1: \nN = %d, SUM = %d\n", n, sum);
}
int main() {
int m = 10;
printSumN(m); /* Calling Method - 1 */
return 0;
}
CP - Functions - Basics -
01/02/2021 17
IIIT Sri City
An Updated getSumN(n)
✧ Compute and print the sum of the first N natural Numbers
✧ Another approach using two variables.
#include <stdio.h>
void getSumN( int n ) { /* Method 2 - Using two variables, left(MIN) & right(MAX)
*/
int i = 1, sum = 0;
int left = i, right = n;
while (left < right) {
sum += left + right;
left++; right--;
}
/* Sum Correction for ODD numbers */
sum += (n % 2 == 1) ? ((int) n/2 + 1) : 0;
printf("\nMethod - 2:\nN = %d, SUM = %d\n", n, sum);
}
int main() {
int m = 10;
getSumN(m); /* Calling Method - 2 */
return 0;
}
CP - Functions - Basics -
01/02/2021 18
IIIT Sri City
Function with Two arguments
✧ Problem: Compute the sum of 2 numbers
✧ This function computes and prints the sum of 2 numbers
#include <stdio.h>
int main() {
int m = 21, n = 14;
add(m, n);
return 0; Function with no return
} Value
CP - Functions - Basics -
01/02/2021 19
IIIT Sri City
Function with no return value
✧ Function that prints if a number is divisible by 7 or not?
return;
} Optional (not
needed!!)
int main( ) {
int n = 28;
div7(n);
Function with no return
return 0;
} Value
CP - Functions - Basics -
01/02/2021 20
IIIT Sri City
Function with return value
✧ Problem: Compute the GCD of two numbers
✧ This function returns GCD of two given numbers to the main()
#include <stdio.h>
Int getGCD( int m, int n ) { /* Computing GCD of m and n where m > n */
int temp;
while ( ( m % n) != 0 ) {
temp= m % n;
m = n;
n = temp;
}
return n;
}
int main() {
int m = 21, n = 14, k; Function getGCD() returns
print(“\n m = %d, n = %d”, ); the GCD of m and n and
k = getGCD(m, n); stores GCD in the variable
print(“\nGCD = %d”, k); k
return 0;
}
CP - Functions - Basics -
01/02/2021 21
IIIT Sri City
Function with 1-D array
✧ Problem: Check a given number is present in the array or not?
✧ This function returns 1 if the number is present; 0, otherwise
#include <stdio.h>
void printValues( int a[], int n) {
for ( int i = 0; i < n; i++) printf(" %d ", a[i]);
printf("\n");
}
int Search( int a[], int n, int k) {
for ( int i = 0; i < n; i++) {
if ( k == a[i] ) return 1;
}
return 0;
}
int main() {
int n = 5; // Size of the array
int a[5] = {12, 6, 2, 11, 5}; // An array of 5 elements
int k = 5; // The element to be searched in the array
printValues(a, n);
int ret = Search(a, n, k);
if (ret == 1) printf("\n%d is present in the array\n", k);
else printf("\n%d is NOT present in the array\n", k);
return 0;
}
CP - Functions - Basics -
01/02/2021 22
IIIT Sri City
Passing Values between Functions
Problem: Check and print an occurrence of a given number in an array
#include <stdio.h>
void printValue ( int val) {
printf(” %d ”, val);
}
int Search( int a[], int n, int k) {
for ( int i = 0; i < n; i++) {
if ( k == a[i] ) {
printValue(a[i]);
return 1;
}
}
return 0;
}
int main() {
int n = 5, k = 5;
int ret = Search(a, n, k);
if (ret == 1) printf("\n%d is present in the array\n", k);
else printf("\n%d is NOT present in the array\n", k);
return 0;
}
CP - Functions - Basics -
01/02/2021 23
IIIT Sri City
Passing Values between Functions
Problem: Check and print all occurrences of a given number in an array
#include <stdio.h>
void printMessage(char ch[] ) {
printf("%s\n", ch);
}
void printValue( int val ) {
printf(" %d ", val);
}
void Search( int a[], int n, int k) {
printMessage("Printing all occurrences");
for ( int i = 0; i < n; i++) {
if ( k == a[i] )
printValue(a[i]);
}
printf("\n");
}
int main() {
int n = 10, k = 5;
int a[10] = {2, 13, 71, 28, 5, 5, 4, 8, 5, 1};
Search(a, n, k);
return 0;
}
CP - Functions - Basics -
01/02/2021 24
IIIT Sri City
Macros
Macros Use function if the sequence of steps is long
✧ If small, use macros or inline function, to eliminate the
need for retyping and time overhead.
✧ Need #define compiler directive
✧ Find the area of a triangle (given: base and height)
#define area(base, height) (o.5 * base * height)
CP - Functions - Basics -
01/02/2021 25
IIIT Sri City
26
Scope of a variable
• Part of the program from which the value of the variable can
be used (seen)
• Scope of a variable - Within the block in which the variable
is defined
• Block = group of statements enclosed within { }
• Local variable – scope is usually the function in which it is
defined
• So two local variables of two functions can have the same
name, but they are different variables
• Global variables – declared outside all functions (even main)
• scope is entire program by default, but can be hidden in a
block if local variable of same name defined
27
#include <stdio.h>
int A = 1;
Variable
void main() Scope
Global variable
{
myProc();
printf ( "A = %d\n", A);
}
Hides the global A
void myProc()
{ int A = 2; Output:
if ( A==2 )
{ A=3
A = 3;
printf ( "A = %d\n", A);
} A=1
}
Compute GCD of two numbers
28
12 ) 45 ( 3
int main() {
int A, B, temp; 36
scanf (“%d %d”, &A, &B); 9 ) 12 ( 1
if (A > B) { 9
temp = A; A = B; B = temp; 3 ) 9 ( 3
}
9
while ((B % A) != 0) {
0
temp = B % A;
B = A;
A = temp; Initial: A=12, B=45
Iteration 1: temp=9, B=12,A=9
}
Iteration 2: temp=3, B=9, A=3
printf (“The GCD is %d”, A); B % A = 0 ➔ GCD is 3
}
gcd.c
29
int x, y, z;
scanf(“%d%d”, &x, &y);
z = gcd(x,y);
printf(“GCD of %d and %d is %d\n”, x, y, z);
30
Value returned
Exercises
✧ Write a function to compute GCD of 4 numbers (use
the function that finds the GCD of two numbers)
✧ Write a function to check whether the number is an
Armstrong number of not?
✧ Write a function to check whether the given string (that
includes spaces as well) is a palindrome or not?
✧ A number is perfect if is equal to the sum of its positive
divisors excluding the number itself. Now Generate n (=
10) numbers randomly and store them in an array. Write
functions to find the sum of all perfect numbers present
in the array
✧ Write a function to find the kth smallest element in a
subarray
CP - Functions - Basics -
01/02/2021 31
IIIT Sri City