Friday, March 8, 2013

C Programming: Swapping Values

Leave a Comment
C Programming: Swapping Values. This program will help enhance your skills in manipulating variables and its value. Swapping values is very helpful in some programs especially sorting algorithms like bubble sort. In this program we need a temporary variable to store the value of the first variable. There are two versions of the program here, first one has no functions and the other one have.

#include <stdio.h>
#include <conio.h>

 int main()

{
           int x = 5, y = 7, temp;

           printf("Before swapping: x = %d and y = %d\n", x, y);

      
           temp = x;
           x = y;
           y = temp;

           printf("\nAfter swapping: x = %d and y = %d", x, y);


           getch();

           return 0;
}

Program with function:
#include <stdio.h>
#include <conio.h>

void swap(int, int);     //function prototype
int main()
{
           int x = 5, y = 7;

           printf("Before swapping: x = %d and y = %d\n", x, y);


           printf("\nAfter swapping: ");
          
           swap(x, y);        //function call for swap           

           getch();          
           return 0;

void swap(int x, int y)
{
           int temp;
           
           temp = x;
           x = y;
           y = temp;
            
           printf("x = %d and y = %d", x, y);
}

Here's the output of the program: 


0 comments:

Post a Comment