Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    C Program to Swap the Value of Two Variables Using a Function

    C Programming Examples


    In this example C program, a user-defined function swaps the values of two variables. It uses a temporary variable to replace the values of variables from each other and print the output to the screen.

    Example:

    #include <stdio.h>
    
    void swap (int *n1, int *n2)
    {
      int temp;
      temp = *n2;
      *n2 = *n1;
      *n1 = temp;
    }
    
    void main ()
    {
      /* Declaration of variables used within this program. */
      int num1, num2;
    
      /* Take input from the user and save it to the first variable. */
      printf("Enter first number:\n");
      scanf ("%d", &num1);
    
      /* Take input from the user and save it to the second variable. */
      printf("Enter second number:\n");
      scanf ("%d", &num2);
    
      /* Printing the use input before swapping. */
      printf("\nBefore Swapping\n");
      printf("First number: %d\n", num1);
      printf("Second number: %d\n\n", num2);
    
      /* Swapping the variables. */
      swap (&num1, &num2);
    
      /* Printing the variables after the swapping. */
      printf("\nAfter Swapping\n");
      printf("First number: %d\n", num1);
      printf("Second number: %d\n\n", num2);
    }
    

    Program Output:

    Enter first number:
    10
    Enter second number:
    5
    Before Swapping
    First number: 10
    Second number: 5
    
    After Swapping
    First number: 5
    Second number: 10


    Found This Page Useful? Share It!
    Get the Latest Tutorials and Updates
    Join us on Telegram

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.