C Program to swap two numbers without third variable

C Program to swap two numbers without third variable

C Program to swap two numbers without third variable:

We can swap two numbers without using third variable. There are two common ways to swap two numbers without using third variable:

  1. By + and –
  2. By * and /
Program 1: Using + and –

Let’s see a simple c example to swap two numbers without using third variable.

#include<stdio.h>

int main()

{

int a=10, b=20;

printf(“Before swap a=%d b=%d”,a,b);

a=a+b;//a=30 (10+20)  

b=a-b;//b=10 (30-20)  

a=a-b;//a=20 (30-10)  

printf(“\nAfter swap a=%d b=%d”,a,b);

return 0;

}

Output:

Before swap a=10 b=20
After swap a=20 b=10
Program 2: Using * and /

Let’s see another example to swap two numbers using * and /.

#include<stdio.h>

#include<stdlib.h>

int main()

{

int a=10, b=20;

printf(“Before swap a=%d b=%d”,a,b);

a=a*b;//a=200 (10*20)  

b=a/b;//b=10 (200/20)  

a=a/b;//a=20 (200/10)  

system(“cls”);

printf(“\nAfter swap a=%d b=%d”,a,b);

return 0;

}

Output:

Before swap a=10 b=20
After swap a=20 b=10


 

Related Post:

Features of C Programming Language

Variables in C

Data Types in C

Keywords in C

C Operators

Comments in C

Escape Sequence in C

C Functions

Storage Classes in C

Dynamic memory allocation in C

Factorial Program in C

Leap year program in C

Fibonacci Series in C

Prime Number program in C

Palindrome program in C

Sum of digits program in C

Escape Sequence in C

ASCII value in C

Difference Between Type Casting and Type Conversion in C

Difference Between Variables and Constants

Matrix multiplication in C

C Program to generate Fibonacci Triangle

C Program to print “hello” without semicolon

C Program to reverse number

Count the number of digits in C

Tokens in C

C Identifiers

C Strings

Compile time vs Runtime in C

C break statement

C goto statement

Type Casting in C

C String Functions

C Pointers

Dangling Pointers in C

void pointer in C

Pointer to Pointer in C

Recursion in C

Call by value and Call by reference in C

File Handling in C

C fprintf() and fscanf()

C fputc() and fgetc()

C fputs() and fgets()

C fseek() function

Constant Pointers in C