Friday, 29 March 2019

CP: Swap two numbers

Que: Write a program to swap two numbers. 

Swapping two variables refers to mutually exchanging the values of the variables. Generally, this is done with the data in memory.

The simplest method to swap two variables is to use a third temporary variable : 


Code:

#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;

}
_________________________________________________________________________________
Swapping of two numbers without third variable

Code:

#include <stdio.h>

int main()
{
   int a, b;

   printf("Input two integers (a & b) to swap\n");
   scanf("%d%d", &a, &b);

   a = a + b; 
   b = a - b;
   a = a - b;

   printf("a = %d\nb = %d\n",a,b);
   return 0;

}

























No comments:

Post a Comment

LAB 7 Arduino with Seven Segment Display || Arduino Tutorial || Code and Circuit Diagram || Project

  LAB 7 Arduino with Seven Segment Display || Arduino Tutorial || Code and Circuit Diagram || Project Dear All We will learn how to Connec...