C Program to swap the two numbers

In this example, discuss how to swapping the number in the c programming language. Following is the solution of the problem.


Code:

#include<stdio.h>

int main() {

   int firstnum, secondnum, temp;

      printf("Enter firstnum number: ");

      scanf("%d", &firstnum);

      printf("Enter secondnum number: ");

      scanf("%d", &secondnum);


      // Value of firstnum is assigned to temp

      temp = firstnum;

      firstnum = secondnum;


      // Value of temp  is assigned to secondnum

      secondnum = temp;


      printf("\nAfter swapping, firstnumNumber = %d\n", firstnum);

      printf("After swapping, secondnumNumber = %d", secondnum);

      return 0;

}

Output:

Enter firstnum number: 4

Enter secondnum number: 5


After swapping, firstnumNumber = 5

After swapping, secondnumNumber = 4


Here,is another way of swapping the two numbers without using helping variable.

Code: swapping the two numbers without helping variable

#include<stdio.h>
int main() {

   int firstnum, secondnum;

      printf("Enter firstnum number: ");
      scanf("%d", &firstnum);
      printf("Enter secondnum number: ");
      scanf("%d", &secondnum);

      // swap the numbers

      firstnum = firstnum+secondnum;
      secondnum=firstnum-secondnum;
      firstnum = firstnum-secondnum;
      



      printf("\nAfter swapping, firstnumNumber = %d\n", firstnum);
      printf("After swapping, secondnumNumber = %d", secondnum);
      return 0;
      
}

output:

Enter firstnum number: 4

Enter secondnum number: 5


After swapping, firstnumNumber = 5

After swapping, secondnumNumber = 4


Comments

Popular posts from this blog

Diferrence between flutter and react native

Flutter Widgets

Flutter layout