Tuesday, March 31, 2020

C program to swap two numbers

C program to swap two numbers

#include
int main()
{
      double first, second, temp; // initialization of constant value 
      printf("Enter first number: "); // user input value
      scanf("%lf", &first); // Storing value
      printf("Enter second number: "); // user input value
      scanf("%lf", &second); // Storing value

      // Value of first is assigned to temp
      temp = first;

      // Value of second is assigned to first
      first = second;

      // Value of temp (initial value of first) is assigned to second
      second = temp;

      printf("\nAfter swapping, firstNumber = %.2lf\n", first); // Final display result
      printf("After swapping, secondNumber = %.2lf", second); // Final display result
      return 0;
}

Output 

Enter first number: 4.6
Enter second number: 4.5

After swapping, firstNumber = 4.5
After swapping, secondNumber = 4.6
How program works ?

  • In this program, the temp variable is assigned the value of the  first  variable. 
  • Then, the value of the first variable is assigned to the  second variable.
  • Finally, temp  (Which hold the initial value of first ) is assigned to second.This completes the swap process.
Happy coding

0 comments:

Post a Comment

Recent Posts