0% found this document useful (0 votes)
3 views23 pages

C Unit 4

The document covers the concept and need for functions in C programming, including library functions and user-defined functions. It explains function syntax, types of functions, and the differences between local and global variables. Additionally, it provides examples of various functions, including recursive functions and string manipulation functions.
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)
3 views23 pages

C Unit 4

The document covers the concept and need for functions in C programming, including library functions and user-defined functions. It explains function syntax, types of functions, and the differences between local and global variables. Additionally, it provides examples of various functions, including recursive functions and string manipulation functions.
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

1

Unit - IV Functions (14 Marks)


4.1 Concept and need of functions.
4.2 Library functions: Math functions, String handling functions, other miscellaneous
functions such as getchar(), putchar(), malloc(), calloc().
4.3 Writing User defined functions - function definition, functions declaration, function call,
scope of variables - local variables, global variables.
4.4 Function parameters: Parameter passing- call by value & call by reference, function return
values, function return types ,declaring function return types, The 'return' statement.
4.5 Recursive functions.

What is a Function?
A function is a named block of code that performs a specific task. A function can take inputs
(called parameters), execute a block of statements, and optionally return a result.
A function allows you to write a piece of logic once and reuse it wherever needed in the
program.
This helps keep your code clean, organized, easier to understand and manage.
Why Do We Need Functions?

Source: [Link]

Function Syntax

 Return type: Specifies the type of value the function will return. Use void if the function
does not return anything.

1 prepared by: yogita k


2

 Function name: A unique name that identifies the function. It follows the same naming
rules as variables.
 Parameter list: A set of input values passed to the function. If the function takes no
inputs, this can be left empty or written as void.
 Function body: The block of code that runs when the function is called. It is enclosed in
curly braces { }.
Example:
Without using function With using functiom
printf("Hello\n"); void printHello()
printf("Hello\n"); { Function
printf("Hello\n"); printf("Hello\n"); definition
}

printHello(); Calling function


printHello();
printHello();

Function A declaration tells the compiler about the int add(int a, int b);
Declaration function's name, return type, and
parameters before it is actually used. It
does not contain the function's body. This
is often placed at the top of the program
or in a header file.
The declaration introduces the function to
the compiler, and the definition explains
what it actually does.
Function A definition provides the actual int add(int a, int b)
Definition implementation of the function. It includes {
the full code or logic that runs when the return a + b;
function is called. }
Once a function is defined, you can use it #include <stdio.h>
by simply calling its name followed by // Function definition
Calling a parentheses. This tells the program to int add(int a, int b)
Function execute the code inside that function. {
return a + b;
}

int main()
{
// Function call
int result = add(5, 3);
printf("The sum is: %d", result);
return 0;
}

2 prepared by: yogita k


3

Types of Functions:

[Link] Functions:
Library functions in C provides a wide range of functionalities and features including string
manipulation,input/output operations , mathematical calculations, file handling, memory
management and more. These functions are typically declared in header files and can be
accessed in the program by including the appropriate header file in your C program.

2. User-defined functions:

User-defined functions in c programming is some what same as inbuilt [Link] user


defined functions that are created by the programmer to perform specific operations or task.
These functions are not available in c Library or predefined in the c programming language
but are defined and created by the user to meet their specific task and requirements.

Example:
#include <stdio.h>
Output: The sum is: 8
void addition(int x, int y)
{
int tot = x + y;
printf("The sum is: %d\n", tot);
}
int main()
{
int x = 5,y=3;
addition(x, y);
return 0;
}

3 prepared by: yogita k


4

Types of User Defined Functions


User defined functions are classified based on:
 Arguments (Parameters)
 Return Value
There are 4 Types
Type 1: No Arguments, No Return Value
✔ Does not take input
✔ Does not return value
Syntax Example
void functionName() #include <stdio.h>
{ void greet()
// statements {
} printf("Welcome Students");
}
int main()
{
greet();
return 0;
}
Type 2: Arguments, No Return Value
✔ Takes input
✔ Does not return value
Syntax Example
void functionName(type var1, type var2) #include <stdio.h>
{ void add(int a, int b)
// statements {
} printf("Sum = %d", a + b);
}
int main()
{
add(5, 3);
return 0;
}
Type 3: No Arguments, Return Value
✔ Does not take input
✔ Returns value
Syntax Example
return_type functionName() #include <stdio.h>
{ int getNumber()
return value; {
} return 10;
}
int main()
{
int num;
num = getNumber();

4 prepared by: yogita k


5

printf("%d", num);
return 0;
}
Type 4: Arguments and Return Value (Most Important)
✔ Takes input
✔ Returns value
Syntax Example
return_type functionName(type var1, type #include <stdio.h>
var2) int add(int a, int b)
{ {
return value; return a + b;
} }

int main()
{
int result;
result = add(10, 20);
printf("Sum = %d", result);
return 0;
}
Use of return Keyword in C
The return keyword is used to:
1. Send a value back to the calling function.
2. Terminate (end) the execution of a function.
Why Do We Use return?
 To give output from a function.
 To stop function execution.
 To transfer control back to main() or calling function.

Local and Global Variables in C


A local variable is a variable declared inside a function or block.
It can be used only inside that function.
#include <stdio.h> Output:
void display()
{ x = 10
int x = 10; // Local variable
printf("x = %d", x);
}

int main() Points to remember:


{ ✔ x is accessible only inside display()
display(); ✔ Cannot be used in main()
return 0;
}
#include <stdio.h> Output: Error: x not declared
void display()
{
int x = 10;
5 prepared by: yogita k
6

}
int main()
{
printf("%d", x); // Error: x not declared
}
Characteristics of Local Variables:
 Declared inside function
 Scope limited to that function
 Created when function starts
 Destroyed when function ends

Global Variables
 A global variable is declared outside all functions.
 It can be accessed by all functions in the program.
#include <stdio.h> Output:
int x = 100; // Global variable x = 100
void display() x = 100
{
printf("x = %d\n", x);
}
int main()
{
display();
printf("x = %d", x);
return 0;
}
Characteristics of Global Variables
 Declared outside functions
 Accessible throughout program
 Lifetime is entire program execution
 Stored in global memory area
Combined example of local and global variable:
#include <stdio.h>
int x = 50; // Global variable
void test() Output:
{ Global x = 50
int y = 20; // Local variable Local y = 20
printf("Global x = %d\n", x); Global x in main = 50
printf("Local y = %d\n", y);
}
int main()
{
test();
printf("Global x in main = %d", x);
return 0;
}

6 prepared by: yogita k


7

Comparison: Local vs Global Variables in C


Basis of Local Variable Global Variable
Comparison
Definition Variable declared inside a function or Variable declared outside all
block functions
Place of Inside main() or any other function At the top of program,
Declaration before all functions
Scope Accessible only within the function in Accessible throughout the
which it is declared entire program
Visibility Not visible outside the function Visible to all functions
Lifetime Exists only while the function is Exists throughout the entire
executing execution of program
Data Sharing Cannot share data between functions Can share data between
directly multiple functions
Security More secure (limited access) Less secure (can be modified
anywhere)
Name Conflict No conflict outside function Risk of name conflict in large
programs
Priority Has higher priority inside its function Lower priority if local variable
(over global variable with same name) with same name exists
Example int x = 10; inside function int x = 10; outside all
Declaration functions
Effect on Program Encourages modular programming Can make debugging
Design difficult if overused
Destruction Destroyed automatically when function Destroyed only when
ends program terminates

Exercise:
// Program to Find Square of a Number Using
Function
#include <stdio.h>
// Function declaration
int square(int a);
int main()
{
int num, result;
printf("Enter a number: ");
scanf("%d", &num);
result = square(num); // Function call
printf("Square = %d", result);
return 0;
}

// Function definition
int square(int a)
{
return a * a;
}
7 prepared by: yogita k
8

Program to Calculate Simple Interest Using Function


#include <stdio.h> Enter Principal, Rate and Time:
10000
// Function declaration 5
float simpleInterest(float p, float r, float t); 2
Simple Interest = 1000.00
int main()
{
float p, r, t, si;
printf("Enter Principal, Rate and Time: ");
scanf("%f %f %f", &p, &r, &t);
si = simpleInterest(p, r, t); // Function call
printf("Simple Interest = %.2f", si);
return 0;
}

// Function definition
float simpleInterest(float p, float r, float t) {
return (p * r * t) / 100;
}

Program to Check Whether a Number is Prime Using Enter a number: 5


Function Prime Number
#include <stdio.h>
// Function declaration
void checkPrime(int n);

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

checkPrime(num); // Function call

return 0;
}

// Function definition
void checkPrime(int n) {
int i, flag = 0;

if(n <= 1) {
printf("Not Prime");
return;
}

for(i = 2; i <= n/2; i++) {


if(n % i == 0) {
8 prepared by: yogita k
9

flag = 1;
break;
}
}

if(flag == 0)
printf("Prime Number");
else
printf("Not Prime");
}
Program to Swap Two Numbers Using Function (Call by
Value)
#include <stdio.h>

// Function declaration
void swap(int a, int b);

int main() {
int x, y;

printf("Enter two numbers: ");


scanf("%d %d", &x, &y);

swap(x, y); // Function call

return 0;
}

// Function definition
void swap(int a, int b) {
int temp;

temp = a;
a = b;
b = temp;

printf("After Swapping: %d %d", a, b);


}

//find even and odd number Enter an integer: 5


#include <stdio.h> 5 is Odd.
--
// Function declaration Enter an integer: 10
void checkOddEven(int num);
10 is Even.
int main() {
int number;

// Taking input from user


printf("Enter an integer: ");
scanf("%d", &number);

9 prepared by: yogita k


10

// Function call
checkOddEven(number);
return 0;
}

// Function definition
void checkOddEven(int num) {
if (num % 2 == 0)
printf("%d is Even.\n", num);
else
printf("%d is Odd.\n", num);
}
#include <stdio.h> 10 is Even.
// Function declaration 5 is Odd.
void checkOddEven(int num); 14 is Even.
int main()
{
// Passing value to function (Call by Value)
checkOddEven(10);
checkOddEven(5);
checkOddEven(14);
return 0;
}
// Function definition
void checkOddEven(int num) {
if (num % 2 == 0)
printf("%d is Even.\n", num);
else
printf("%d is Odd.\n", num);
}
#include <stdio.h> Factorial of 5 is 120
// Function declaration
long int factorial(int n);
int main()
{
int number = 5; // Value assigned directly
long int result;
// Function call
result = factorial(number);
printf("Factorial of %d is %ld\n", number, result);
return 0;
}
// Function definition
long int factorial(int n)
{
int i;
long int fact = 1;
for(i = 1; i <= n; i++) {
fact = fact * i;
}

return fact;
}

10 prepared by: yogita k


11

//Fibonacci series Fibonacci Series up to 7 terms:


#include <stdio.h> 0112358
// Function declaration
void fibonacci(int n);
int main()
{
int number = 7; // Number of terms (assigned directly)
// Function call
fibonacci(number);
return 0;
}
// Function definition
void fibonacci(int n)
{
int first = 0, second = 1, next, i;
printf("Fibonacci Series up to %d terms:\n", n);

for(i = 1; i <= n; i++)


{
printf("%d ", first);
next = first + second;
first = second;
second = next;
}
}

C String Functions
C language provides various built-in functions that can be used for various operations and
manipulations on strings. These string functions make it easier to perform tasks such as
string copy, concatenation, comparison, length, etc.
The <string.h> header file contains these string functions.
strlen()
The strlen() function is used to find the length of a string. It returns the number of
characters in a string, excluding the null terminator ('\0').
#include <stdio.h> 11
#include <string.h>
int main() {
char s[] = "vidyalankar";
// Finding and printing length of string s
printf("%lu", strlen(s));
return 0;
}
strcpy()
The strcpy() function copies a string from the source to the destination. It copies the entire
string, including the null terminator.
#include <stdio.h> Hello
#include <string.h>
int main() { Hello
char src[] = "Hello";

11 prepared by: yogita k


12

char dest[20];
// Copies "Hello" to dest
strcpy(dest, src);
printf("%s", src);
printf("\n%s", dest);
return 0;
}
strcat()
The strcat() function is used to concatenate (append) one string to the end of another. It
appends the source string to the destination string, replacing the null terminator of the
destination with the source string’s content.
#include <stdio.h> Hello, IF2K-A
#include <string.h>

int main() {
char s1[30] = "Hello, ";
char s2[] = "IF2K-A";

// Appends "Geeks!" to "Hello, "


strcat(s1, s2);
printf("%s", s1);
return 0;
}
strcmp()
The strcmp() is a built-in library function in C. This function takes two strings as arguments,
compares these two strings lexicographically and returns an integer value as a result of
comparison.
#include <stdio.h> s1 is lexicographically smaller than s2
#include <string.h>

int main() {
char s1[] = "Apple";
char s2[] = "Applet";
// Compare two strings
// and print result
int res = strcmp(s1, s2);
if (res == 0)
printf("s1 and s2 are same");
else if (res < 0)
printf("s1 is lexicographically "
"smaller than s2");
else
printf("s1 is lexicographically "
"greater than s2");
return 0;
}

12 prepared by: yogita k


13

#include <stdio.h> Enter first string: VP


#include <string.h> Enter second string: IF
int main() { Strings are not equal
char str1[20], str2[20];

printf("Enter first string: "); Enter first string: if2k


scanf("%s", str1); Enter second string: if2k
Strings are equal
printf("Enter second string: ");
scanf("%s", str2);
Enter first string: VP
if(strcmp(str1, str2) == 0) Enter second string: vp
printf("Strings are equal"); Strings are not equal
else
printf("Strings are not equal");

return 0;
}
strrev()
strrev() is a function used to reverse a string. It changes the original string into reverse
order.
Syntax: strrev(string_name);
Example:
#include <stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("Enter a string: ");
scanf("%s", str);
strrev(str);
printf("Reversed String: %s", str);
return 0;
}
Note: strrev() is not a standard C function.
It is available in Turbo C

13 prepared by: yogita k


14

Output:

Write a code to reverse a string without using strrev() function:


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

int main()
{
char str[50];
int i, len;

printf("Enter a string: ");


scanf("%s", str);

len = strlen(str);

printf("Reversed String: ");


for(i = len - 1; i >= 0; i--) {
printf("%c", str[i]);
}

return 0;
}

Math Function in C
Math functions in C are predefined library functions used to perform mathematical
operations such as square root, power, logarithm, trigonometric calculations, rounding, etc.
All mathematical functions are declared in the <math.h> header file.
Common Math Functions are:
Function Syntax Description Header File
sqrt() sqrt(x) Square root of x <math.h>
pow() pow(x,y) x raised to power y <math.h>
ceil() ceil(x) Rounds value upward <math.h>

14 prepared by: yogita k


15

floor() floor(x) Rounds value downward <math.h>


fabs() fabs(x) Absolute value (float) <math.h>
sin() sin(x) Sine of angle x (in radians) <math.h>
cos() cos(x) Cosine of angle x (in radians) <math.h>
log() log(x) Natural logarithm (base e) <math.h>
log10() log10(x) Logarithm base 10 <math.h>
exp() exp(x) Exponential value (e^x) <math.h>
Example:

#include <stdio.h> sin(0) = -0.99


#include <math.h> // Required header file cos(0) = 0.15
int main() { log(10) = 0.69
double angle = 30; exp(2) = 7.39
double num = 2.0;
printf("sin(0) = %.2lf\n", sin(angle));
printf("cos(0) = %.2lf\n", cos(angle));
printf("log(10) = %.2lf\n", log(num));
printf("exp(2) = %.2lf\n", exp(num));
return 0;
}
#include <stdio.h> Square root = 4.00
#include <math.h> // Header file for math functions
int main()
{
double num = 16.0, result;
result = sqrt(num);
printf("Square root = %.2lf", result);
return 0;
}
#include <stdio.h> Result = 9.00
#include <math.h> // Header file for math functions
int main() {
double result;
result = pow(3, 2);
printf("Result = %.2lf", result);
return 0;
}
#include <stdio.h> Original number = 4.30
#include <math.h> // Required for ceil() and floor() Ceil value = 5.00
int main() Floor value = 4.00
{
double num = 4.3;
printf("Original number = %.2lf\n", num);
printf("Ceil value = %.2lf\n", ceil(num));
printf("Floor value = %.2lf\n", floor(num));
return 0;
}

15 prepared by: yogita k


16

return in main() Function


 main() usually has return type int.
 return 0; indicates that the program executed successfully.
 It sends value 0 back to the operating system.
 It also terminates the program.

return in User-Defined Function


In user-defined functions, return sends the calculated value back to the calling
function.
Basis of return in main() return in User-Defined Function
Comparison
Purpose Terminates the program and returns Sends calculated value back to
status to Operating System calling function
Return Type Usually int Depends on function declaration
(int, float, char, double etc.)
Syntax return 0; return expression;
Meaning of 0 → Successful execution Value is used by calling function
Value
Example return 0; return a + b;
In void Function Not applicable (main usually int) Only return; (without value)
allowed

Other miscellaneous functions such as getchar(), putchar(), malloc(), calloc()


getchar()
getchar() is used to read a single character from the keyboard.
Header file is #include <stdio.h>
Suntax:char_variable = getchar();
#include <stdio.h> Enter a character: V
int main() You entered: V
{
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: %c", ch);
return 0;
}
putchar()
putchar() is used to display a single character on the screen.
Header file is #include <stdio.h>
Syntax: putchar(character);
#include <stdio.h> B
int main()
{
char ch = 'B';
putchar(ch);
return 0;

16 prepared by: yogita k


17

}
Summary of getchar() and putchar()

Feature getchar() putchar()


Header File #include <stdio.h> #include <stdio.h>
Purpose Reads a single character from keyboard Prints a single character to screen
Syntax ch = getchar(); putchar(ch);
Return Type int (character value) int
Input/Output Input function Output function
Example ch = getchar(); putchar('A');
Usage Used for character input Used for character display
malloc()
malloc() is used to allocate memory dynamically at runtime.
Header file is #include <stdlib.h>
Syntax: pointer = (type*) malloc(size_in_bytes);
example

#include <stdio.h> Output :


#include <stdlib.h> Memory allocated successfully
int main() {
int *ptr;
ptr = (int*) malloc(3 * sizeof(int));
if(ptr == NULL) {
printf("Memory not allocated");
} else {
printf("Memory allocated successfully");
}
free(ptr); // Free allocated memory
return 0;
}

Line Meaning
#include <stdio.h> Used for input/output functions like printf()
#include <stdlib.h> Used for memory functions like malloc() and free()
int *ptr; Declares a pointer variable to store address of integer
memory
malloc(3 * sizeof(int)) Allocates memory for 3 integer values dynamically
(int*) Typecasting to integer pointer
ptr == NULL Checks whether memory allocation failed
printf("Memory not allocated"); Executes if allocation fails
printf("Memory allocated Executes if allocation succeeds
successfully");
free(ptr); Releases allocated memory
return 0; Ends program successfully

calloc()
calloc() is used to allocate memory for multiple elements and initializes them to zero.
17 prepared by: yogita k
18

Header file is #include <stdlib.h>


Syntax: pointer = (type*) calloc(number_of_elements, size_of_each_element);
#include <stdio.h> Memory allocated successfully
#include <stdlib.h>
int main()
{
int *ptr;
ptr = (int*) calloc(3, sizeof(int));
if(ptr == NULL)
{
printf("Memory not allocated");
}
else {
printf("Memory allocated successfully");
}
free(ptr);
return 0;
}
Explanation of code

Line Explanation
#include <stdio.h> Used for input/output functions like printf()
#include <stdlib.h> Required for memory functions like calloc() and free()
int *ptr; Declares a pointer variable to store address of allocated memory
calloc(3, sizeof(int)) Allocates memory for 3 integer elements
(int*) Typecasting to integer pointer
3 Number of elements to allocate
sizeof(int) Size of each integer element
ptr == NULL Checks if memory allocation failed
free(ptr); Frees (releases) allocated memory
return 0; Ends the program successfully
Summary of malloc() and calloc()

Feature malloc() calloc()


Header File #include <stdlib.h> #include <stdlib.h>
Full Form Memory Allocation Contiguous Allocation
Purpose Allocates single block of Allocates multiple blocks of memory
memory
Syntax ptr = (type*) malloc(size); ptr = (type*) calloc(n, size);
Arguments 1 argument (total size in 2 arguments (number of elements, size of
bytes) each element)
Initialization Garbage values Initializes memory to zero
Speed Faster Slightly slower
Return Value Returns pointer to allocated Returns pointer to allocated memory
memory
Failure Returns NULL if memory not Returns NULL if memory not allocated
Condition allocated

18 prepared by: yogita k


19

Recursive functions

A recursive function in C is a function that calls itself. A recursive function is used when a
certain problem is defined in terms of itself. Although it involves iteration, using iterative
approach to solve such problems can be tedious. Recursive approach provides a very concise
solution to seemingly complex problems.

Syntax:
void recursive_function()
{
recursion(); // function calls itself
}
int main(){
recursive_function();
}

Examples:

Factorial of a number without recursion Factorial of a number with recursion


#include <stdio.h> #include <stdio.h>
#include <math.h> #include <math.h>
// function declaration
int factorial(int); /* function declaration */
int main() int factorial(int f)
{ {
int a = 5; if(f==0 || f==1)
int f = factorial(a); return 1;
printf("a: %d \n", a); else
printf("Factorial of a: %d", f); return f * factorial(f - 1);
} }
int factorial(int x) int main()
{ {
int i; int f,r;
int f = 1; printf("Enter a number=");
for (i = 5; i >= 1; i--) scanf("%d",&f);
{ r = factorial(f);
f=f* i; printf("Factorial of %d is %d",f,r);
} return 0;
return f; }
}
Output:
Output: Enter a number=4
a: 5 Factorial of 4 is 24
Factorial of a: 120

19 prepared by: yogita k


20

Sum of Natural Numbers without recursion Sum of Natural Numbers with recursion
#include <stdio.h> #include <stdio.h>
int main() int sum(int n)
{ {
int n = 6; if(n == 1) // base condition
int sum = 0; return 1;
int i; else
for(i = 1; i <= n; i++) return n + sum(n - 1); // recursive call
{ }
sum = sum + i; int main()
} {
printf("Sum = %d", sum); int num = 6;
return 0; printf("Sum = %d", sum(num));
} return 0;
}
Output:
Sum = 21 Output:
Sum = 21

Fibonacci series without recursion Fibonacci series with recursion


#include <stdio.h> #include <stdio.h>
int main() int fibonacci(int n)
{ {
int t; if(n == 0)
int a = 0, b = 1, c; return 0;
int i; else if(n == 1)
printf("Enter term:"); return 1;
scanf("%d",&t); else
printf("Fibonacci Series: "); return fibonacci(n-1) + fibonacci(n-2);
for(i = 0; i < t; i++) }
{ int main()
printf("%d ", a); {
c = a + b; int i,t;
a = b; printf("Enter term:");
b = c; scanf("%d",&t);
} for(i=0; i<t; i++)
return 0; {
} printf("%d ", fibonacci(i));
}
Output: return 0;
Enter term:8 }
Fibonacci Series: 0 1 1 2 3 5 8 13
Output:
Enter term:8
0 1 1 2 3 5 8 13

20 prepared by: yogita k


21

Reverse a Number Using Recursion


#include <stdio.h> #include <stdio.h>
int main() void reverse(int n)
{ {
int num = 1234; if(n == 0)
int remainder; return;
int reverse = 0; printf("%d", n % 10);
while(num != 0) reverse(n / 10);
{ }
remainder = num % 10; // get int main()
last digit {
reverse = reverse * 10 + remainder; int num = 1234;
num = num / 10; // remove printf("Reversed Number: ");
last digit reverse(num);
} return 0;
printf("Reversed Number = %d", reverse); }
return 0;
} Output:
Reversed Number: 4321
Output:
Reversed Number = 4321

Call by Value and Call by Reference


1. Call by Value
Definition
In Call by Value, a copy of the actual variable value is passed to the function.
The function works on the copy, so changes inside the function do NOT affect the
original variable.
Key Point
Original variable remains unchanged.
Example:
#include <stdio.h> Output:
void swap(int a, int b) Inside function: a = 20 b = 10
{
int temp; Outside function: x = 10 y = 20
temp = a;
a = b;
b = temp;
printf("Inside function: a = %d b = %d\n", a, b);
}
int main()
{
int x = 10, y = 20;
swap(x, y);
printf("Outside function: x = %d y = %d", x, y);
return 0;
}
21 prepared by: yogita k
22

Explanation

 x and y values are copied to a and b.


 Changes happen only in a and b.
 Original values remain the same.

Memory Representation
Main Function
x = 10 y = 20

copy copy

Function swap()

a = 10 b = 20

Changes in a and b do not affect x and y.

2. Call by Reference

Definition

In Call by Reference, the address of variables is passed to the function using pointers.

The function works with the original memory location, so changes inside the function
affect the original variable.

Key Point

➡ Original variable is modified.

#include <stdio.h> Output:


void swap(int *a, int *b) After swapping: x = 20 y = 10
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int x = 10, y = 20;
swap(&x, &y);
printf("After swapping: x = %d y = %d", x,
y);
return 0;
}

22 prepared by: yogita k


23

Differences between call by value and call by reference in C (VIMP)

Properties Call by value Call by reference


Data copying In call by value, a copy of the value In call by reference, the memory
of the argument is passed to the address of the argument is passed
function to the function.
Original value any changes made to the parameter any changes made to the
modification inside the function do not affect the parameter inside the function
original value passed to the function affect the original value passed to
the function.
Memory usage Call by value needs more memory Call by reference uses less memory
Performance Call by value is generally faster than Call by reference is slower than call
call by reference by value
Function In call by value, the function In call by reference, the parameter
definition definition does not require any must be declared as a C language
special syntax pointer in the function definition.

23 prepared by: yogita k

You might also like