0% found this document useful (0 votes)
5 views15 pages

PPS Mod4

The document provides an overview of C functions, including their syntax, declaration, definition, and calling methods. It explains parameter passing techniques such as pass by value and pass by reference, and discusses dynamic memory allocation using functions like malloc, calloc, free, and realloc. Additionally, it covers recursion, its limitations, and includes examples of standard library functions and header files in C.

Uploaded by

Sunny
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views15 pages

PPS Mod4

The document provides an overview of C functions, including their syntax, declaration, definition, and calling methods. It explains parameter passing techniques such as pass by value and pass by reference, and discusses dynamic memory allocation using functions like malloc, calloc, free, and realloc. Additionally, it covers recursion, its limitations, and includes examples of standard library functions and header files in C.

Uploaded by

Sunny
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

C Functions:

A function in C is a set of statements that when called perform some specific tasks. It is the
basic building block of a C program that provides modularity and code reusability. The
programming statements of a function are enclosed within { } braces.

Syntax of Functions in C

The syntax of function can be divided into 3 aspects:

1. Function Declaration

2. Function Definition

3. Function Calls

Function Declarations:
In a function declaration, we must provide the function name, its return type, and the
number and type of its parameters. A function declaration tells the compiler that there is a
function with the given name defined somewhere else in the program.
Syntax
return_type name_of_the_function (parameter_1, parameter_2);
The parameter name is not mandatory while declaring functions. We can also declare the
function without using the name of the data variables.
Example
int sum(int a, int b); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names
Function Definition

The function definition consists of actual statements which are executed when the function is called
(i.e. when the program control comes to the function).

return_type function_name (para1_type para1_name, para2_type para2_name)


{
// body of the function
}

Function Call
A function call is a statement that instructs the compiler to execute the function. We use the function
name and parameters in the function call.

In the below example, the first sum function is called and 10,30 are passed to the sum function. After
the function call sum of a and b is returned and control is also returned back to the main function of
the program.
Example of C Function:

// C program to show function


// call and definition
#include <stdio.h>

// Function that takes two parameters


// a and b as inputs and returns
// their sum
int sum(int a, int b) {
return a + b;
}
int main()
{
// Calling sum function and
// storing its value in add variable
int add = sum(10, 30);
printf("Sum is: %d", add);
return 0;
}
OUTPUT: Sum is: 40

--------------------------------------------------------------------------------------------------------------
Function Return Type:
Function return type tells what type of value is returned after all function is executed. When
we don’t want to return a value, we can use the void data type.
Example:
int func(parameter_1,parameter_2);
The above function will return an integer value after running statements inside the function.
Function Arguments:
Function Arguments (also known as Function Parameters) are the data that is passed to a
function.
Example:
int function_name(int var1, int var2);
============================================================

Parameter Passing Techniques in C


Last Updated : 11 Oct, 2024

In C, there are different ways in which parameter data can be passed into and out of
methods and functions. Let us assume that a function B() is called from another function A().
In this case, A is called the “caller function” and B is called the “called function or callee
function”. Also, the arguments which A sends to B are called actual arguments and the
parameters of B are called formal arguments.
Terminology
 Formal Parameter: A variable and its type as it appears in the prototype of the
function or method.
 Actual Parameter: The variable or expression corresponding to a formal parameter
that appears in the function or method call in the calling environment.
 Modes:
o IN: Passes info from caller to the callee.
o OUT: Callee writes values in the caller.
o IN/OUT: The caller tells the callee the value of the variable, which the callee
may update.
Parameter passing techniques in C, such as 1)pass by value and 2) pass by reference, are
fundamental for controlling data flow.
Methods of Parameter Passing in C
There are two ways in which we can pass the parameters to the function in C:
1. Pass By Value
This method uses in-mode semantics. Changes made to formal parameters do not get
transmitted back to the caller. Any modifications to the formal parameter variable inside the
called function or method affect only the separate storage location and will not be reflected
in the actual parameter in the calling environment. This method is also called call by value.

// C program to illustrate the call by value


#include <stdio.h>
void func(int a, int b) {
a += b;
printf("In func, a = %d b = %d\n", a, b);
}
int main(void) {
int x = 5, y = 7;
// Passing parameters
func(x, y);
printf("In main, x = %d y = %d\n", x, y);
return 0;
}
OUTPUT:
In func, a = 12 b = 7
In main, x = 5 y = 7

2. Pass by Reference / Pass by Pointers:


This technique uses a pointer. In function we pass memory address (pointer) of a variable
rather than passing the actual value of variable. This passing technique allows the function
to access and modify the content at that particular memory location.
Example of Pass by Pointers
// C program to demonstrate the pass by pointer in Function
#include <stdio.h>
// Function to modify the value passed as pointer to an int
void modifyVal(int* myptr)
{
// Access and modifying the value pointed by myptr
*myptr = *myptr + 5;
}
int main()
{
int x = 5;
int* myptr = &x;
// Passing the pointer ptr to the function
modifyVal(myptr);
// printitng the modified value of x
printf("Modified value of x is: %d\n", x);
return 0;
}

Output:
Modified value of x is: 10
c standard functions and libraries:
Here are some C standard functions :
 printf: A standard library function that is defined in the stdio.h header file
 strlen: A function that determines the length of a string, excluding the ending null
character
 strcmp: A commonly used function for string and character manipulation
 strcpy: A commonly used function for string and character manipulation
 fgets: A function that reads a line of text from a file or the standard input
 system: A function that executes operating system commands on the terminal
 fmod: A function with the system include file math.h and the function prototype
double fmod(double x, double y)
 fopen: A function with the system include file stdio.h and the function prototype FILE
*fopen(const char *filename, const char *mode)
 fprintf: A function with the system include file stdio.h and the function prototype int
fprintf(FILE *stream, const char *format-string, arg-list)
 fputc: A function with the system include file stdio.h and the function prototype int
fputc(int c, FILE *stream)

C Library Functions
The Standard Function Library in C is a huge library of sub-libraries, each of which contains
the code for several functions. In order to make use of these libraries, link each library in the
broader library through the use of header files. The actual definitions of these functions are
stored in separate library files, and declarations in header files. In order to use
these functions, we have to include the header file in the program. Below are some header
files with descriptions:

S
No. Header Files Description

It checks the value of an expression that we expect to be true


1 <assert.h> under normal circumstances.
If the expression is a nonzero value, the assert macro does nothing.

2 <complex.h> A set of functions for manipulating complex numbers.

3 <float.h> Defines macro constants specifying the implementation-specific


properties of the
S
No. Header Files Description

floating-point library.

These limits specify that a variable cannot store any value beyond
4 <limits.h> these limits, for example-
An unsigned character can store up to a maximum value of 255.

The math.h header defines various mathematical functions and one


macro. All the Functions
5 <math.h>
in this library take double as an argument and return double as the
result.

The stdio.h header defines three variable types, several macros,


6 <stdio.h> and various
function for performing input and output.

7 <time.h> Defines date and time handling functions.

Strings are defined as an array of characters. The difference


between a character array
8 <string.h>
and a string is that a string is terminated with a special character ‘\
0’.

========================================================
========================================================
UNIT – 2:
RECURSION :
Recursion is a programming technique that involves a function calling
itself, either directly or indirectly, to break down a problem into
smaller, more manageable pieces:
 Find Factorial of a Number Using Recursion:
The idea is to use the recursive function with the argument N which will progressively
decrement by 1 till it reaches 0. In each recursive call, we return the function call for
decremented N after multiplying it with current N. At the end, we will be left with the
factorial of N.
 Create a function factorial() that takes the number N as argument.
 If N is 0 or 1, return 1.
 Otherwise, return N multiplied by the factorial (N-1).
Program to Find the Factorial Using Recursion:

// C program to find factorial of given number using recursion


#include <stdio.h>
unsigned int factorial(unsigned int n) {
if (n == 1) {
return 1;
}
// Multiplying the current N with the previous product of Ns
return n * factorial(n - 1);
}
int main() {
int num = 5;
printf("Factorial of %d is %d", num, factorial(num));
return 0;
}
--------------------------------------------------------------------

Recursion has some limitations, including:


 Memory usage
Recursion uses more memory than non-recursive programs because each recursive call adds
a new function call to the call stack. This can lead to stack overflows if the call stack fills up.
 Speed
Recursive programs are generally slower than non-recursive programs because they need to
save and restore the program's state for each function call.
 Confusing
Recursion can be confusing and difficult to understand unless you're familiar with it.
 Not always the best option
Recursion might not be the best option for an algorithm, especially if:
 The problem doesn't have a clear base case or recursive case
 The recursive case doesn't significantly reduce the problem size
=====================================================================

Dynamic Memory Allocation in C using malloc(), calloc(), free() and


realloc() :

Since C is a structured language, it has some fixed rules for programming. One of
them includes changing the size of an array. An array is a collection of items stored at
contiguous memory locations.

As can be seen, the length (size) of the array above is 9. But what if there is a requirement to
change this length (size)? For example,
 If there is a situation where only 5 elements are needed to be entered in this array. In
this case, the remaining 4 indices are just wasting memory in this array. So there is a
requirement to lessen the length (size) of the array from 9 to 5.
 Take another situation. In this, there is an array of 9 elements with all 9 indices filled.
But there is a need to enter 3 more elements in this array. In this case, 3 indices more
are required. So the length (size) of the array needs to be changed from 9 to 12.
This procedure is referred to as Dynamic Memory Allocation in C.
Dynamic memory allocation using malloc(), calloc(), free(), and realloc() is essential for
efficient memory management in C
Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size of
a data structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided by C
defined under <stdlib.h> header file to facilitate dynamic memory allocation in C
programming. They are:
1. malloc()
2. calloc()
3. free()
4. realloc()

Let’s look at each of them in greater detail.

 C malloc() method :
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single
large block of memory with the specified size. It returns a pointer of type void which can be
cast into a pointer of any form. It doesn’t Initialize memory at execution time so that it has
initialized each block with the default garbage value initially.
Syntax of malloc() in C
ptr = (cast-type*) malloc(byte-size)

 C calloc() method:
1. “calloc” or “contiguous allocation” method in C is used to dynamically allocate the
specified number of blocks of memory of the specified type. it is very much similar to
malloc() but has two different points and these are:
2. It initializes each block with a default value ‘0’.
3. It has two parameters or arguments as compare to malloc().
Syntax of calloc() in C :
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.

 C free() method:
“free” method in C is used to dynamically de-allocate the memory. The memory allocated
using functions malloc() and calloc() is not de-allocated on their own. Hence the free()
method is used, whenever the dynamic memory allocation takes place. It helps to reduce
wastage of memory by freeing it.
Syntax of free() in C
free(ptr);
Example Program to allocate and free the memory:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the
// base address of the block created
int *ptr, *ptr1;
int n, i;
// Get the number of elements for the array
n = 5;
printf("Enter number of elements: %d\n", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
// Dynamically allocate memory using calloc()
ptr1 = (int*)calloc(n, sizeof(int));
// Check if the memory has been successfully
// allocated by malloc or not
if (ptr == NULL || ptr1 == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using malloc.\n");
// Free the memory
free(ptr);
printf("Malloc Memory successfully freed.\n");
// Memory has been successfully allocated
printf("\nMemory successfully allocated using calloc.\n");
// Free the memory
free(ptr1);
printf("Calloc Memory successfully freed.\n");
}
return 0;
}
OUTPUT:
Enter number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.

Memory successfully allocated using calloc.


Calloc Memory successfully freed.

 C realloc() method:
“realloc” or “re-allocation” method in C is used to dynamically change the memory
allocation of a previously allocated memory. In other words, if the memory previously
allocated with the help of malloc or calloc is insufficient, realloc can be used
to dynamically re-allocate memory. re-allocation of memory maintains the already present
value and new blocks will be initialized with the default garbage value.
Syntax of realloc() in C
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.

C program to illustrate realloc() :

#include <stdio.h>
#include <stdlib.h>
int main()
{
int index = 0, i = 0, n,
*marks; // this marks pointer hold the base address
// of the block created
int ans;
marks = (int*)malloc(sizeof(
int)); // dynamically allocate memory using malloc
// check if the memory is successfully allocated by
// malloc or not?
if (marks == NULL) {
printf("memory cannot be allocated");
}
else {
// memory has successfully allocated
printf("Memory has been successfully allocated by "
"using malloc\n");
printf("\n marks = %pc\n",
marks); // print the base or beginning
// address of allocated memory
do {
printf("\n Enter Marks\n");
scanf("%d", &marks[index]); // Get the marks
printf("would you like to add more(1/0): ");
scanf("%d", &ans);

if (ans == 1) {
index++;
marks = (int*)realloc(
marks,
(index + 1)
* sizeof(
int)); // Dynamically reallocate
// memory by using realloc
// check if the memory is successfully
// allocated by realloc or not?
if (marks == NULL) {
printf("memory cannot be allocated");
}
else {
printf("Memory has been successfully "
"reallocated using realloc:\n");
printf(
"\n base address of marks are:%pc",
marks); ////print the base or
///beginning address of
///allocated memory
}
}
} while (ans == 1);
// print the marks of the students
for (i = 0; i <= index; i++) {
printf("marks of students %d are: %d\n ", i,
marks[i]);
}
free(marks);
}
return 0;
}

OUTPUT:

You might also like