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


C is a block structured programming language i.e., If a variable is created within a block then that variable can be accessed only in that block and those variables are called as local variables with in that block.
This program explains the scope of local variables with the help of function. Whenever variables are passed from the main program to function as arguments then the function will create a new copy of variables which exist and can be accessed only in that function. This is how to swap two numbers.

C Program to swap two numbers to understand local variables


Source code:

#include<stdio.h>
void exchange(int, int);

int main()
{ 
   int a, b; 
   a = 5;
   b = 7;
   printf(" In main: a = %d, b = %d\n", a, b); // Step 1
   exchange(a, b);            // Step 2
   printf("\n Back in main: ");
   printf("a = %d, b = %d\n", a, b); //Step 6
   return 0;
} 
void exchange(int a, int b)
{ 
   int temp; 
   printf("\n In function exchange() 
   before change: just received from main... a=%d and b=%d",a,b); //Step 3
   temp = a;
   a = b;
   b = temp;   //Step 4
   printf("\n In function exchange() after change: ");
   printf("a = %d, b = %d\n", a, b);  // Step 5
}


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

Explanation:

Step 1: The values of ‘a’ and ‘b’ in main block before function call are printed to output screen.
Step 2: The function exchange() is called from the main program with ‘a’ and ‘b’ as arguments.
Step 3: After receiving the values of ‘a’ and ‘b’ in function they are printed to output screen.
Step 4: The swapping of ‘a’ and ‘b’ is done in function.
Step 5: After swap the values of ‘a’ and ‘b’ in function are printed to output screen.
Step 6: After return from function the values of ‘a’ and ‘b’ are printed to output screen.

Explore C Programs:C Programs
More information:Swapping