0% found this document useful (0 votes)
2 views37 pages

Module 1 Functions

The document discusses the concept of functions in programming, emphasizing their role in modularity and structured programming. It covers the need for functions, including simplification of coding, easier maintenance, and code reuse, along with details on function declaration, definition, and calling. Additionally, it explains parameter passing methods (call by value and call by reference), and provides examples of functions for mathematical operations and array handling.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views37 pages

Module 1 Functions

The document discusses the concept of functions in programming, emphasizing their role in modularity and structured programming. It covers the need for functions, including simplification of coding, easier maintenance, and code reuse, along with details on function declaration, definition, and calling. Additionally, it explains parameter passing methods (call by value and call by reference), and provides examples of functions for mathematical operations and array handling.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

FUNCTIONS

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


FUNCTIONS
• Programmers break a program into segments known as functions which performs a well-
defined task(Modularity)
• Structured programming approach
• Top-down approach

Calling function

Called function

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


NEED OF FUNCTIONS
 Simplifies the process of total work done since program is divided
into well-defined functions
 Understanding, coding and testing multiple functions are easier
 Maintaining program is easier(the main program can consist of a
series of function calls rather than countless lines of code)
 Workload can be divided(More programmers can work on same
project)
 code sharing(well written functions may be reused in multiple
programs)
 C standard library is an example of the reuse of functions
 Protects data(concept of local data)

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


JEYAVIM SHERIN, SCOPE, VIT-CHENNAI
FUNCTIONS

Functions

Built-in Functions User Defined Functions

printf() sum()
scanf() sub()
… …

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


MATHEMATICAL FUNCTIONS <math.h>

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


USER DEFINED FUNCTIONS

Function Declaration/Prototype

Function Definition

Function Call

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


FUNCTION DECLARATION/PROTOTYPE
• Before using the function, it should be declared
• The compiler must know about
• Number of parameters
• Type of parameters semicolon is must
• Data type of the return value
Compiler do type checking with function call

syntax return_data_type function_name (data_type variable1,...);


or
return_data_type function_name (data_type_list);

int sum(int,int);
• If function declaration is global,
example void sum (int,int); then argument names are
void sum(); optional in declaration
int sum();
int sum(int x,int y);

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


FUNCTION DEFINITION

• When function is defined, space is allocated for that function in memory


• Function definition comprises of two parts
• Function header No semicolon
• Function body Formal arguments
Function
return_data_type function_name (data_type variable1,...) header

syntax
{
statements;
… Function body
return variable; // if return_data_type is not void
}

example
int sum(int x,int y) • Number of arguments and type of arguments in
{ function header and declaration should match
• Function definition itself can act as implicit
} function declaration(the function declaration
can be skipped & function should be defined
A function can only return one value
before used)

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


FUNCTION CALL

• Invokes a function
• Executes the statements in called function, returns control back to calling function

actual arguments

syntax function_name (variable1,variable 2,...);

example sum(a,b);

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


FUNCTIONS
• Function definition before function call • Function definition after function call

#include<stdio.h> #include<stdio.h>

return_type func_name(arguments) return_type func_name(arguments); Function


declaration
{
Function definition int main()
… {
} …
(or) Function
func_name(argument_value); call
int main() …
{ return 0;
… }
func_name(argument_value); Function call
return_type func_name(arguments) Function
… definition
{
return 0;

} }

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


Program to multiply 2 numbers using function

#include<stdio.h>
int multiply(int a, int b); // function declaration
int main()
{
int i, j, result;
printf("Enter 2 numbers to multiply...");
scanf("%d%d", &i, &j);
result = multiply(i, j); // function call
printf("The result of multiplication is: %d", result);
return 0;
}
int multiply(int a, int b) // function defintion
{
return (a*b);
}
Function Declaration
A function declaration is also known as the function prototype and it
consists of 4 parts given below.
• Return type
• Name of the function
• List of parameters
• Terminating semicolon
int sum(int a,int b);
Function definition
RETURN STATEMENT
• Used to terminate the execution of a function and returns the control to the calling function
• If a function do not have a return statement, the control automatically returns to the calling function
after the last statement of the called function is executed

return expression;
(or)
return (expression);

Default return type is int


Only one return value

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


RETURN STATEMENT
Cas Function
Function Type Function Definition Function Call
e Declaration
void fun()
1 No arguments, No return void fun(); fun();
{ /* statements */ }
int fun()
{
No arguments, Return
2 int fun(); /* statements */ int result = fun();
value
return value;
}
void fun(int a, int b)
{
3 Arguments, No return void fun(int a, int b); fun(x, y);
/* statements */
}
int fun(int a, int b)
{
int result = fun(x,
4 Arguments, Return value int fun(int a, int b); /* statements */
y);
return value;
}

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


FUNCTIONS-Armstrong/Perfect number
Function definition after main() function
//function definition
#include <stdio.h> void checkarmstrong(int num)
//function declaration {
void checkarmstrong(int n1); int d, sum,n1;
void checkperfect(int n1); sum = 0;
int main() n1=num;
{ while (num != 0)
int n; {
scanf(“%d”,&n); d = num % 10; // find the last digit of the number
//function call sum += d * d * d; //calculate the cube of the last digit and adds to sum
checkarmstrong(n); num = num / 10;
checkperfect(n); }
return 0; if(n1 == sum)
} printf(" The %d is an Armstrong number.\n\n", n1);
else
printf(" The %d is not an Armstrong number.\n\n", n1);

}
JEYAVIM SHERIN, SCOPE, VIT-CHENNAI
FUNCTIONS-Armstrong/Perfect number (contd.)
void checkperfect(int n1)
{
int i, sum, num;
sum = 0;
num = n1;
for(i=1; i<num; i++)
{
/* If i is a divisor of n1 */
if(num%i == 0)
{
sum += i;
}
}
if(n1 == sum)
printf(" The %d is a Perfect number.\n", n1);
else
printf(" The %d is not a Perfect number.\n", n1);

}
JEYAVIM SHERIN, SCOPE, VIT-CHENNAI
FUNCTIONS-palindrome
Function definition before main() function

#include <stdio.h>
int ispalindrome(int num) { int main() {
int original = num; int number;
int reversed = 0, digit; printf("Enter a number: ");
while (num != 0) { scanf("%d", &number);
digit = num % 10; if (ispalindrome(number))
reversed = reversed * 10 + digit; printf("%d is a Palindrome number.\n", number);
num = num / 10; else
} printf("%d is Not a Palindrome number.\n", number);
if (original == reversed) return 0;
return 1; }
else
return 0;
}

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


FUNCTIONS
CALL BY VALUE &ADDRESS

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


PARAMETER PASSING TO FUNCTION
• Call by Value
• Call by Address/Reference

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


CALL BY VALUE VS CALL BY REFERENCE
Call By Value Call By Address
Address of variables(location of variables) is
Values of variables are passed as arguments
passed as arguments
The value of each variable in calling function is The address of actual variables in the calling
copied into corresponding dummy variables of the function are copied into the dummy variables of
called function. the called function.
The changes made to the dummy variables in the
Using addresses we can access to the actual
called function have no effect on the values of actual
variables able to manipulate them.
variables in the calling function.
Requires more memory Requires less memory
Requires less time as there is no copying
Requires more time as it involves copying values

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


PASS BY VALUE
No return Returning value

#include <stdio.h>
#include <stdio.h> Value in calling
int add(int n);
void add(int n); function changes if we
int main()
int main() return the value
{
{
int n = 10;
int n = 10;
n=add(n);
add(n);
printf(“calling function:%d”,n);
printf(“calling function:%d”,n);
return 0;
return 0;
}
}
int add(int n)
void add(int n)
{
{
n=n+10;
n=n+10;
printf(“called function:%d",n);
printf(“called function:%d",n); Drawback:
return n;
} • Consumes
}
Output: additional storage
Output:
called function:20 space
called function:20
calling function:10 • Time required for
calling function:20
copy

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


PASS BY VALUE & REFERENCE/ADDRESS
Pass by value Pass by Address

#include <stdio.h>
#include <stdio.h>
void swap(int*, int*);
void swap(int x, int y);
int main()
int main()
{
{
int a = 10, b = 20;
int a = 10, b = 20;
swap(&a, &b);
swap(a, b);
printf("a=%d b=%d\n", a, b);
printf("a=%d b=%d\n", a, b);
return 0;
return 0;
}
}
void swap(int* x, int* y)
void swap(int x, int y)
{
{
int t;
int t;
t = *x;
t = x;
*x = *y;
x = y;
*y = t;
y = t;
printf("x=%d y=%d\n", *x, *y);
printf("x=%d y=%d\n", x, y);
}
}
Output: x=20 y=10 a=10 b=20
Output: x=20 y=10 a=20 b=10
JEYAVIM SHERIN, SCOPE, VIT-CHENNAI
FUNCTIONS & ARRAYS
Function call No []

function_name(array_name);
Function declaration
return_type function_name(data_type array_name[]);

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


PASSING
FUNCTIONS
1D ARRAY&TO
ARRAYS
FUNCTION
#include <stdio.h> // array a[] points to arr
void sort(int a[], int n)
void sort(int[], int); {
int i, j, temp;
int main()
{ for(i = 0; i < n; i++)
int arr[20], n, i; {
for(j = i + 1; j < n; j++)
printf("Enter number of elements: "); {
scanf("%d", &n); if(a[j] < a[i])
{
if (n > 20 || n <= 0) { temp = a[i];
printf("Invalid array size"); a[i] = a[j];
return 0; a[j] = temp;
} }
}
printf("Enter array elements:\n"); }
for(i = 0; i < n; i++)
scanf("%d", &arr[i]); printf("Sorted List:\n");
for(i = 0; i < n; i++)
sort(arr, n); printf("%d\n", a[i]);
}
return 0;
}
JEYAVIM SHERIN, SCOPE, VIT-CHENNAI
PASSING
FUNCTIONS
2D ARRAY&TO
ARRAYS
FUNCTION
int arr[][n])
#include<stdio.h> (or)
int main(void) {
void assign(int m, int n, int arr[m][n]) { int m = 2, n = 2;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int arr[m][n];
arr[i][j] = i + j; assign(m, n, arr);
} return 0;
} }
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
printf("%d", arr[i][j]);
}
printf("\n");
}
}
JEYAVIM SHERIN, SCOPE, VIT-CHENNAI
RETURNING STATIC ARRAY TO FUNCTION

We can’t return static 2D arrays from functions in C

We need to return a pointer to an array. This means


you’d allocate some heap memory for your array(s), and
then initialize the array(s) and then return the pointer.
Heap memory is a part of a program’s memory used for dynamic
memory allocation.

We can only do it by dynamic memory allocation.


JEYAVIM SHERIN, SCOPE, VIT-CHENNAI
Heap vs Stack
Characteristics of Heap Memory
Stack Memory Heap Memory
Feature Description
Dynamic
Allocation Static allocation allocation
time Runtime
Fixed size Variable size
Size Flexible (dynamic)
Automatic Manual
Lifetime Until it is explicitly freed deallocation deallocation
Access Through pointers Faster Slower
Speed Slower than stack
Function calls & Dynamic data
Control Programmer-managed local variables structures

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


#include <stdio.h>
#include <stdlib.h>

Heap Memory in C (Functions Used) int main() {


int *ptr;

Function Purpose ptr = (int *)malloc(5 * sizeof(int)); // heap memory

malloc() Allocates memory if(ptr == NULL) {


printf("Memory not allocated");
Allocates & initializes
calloc() memory return 0;
}
realloc() Resizes allocated memory
for(int i = 0; i < 5; i++)
free() Frees allocated memory ptr[i] = i + 1;

for(int i = 0; i < 5; i++)


printf("%d ", ptr[i]);

free(ptr); // deallocate heap memory


return 0;
JEYAVIM SHERIN, SCOPE, VIT-CHENNAI
}
RECURSION
• When a function calls itself (i.e) When a function calls a copy of itself
• Alternate to iterative solutions
• Solution to a problem depends on solutions to smaller instances

Advantages:

• Makes the program elegant.


• It adds clarity to the program code and also reduces the time to write the code.
• Reduces time complexity.
• It is best for solving problems based on tree structures.

Disadvantages :

• It is slower than non recursive programs due to the overhead of maintaining the stack.
• It requires more memory for the stack.

• For better performance, use loops instead of recursion. Because recursion is slower.
JEYAVIM SHERIN, SCOPE, VIT-CHENNAI
RECURSION
• Divide a problem into sub problems
• Solve the subproblems
• Combine the results

return_type function_name(arguments)
{
if(base condition)
return ;
else
return function_name(arguments)

base condition When it is met, it terminates the recursion.


to make sure that the program will terminate.
Otherwise, it goes into an infinite loop.

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


RECURSION-Factorial
if(n==0 || n==1)
fact(5) return 1;
else
return 5*fact(4);

if(n==0 || n==1)
fact(4) return 1;
else
return 4*fact(3);

if(n==0 || n==1)
fact(3) return 1;
else
return 3*fact(2);

if(n==0 || n==1)
return 1;
fact(2) else
return 2*fact(1);

fact(1) if(n==0 || n==1)


return 1;

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


RECURSION-Factorial

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI


RECURSION-Reverse list of integers
#include<stdio.h>
int show(int n)
{
if(n<1)
return;
else
{
printf("%d",n);
show(n-1);
printf("%d",n);

}
}
int main()
{
int n;
scanf("%d",&n);
show(n);
return 0;
} JEYAVIM SHERIN, SCOPE, VIT-CHENNAI
RECURSION(Fibonacci Series)
#include<stdio.h>
int fib(int);
int main ()
{
int num,fibo;
scanf(“%d”,&num);
fibo = fib(num);
printf("Result is: %d",fibo);
}
int fib(int num)
{
if (num==0||num==1)
{
return num;
}
else
{
return fib(num-1)+fib(num-2);
}
} JEYAVIM SHERIN, SCOPE, VIT-CHENNAI
1. Write a C program using a function to print your name and roll number.
2. Write a function that accepts two integers and prints their sum.
3. Write a program using a function to find the square of a number.
4. Write a function to check whether a number is even or odd.
5. Write a C program using a function to find the maximum of two numbers.
6. Write a function that returns the sum of two numbers and display the result in
main().
7. Write a function to return the factorial of a number.
8. Write a function to return the reverse of a given number.
9. Write a function that returns the sum of digits of a number.
[Link] a function to check whether a number is prime or not.

JEYAVIM SHERIN, SCOPE, VIT-CHENNAI

You might also like