C program to swap two numbers to understand concept of global variables


This program explains the concept of swap two numbers with the help of global variables. The name itself defines what global variables are. Since they exist through out the program they can be accesed and modified any where in the program.

C Program to swap two numbers


Source code:

#include<stdio.h>
void exchange(void);
int a, b; /* declaration of global variables *///step 1

int main()
{ /* main program starts here...*/
	a = 5;                                     //step 2
	b = 7;
	printf(" In main: a = %d, b = %d\n", a, b);
	exchange(); /* function call, no parameters are passed */  //step 3
	printf("\n Back in main: ");
	printf("a = %d, b = %d\n", a, b);
	return 0;
} /* main program ends here */

void exchange(void)
{ /* function body starts here...*/
	int temp; /* decl. of local variable in function*/
	printf("\n In function exchange() before change: just received from\
	main... a=%d and b=%d",a,b);
	temp = a;                                               //step 4
	a = b;
	b = temp; /* interchange over */                         //step 5
	printf("\n In function exchange() after change: ");
	printf("a = %d, b = %d\n", a, b);
} /* function body ends here*/


edit-code-image

Sample test cases:

 In main: a = 5, b = 7
 In function exchange() before change: just received from       main... a=5 and b=7
 In function exchange() after change: a = 7, b = 5
 Back in main: a = 7, b = 5

Explanation:

Step 1: Declare the global variables a and b.
Step 2: Initialize the variables a & b.
Step 3: Now pass the variable a & b to the method ‘exchange’
Step 4: In the method ‘exchange’ the variables are swapped using a temporary variable
Step 5: The value of a is assigned to temporary variable temp and the value of b is assigned to a and then temp value is assigned back to b. Thus swapping is done!

More Content:Explore More