Problem: Write a program that swaps two numbers using pointers.

Source Code:

  1. #include <stdio.h>
  2. int main()
  3. {
  4.                //variable declearation.
  5.    int x, y, *a, *b, temp;
  6.               //Input any number from the user
  7.    printf("Enter the value of x and y\n");
  8.    scanf("%d%d", &x, &y);
  9.    printf("Before Swapping\nx = %d\ny = %d\n", x, y);
  10.              //Compute swapping of the number
  11.    a = &x;
  12.    b = &y;
  13.    temp = *b;
  14.    *b = *a;
  15.    *a = temp;
  16.               //display the swap number.
  17.    printf("After Swapping\nx = %d\ny = %d\n", x, y);
  18.    return 0;
  19. }


Output:  

Output 1:

Enter the value of x and y

56

45

Before Swapping

x = 56

y = 45

After Swapping

x = 45

y = 56

Output 2:

Enter the value of x and y

26

89

Before Swapping

x = 26

y = 89

After Swapping

x = 89

y = 26


0 comments:

Post a Comment