Write c++ program. Enter 10 numbers(int) from the keyboard and find the difference between their maximum and minimum values (using a pointer)
时间: 2024-02-02 08:02:36 浏览: 101
Sure! Here's the C++ program that finds the difference between the maximum and minimum values of 10 numbers entered from the keyboard using a pointer:
```c++
#include <iostream>
using namespace std;
int main()
{
int numbers[10];
int *ptr = numbers;
cout << "Enter 10 numbers: " << endl;
for(int i=0; i<10; i++)
{
cin >> *(ptr+i);
}
int max_val = *ptr;
int min_val = *ptr;
for(int i=1; i<10; i++)
{
if(*(ptr+i) > max_val)
{
max_val = *(ptr+i);
}
if(*(ptr+i) < min_val)
{
min_val = *(ptr+i);
}
}
cout << "Difference between maximum and minimum values: " << max_val - min_val << endl;
return 0;
}
```
In this program, we first declare an array of size 10 to hold the input numbers and a pointer to point to the first element of the array. Then, we prompt the user to enter 10 numbers and read them into the array using pointer arithmetic.
Next, we initialize two variables, `max_val` and `min_val`, with the value of the first element of the array. We then loop through the remaining elements of the array, comparing each element with the current maximum and minimum values and updating them accordingly.
Finally, we output the difference between the maximum and minimum values.
Note that we use the dereference operator `*` to access the values of the array elements through the pointer, and the pointer arithmetic operator `+` to move the pointer to the next element of the array.
阅读全文