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

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

👁 921 Views
💻 Practical Program
📘 Step by Step Learning
write a program that uses a function to swap values stored in two integer variables to understand the concept of local variables.

Program Code

#include "stdio.h"

void exchange(int, int);

int main()
{ /* main() program body starts here...*/
	int a, b; /* local variables */
	a = 5;
	b = 7;
	printf(" In main: a = %d, b = %d\n", a, b);
	exchange(a, b); 
	printf("\n Back in main: ");
	printf("a = %d, b = %d\n", a, b);
	return 0;
} /* main() program body ends here... */

void exchange(int a, int b)
{ /* function body starts here...*/

	int temp; /* local variable */
	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...*/
 

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 = 5, b = 7

 

Explanation

None

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.