How do I find highest value using pointer? - c++

I want to find the highest value from an array using two given pointer int *p,*max;, but the code doesn't work.
#include <iostream>
#include <string>
using namespace std;
int main() {
int a[10], i, index;
int *p, *max;
for (i = 0; i < 10; i++) cin >> a[i];
max = 0;
p = &a[10];
for (index = 0; index < 10; index++) {
if ((p[index]) > *max) {
*max = (p[index]);
}
}
cout << "Highest value=" << *max << endl << "is at index=" << index << endl;
return 0;
}

The code is buggy. First of all, you assign
p=&a[10];
This assigns p to a memory address past a. Furthermore, you then index as p[index], which essentially is the same as a[10 + index].
Also, max is a wild pointer. It does not point to anything. You are assigning values to an undefined memory location.
I would strongly suggest to read up on pointers and to properly understand them before using them. Also, in modern C++, it is not very often than you need pointers.
Also, in idiomatic C++, we would probably write
auto p = std::max_element(a, a + 10);

There are several problems.
First, p should point to the array's first element, so you should have p = &a[0].
You can also rely on implicit conversion and just write p = a;, which is exactly the same.
&a[10] is the pointer "one-past-the-end" of the array, and dereferencing it is undefined.
Next, you want max to point to the maximum element.
It should also start at the beginning of the array, like p.
Then, when you find a new maximum, you should make max point to that element, not change the value max points to.
Lastly, index will always be 10 after the search loop.
(Take a few moments to think about why.)
You don't need it – the index is the difference between the location of the maximum element and the beginning of the array.
int main()
{
int a[10];
for(int i = 0; i < 10; i++)
cin >> a[i];
int* max = &a[0];
int* p = &a[0];
for (int index = 0; index < 10; index++){
if (p[index] > *max){
max = &p[index];
}
}
cout << "Highest value= " << *max << endl << "is at index= "<< max - a << endl;
}

I'd remove p and use a range-based for-loop where possible and iterators when it'll improve performance.
Comments in the code:
#include <iostream>
#include <iterator>
// using namespace std; // don't do this
int main() {
using std::cin, std::cout;
int a[10];
// use a range-based for-loop:
for(int& aref : a) { // aref is a reference to the current element in a
// check that extraction from std::cin actually works
if(!(cin >> aref)) {
std::cerr << "error reading int\n";
return 1;
}
}
// initialize max to point at the first element
auto max = std::begin(a);
// Start at the second element since max is already set to point at the first element.
// Don't use magic numbers. Define a constant or use std::size(<array>)
// ...or use iterators like in this example:
for(auto curr = std::next(std::begin(a)); curr != std::end(a); ++curr) {
if(*curr > *max) {
max = curr;
}
}
// you can use std::distance ot calculate the index for max:
cout << "Highest value=" << *max << '\n'
<< "is at index=" << std::distance(std::begin(a), max) << '\n';
}

The solution to this problem is recognizing that max should always point to the maximum item seen in the array a so far so instead of initializing max to 0 you start by initializing it to point to the first item in a which is &a[0] or just a.
I tried to make the least amount of changes to the original code:
#include <iostream>
#include<string>
using namespace std;
int main()
{
int a[10],i,index;
int *p,*max;
for(i=0;i<10;i++)
cin>>a[i];
max=a; // Initialize max to point to the first item in a
p=a;
for(index=0;index<10;index++){
if((p[index])>*max){
max=(&p[index]); // Now make max point to the new maximum item
}
}
cout<<"Highest value="<<*max<<endl<<"is at index="<<max - p<<endl;
return 0;
}
Here is the code in ideone:
https://ideone.com/BwE45C
As mentioned in the comments below p probably is not being used as the question expects so I have rewritten the code to iterate using p
#include <iostream>
#include<string>
using namespace std;
int main()
{
int a[10],i,index;
int *max;
for(i=0;i<10;i++)
cin>>a[i];
max=a;
for(int* p=a;p<a+10;p++){ // p is now a pointer that is used to iterate through the array
if(*p>*max){
max=p; // max points to the new maximum
}
}
cout<<"Highest value="<<*max<<endl<<"is at index="<<max - a<<endl;
return 0;
}
The new ideone link for this is here: https://ideone.com/bk3zoS

Related

How to output the maximum value inside an array

#include <iostream>
using namespace std;
void value(int array[],int size){
int minimum;
int maximum;
minimum = array[0];
for(int x = 0; x < size; x++){
if(minimum > array[x+1]){
minimum = array[x+1];
}
}
maximum = array[0];
for(int x = 0; x < size; x++){
if(maximum < array[x+1]){
maximum = array[x+1];
}
}
cout << "Minimum Value is: " << minimum << endl;
cout << "Maximum Value is: " << maximum;
}
int main(){
int size;
cout << "Number of values you want to input: ";
cin >> size;
cout << "Input " << size << " values" << endl;
int array[size];
for(int x = 0; x < size; x++){
cout << "Input #" << x+1 <<": ";
cin >> array[x];
}
value(array,size);
return 0;
How can I output the maximum value inside the array? whenever I print the value the maximum value always return a number that is not present inside the array but the minimum seems fine, its only the maximum value that I am encountering a problem, I tried every possible answer that I know but it doesn't work, I hope ya'll can help Thank you in advance
for(int x = 0; x < size; x++){
If you have an array with ten values, size will be 10. If you work out, with paper and pencil, what this for loop does, you will see that it iterates for values of x 0 through 9, that's what this says. x starts with 0. When it reaches 10, x < size will be false and the loop ends, so the loop runs with x ranging from 0 to 9.
if(minimum > array[x+1]){
Since x will range from 0-9, it logically follows that x+1 will range from 1 to 10, and so this if statement will check the values in array[1] through array[10].
In C++ array indexes start with 0, not 1. The values in your array are array[0] through array[9]. array[10] does not exist, so the above code is undefined behavior.
Furthermore:
int array[size];
This is not valid C++ either. Your C++ compiler may allow this as a non-standard C++ extension, but array sizes must be fixed, constant sizes in C++, determined at compile time. You can't use a non-constant variable to set the size of an array, C++ does not work this way. If you need to have an array of size that's determined at runtime then you need to use std::vector instead of a plain array, and change the rest of your code accordingly.
Mistake 1
Your example has undefined behavior because of the expression array[x+1]. That is, for the last iteration of the for loop, you're going out of bounds of the array and so have undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
Mistake 2
In standard C++, the size of an array must be a compile time constant. So in your code:
int size;
cin >> size;
int array[size]; //NOT STANDARD C++
The statement int array[size]; is not standard C++ because size is not a constant expression.
Additionally you don't need 2 separate for loops when you can achieve the goal in 1 for loop as shown below.
Solution 1
You can use std::vector as shown below:
#include <iostream>
#include <vector>
#include <climits>
//this function take a vector as input
void value(const std::vector<int>& arr)
{
int max_num = INT_MIN;
int min_num = INT_MAX;
//iterate through the vector to find the max and min value
for(const int& element: arr)
{
if(element > max_num)
{
max_num = element;
}
if(element < min_num)
{
min_num = element;
}
}
std::cout<<"maximum is: "<<max_num<<std::endl;
std::cout<<"minimum is: "<<min_num; //return the difference of mx and min value
}
int main()
{
int n;
std::cout<<"elements: ";
std::cin >> n;
//create vector of int of size n
std::vector<int> arr(n);
//take elements from user
for(int i=0; i<n; i++)
{
std::cin >> arr[i];
}
value(arr);
return 0;
}
Demo
Solution 2
You can make the function a function template so that you don't need to pass a separate argument to the function as shown below:
#include <iostream>
#include <climits>
//N is a nontype template parameter
template<std::size_t N>
void value(const int (&array)[N]){
int max_num = INT_MIN;
int min_num = INT_MAX;
//iterate through the array to find the max and min value
for(const int& element: array)
{
if(element > max_num)
{
max_num = element;
}
if(element < min_num)
{
min_num = element;
}
}
std::cout<<"maximum is: "<<max_num<<std::endl;
std::cout<<"minimum is: "<<min_num;
}
int main(){
int array[3] = {};
for(int x = 0; x < sizeof (array) / (sizeof (array[0])); x++){
std::cout << "Input #" << x+1 <<": ";
std::cin >> array[x];
}
value(array); //no need to pass the second argument
return 0;
}
Demo
Also note that with C++17, you can use std::size instead of sizeof (array) / (sizeof (array[0])) to find the length of the array.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.

How can I print the numbers in main function?

I am new to c++ language. I am trying to solve a problem using function. I have to print the pentagon numbers untill the integer input, but when function returns the values, it only prints one value. I would love some help with it.
#include<iostream>
using namespace std;
int pent(int num){
int p;
for(int i=1;i<=num;i++){
p=(i*(3*i-1)/2);
}
return p;
}
int main(){
int num;
cin>>num;
int sender=pent(num);
cout<<sender<<endl;
return 0;
}
Your function returns int, that is a single integer. To return more, you can use std::vector. As you probably are not familiar with it, I will give you some pointers...
The most simple constructor creates a vector with no entries:
std::vector<int> x;
You can reserve space for elements via reserve:
x.reserve(num);
The vector still has no elements, but it already allocated enough space to hold num elements. This is important, because when we will add elements the vector will grow and that potentially requires to copy all elements to a different place in memory. We can avoid such frequent reallocations by reserving enough space upfront.
To add elements to the vector you can use push_back:
x.push_back(42);
Eventually to print all elements of the vector we can use a range-based for loop:
for (auto element : x) std::cout << element << " ";
So you can rewrite your code like this:
#include <iostream>
#include <vector>
std::vector<int> pent(int num){
std::vector<int> result;
result.reserve(num);
for(int i=1;i<=num;i++){
result.push_back(i*(3*i-1)/2);
}
return result;
}
int main(){
int num;
std::cin >> num;
auto sender = pent(num);
for (auto number : sender) std::cout << number << " ";
}
In your program, from your pent() function you are only returning last calculated value. In you ever time, you are overwriting you variable p.
So there is a way which #asmmo is suggesting, to print in pent() function.
Or you can pass a vector to your pent() function and store values in that and print it in main function.
For your ref:
void pent(int num, vector<int> &arr) {
int p;
for (int i = 1; i <= num; i++) {
arr[i-1] = (i*(3 * i - 1) / 2);
}
}
int main() {
int num;
cin >> num;
vector<int> arr(num);
pent(num, arr);
for (int i = 0; i < num; i++) {
cout << arr[i] << endl;
}
return 0;
}

The check with the module in the loop doesn`t work

There is a task. It is necessary in a one-dimensional array of N real numbers to calculate the number of the maximum modulo element among unpaired numbers.
I wrote the code, but it does not work. I can’t understand what’s wrong with him.
#include <iostream>
#include <math.h>
using namespace std;
int main() {
setlocale(0, "");
const int KolEl = 5;
int mas[KolEl];
int max = abs(mas[0]);
int result;
for (int i = 0; i < KolEl; i++)
{
cout << " Введите елемент[" << i << "] = ";
cin >> mas[i];
if (mas[i] % 2 == 1) {
if (abs(mas[i]) > max) {
result = i;
cout << result << endl;
}
}
}
system("pause");
}
You initialize max as:
int mas[KolEl];
int max = abs(mas[0]);
However, the values in mas[] are garbage values (read: undefined behavior). So now the value in max is also UB.
You then go on to use that value to compare to the input you take:
if (abs(mas[i]) > max) {
So the result of that comparison is undefined.
You probably meant to declare max as something like:
int max = INT_MIN;
So that the first comparison will always be true (every int except INT_MIN will be greater than it).

C++ Variable not properly receiving new value from vector?

I'm trying to write a program that creates and fills a vector with int values, then searches through it and returns the minimum value, recursively. I have the code written out and building, but it returns a weirdly large value for minimum every time- I have a feeling it's not properly assigning the smallest value to int minimum, but I'm not sure. Any thoughts?
#include <iostream>
#include <conio.h>
#include <vector>
using namespace std;
int vectorSize;
int minimum;
int result = -1;
int start;
int ending;
int answer;
int test;
int recursiveMinimum(vector<int>, int, int);
void main() {
cout << "How many values do you want your vector to be? ";
cin >> vectorSize;
cout << endl;
vector<int> searchVector(vectorSize);
start = 0;
ending = searchVector.size() - 1;
for (int i = 0; i < vectorSize; i++) {
cout << "Enter value for position " << i << " " << endl;
cin >> searchVector[i];
}
for (int x = 0; x < vectorSize; x++) {
cout << searchVector[x] << " ";
}
int answer = recursiveMinimum(searchVector, start, ending);
cout << "The smallest value in the vector is: " << answer;
_getch();
}
int recursiveMinimum(vector<int> searchVector, int start, int end) {
if (start < end) {
if (searchVector[start] < minimum) {
minimum = searchVector[start]; //this part seems to not work
}
start++;
recursiveMinimum(searchVector, start, end);
}
else {
return minimum;
}
}
`
Your minimum variable is not initialised, which leads to undefined behaviour. It should be set to the first value in the vector:
minimum = searchVector[0];
int answer = recursiveMinimum(searchVector, start, ending);
Additionally, ending is off by one, which makes it pick 6 as the smallest value out of [6, 9, 8, 4].
So, ultimately, your code should look like this:
minimum = searchVector[0];
int answer = recursiveMinimum(searchVector, start, ending + 1); // note the + 1
While irrelevant to the question, I advise you to use a tail call in recursiveMinimum, as explained here:
start++;
return recursiveMinimum(searchVector, start, end);
The main issue is that you do not initialise minimum. Hence, comparison searchVector[start] < minimum might never become true, and minimum remains uninitialized.
As a quick fix, write int minimum = MAX_INT; instead of int minimum;. MAX_INT is the maximum positive integer value (defined in limits.h). So the values in your array will never be greater that this value, and your minimum search loop will work (unless there are other issues; but for that, please consult the debugger :-) )

C++ Program Apparently Printing Memory Address instead of Array

#include <iostream>
using namespace std;
int main(){
int findMax(int *);
const int MAX = 100;
int values[MAX];
char ivals[256];
// Get the space-separated values from user input.
cin.getline(ivals, 256, '0');
char *helper;
// Clean input array and transfer it to values.
for(int i = 0; i < (MAX) && ivals[i] != 0; i++){
helper = ivals[i * 2];
values[i] = atoi(helper);
}
int mval = findMax(values);
cout << values << endl << mval;
return 0;
}
//Function to find the maximum value in the array
int findMax(int arr[]){
int localmax = 0;
for(int i = 0; i < (sizeof(arr)/sizeof(int)); i++){
if(arr[i] > localmax){
localmax = arr[i];
}
}
return localmax;
}
The purpose of this program is for the user to input a space-separated series of values ended by a 0. That array is then to be analyzed to find the max. I figured out how to convert what is originally a char[] into an int[] so that I can use the findMax() function on it without error but the sorting loop seems to have a problem of its own and when "cout << values << endl << mval;" is called, it returns only a memory address instead of what should be a non-spaced sequence of ints. Can anybody explain what I am doing wrong? It seems that I may have made some mistake using the pointers but I cannot figure out what.
Printing values won't print the contents of the array as you expect, it will print the memory location of the first element of the array.
Try something like this instead:
#include <iterator>
#include <algorithm>
// ...
copy(&values[0], &values[MAX], ostream_iterator(cout, " "));
Sorry I can't post actual working code, but your original post is a mess with many syntax and syntactic errors.
EDIT: In the interest of being more complete and more approachable & understandable to beginners, I've written a small program that illustrates 4 ways to accomplish this.
Method 1 uses copy with an ostream_iterator as I've done above.
Method 2 below is probably the most basic & easiest to understand.
Method 3 is a C++0x method. I know the question is tagged C++, but I thought it might be educational to add this.
Method 4 is a C++ approach using a vector and for_each. I've implemented a functor that does the dumping.
Share & Enjoy
#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
struct dump_val : public unary_function<int,void>
{
void operator()(int val)
{
cout << val << " ";
}
};
int main(){
int vals[5] = {1,2,3,4,5};
// version 1, using std::copy and ostream_iterator
copy(&vals[0], &vals[5], ostream_iterator<int>(cout, " "));
cout << endl;
// version 2, using a simple hand-written loop
for( size_t i = 0; i < 5; ++i )
cout << vals[i] << " ";
cout << endl;
// version 3, using C++0x lambdas
for_each(&vals[0], &vals[5], [](int val)
{
cout << val << " ";
}
);
cout << endl;
// version 4, with elements in a vector and calling a functor from for_each
vector<int> vals_vec;
vals_vec.push_back(1);
vals_vec.push_back(2);
vals_vec.push_back(3);
vals_vec.push_back(4);
vals_vec.push_back(5);
for_each( vals_vec.begin(), vals_vec.end(), dump_val() );
cout << endl;
}
When you pass around an array of X it's really a pointer to an array of X that you're passing around. So when you pass values to cout it only has the pointer to print out.
You really should look into using some of the standard algorithms to make your life simpler.
For example to print all the elements in an array you can just write
std::copy(values, values+MAX, std::ostream_iterator<int>(std::cout, "\n"));
To find the max element you could just write
int mval = *std::max_element(values, values+MAX);
So your code becomes
#include <iostream>
using namespace std;
int main(){
const int MAX = 100;
int values[MAX];
char ivals[256];
// Get the space-separated values from user input.
cin.getline(ivals, 256, '0');
char *helper;
// Clean input array and transfer it to values.
for(int i = 0; i < (MAX) && ivals[i] != 0; i++){
helper = ivals[i * 2];
values[i] = atoi(helper);
}
copy(values, values+MAX, ostream_iterator<int>(cout, "\n"));
cout << *std::max_element(values, values+MAX);
return 0;
}
Doing this removes the need for your findMax method altogether.
I'd also re-write your code so that you use a vector instead of an array. This makes your code even shorter. And you can use stringstream to convert strings to numbers.
Something like this should work and is a lot less code than the original.
int main(){
vector<int> values;
char ivals[256];
// Get the space-separated values from user input.
cin.getline(ivals, 256, '0');
int temp = 0;
stringstream ss(ivals);
//read the next int out of the stream and put it in temp
while(ss >> temp) {
//add temp to the vector of ints
values.push_back(temp);
}
copy(values.begin(), values.end(), ostream_iterator<int>(cout, "\n"));
cout << *std::max_element(values.begin(), values.end());
return 0;
}
Array of int is promoted to a pointer to int when passed to a function. There is no operator << taking ordinary array. If you want to use operator << this way, you need to use std::vector instead.
Note: it is possible technically to distinguish array when passed to a function using template, but this is not implemented for standard operator <<.
for(int i = 0; i < (sizeof(arr)/sizeof(int)); i++){
sizeof(arr) here is the size of the pointer to the array. C++ will not pass the actual array, that would be grossly inefficient. You'd typically only get one pass through the loop. Declare your function like this:
int findMax(int* arr, size_t elements) {
//...
}
But, really, use a vector.
Oh, hang on, the question. Loop through the array and print each individual element.