C Program to accept two numbers and interchange two values using functions
#include<conio.h>
#include<stdio.h>
void swap (int a, int b);
main( )
{
int a,b;
clrscr( );
printf(“enter value for a;”);
scanf(“%d”,&a);
printf(“enter value for b;”);
scanf(“%d”,&b);
swap(a,b);
getch( );
}
void swap(int a,int b)
}
int c;
c=a;
a=b;
b=c;
printf(“\na=%d”,a);
printf(“\nb=%d”,b);
}
How to create a function that accepts 2 parameters and changes the value of both parameters
There are times when we want to create a function that takes two parameters and returns the same type of output as the input. Sometimes it may be a basic operation, but sometimes it may be more complicated. Let us consider an example where we have to change the values of two variables, but keep their type.
Consider the following program:
int x = 5, y = 3;
printf(“%d %d”, x, y);
The output of the above code is 3. But what if you want to get the output as 12? That is possible using the following code:
int x = 5, y = 3;
printf(“%d %d”, x++, ++y);
This time, we get the desired output as 12. The difference between the above two codes is the way the compiler evaluates the expression. Here is the output of the two statements:
Statement 1:
x++, ++y
Expression 1:
x++
Expression 2:
++y
We see that Expression 2 is evaluated before Expression 1.
Now, the question is, how can we create a function that accepts 2 parameters and does the same thing. Here is the solution:
int x = 5, y = 3;
int swap_xy(int x, int y)
{
return x++, ++y;
}
printf("%d %d", swap_xy(x, y));
Here, we can observe that the two expressions are evaluated in a different order.
That is why the output is 12. In the above example, we changed the values of the two variables and kept the types of those variables the same. But in real life, we often have to do the opposite. Consider the following example:
int x = 5, y = 3;
int a = x++, b = y++;
printf(“%d %d”, a, b);
Here, we get the output as 13. Here is the reason:
a = 5, b = 4
Now, the two expressions are evaluated in a different order:
Expression 1:
a = 5, b = 4
Expression 2:
x++, ++y
This time, Expression 2 is evaluated before Expression 1.
That is why the output is 13.
So, this is one of the most important things in programming. A function that accepts 2 parameters and changes the value of both the parameters