C LAB‎ > ‎(Sem1) Introduction to C‎ > ‎

WAP to Swap two numbers (using pointers and functions) (call by reference).

posted Oct 29, 2010, 9:02 PM by Neil Mathew   [ updated Dec 1, 2010, 8:49 PM ]

SOURCE CODE:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<stdio.h>
 
void Swap(int *a, int *b)
{                // *Note the syntax of pointers for arguments
 
//Swapping:
 
int temp;
 
temp=*a;   // *(pointer_variable) to access the value
*a=*b;
*b=temp;
 
}
 
int main()
{
 
int a,b;
 
printf("\n Enter the value of A: ");
scanf("%d",&a);
 
printf(" Enter the value of B: ");
scanf("%d",&b);
 
Swap(&a,&b); // *Note the & during such a call
  printf("\n After Swapping... \n");   printf(" A: %d", a); printf("\n B: %d", b);   return 0; }

OUTPUT:

 Enter the value of A: 4
 Enter the value of B: 9
 After Swapping... 
 A: 9
 B: 4
Comments