Using pointers write a program to swap two numbers using a user definedfunction(Call by reference)
Question
Using pointers write a program to swap two numbers using a user definedfunction(Call by reference)
Solution
Sure, here is a simple C++ program that uses pointers to swap two numbers using a user-defined function (Call by reference).
#include <iostream>
using namespace std;
// Function to swap values using pointers
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10;
int y = 20;
cout << "Before swapping: " << endl;
cout << "x = " << x << ", y = " << y << endl;
// Call the swap function
swap(&x, &y);
cout << "After swapping: " << endl;
cout << "x = " << x << ", y = " << y << endl;
return 0;
}
In this program, the swap function takes two pointers as arguments. Inside the function, a temporary variable temp is used to hold the value of *a (which is the value pointed to by a). Then, the value of *b is assigned to *a, and the value of temp is assigned to *b. This effectively swaps the values of the variables that a and b point to.
Similar Questions
Write a C++ program that takes two integers as input and swaps their values without using a temporary variable. sample input and output Enter two integers: 10 20 Before swapping: num1 = 10, num2 = 20After swapping: num1 = 20, num2 = 10
12345678910111213141516#include <stdio.h>void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; printf("%d %d", *x, *y);}int main() { int a = 120; int b = 121; printf("%d %d\n", a, b); swap(&a, &b); return 0;}
Given datatype of two variable as an integer value and address of two variables as a void pointer to the function common_swap(). Do swap the values pointed by the two pointer variables. The integer value from 1 to 6 means the datatype. 1. char(%c) 2. short int(%hd) 3.long int(%ld) 4. long long int(%lld) 5. float(%f) 6. double(%lf).
Write a program to add two numbers using pointers
Consider the following C functionvoid swap (int a, int b){ int temp; temp = a; a = b; b = temp;}.In order to exchange the values of two variables x and y.a.Call swap (x, y)b.Call swap (&x, &y)c.swap(x,y) cannot be used as it does not return any valued.swap(x,y) cannot be used as the parameters are passed by value
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.