0% found this document useful (0 votes)
22 views

3 1 Functions

Functions in C are program segments that carry out specific tasks, with each function defined by its return type, name, parameters, and body. Every C program must contain at least one function called main() that begins execution, and functions can be called from within other functions to divide up and organize code logically. Functions allow code to be reused by calling the function multiple times to perform the same task rather than repeating the same code.

Uploaded by

jaiselvamani3
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)
22 views

3 1 Functions

Functions in C are program segments that carry out specific tasks, with each function defined by its return type, name, parameters, and body. Every C program must contain at least one function called main() that begins execution, and functions can be called from within other functions to divide up and organize code logically. Functions allow code to be reused by calling the function multiple times to perform the same task rather than repeating the same code.

Uploaded by

jaiselvamani3
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
You are on page 1/ 31

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

✧ A function will carry out its intended task whenever it


is called or invoked
✧ Can be called multiple times

CP - Functions - Basics -
01/02/2021 2
IIIT Sri City
Functions – Characteristics
✧ Every C program consists of one or more functions

✧ One of these functions must be called main()


✧ Every C program has at least one function – main() –
and all the most trivial programs can define
additional functions.
✧ You can divide up your code into separate functions
✧ How you divide up your code among different
functions is up to you, but logically the division is such
that each function performs a specific task

✧ Note that the execution of a C program always


begins by carrying out the instructions in main()
✧ Functions call other functions as instructions
CP - Functions - Basics -
01/02/2021 3
IIIT Sri City
Defining a Function
✧ The general skeleton of a function in C is as follows:
return_type function_name ( parameter list ) {
// body of the function
}
✧ A function definition in C consists of:
✧ a function header and
✧ a function body

✧ 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

Calling function (Caller)


Called function (Callee) parameter

void main() float cent2fahr(float data)


{ float cent, fahr; {
scanf(“%f”,&cent); float result;
fahr = cent2fahr(cent); result = data*9/5 + 32;
printf(“%fC = %fF\n”, return result;
cent, fahr);
}
}

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

int getMax (int num1, int num2) {


/* local variable declaration */
Return int result;
Type
if (num1 > num2)
result = num1; Body of the function
Return else
value result = num2;
return result;
} CP - Functions - Basics -
01/02/2021 8
IIIT Sri City
Scope of the Variables
✧ Scope of the variables defined in a function?

int getMax (int num1, int num2) {


/* local variable declaration */
int result;
if (num1 > num2)
result = num1;The values of the variables:
else num1, num2, and results are
purely local in this function.
result = num2;
Once the execution is over,
return result; these variables are not available
} for other parts of the program

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

int getMax(int num1, int num2) {


return ((num1 > num2) ? num1 : num2);
}

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);

int max = getMax(m,n);


printf("\nMax = %d\n", max);

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 getMax(int num1, int num2) {


return ((num1 > num2) ? num1 : num2);
}

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 Declaration is required */


int getMax(int, int); Function getMax() is
defined afer main().
int main(void) {
int m = 10, n = 27; So the function declaration
printf("\nm = %d, n = %d\n", m, n); is needed
/* Calling the function */
int max = getMax(m,n);

printf("\nMax = %d\n", max);


return 0;
}
int getMax(int num1, int num2) {
return ((num1 > num2) ? num1 : num2);
}
CP - Functions - Basics -
01/02/2021 13
IIIT Sri City
14

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

✧ arguments can be passed to a function using any


o the above way
CP - Functions - Basics -
01/02/2021 15
IIIT Sri City
A Simple Function
✧ Let us look at the following function

void PrintGreetings() {
printf(“\nWelcome”);
printf(“\n This is Anna Univ\n”);
}

✧ The above function has


✧ no arguments and
✧ no return value
✧ But prints the greetings message

✧ Functions can also have arguments (one or more


depending on the specific task in hand

✧ Let us look at some more examples in the sequel.

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>

void add( int m, int n ) {


int sum = 0;
sum = m + n;
printf(“\nSum = %d\n”, sum);
}

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?

#include <stdio.h> return type is void


void div7( int n ) {
if ( (n % 7) == 0 )
printf(“\n%d is divisible by 7\n”, n);
else
printf(“\n%d is NOT divisible by 7\n”, n);

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)

Identifier Arguments Definition of Macros


✧ Define it once and use it anywhere in the program
printf("\nArea = %f\n", area(4.0, 6.0));

✧ NOTE: Remember to pass only values as arguments. If you


wish to pass expressions as arguments, use ( ) suitably

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

Compute GCD of two numbers


(with function)

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

Return-value type Formal parameters

int gcd (int A, int B)


{
int temp;
while ((B % A) != 0) {
temp = B % A;
B = A;
A = temp;
}
return (A);
BODY
}

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

You might also like