C programming to swap numbers and strings

In this article, we are going to show you that how you can swap two numbers. We are also going to show that how we can swap strings using the same method.

C programming to swap numbers


Algorithm Explanation:

Think that you have two-friend name Jhon and Ron. Jhon has a red ball and Ron have a yellow ball. You take the red ball from Jhon and give it to Ron and then you take that yellow ball from Ron and give it to Jhon. It is a simple way to swap the ball between two people.

In that same way, you can swap values using c programming. To swap values you need a temporary variable. This temporary variable will swap them.

Here is an example code for better understanding:

#include<stdio.h>
int main() {
      double Jhon, Ron, Me;
      printf("Enter Jhon's number: ");
      scanf("%lf", &Jhon);
      printf("Enter Ron's number: ");
      scanf("%lf", &Ron);
      Me = Jhon;
      Jhon = Ron;
      Ron = Me;
      printf("\nAfter swapping, Jhon's Number = %lf\n", Jhon);
      printf("After swapping, Ron's Number = %lf", Ron);
      return 0;
}


Output:

Enter Jhon's number: 100
Enter Ron's number: 200
After swapping, Jhon's Number = 200.000
After swapping, Ron's Number = 100.000

First, we have to declare three variables. Here we declare three double type variables for Jhon, Ron, and Me. Take the user input using scanf. We need the number of Jhon and Ron and then store them inside those variables. Then store Jhon's value inside the temporary variable 'Me' and then store Ron's value inside the Jhon variable. Finally, replace the value of Ron using that temporary variable. Print them and then you can see the swapped result.

Using this same method you can easily swap strings. Here is another example code for you.

#include <stdio.h>
int main() {
    int a, b;
    printf("Enter a: ");
    scanf("%d", &a);
    printf("Enter b: ");
    scanf("%d", &b);

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

    printf("After swapping, a = %d\n", a);
    printf("After swapping, b = %.d", b);
    return 0;
}


Output:

Enter a: 5
Enter b: 7
After swapping, a = 7
After swapping, b = 5

Comment below if you face any problem understanding. Enable the e-mail subscription to get all new posts directly to your mailbox.

Post a Comment (0)
Previous Post Next Post