Swapping two numbers has always remained a programming challenge for newbies. The following program in C will demonstrate the concept in a well documented fashion.
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 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
/** This program demonstrate the concept of pass by reference */ #include<stdio.h> #include<conio.h> //function declaration void swap(int *ptr1, int *ptr2); //main implementation int main(void) { //declare some variable int first_number, second_number; //read these values from the user printf("Enter two values: "); scanf("%d%d", &first_number, &second_number); //display the values printf("\n//////////In main ////////////////////////////\n"); printf("Address of the variables:\nFirst Number = %u\nSecond Number =%u", &first_number, &second_number); printf("\nValues of the variables before swapping:\n"); printf("\nFirst Number = %d\n Second Number = %d ", first_number, second_number); //call the function swap(&first_number, &second_number); //see the values after the function call printf("\n//////////In Main////////////////////////////\n"); printf("Address of the variables:\nFirst Number = %u\nSecond Number =%u", &first_number, &second_number); printf("\nValues of the variables after swapping:\n"); printf("\nFirst Number = %d\nSecond Number = %d ", first_number, second_number); getch(); return 0; } //function definition void swap(int *ptr1, int *ptr2) { //declare a temporary variable int temp; temp = *ptr1; *ptr1 = *ptr2; *ptr2 = temp; printf("\n/////////////In Function/////////////////////////\n"); printf("Address of the variables:\nFirst Number = %u\nSecond Number =%u", ptr1, ptr2); //display the values printf("\nValues of the variables after swapping:\n"); printf("\nFirst Number = %d\nSecond Number = %d ", *ptr1, *ptr2); } |
Leave a Reply
You must be logged in to post a comment.