I need a function written in visual studio using c++ that interchanges two values of type int. Also i need to write a driver program to test my function.
How to write a function that interchanges two values of type int in Visual Studio?
int valuechage(int a, int b, int c)
{
a = 1;
b = 3;
c = b;
a = b;
b = a;
return 0;
}
Reply:For interchanging values of two variables from within a function, you should be using either reference variables or pointer.
Using reference variable:-
/*---------------------------------*/
void change(int %26amp;a, int %26amp;b)
{
int c = a;
a = b;
b = c;
return;
}
int main()
{
int a = 10;
int b = 20;
cout %26lt;%26lt; "Original" %26lt;%26lt; endl;
cout %26lt;%26lt; "a: " %26lt;%26lt; a %26lt;%26lt; endl;
cout %26lt;%26lt; "b: " %26lt;%26lt; b %26lt;%26lt; endl;
change(a,b);
cout %26lt;%26lt; "Modified" %26lt;%26lt; endl;
cout %26lt;%26lt; "a: " %26lt;%26lt; a %26lt;%26lt; endl;
cout %26lt;%26lt; "b: " %26lt;%26lt; b %26lt;%26lt; endl;
}
/*---------------------------------*/
Using pointer:-
/*---------------------------------*/
void change(int *a, int *b)
{
int c = *a;
*a = *b;
*b = *c;
return;
}
int main()
{
int a = 10;
int b = 20;
cout %26lt;%26lt; "Original" %26lt;%26lt; endl;
cout %26lt;%26lt; "a: " %26lt;%26lt; a %26lt;%26lt; endl;
cout %26lt;%26lt; "b: " %26lt;%26lt; b %26lt;%26lt; endl;
change(%26amp;a,%26amp;b);
cout %26lt;%26lt; "Modified" %26lt;%26lt; endl;
cout %26lt;%26lt; "a: " %26lt;%26lt; a %26lt;%26lt; endl;
cout %26lt;%26lt; "b: " %26lt;%26lt; b %26lt;%26lt; endl;
}
/*---------------------------------*/
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment