Minimum integer in array of integers C++ - c++

I am trying to create a program to find the minimum integer in an array of integers. This is my code:
#include<iostream>
using namespace std;
int findMinimum(int array);
int findMinimum(int array){
int arraySize = sizeof(array)/sizeof(int);
int minimum = array[0];
for (int i = 0; i < arraySize; i++){
if (arraySize[i] < minimum){
minimum = arraySize[i];
}
}
return minimum;
}
int main(){
int array[7] = {17,2,10,291,28,10,11};
int minimum = findMinimum(array);
cout << "The minimum of the array is: " << minimum;
}
I am getting this error:
/Users/Danny/Desktop/C++/Practice/arrays.cpp:9:22: error: subscripted value is not an array, pointer, or vector
int minimum = array[0];
~~~~~^~
/Users/Danny/Desktop/C++/Practice/arrays.cpp:11:18: error: subscripted value is not an array, pointer, or vector
if (arraySize[i] < minimum){
~~~~~~~~~^~
/Users/Danny/Desktop/C++/Practice/arrays.cpp:12:26: error: subscripted value is not an array, pointer, or vector
minimum = arraySize[i];
~~~~~~~~~^~
/Users/Danny/Desktop/C++/Practice/arrays.cpp:20:17: error: no matching function for call to 'findMinimum'
int minimum = findMinimum(array);
^~~~~~~~~~~
/Users/Danny/Desktop/C++/Practice/arrays.cpp:7:5: note: candidate function not viable: no known conversion from 'int [7]' to 'int' for 1st argument
int findMinimum(int array){
How do I fix these errors? Thank you.

The function head should be:
int findMinimum(int* array)
However, for an int*, this won't work:
int arraySize = sizeof(array)/sizeof(int);
Therefore you should also pass the size to the function:
int findMinimum(int* array, int size)
You should also consider to use std::vector instead of the array.

This may be cheating:
#include <algorithm>
#include <iostream>
#include <iterator>
int main() {
int array[7] = { 17, 2, 10, 291, 28, 10, 11 };
int min = *std::min_element(std::begin(array), std::end(array));
std::cout << "The minimum of the array is: " << min << '\n';
return 0;
}

What you passed in this line
int minimum = findMinimum(array);
is actually a pointer to an int array... actually, the pointer to the first element. So, you want to change your function signature to
int findMinimum(int* array)
In the modified function int findMinimum(int* array), the line below will be wrong
int arraySize = sizeof(array)/sizeof(int);
because, array is already a decomposed pointer here... so you want to change the function again to
int findMinimum(int* array, int size)
Your complete program will be:
#include<iostream>
using namespace std;
int findMinimum(int* array, int arraySize);
int findMinimum(int* array, int arraySize){
int minimum = array[0];
for (int i = 0; i < arraySize; i++){
if (arraySize[i] < minimum){
minimum = arraySize[i];
}
}
return minimum;
}
int main(){
int array[7] = {17,2,10,291,28,10,11};
int minimum = findMinimum(array, sizeof(array)/sizeof(int));
cout << "The minimum of the array is: " << minimum;
}

Related

returning an array address from function in c++ issue

i'm new to programming , this code gives me syntax error in line => int *result = apply_all(array1,5,array2,3) this is the error: expected primary-expression before '}' token|
i'm trying to write function called apply_all expects 2 arrays of integers and their sizes and dynamically allocates a new array of integers whose size is the product of 2 array sizes.
the function should loop through the 2nd array and multiple each element accross each element of array 1 and store the product in newly created array. the function is returning a pointer of to the newly allocated array.
also i wrote a function which is print to display the 1st & 2nd & newly array.
#include <iostream>
using namespace std;
//function prototype
int *apply_all(int *array1 ,int size1,int *array2,int size2);
void print(int *array,int size);
int main()
{
int array1[] {1,2,3,4,5};
int array2[] {10,20,30};
cout << "Array 1:";
print(array1,5);
cout << "Array 2:";
print(array2,3);
int *result = apply_all(array1,5,array2,3);
cout << "Result : ";
print(result,15);
delete [] result;
return 0;
}
int *apply_all(int *array1 ,int size1,int *array2,int size2)
{
int *result {nullptr};
result = new int[size1 * size2];
for (int i{0};i<size2;i++)
for(int j{0};j<size1;j++)
*(result[i*5+j]) = *(array1[i])**(array2[j]);
return result;
}
void print(int *array,int size)
{
for(auto num:array)
cout << num << endl;
}
On this line:
*(result[i*5+j]) = *(array1[i])**(array2[j]);
since result[i*5+j] gives you an int, you are trying to dereference an int, which is not possible.
You just need to do:
result[i*5+j] = array1[i] * array2[j];
Also, in print, your range-for loop won't work with a pointer. You need to do:
for(int i = 0; i < size; ++i)
cout << array[i] << endl;
Also, in apply_all, your loop bounds are incorrect. i needs to go till size1, and j needs to go to size2.
Here's a demo.
Since you are new, a simple work around would be creating an array with buffer space to store your results in and passing the pointer for this into apply_all. You could then write to this array which (being declared in main) should be very easy to access and cause few errors and use a c-string like ending to know when your results are over and to stop printing from the array (c-strings end with a value of 0 so that programs don't read unrelated memory). eg:
int buf[99];
apply_all(array_1, size1, array_2, size2, buf, size3);
for (int x = 0; buf[x] != end of buf var; x++;)
{
print(buf[x])
}
and
apply_all()
{
buf[start-end] = whatever you want;
buf[end + 1] = some variable that won't appear in buffer; //max int size?
}

Dynamically allocated array

I'm learning pointers in but I'm stuck on dynamic allocation of arrays.
The code below provides a function to find the element with the lowest value.
A dynamically allocated array is passed as a parameter to it.
#include <cstdlib>
#include <iostream>
using namespace std;
int findMin(int *arr, int n);
int main()
{
int *nums = new int[5];
int nums_size = sizeof(*nums);
cout << "Enter 5 numbers to find the minor:" << endl;
for(int i = 0; i < nums_size; i++)
cin >> nums[i];
cout << "The minor number is " << findMin(*nums, nums_size);
delete [] nums;
return 0;
}
But it return this error:
error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
How can I pass that array to the function?
Just for curiosity: why the for loop allows me to enter 4 value if my array is made up of 5 elements?
How can I pass that array to the function?
nums is already a type int*, you don't need to dereference it:
findMin(nums, nums_size);
why the for loop allows me to enter 4 value if my array is made up of 5 elements?
int nums_size = sizeof(*nums); does not do what you think it does. It's equivalent to sizeof(nums[0]), which is equivalent to sizeof(int), which happens to be equal to 4 at your machine.
There is no way to extract size of array allocated on the heap, you need to save the size on your own:
int nums_size = 5;
int* nums = new int[nums_size];
#include <cstdlib>
#include <iostream>
using namespace std;
int findMin(int *arr, int n){
int mn=INT_MAX;
for(int i=0;i<n;i++){
if(arr[i]<mn){
mn=arr[i];
}
}
return mn;
};
int main()
{
int nums_size = 5;
int *nums = new int[nums_size];
cout << "Enter 5 numbers to find the minor:" << endl;
for(int i = 0; i < nums_size; i++)
cin >> nums[i];
cout << "The minor number is " << findMin(nums, nums_size);
delete [] nums;
return 0;
}
The above code works fine. Your error was in passing the array to the function.
Also to add -
Your code made only 4 iterations coz sizeof(*nums) returned the size of base index element pointed by pointer, i.e ,sizeof(num[0]). So I made a minor change and now it works fine.

Modify a variable passed by reference

I'm working on a function that finds the smallest element in an array. I'm trying to modify the variable s using pass by reference. I'm brand new to C++ and I'm not sure if I have done pass-by-reference correctly. Can anyone confirm that this is the correct way to do this, or suggest better ways to approach a min value function with pass by reference?
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
using namespace std;
int smallestElm(int numArray[], int length, int &smallest);
int main() {
int n[3] = {2,5,3};
int s = 0;
int length = 0;
cout << smallestElm(n, length, s) << endl;
}
int smallestElm(int numArray[], int length, int &smallest) {
smallest = numArray[0];
length = sizeof (numArray) / sizeof (int);
for (int i = 1; i < length; i++) {
if (numArray[i] < smallest) {
smallest = numArray[i];
}
cout << smallest << endl;
return 0;
}
}
Yes this is correct, as you should be able to tell by yourself, by modifying your main function like this:
int main() {
int s = 0;
// call your function
cout << s << endl; // Here you print 's', thus you confirm whether you are right or not
}
If s wouldn't change its value, then your pass by reference won't be correct (since s does change its value inside the body of the function).
As for the function, it's wrong, since it will return before checking all the elements! So, change that to something like this to check all the elements of the array before saying for certain which the smallest element is:
#include <stdlib.h>
#include <iostream>
using namespace std;
void smallestElm(int numArray[], size_t length, int &smallest);
int main() {
int n[] = {2,5,3}; // size is not needed, it's automatically computed by the compiler
int s = 0;
size_t length = 3;
smallestElm(n, length, s);
cout << "smallest element = " << s << endl;
return 0;
}
void smallestElm(int numArray[], size_t length, int &smallest) {
smallest = numArray[0];
for (int i = 1; i < length; i++) {
if (numArray[i] < smallest) {
smallest = numArray[i];
}
cout << smallest << endl;
}
}
Output:
Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
2
2
smallest element = 2
Don't forget that STL provides min_element, that you could use like this:
#include <algorithm>
#include <iostream>
using namespace std;
int main() {
int n[] = {2,5,3};
int *s = std::min_element(n, n + 3); // 3 size of the array
cout << "smallest element = " << *s << endl;
return 0;
}
Output:
Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall main.cpp
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
smallest element = 2
Can anyone confirm that this is the correct way to do this
Yes, that is the correct way to declare a reference argument. And yes, you can modify objects through a reference.
or suggest better ways to approach a min value function ...
A better way would arguably be to return the min value, instead of modifying an argument. Right now the function always returns 0, which seems useless.
... with pass by reference
That's a silly idea, but your approach is correct way to pass by reference. The function itself has multiple bugs.
It seems to always return after the first iteration, so it'll always find one of the first 2 element to be "smallest".
The value of int length argument is never used. It is overridden before use.
sizeof (numArray) returns the size of the pointer numArray which is not in any way related to the size of the pointed array.
The function always uses numArray[0] so it will have undefined behaviour if length == 0.
It's correct your code, but there is another way: Using a pointer to int, into the function argument and invoke this with the address of memory of variable s, as the below sample shows:
#include <stdlib.h>
#include <iostream>
using namespace std;
void smallestElm(int numArray[], size_t length, int *smallest);
int main() {
int n[] = {2,5,3}; // size is not needed, it's automatically computed by the compiler
int s = 0;
size_t length = 3;
smallestElm(n, length, &s);
cout << "smallest element = " << s << endl;
return 0;
}
void smallestElm(int numArray[], size_t length, int *smallest) {
*smallest = numArray[0];
for (int i = 1; i < length; i++) {
if (numArray[i] < *smallest) {
*smallest = numArray[i];
}
cout << *smallest << endl;
}
}

Caling function that uses array as parameter

I'm having some difficulty with my syntax. The purpose of the below program is to print an array of 20 random numbers, find the max of the array and then print the array and the max. I've got the sections to initialize and create the array without any problem, but my issue is with the find_max function. In the main function, I'm trying to work out the syntax to call my find_max function there so I can print the results. If anyone can help to fix my syntax, I'd really appreciate it.
#include <cstdlib>
#include <iostream>
using
namespace std;
void
init_array(int array[], int size, int range)
{
for (int index = 0; index < size; index++)
array[index] = rand() % range;
}
void print_array(int array[], int size)
{
for (int index = 0; index < size; index++)
cout << array[index] << " ";
cout << endl;
}
int find_max (int array[], int size)
{
int max = array[0];
for (int index = 0; index < size; index++)
{
if (array[index] > max)
max = array[index];
}
return max;
}
int main()
{
// Declare array of integers
const int size = 20;
int array[size] = {0};
int max = find_max(array,size);
// Initialize and print array
init_array(array, size, 100);
print_array(array, size);
cout << "The max is:" << max << endl;
return 0 ;
}
Your call of find_max needs to use your declared variables and that after you call init_array. Otherwise your array is empty.
The call to find_max should look like this:
int max = find_max(data, DATA_SIZE);
You try to find max before the array is initialized. That is not what you want. The following works:
const int DATA_SIZE = 20;
int data[DATA_SIZE] = {0};
// Initialize and print array
init_array(data, DATA_SIZE, 100);
print_array(data, DATA_SIZE);
// Find maximum value
int max = find_max(data, DATA_SIZE);
cout << "max = " << max << endl;
return 0;
Well, when declaring the array this way:
int data[DATA_SIZE] = {0};
so all 20 elements in it equals zero.
your main function should look like this:
int main()
{
// Declare array of integers
const int DATA_SIZE = 20;
int data[DATA_SIZE] = {0};
// Initialize and print array
init_array(data, DATA_SIZE, 100);
cout<< find_max(data, DATA_SIZE)<< endl;
print_array(data, DATA_SIZE);
return 0 ;
}
you give the 20 elements random values first by calling init_array and then you try finding the Max of them.
You can give your function the start address of your array and the size of array, then you can use pointers to traverse the array. :)

Pointers; Simple Allocation of An Array

I get an error under "int dArray[size]" saying that size needs to be a constant. Can someone explain what that means exactly?
I want it to be an array of size 4 and output 1, 3, 5, and 7.
#include <iostream>
using namespace std;
int *AllocateArray(int size, int value){
int dArray[size];
for (int i = 0; i <= size; i++){
dArray[i] = value;
value + 2;
}
}
int main(){
AllocateArray(4, 1);
}
Solved:
Here is the code that ended up working.
#include <iostream>
using namespace std;
int *AllocateArray(int size, int value){
int * Array = new int[size];
for (int i = 0; i < size; i++){
Array[i] = value;
value = value + 2;
}
for (int i = 0; i < size; i++){
cout << Array[i] << endl;
}
return Array;
}
int main(){
int *dArray = AllocateArray(4, 1);
}
In int dArray[size] size is not a constant value. Because of that you are getting that error. What you probably wanted to do was make a new array using a pointer and new like:
int * dArray = new int[size];
C++ requires that the size of arrays are determined at compile-time. As size is determined at runtime, the compiler complains.
If you are interested in having array-like behaviour with a size unknown at compile-time, then consider using std::vector.
The size of array should be a known constant in compile time, so that compiler can allocate correct memory for that array on the stack. Remember that such a declare is for stack variable. If you do want dynamic array, try std::vector.
You have to declare the size of an array using numbers, #define or const unsigned int. Otherwise they are considered variable length arrays.
Example:
const unsigned int MAX_ARRAY_SIZE = 14;
double my_array[MAX_ARRAY_SIZE];