Swapping of two numbers in C

VIGNESWARAN.S
3 min readJun 9, 2021

What we are going to learn from this blog?

we are going to learn about swapping in C.

What is swapping of two numbers?

Swap two numbers means exchange the values of two variables with each other. For example variable num1 contains 20 and num2 contains 40 after swap there values num1 contains 40 and num2 contains 20.

Algorithm

Lets find out how should we draw a solution step-by-step − START Var1, Var2, Temp Step 1 → Copy value of Var1 to Temp Step 2 → Copy value of Var2 to Var1 Step 3 → Copy value of Temp to Var2 STOP.

Flowchart

Explanation of the program

  1. Initially we usually gives #include<stdio.h>and #include<conio.h>

2.second we should use the swap function to perform swap operation.Then declare x and y.

3.Third is main function.Inside the main function we are declaring the variable as a,b.

→printing the statement as “program to perform swapping of two numbers using user define function” and in the next line we are printing “Enter numbers one by one” for the user comfortable.

→Then inside the scanf we usually give %d for int data type.

→Again we are printing the statement as “Before swapping ,the values are”

→Then we are calling the function as swap(a,b)

call by value

>In call by value method,the value of the variable is passed to the function parameter.

>The value of the actual parameter cannot be modified by formal parameter.

>Different memory is allocated for both actual and formal parameters.Because value of actual parameter is copied to formal parameter.

→Then we are declaring the third variable as ‘t’

→We are assigning the value of x in t

→Then x will be free

→After that assigning the value of y in x.

→ y will be free

→Then assigning the value of t in y.

→At the end values are swapped.

Program or Source code

Output

For any reference

--

--