Knowee
Questions
Features
Study Tools

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 defined function (Call by reference)

🧐 Not the exact question you are looking for?Go ask a question

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.

This problem has been solved

Similar Questions

Select the correct answerC functions parameters are always by default:OptionsPass by referencePass by valuePass by pointerAll given options are correct

write a program in java to display the number after swapping without using third variable

What is the output of the following code snippet?int x = 5;int y = 10;int *ptr = &x;*ptr = y;printf("%d", x);510015Generates a compilation error

In C, what is the typical form of a function declaration when implementing call by value?

What is the correct syntax for using the indirection operator to print the value pointed to by a pointer ptr?

1/1

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.