Computer Science, asked by rocico5200, 1 year ago

Swapping of two numbers without using third variable

Answers

Answered by PUBGNISHCHAY
0

Answer:

Swapping of two numbers in C

#include <stdio.h>

int main()

{

int x, y, t;

printf("Enter two integers\n");

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

printf("Before Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y);

t = x;

x = y;

y = t;

printf("After Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y);

return 0;

}

C# example to swap two numbers without using third variable.

using System;

public class SwapExample

{

public static void Main(string[] args)

{

int a=5, b=10;

Console.WriteLine("Before swap a= "+a+" b= "+b);

a=a*b; //a=50 (5*10)

b=a/b; //b=5 (50/10)

a=a/b; //a=10 (50/5)

Console.Write("After swap a= "+a+" b= "+b);

}

}

Output:

Before swap a= 5 b= 10

After swap a= 10 b= 5

Program 2: Using + and -

Let's see another example to swap two numbers using + and -.

using System;

public class SwapExample

{

public static void Main(string[] args)

{

int a=5, b=10;

Console.WriteLine("Before swap a= "+a+" b= "+b);

a=a+b; //a=15 (5+10)

b=a-b; //b=5 (15-10)

a=a-b; //a=10 (15-5)

Console.Write("After swap a= "+a+" b= "+b);

}

}

This only what I know......

HOPE this helps you.......

Answered by pranalipatil3620
2

Answer:

#include<iostream>

using namespace std;

void swap(int &x,int &y)

{

x=x+y;

  y=x-y;

  x=x-y;

}

int main()

{

int a,b;

   cin>>a>>b;

   cout<<"Before swapping a= "<<a<<" and b="<<b;

   swap(a,b);

   cout<<"\nAfter swapping a= "<<a<<" and b="<<b;

}

Explanation:

cpp code

Similar questions