0% found this document useful (0 votes)
59 views43 pages

Function in C

Uploaded by

sammaparween1992
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)
59 views43 pages

Function in C

Uploaded by

sammaparween1992
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/ 43

1

Function in C
What is function in general? 2
 In C programming, a function is a block of code that performs a specific task or
coherent type of task .

 Functions help in breaking down a large program into smaller, manageable, and
reusable pieces of code.

 They package up sets of instructions that can be used over and over again.

 This modular approach enhances readability, maintainability, and debugging.


Advantages of Function 3

1. Modularity:
Functions help break down complex problems into smaller, more manageable pieces. Each
function performs a specific task, making the program easier to understand and manage.

2. Code Reusability:
Functions can be reused across multiple programs or within the same program, reducing code
duplication. Once a function is written, it can be called anywhere, promoting reusability.

3. Maintainability:
Functions simplify the process of updating and maintaining code. When a change is required,
it can be made in the function, and all calls to that function will reflect the change, reducing
the risk of errors.
Advantages of Function 4

4. Abstraction:
Functions provide a way to abstract details. The caller of a function doesn't need to know the
internal workings of the function, just its interface (i.e., the input parameters and return type).
This abstraction makes the code cleaner and easier to work with.

5. Testing and Debugging:


Functions make it easier to test and debug the code. Each function can be tested
independently, ensuring that it works correctly before integrating it into the larger program.
This isolation helps in identifying and fixing issues more efficiently.

6. Organization:
Functions help in organizing code logically. Grouping related code into functions makes the
program structure more coherent and easier to navigate.
Advantages of Function 5

7. Parameterization:
Functions can accept parameters, making them versatile and adaptable to different
situations. This allows the same function to operate on various data inputs, enhancing flexibility.

8. Efficiency:
Functions can improve efficiency by reducing code repetition. By consolidating repeated
code into a single function, the overall size of the code is reduced, which can also lead to
performance improvements.

9. Library Creation:
Functions are the building blocks of libraries. By writing reusable functions and organizing them
into libraries, developers can create powerful tools that can be shared and used across
multiple projects.
Advantages of Function 6

10. Scope Management:


Functions create their own scope, which helps manage variable visibility and lifetime.
Variables declared inside a function are local to that function, preventing unintended
interactions with other parts of the program.
Types of Function 7

Different types of functions in C are


1. Library functions
2. User defined functions

1. Library function
Library functions are predefined functions provided by C's standard library. These
functions are declared in various header files and are linked to your program at compile
time. Some of examples of Library functions are
 printf() and scanf() for input and output operations (stdio.h).
 malloc() and free() for dynamic memory allocation (stdlib.h).
 strcpy() and strlen() for string handling (string.h).
 sqrt() and pow() for mathematical calculations (math.h).
Types of Function 8

Different types of functions in C are


1. Library functions
2. User defined functions

2. User-defined Functions
 User-defined functions are created by the programmer to perform specific tasks.
 They help in modularizing code by breaking it into smaller, manageable pieces.
 There are several types of user-defined functions based on their return type and
parameters.
Difference between user defined function and 9
library function
How function works? 10

 C program doesn't execute the statement in function until the function is called.
 When function is called the program can send the function information in the form of
one or more argument.
 When the function is used it is referred to as the called function
 Functions often use data that is passed to them from the calling function
 Data is passed from the calling function to a called function by specifying the variables
in a argument list.
 Argument list cannot be used to send data. Its only copy data/value/variable that pass
from the calling function.
 The called function then performs its operation using the copies.
Components of user defined function 11

1. Function Declaration (Prototype)


2. Function Definition
3. Function Call
4. return statement
Components of user defined function 12

1. Function Declaration (Prototype)


 Provides the compiler with the description of functions that will be used later in the program
 Its define the function before it been used/called
 Function prototypes need to be written at the beginning of the program in global section of a
program.
The function prototype must have :
 A return type indicating the variable that the function will be return
Syntax for Function Prototype
return-type function_name( arg-type name-1,...,arg-type name-n);
Function Prototype Examples:
 double squared( double number );
 void print_report( int report_number );
 int get_menu_choice( void);
Components of user defined function 13

2. Function Definition
 Contains the actual code to be executed when the function is called.
 Comprises the return type, function name, parameters (if any), and the body of the function
enclosed in curly braces {}.
 Should be identical to the function prototype.
Syntax of Function Definition
return-type function_name(arg-type name-1,...,arg-type name-n)
{
declarations;
statements; Body of a function
return(expression);
}
Components of user defined function 14

Example1
int add(int a, int b)
{
return a + b;
}
The function name is add
This function accepts two arguments a and b of the type int. The function return an int
value (sum of a and b).

Note that if the function is returning a value, it needs to use the keyword return.
Components of user defined function 15

3. Function Call
 A statement that executes the function.
 Includes the function name followed by arguments enclosed in parentheses.
 A function call is an expression that transfers control to a function.
 When a function is called, the control of the program shifts to the called function.
 After executing the function body, the control returns to the calling function.
 If return type of function is void then we don’t need variable to collect value returned
by function. We simply call function by it’s name in main() function.
syntax:
function_name(argument_list)
Components of user defined function 16

3. Function Call
 If return type of a function is other than void then we need to collect value returned by
function in a variable of return type of function.
 If the return type of a function is other than void, then we need to store the value
returned by the function in a variable of the same return type.

Example:
Example of function call 17

#include <stdio.h>
int add(int a, int b);
int main() {
int result;
int num1 = 5, num2 = 10;
result = add(num1, num2);//Functin Call
printf("The sum of %d and %d is %d\n", num1, num2, result);
return 0;
}
int add(int a, int b) {
return a + b;
}
Components of user defined function 18

4. Return and void statement of a function


 The return statement in C is used to exit a function and optionally return a value to the
function's caller.
 It can be used in any function, including main(), to provide a result or simply indicate that the
function has finished executing.
 In C, the void keyword is used to specify that a function does not return a value.
Syntax
return expression;
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0; // Indicate successful execution
}
Components of user defined function 19

4. return statement
 The return statement in C is used to exit a function and optionally return a value to the
function's caller.
 It can be used in any function, including main(), to provide a result or simply indicate that the
function has finished executing.
Syntax
return expression;
#include <stdio.h>

int main() {
printf("Hello, World!\n");
return 0; // Indicate successful execution
}
Actual Arguments and Formal Arguments 20

“Actual arguments" and “Formal arguments" refer to the parameters involved in function
calls and definitions.
Actual Arguments
 Actual arguments (or actual parameters) are the values or expressions provided to a
function when it is called.
 These are the real inputs that the function uses during its execution.

Formal Arguments
 Formal arguments (or formal parameters) are the variables defined by the function that
receive the values of the actual arguments.
 These are placeholders used in the function definition.
Example of Actual Arguments and Formal 21
Arguments
#include <stdio.h>

// Function declaration with formal arguments

int add(int x, int y);

int main() {

int a = 5, b = 10;

int result;

// Function call with actual arguments

result = add(a, b);

// Print the result

printf("The sum of %d and %d is %d\n", a, b, result);

return 0;

// Function definition with formal arguments

int add(int x, int y) {

return x + y;

}
Types of user defined functions in c 22

User-defined functions can be categorized based on their return types and


the presence of arguments. The the main types are:

 Functions with No Return Value and No Parameters


 Functions with No Return Value but With Parameters
 Functions with Return Value but No Parameters
 Functions with Return Value and Parameters
Functions with No Return Value and No Parameters
23

 These functions do not return any value to the caller and do not take any arguments.
 They are often used for performing tasks like printing messages or initializing variables.
 Not able to get any value from the calling function Not returning any value
 There is no data transfer between the calling function and called function.
Example:
#include <stdio.h>

void greet() {

printf("Hello, World!\n");

int main() {

greet();

return 0;

}
Functions with No Return Value but with Parameters
24

 These functions do not return any value but take arguments to perform their tasks.

Example
#include <stdio.h>
void printSum(int a, int b) {
printf("The sum of %d and %d is %d\n", a, b, a + b);
}
int main() {
printSum(5, 10);
return 0;
}
Functions with Return Value but with No Parameters
25

 These functions return a value to the caller but do not take any arguments.
Example
#include <stdio.h>
int getNumber() {
return 42;
}
int main() {
int num = getNumber();
printf("The number is %d\n", num);
return 0;
}
Functions with Return Value Parameters
26

 These functions return a value to the caller and also take arguments.
 This type is the most versatile and commonly used.
Example
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int sum = add(5, 10);
printf("The sum of 5 and 10 is %d\n", sum);
return 0;
}
Recursive Function in C
27

 Recursion is a technique in C programming where a function calls itself to solve smaller


instances of the same problem.
 This technique can be particularly useful for problems that can be broken down into
smaller, similar sub-problems, such as calculating factorials, generating Fibonacci
sequences
 Base Case: The condition under which the recursion ends. Without a base case, the
function would call itself indefinitely, leading to a stack overflow.
 Recursive Case: The part of the function where the function calls itself with a smaller or
simpler sub-problem
Recursive Function in C
28

Example : Factorial Function


Recursive Function in C
29
Example : Factorial Function
#include <stdio.h>
// Recursive function to calculate factorial
int factorial(int n) {
if (n == 0) {
return 1; // Base case: 0! = 1
} else {
return n * factorial(n - 1); // Recursive call
}
}
int main() {
int num = 5;
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
Recursive Function in C
30
Step by step breakdown of the recursive call
Step1 : factorial(5) is called
Step2: Since n!=0, it returns 5 * factorial(4)
Step3: factorial(4) is called
Step4: Since n!=0, it returns 4* factorial(3)
Step5: factorial(3) is called
Step6: Since n!=0, it returns 3* factorial(2)
Step7: factorial(2) is called
Step8: Since n!=0, it returns 2* factorial(1)
Step9: factorial(1) is called
Step10: Since n!=0, it returns 1* factorial(0)
Step11: Since n==0, it returns 1
Recursive Function in C
31
The diagram below illustrates the recursive calls and the return process:

factorial(5)

--> 5 * factorial(4)

--> 4 * factorial(3)

--> 3 * factorial(2)

--> 2 * factorial(1)

--> 1 * factorial(0)

--> 1

<-- 1 * 1 = 1

<-- 2 * 1 = 2

<-- 3 * 2 = 6

<-- 4 * 6 = 24

<-- 5 * 24 = 120
Recursive Function in C
32
The diagram below illustrates the recursive calls and the return process:

factorial(5)

--> 5 * factorial(4)

--> 4 * factorial(3)

--> 3 * factorial(2)

--> 2 * factorial(1)

--> 1 * factorial(0)

--> 1

<-- 1 * 1 = 1

<-- 2 * 1 = 2

<-- 3 * 2 = 6

<-- 4 * 6 = 24

<-- 5 * 24 = 120
Concept of storage classes in C
33

 Storage classes determine the scope (visibility) and lifetime of variables and/or functions
within a C program.

There are four storage classes in C


1. Automatic (auto)
2. External (extern)
3. Static (static)
4. Register (register)
Concept of storage classes in C
34
1. Automatic (auto)

 Default Storage Class: The auto storage class is the default for all local variables. If you do not
specify a storage class for a local variable, it is automatically assumed to be auto.
 Scope: Variables declared with the auto keyword have a local scope, meaning they are only
visible within the block (or function) in which they are defined.
 Lifetime: The lifetime of an automatic variable is limited to the duration of the block (or
function) in which it is defined. Once the block or function exits, the variable is destroyed, and
its memory is reclaimed.
 Keyword: The auto keyword is rarely used explicitly because it is the default behavior.
Concept of storage classes in C
35
1. Automatic (auto)
Example:
#include <stdio.h>
void exampleFunction() {
auto int a = 5; // 'auto' keyword is optional here
printf("Value of a: %d\n", a);
}
int main() {
exampleFunction();
// 'a' is not accessible here, it's out of scope
return 0;
}
Concept of storage classes in C
36

2. External (extern)

 Global Scope: Variables declared with the extern keyword have a global scope,
meaning they can be accessed from any function within the same or other files.
 Lifetime: The lifetime of an external variable is the entire duration of the program. They
are allocated memory at the start of the program and are deallocated at the end.
 Keyword: The extern keyword is used to declare a global variable or function in another
file.
Concept of storage classes in C 37
2. External (extern) void function1() {

Example: extern int globalVariable; // Declaration of the global


variable
#include <stdio.h>
globalVariable = 20; // Modify the global variable
// Definition of the global variable
printf("Value of globalVariable in function1: %d\n",
int globalVariable = 10; globalVariable);
void function1(); }
void function2();

void function2() {
int main() { extern int globalVariable; // Declaration of the global
printf("Initial value of globalVariable in main: variable
%d\n", globalVariable); globalVariable = 30; // Modify the global variable
function1(); printf("Value of globalVariable in function2: %d\n",
function2(); globalVariable);

return 0; }

}
Concept of storage classes in C
38

3. Static (For information purpose only, it is not in syllabus)

 Persistent Lifetime: Variables declared with the static keyword have a persistent lifetime,
meaning they retain their value between function calls.
 Scope: The scope of a static variable can be either local or global. A static local variable is
only accessible within the block or function where it is defined, while a static global variable is
only accessible within the file it is defined in.
 Initialization: Static variables are initialized only once, and if not explicitly initialized, they are
initialized to zero.
Concept of storage classes in C
39

3. Static (For information purpose only, it is not in syllabus)

 Persistent Lifetime: Variables declared with the static keyword have a persistent lifetime,
meaning they retain their value between function calls.
 Scope: The scope of a static variable can be either local or global. A static local variable is
only accessible within the block or function where it is defined, while a static global variable is
only accessible within the file it is defined in.
 Initialization: Static variables are initialized only once, and if not explicitly initialized, they are
initialized to zero.
Concept of storage classes in C 40
3. Static (For information purpose only, it is not int main() {
in syllabus)
staticExample();
Example
staticExample();
#include <stdio.h>
staticExample();
return 0;
void staticExample() {
}
static int count = 0; // Static variable
Output:
initialization
Count:1
count++;
Count:2
printf("Count: %d\n", count);
Count:3
}
Concept of storage classes in C
41

4. Register Storage Class

 Fast Access: The register keyword hints to the compiler that the variable will be heavily
used and should be stored in a CPU register for faster access, if possible.
 Scope: Register variables have the same scope as automatic variables, meaning they
are local to the block or function where they are defined.
 Lifetime: The lifetime of a register variable is the same as that of an automatic variable,
limited to the duration of the block or function.
 Limitations: You cannot take the address of a register variable using the & operator
because it may be stored in a register rather than in memory.
Concept of storage classes in C
42

4. Register Storage Class (Example)


#include <stdio.h>
void registerExample() {
register int counter; // Register variable
for (counter = 0; counter < 10; counter++) {
printf("%d ", counter);
}
printf("\n");
}
int main() {
registerExample();
return 0;
}
43

You might also like