C program to swap two numbers?

Today i am going to tell you "How to swap two number with or without third varaible in C language?"
Swap two number in C

Program To Swap Two Numbers Using Third Variable
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
int main()
{
      double a, b, c;
 
      printf("Enter first number: ");
      scanf("%d", &a);
 
      printf("Enter second number: ");
      scanf("%d",&b);
 
      c = a;
      
      a = b;
 
      b = c;
 
      printf("\nAfter swapping, First Number = %.2d\n", a);
      printf("After swapping, Second Number = %.2d", b);
 
      return 0;
}
Output:

Enter first number: 15
Enter second number: 30

After swapping, First Number = 30
After swapping, Second Number = 15

Program To Swap Two Numbers Using Third Variable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
int main()
{
    double a, b;
 
    printf("Enter first number: ");
    scanf("%d", &a);
 
    printf("Enter second number: ");
    scanf("%d",&b);
 
    // Swapping process
 
    a= a - b;
    b= a + b;
    a= b - a;
 
    printf("\nAfter swapping, First Number = %.2lf\n", a);
    printf("After swapping, Second Number = %.2lf", b);
 
    return 0;
}
Output:

Enter first number: 5
Enter second number: 3

After swapping, First Number = 3
After swapping, Second Number = 5


Hope you enjoyed the tutorial.


Thanks.
C program to swap two numbers? C program to swap two numbers? Reviewed by CodiBucket on 10:01 Rating: 5

No comments:

Powered by Blogger.