Caling function that uses array as parameter - c++

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. :)

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?
}

Having trouble with my C++ program. Involes resizing an integer array dynamically

Here is what I have so far: http://cpp.sh/54vn3
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <cstdlib>
using namespace std;
int *reSIZE(int *&original, int &SIZE, const int &maxSIZE); //function prototype resize
void sortFUNC(int *&original, int &SIZE, const int &maxSIZE); //function prototype sortFUNC
int main()
{
int SIZE = 4; //size of current array
int maxSIZE = 10; //size of final array
int *original = new int[SIZE] {5, 7, 3, 1}; //old(current) array
cout << "Elements in array: "; //test output
reSIZE(original, SIZE, maxSIZE); //call function resize
cout << endl << endl; //blank line
cout << "Elements in array in increasing order: "; //test output
sortFUNC(original, SIZE, maxSIZE); //call function sortFUNC
cout << endl << endl;
return 0;
}
int *reSIZE(int *&original, int &SIZE, const int &maxSIZE)//function definition
{
int *temporiginal = new int[SIZE + 3]; //(final)new array
for (int i = 0; i < SIZE; i++) //copy old array to new array
{
temporiginal[i] = original[i];
cout << original[i] << setw(3);
}
delete[] original; //delete old array
original = temporiginal; //point old array to new array
return temporiginal;
}
void sortFUNC(int *&original, int &SIZE, const int &maxSIZE)
{
for (int i = 0; i < SIZE; i++)
{
int smallest = original[i];
int smallestINDEX = i;
for (int m = i; m < SIZE; m++)
{
if (original[m] < smallest)
{
smallest = original[m];
smallestINDEX = m;
}
}
swap(original[i], original[smallestINDEX]);
}
int *temporiginal = new int[SIZE + 3];
for (int i = 0; i < SIZE; i++)
{
temporiginal[i] = original[i];
cout << original[i] << setw(3);
}
delete[] original;
original = temporiginal;
}
I want to add a few elements at the end of the array in main, but when I do, the program crashes when I run it. The resize function that I created is supposed to expand the function in main to hold 10 elements. The one in main originally holds 4. The new array is supposed to change that to 10. How do I add three more integers to the array in main without it crashing? Is my resize function wrong? Or is it a problem in my main? The program that is shown right now works as is. But when I add another integer in the array in main, it crashes. Like, if I add a 2 after the 1.
Thanks.
Edit: I was able to add elements at the end of the array in main by adding them in the resize function.
cpp.sh/35mww
Like mentioned earlier, maxSIZE isn't being used. There are more useless stuff as well. I have to clean this up, but I figured out what I was trying to figure out. I don't know how to use structures yet. I know that there are a lot of different ways to write a program. I'm just a beginner.
Thanks, everyone.
You need to modify the value of size everytime you call the function rezise other wise even if u call the function resize 3 times u always will have SIZE+3 on your array size.After call resize try
original[4] = 0;
original[5] = 0;
original[6] = 0;
and after that try to do this.
original[7] = 0;
you should be able to see your mistake

Function and Array in C++: Unexpected output

I need some help here please.
I just started learning C++ (coming from Python background).
I'm trying to familiarize myself with arrays and functions. Wrote a bunch of functions to do as stated, above each one.
However, the function which is supposed to sum elements in an array and return their sum, seem to be adding 10 to the result, no matter the argument supplied as input. What am I doing wrong please, as I can't seem to find this out. Any help on general layout of my code also would be appreciated.
// WORKING WITH ARRAYS AND FUNCTIONS
#include<iostream>
using namespace std;
// FUNCTION TO INSTANTIATE ARRAY INT OF LENGTH N.
int* array_creator(int n)
{
static int ary_of_ten[10]; //declare array
for (int i=0; i<n; i++) //use loop to fill it up
{
ary_of_ten[i] = i+1;
}
return ary_of_ten;
}
//FUNCTION TO PRINT ARRAY ELEMENTS
void* array_printer(int arr[], int array_lenght)
{
for (int i=0; i<array_lenght-1; i++)
{
cout << arr[i] << " ";
}
cout << arr[array_lenght-1] << endl;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS ARRAY OF SQUARE OF EACH ELEMENT
int* square_array(int *p, int array_length)
{
const int ary_sz(array_length);
static int sqd_values[10];
for (int i=0; i<ary_sz; i++)
{
*(sqd_values + i) = *(p+i) * *(p+i);
}
return sqd_values;
}
//FUNCTION ACCEPTS INT ARRAYS AND RETURNS SUM OF ITS ELEMENTS
int sum_array(int *arry, int array_length)
{
int summation;
for(int i=0; i<array_length; i++)
{
summation += *(arry + i);
}
return summation;
}
int main()
{
cout << sum_array(array_creator(10), 3) << endl;
array_printer(array_creator(10), 10); //print array of 1-10 elements
array_printer(square_array(array_creator(10), 10), 10); //prt arry of sqrd values
return 0;
}
summation shuld be initialized to 0.
int summation=0;

Minimum integer in array of integers 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;
}

copying elements from one array to another

I am getting a crash error at run time and not sure what exactly to do with the function or how to get the data for it.
FUNCTION DETAILS
Write a function that accepts an int array and size as arguments, then create a new array that is one element bigger than the given. Setting the first element to 0, then copying over what is in the argument array to the new array.
MAIN DETAILS
Use in a program reading int n from input, then read int n from file data name data
passing it to element shifter, then printing it to output (one per line).
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int element_shift(int elmts[], int size) {
int new_size = size + 1;
int shifter[new_size];
int *elmt_sft;
shifter[0] = 0;
for (int i = 1; i >= new_size; i++) {
shifter[i + 1] = elmts[i];
}
return *elmt_sft;
}
int main() {
fstream infile;
infile.open("D:\\data.txt");
int n, x;
infile >> x;
cout << "size of array: ";
cin >> n;
const int ARRAY_SIZE = n + x;
int elements[ARRAY_SIZE];
element_shift(elements, ARRAY_SIZE);
system("PAUSE");
return EXIT_SUCCESS;
}
First of all ARRAY_SIZE declared in the main function is not a constant variable but defined at run-time depending on user inputs. This means that the array elements should be created dynamically. On the other hand you read some x variable which is only used to define the size of the array and didn't initialized the array at all. I guess that the problem statement is to read the size of the array from the input, then the data of the array from the file.
There are also lot of mistakes in element_shift function.
Your code should look like something similar to this:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
void element_shift(int* elmts, int size)
{
int new_size = size + 1;
int* shifter = new int[new_size];
shifter[0] = 0;
for(int i = 0; i < size; ++i)
{
shifter[i + 1] = elmts[i];
}
delete [] elmts;
elmts = shifter;
}
int main()
{
fstream infile;
infile.open("D:\\data.txt");
int n;
cout << "size of array: ";
cin >> n;
int* elements = new int[n];
for (int i = 0; i < n; ++i) {
infile >> elements[i];
}
element_shift(elements, n);
for (int i = 0; i < n; ++i) {
std::cout << elements[i] << std::endl;
}
return EXIT_SUCCESS;
}
First off, you spend alot of time creating the shifted array but don't return it back.
int element_shift(int elmts[], int size) {
int new_size = size + 1;
int shifter[new_size];
int *elmt_sft;
shifter[0] = 0;
for (int i = 1; i >= new_size; i++) {
shifter[i + 1] = elmts[i];
}
return *elmt_sft;
}
The elmt_sft pointer is never assigned. You are trying to access memory that is not there by using *elmt_sft. This may be causing your error. Also this function has no way of returning the new array shifter because that variable is locally declared and will disappear once the function exits. If you want to create something new in the function and still have it in memory once the function exits, I recommend creating the array dynamically and returning a pointer to it.
This is untested but should start you in the right direction. It will return a separate dynamically allocated array that will not override your other one.
int* element_shift(int elmts[], int size) {
int *result_array = new int[size + 1]; //dynamically create new array MAKE SURE TO DELETE
result_array[0] = 0; //set 0 index to 0
for (int i = 1; i < size + 1; i++)//start at 1 of the result and put value in
{
result_array[i] = elmts[i - 1];
}
return result_array; //returning pointer
}