C program to swap two numbers without temporary variable - My CS Tutorial - My CS Tutorial

Breaking

Programming languages full tutorial and programs, exam papers, visual basic( Vb.net ), information of new technologies and more....

Saturday, November 16, 2019

C program to swap two numbers without temporary variable - My CS Tutorial

In this post we will learn how to write a C program that swap two numbers without temp variable.Given two numbers and swap these numbers in this program without using any temporary variable.


Solution



  • In this program we will use two variables as firstnumber and secondnumber for two numbers for swapping.
  • We will use double data type in this program.
  • We will use some logics as:-
      firstNumber = firstNumber - secondNumber;
    secondNumber = firstNumber + secondNumber;
    firstNumber = secondNumber - firstNumber;


  • After it we will print the numbers using printf statements.

Example:-



Input firstnumber=20.5
Input secondnumber=25.7

After swapping

Output firstnumber=25.7
Output secondnumber=20.5





C program code


#include <stdio.h>
#include<conio.h>
void main()
{
    double firstNumber, secondNumber;
    printf("\n Enter first number:  ");
    scanf("%lf", &firstNumber);
    printf("\n Enter second number:  ");
    scanf("%lf",&secondNumber);
    // Swapping process
    firstNumber = firstNumber - secondNumber;
    secondNumber = firstNumber + secondNumber;
    firstNumber = secondNumber - firstNumber;
    printf("\nAfter swapping,the first Number = %.2lf\n", firstNumber);
    printf("After swapping,the second Number = %.2lf", secondNumber);
    getch();

}




OUTPUT 1




OUTPUT 2






In first output,the value of input first and second number is 20.5 and 25.7
After swapping
The value of first number 25.7 and second number 20.5

In second output,the value of input first and second number is 15 and 10
After swapping
The value of first number 10 and second number 15


Please share this post and blog link with your friends.For more programs use this blog.
If you have any problem comment in comment box, subscribe for notifications of new post on your email and follow this blog.

Created by-- HARSH CHAUHAN

No comments:

Post a Comment