Calling methods with arrays in C++ - c++

My problem is that I have trouble calling the int computePattern method in int main(). I am able to use the insertNumber method. But i don't know how to use the computePattern method. The method is to compute the number of patterns and return the count. The pattern is that both adjacent numbers must be greater than 7. Hence, there are only 5 pairs to check as there are 10 numbers. For now the output is only the random arrays which worked, but I need to print out the number of patterns too. I need to use methods as it is required in the question.
int insertNumber(int b )
{
int a = rand()%10+1;
return a;
}
int computePattern(int* inArray, int size )
{
int patterns=0;
for(int z=0;z<size;z=z+2)
{
if(inArray[z]+inArray[z+1]>7)
{
patterns ++ ;
}
}
return patterns;
}
int main()
{
int arrays[10];
srand(time(0));
for ( int b=0; b<10 ; b++)
{
arrays[b] = insertNumber(b);
}
cout << "Arrays";
for ( int c= 0; c<10; c++)
{
cout << " " ;
cout << arrays[c];
}
int patterns =computePattern(arrays,10);
cout<<endl;
cout << "Patterns" <<patterns;
}

The array in computePattern remains uninitialised. Ergo, it will contain random variables in the memory which will mess up your computational path.
You should maybe modify the function to int computePattern(int z, int array[]). Then pass the array from the main scope.

You have different arrays in main than in computePattern. Just because they share a name doesn't mean they're the same variable. Each one of them is function scope. A better way is to pass in the address and size of the array.
int computePattern(int* inArray, int size)
{
int patterns=0;
for(int z=0; z<size-1; z+=2)
{
if((inArray[z] + inArray[z+1]) > 7)
{
patterns++;
}
}
return patterns;
}
//... then in main...
int patterns=computePattern(arrays, 10);
cout << patterns;

Related

How do I use pointers with arrays in c++ and return a pointer value?

I am trying to use pointers whenever possible in the following code and am having difficulty figuring out how, exactly, to institute the pointers and how to return a pointer value at the end of my first function. I have done some research on the subject but none of the methods I found have been helpful so far, so I was hoping you may have some specialized tips.
Note: I am a beginner.
#include <iostream>
using namespace std;
int mode(int *pies[], int size) {
int count = 1;
int max = 0;
int *mode=pies[0];
for (int i=0; i<size-1; i++)
{
if (pies[i] == pies[i+1])
{
count++;
if (count>max)
{
max = count;
mode = pies[i];
}
}
else
count = 1;
}
return *mode;
}
int main() {
int n;
cout<<"Input the number of people: "<<endl;
cin>>n;
int survey[n];
cout << "Enter the amount of pie eaten by each person:" << endl;
for(int i = 0; i < n; i++) {
cout <<"Person "<<(i + 1)<< ": "<<endl;
cin>>survey[i];
}
cout<<"Mode: "<<mode(survey, n)<< endl;
return 0;
}
Here is an attempt to answer.
In your main(), you call the mode() function with mode(survey, n) while int survey[n]; is an array of int, so you may use int mode(int *pies, int size) instead of int mode(int *pies[], int size) (as the array int survey[n] can be implicitly converted into pointer).
However, you need to modify two more things in your function:
int *mode=pies[0]; is wrong as pies[0] is the first element of an array of int, thus is an int, while int* mode is a pointer on an int which is incompatible. mode should be an int to receive pies[0]. The correct code is then int mode = pies[0].
Your function signature is int mode(int *pies, int size), thus, again, you should return an int. You should then just return mode;
These are only hints on how to make the code compile.
Your next step is to formalize what you would like it to do and then modify the code accordingly
NB: The correct practice is to think about what you would like to achieve first and then code afterwards (but let us say that this is for the sake of helping each other)
To get started using pointers, you may look at some simple tutorials at first:
http://www.cplusplus.com/doc/tutorial/arrays/
https://www.programiz.com/c-programming/c-pointers
https://www.programiz.com/c-programming/c-pointers-arrays
https://www.geeksforgeeks.org/pointer-array-array-pointer/
https://www.geeksforgeeks.org/how-to-return-a-pointer-from-a-function-in-c/
https://www.tutorialspoint.com/cprogramming/c_return_pointer_from_functions.htm
Here is the modified code with the stated modifications above (it compiles):
#include <iostream>
using namespace std;
int mode(int *pies, int size) {
int count = 1;
int max = 0;
int mode=pies[0];
for (int i=0; i<size-1; i++)
{
if (pies[i] == pies[i+1])
{
count++;
if (count>max)
{
max = count;
mode = pies[i];
}
}
else
count = 1;
}
return mode;
}
int main() {
int n;
cout<<"Input the number of people: "<<endl;
cin>>n;
int survey[n];
cout << "Enter the amount of pie eaten by each person:" << endl;
for(int i = 0; i < n; i++) {
cout <<"Person "<<(i + 1)<< ": "<<endl;
cin>>survey[i];
}
cout<<"Mode: "<<mode(survey, n)<< endl;
return 0;
}

How to initialize an array in a constructor c++

I need help with this code.
What I want is to make a parametric constructor and initialise/set the value of array in it.
Question: Make a class with arrays of integers and initialise it in a constructor. Then find the smallest and largest numbers using functions.
But I am stuck at how to initialise the array in the constructor.
I want to take data input in both ways
(1) By user, using cin
(2) By giving my own values
class Numbers
{
int Arr[3];
public:
Numbers() //default constructor
{
for (int i=0 ; i<=2 ; i++)
{
Arr[i]=0;
}
}
Numbers(int arr[]) //parameteric constructor
{
for (int i=0;i<=2;i++)
{
Arr[i]=arr[i];
}
}
};
int main()
{
int aro[3] = {0,10,5};
Numbers obj (aro);
return ;
}
The solution is pretty simple. I've made a new program from start again (for sake of understanding). According to your requirement, you wants to get input of array elements from the user dynamically and assign them to a constructor and use a method to print the highest value.
Consider the following code:
#include <iostream>
using namespace std;
const int N = 100;
class Numbers
{
int largest = 0;
public:
Numbers(int, int[]);
void showHighest(void)
{
cout << largest << endl;
}
};
Numbers::Numbers(int size, int arr[])
{
for (int i = 0; i < size; i++)
{
if (arr[i] > largest)
{
largest = arr[i];
}
}
}
int main(void)
{
int arrays[N], total;
cout << "How many elements? (starts from zero) ";
cin >> total;
for (int i = 0; i < total; i++)
{
cout << "Element " << i << ": ";
cin >> arrays[i];
}
Numbers n(total, arrays);
n.showHighest();
return 0;
}
Output
How many elements? (starts from zero) 3
Element 0: 12
Element 1: 16
Element 2: 11
16
Note: I've initialized a constant number of maximum elements, you can modify it. No vectors, etc. required to achieve so. You can either use your own values by removing the total and its followed statements and use only int arrays[<num>] = {...} instead. You're done!
Enjoy coding!
I suggest to use std::vector<int> or std::array<int>.
If you want initialize with custom values you can do std::vector<int> m_vec {0, 1, 2};
Thank you so much for your help. I was basically confused about how to use arrays in a constructor and use setters/getters for arrays in a class. But you all helped a lot. Thanks again.
Numbers(int arr[])
{
for (int i=0;i<=9;i++)
{
Arr[i]=arr[i];
}
Largest=Arr[0];
Smallest=Arr[0];
}
void Largest_Number()
{
header_top("Largest Number");
Largest=Arr[0]; //Using this so we make largest value as index zero
for (int i=0 ; i<=9 ; i++)
{
if(Arr[i]>Largest)
{
setLargest( Arr[i] );
}
}
cout<<"Largest Number: "<<getLargest()<<endl;
}

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;

C++ code malfunctioning

I wrote a basic linear search C++ code. Whenever I run this, the result I get is always the opposite of the expected result.
For instance, I want to search 4. In an array where it is present, it will say the number is not found, but upon searching an absent element, it will say the element is found at position 0.
Even after an hour or so of constantly looking at the code I have not found any solution.
#include <iostream>
using namespace std;
//scanning program
int linearsearch (int A[] , int z, int n, int srchElement) {
for (int z = 0; z < n; z++) {
if (A[z] == srchElement) {
return z;
}
}
return -1;
}
//main program
int main () {
int i, n, A[1000], z;
//asking for size of array
cout << "give size of the array needed to be scanned: ";
cin >> n;
cout << endl;
if (n > 999) {
cout << "invalid value";
return -1;
}
//making sure of the size of the array
cout << "enter " << n << " integers: ";
//asking for the array
for (i = 0; i < n; i++) {
cin >> A[i];
}
int srchElement, index;
do {
cout << endl << "enter element to search (-1 to exit ): ";
//srchElement is defined here
cin >> srchElement;
if (srchElement == -1) break;
index = linearsearch(A, n, srchElement, z);
//calling thscanning function
if (index == -1) {
cout << srchElement << " not present" << endl;
}
//outputting the results of the scan
else {
cout << srchElement << " present " << index << endl;
}
} while (true);
return 0;
}
Your parameters to linearsearch are not in the correct order - you are passing n into the unused z parameter. With your current function you should call it like:
index=linearsearch(A, 8675309, n, srchElement);
I recommend you get rid of z as a parameter, then you won't need to pass a value to it.
Also please note: Spaces and indentation do not make your program run slower, but they do make it a lot easier to read.
The order of arguments in the function definition is not the same as in the function call.
It should be like (Line no 4):
int linearsearch (int A[] , int n, int srchElement, int z)
This is your search function correctly formatted:
int linearsearch (int A[] , int z, int n, int srchElement)
{
for (int z = 0; z < n; z++)
{
if(A[z] == srchElement)
{return z;}
}
return -1;
}
and here is how you call it:
index=linearsearch(A, n, srchElement, z);
You pass a value z in with the call. It is unitialised and does nothing, in main() or in the function.
You pass the arguments into the function in the wrong order. You are:
passing n (from main()) into the unused z value
searching for the uninitialised z (from main())
passing in the element you are looking for as n (array size). (This will quite likely result in out of bounds error, e.g. if searching for -1)
Try this:
int linearsearch (int A[], int n, int srchElement)
{
for (int z = 0; z < n; z++)
{
if(A[z] == srchElement)
{return z;}
}
return -1;
}
and here is how you call it:
index=linearsearch(A, n, srchElement);
You immediate problem: as The Dark spotted, this call:
index=linearsearch(A, n, srchElement, z);
doesn't match the declaration
int linearsearch (int A[] , int z, int n, int srchElement)
Function arguments in C++ are positional: just because the last call argument and the second declaration parameter are both called z doesn't mean anything.
Now, there are several local issues of style:
this kind of function is risky in the first place
int linearsearch (int[],int,int,int)
because it relies on you remembering the correct order for the last three integer parameters. If you must do this, you should be extra careful to give them all distinctive names, be very clear about which is which, and keep the order consistent across families of functions.
It's better, where possible, to help the compiler help you out, by either giving the arguments distinct types (or enumerations, or whatever), or grouping them into a structure.
For example, using a std::vector<int> instead of your array effectively groups int A[] and int n together in an object, so they can't get out of sync and n can't get confused with the other integers floating around
You shouldn't be passing z in the first place. You immediately hide it with a local int z in the loop, so it can't be doing anything. Remove it from both the declaration and the call. This simplification is sufficient to fix your bug.
Your secondary problem is that the code is ugly. It's poorly formatted and hard to read, and and that makes it more difficult to spot mistakes. Try to make your code simple and readable: there's less opportunity for things to go wrong, and its easier to see the problems when they occur.
Your tertiary problem is that the code is bad. Most of this can be done using standard library facilities (making your code simpler), which are themselves well-tested and generally have carefully-designed interfaces. Use them first, and replace if necessary.

How to pass arrays in the main func. w/ c++

#include <iostream>
using namespace std;
const int MAX = 1000;
int ArrMix[MAX];
int *ptrArrPos[MAX];
int *ptrArrNeg[MAX];
int PosCounter = 0;
int NegCounter = 0;
int r;
void accept(int ArrMix[MAX])
{
cout<<"Enter the number of elements in your array: ";
cin>>r;
for (int i = 0; i < r; i++)
{
cout<<"Enter value:";
cin>>ArrMix[i];
}
}
void process(int &i)
{
if(ArrMix[i] >= 0)
{
ptrArrPos[PosCounter] = &ArrMix[i];
PosCounter++;
}
else
{
ptrArrNeg[NegCounter] = &ArrMix[i];
NegCounter++;
}
}
void display(int &i)
{
cout<<"Your passed array is: " << endl;
cout<<ArrMix[i] << endl;
cout <<"Total number of positive integers is: "<<PosCounter<<endl;
cout<<"Your positive array is: "<<endl;
for (int i = 0; i < PosCounter; i++)
{
cout << *ptrArrPos[i] << endl;
}
cout<<endl;
cout <<"Total number of Negative integers is: "<<NegCounter<<endl;
cout<<"Your negative array is: "<<endl;
for (int i = 0; i < NegCounter; i++)
{
cout << *ptrArrNeg[i] << endl;
}
}
int main ()
{
int *i;
int a = &i;
accept(&ArrMix[MAX]);
process(a);
display(a);
system("pause>0");
}
The code you see above is a program use to create a user-defined array list of numbers. It should accept numbers from the user, display the passed array, positive numbers array and its negative numbers array. it should evaluate items, meaning separating negatives #s from positive numbers then creating an array for each. next is to use a counter to identify how many positive #s and negative #s are in each array.
I am having problems in passing the array from one function to another using pointers and calling it in the main function. so please help me?
The expression &ArrMix[MAX] returns a pointer to the integer at index MAX in the array. This index is one beyond the array, meaning you pass a pointer to beyond the array to the function which will then happily write to that memory.
Passing an array is as simple as passing any other argument:
accept(ArrMix);
You also have a problem here:
int *i;
int a = &i;
You declare i to be a pointer to an int. Then you use &i which returns the address of the variable i, in other words a pointer to a pointer to an int, and try to assign this double-pointer to a normal int variable.
It seems to me that you might want to return the number of entries is in the array from the access function, and then loop over the entries the user entered in the array and call process for each value. And then in display instead of taking the ArrMix index it should take the size and loop over that to display the ArrMix array.