Dharanyadevi blogspot subsume with E-books, Notes, Lab Manual, Question Banks, Interview Tips, Viva Questions, Basics and Interview Questions for engineering students. For Any Help Contact dharanyadevi@gmail.com

SEARCH

Image

Wednesday, April 11, 2012

To Swap the Values of Two Variables With and Without Using Pointers

C Program To Swap Two Numbers

C program to swap two numbers with and with out using third variables, swapping in c using pointers and functions (call by reference) , swapping means interchanging. For example if in your c program you have taken two variable a and b where a = 4 and b = 5, then before swapping a = 4, b = 5 after swapping a = 5, b = 4.
In our c program to swap numbers we will use a temp variable to swap two numbers. Swapping is used in sorting that is when we wish to arrange numbers in a particular order either in ascending order or in descending order.

To Swap the Values of Two Variables Without Using Pointers

#include #include  main() {    int x, y, temp;     printf("Enter the value of x and y ");    scanf("%d%d",&x, &y);     printf("Before Swapping\nx = %d\ny = %d\n",x,y);     temp = x;    x = y;    y = temp;     printf("After Swapping\nx = %d\ny = %d\n",x,y);     getch();    return 0; }


To Swap the Values of Two Variables With Using Pointers
# include < stdio.h >
# include < conio.h >
main ( )
{
int a,b;
clrscr();
printf ( “ Enter values of a and b: \n”);
scanf( “ %d%d”, &a,&b);
swap(&a,&b);
printf( “ \n a= %d”, a);
printf( “ \n b= %d”, b);
}
swap ( int *x, int *y)
{
int temp;
temp =*x;
*x=*y;
*y=temp;
return(x);
return(y);
}


Output:
Enter values of a and b:
10 20
a=20
b=10



3 comments:

  1. this link might be help you C program to swap two numbers

    http://programmergallery.com/c-program/c-program-swap-two-numbers.php

    ReplyDelete
  2. Nice article . There is good example swap two number visit
    Swap two number

    ReplyDelete

Refer this site 2 ur frndz