188k views
5 votes
Write C++ programs to implement the required functionality. [CLO-3]. 1) Write a program in C++ to find the maximum number between two numbers using a pointer.

User Suanmeiguo
by
8.1k points

1 Answer

4 votes

Here's a C++ program that uses pointers to find the maximum number between two numbers:

```cpp

#include <iostream>

int findMax(int* num1, int* num2) {

if (*num1 > *num2) {

return *num1;

} else {

return *num2;

}

}

int main() {

int num1, num2;

std::cout << "Enter the first number: ";

std::cin >> num1;

std::cout << "Enter the second number: ";

std::cin >> num2;

int max = findMax(&num1, &num2);

std::cout << "The maximum number is: " << max << std::endl;

return 0;

}

```

In this program, the `findMax` function takes two integer pointers `num1` and `num2` as parameters. It compares the values pointed to by the pointers and returns the maximum number.

In the `main` function, we declare two integer variables `num1` and `num2`. We then prompt the user to enter the values for these variables. We pass the addresses of `num1` and `num2` to the `findMax` function using the `&` operator. The function compares the values using pointers and returns the maximum number. Finally, we display the result to the user.

Note: This program assumes that the user will enter valid integer values. Error handling for invalid inputs is not included in this example.

User Dexterous
by
7.4k points