Home / Programs / write a program that uses a function to swap values stored in two integer variables to understand the concept of global variables.
🚀 Programming Example

write a program that uses a function to swap values stored in two integer variables to understand the concept of global variables.

👁 5,604 Views
💻 Practical Program
📘 Step Learning
write a program that uses a function to swap values stored in two integer variables to understand the concept of global variables.

💻 Program Code

#include<stdio.h>

void exchange(void);
int a, b; /* declaration of global variables */

int main()
{ /* main program starts here...*/
	a = 5;
	b = 7;
	printf(" In main: a = %d, b = %d\n", a, b);
	exchange(); /* function call, no parameters are passed */
	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;
	a = b;
	b = temp; /* interchange over */
	printf("\n In function exchange() after change: ");
	printf("a = %d, b = %d\n", a, b);
} /* function body ends here*/
 
                        

🖥 Program Output

 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

None
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.