This blog is under construction

Sunday, 7 July 2013

C program to swap two numbers without using temporary variable

Write a C program to swap two numbers without using temporary variable.


  #include <stdio.h>

  int main() {
        int num1, num2;

        /* get the first input from user */
        printf("Enter your first data:");
        scanf("%d", &num1);

        /* get second input from user */
        printf("Enter your second data:");
        scanf("%d", &num2);

        printf("Data before swapping:\n");
        printf("num1: %d  num2: %d\n", num1, num2);

        /* swap the given data */
        num1 = num1 + num2;
        num2 = num1 - num2;
        num1 = num1 - num2;

        /* print the results */
        printf("Data after swapping:\n");
        printf("num1: %d   num2: %d\n", num1, num2);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your first data:100
  Enter your second data:200
  Data before swapping:
  num1: 100  num2: 200
  Data after swapping:
  num1: 200   num2: 100





See Also:

No comments:

Post a Comment