C program to swap two numbers (Using a temporary variable)

by | Jan 6, 2023 | C, C Programs

Introduction

In this program, you will learn to swap two numbers in the C language using a third temporary variable.

To understand this program, you should know about

1. C Data types

2. C programming operators

Program

#include<stdio.h>
int main()
{
float a,b;
printf("Enter two numbers:\n");
scanf("%f %f",&a,&b);
printf("Before swaping numbers are:\na=%f\nb=%f",a,b);


float temp; // temp is a temporary variable
temp=a; //value of a is assigned to temp
a=b; //value of b is assigned to a
b=temp; // value of temp is assigned to b


printf("\nAfter swaping numbers are:\na=%f\nb=%f",a,b);
return 0;
}

 

Output

Explanation

In the above program, the user is asked to enter two values.

The user enters a=25 and b=45.

float temp; by declaring this temporary variable ‘temp’ we will swap the numbers entered by the user.

temp=a; the value of variable ‘a’ is assigned to variable ‘temp’. This results in a vacancy in the memory block of variable ‘a’. Thus, temp=25

a=b; the value of variable ‘b’ is assigned to ‘a’. Now, there is a vacancy in the memory block of variable ‘b’. Thus, a=45

b=temp; the value of ‘temp’ is assigned to ‘b’. Thus, b=25

Hence the values entered by the user are swapped.

 

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.