C program to swap two numbers

Below are the steps-

Step 1) Start

Step 2) Declare variables a, b and temp

Step 3) Read variables a and b

Step 4) temp<-a

Step 5) a<-b

Step 6) b<-temp

Step 7) Print the values of a and b

Step 8) Stop

Program:

/* C program to swap two numbers */
  #include<stdio.h>
  int main() {
        int a, b, temp;
 
        printf("Enter the value for a:");
        /* get the value for 'a' from the user */
        scanf("%d", &a);
 
        printf("Enter the value for b:");
        /* get the value for 'b' from the user */
        scanf("%d", &b);
 
        /* store the value of a  in temp */
        temp = a;
        /* store the value of b in a */
        a = b;
        /* store the value in temp to b */
        b = temp;
 
        /* print the results */
        printf("Result after swapping:\n");
        printf("Value of a: %d\n", a);
        printf("Value of b: %d\n", b);
        return 0;
  }

Output:

  Enter the value for a: 10
  Enter the value for b: 20
  Value of a: 20
  Value of b: 10

No comments:

Post a Comment