Practical 7 (Swap)
Practical 7 (Swap)
Aim: Program to swap two numbers using call by reference(Swapping of two numbers)
Theory:
a function is a block of code that perform a specific task and it runs only when it is called.There
are basically two types of function:
2. User-Defined Functions
These are the functions that a developer or the user declares, defines, and calls in a
program. This increases the scope and functionality, and reusability of C programming as we can
define and use any function we want. A major plus point of C programming is that we can add a
user-defined to any library to use it in other programs.
Function Prototype:
A function prototype is also known as a function declaration which specifies the function’s
name, function parameters, and return type. The function prototype does not contain the body
of the function. It is basically used to inform the compiler about the existence of the
user-defined function which can be used in the later part of the program.
Syntax
Function Definition:
Once the function has been called, the function definition contains the actual statements that will
be executed. All the statements of the function definition are enclosed within { } braces.
Syntax
Function Call:
In order to transfer control to a user-defined function, we need to call it. Functions are called
using their names followed by round brackets. Their arguments are passed inside the brackets.
Syntax
1. Call by value
In call by value, a copy of the value is passed to the function and changes that are made to the
function are not reflected back to the values. Actual and formal arguments are created in
different memory locations.
E.g z=add(a,b);
2. Call by Reference
In a call by Reference, the address of the argument is passed to the function, and changes that are
made to the function are reflected back to the values. We use the pointers of the required type to
receive the address in the function.
E.g swap(&a,&b)
Algorithm:
Step 1: Start
Step 2: Set a <-10 and b <-20
Step 3: call the function swap(&a,&b)
Step 3a: start function
Step 3b: Assign t <- *x
Step 3c: Assign *x <- *y
Step 3d: Assign *y <- t
Step 3e: End function
Step 4: Print x and y.
Step 5: End
Flowchart:
Result:
In this way, we have implemented swapping of two numbers using call by reference.
Name:
PRN:
Branch:
Aim: Program to swap two numbers using call by reference(Swapping of two numbers)
using C.
#include <stdio.h>
swap (int *, int *);
int main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(&a, &b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
return 0;
}
swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Output:
Name:
PRN:
Branch:
Aim: Program to swap two numbers using call by reference(Swapping of two numbers)
using python.
print("After swapping:")
print("First number:", num1)
print("Second number:", num2)
Output: