I am getting the error:
Invalid conversion from int to int*.
I have not created any int* (I think) and when I change the offending lines to be int*, There are no build errors but the program crashes upon launch.
Here is my code:
//Main:
int main(){
//Varibales:
Random randomInt;
clock_t start;
clock_t End;
double duration;
double clocksPerSec;
int result;
int arraySize;
//Repeat 100 times:
for(int i=1; i<=100; i++){
//Set array size:
arraySize = i*500;
//Create the array:
int testArray[arraySize];
//For the array size:
for(int j=0; j<arraySize; j++){
//Add random number to array:
testArray[j] = randomInt.randomInteger(1, 10000);
}
//Run the test:
start = clock();
result = algorithmTest(testArray[arraySize], arraySize);
End = clock();
//Calculate execution time:
duration = End - start;
clocksPerSec = duration/CLOCKS_PER_SEC;
//Display the result:
cout << "The median is: ";
cout << result << endl;
cout << "Exection time was: ";
cout << clocksPerSec;
cout << "s\n" << endl;
}
//Return 0:
return 0;
}
It seams to be throwing the error when i call algorithmTest(); Here it is:
//First Test:
int algorithmTest(int testArray[], int Size){
//Declare variables:
int k = Size/2;
int numSmaller;
int numEqual;
//For every element in the array:
for(int i=0; i<Size; i++){
//Set varibales to 0:
numSmaller = 0;
numEqual = 0;
//For every element in the array:
for(int j=0; j<Size; j++){
//If j is less than i:
if(testArray[j] < testArray[i]){
//Increment numSmaller:
numSmaller++;
//Else if j is equal to i:
}else if(testArray[j] == testArray[i]){
//Increment numEqual:
numEqual++;
}
}
//Determine if the median was found:
if(numSmaller < k && k <= (numSmaller + numEqual)){
//Retrun the medain:
return testArray[i];
}
}
//Return 0:
return 0;
}
result = algorithmTest(testArray[arraySize], arraySize);
should be
result = algorithmTest(testArray, arraySize);
Your function int algorithmTest(int testArray[], int Size) takes an int[] as first argument, while you pass a testArray[arraySize], where [i] operator means fetch the value at ith element of testArray, which is an int. Therefore you encounter that error.
In order to clarify something, the [...] in the line int testArray[arraySize]; is different from the [...] in the line result = algorithmTest(testArray[arraySize], arraySize);: first one is for indicating array's size, while the second one is for accessing the element.
Look at the definition of AlgorithmTest. You require an int[] (also known as int*) as first parameter, but when you call it you give it an actual int
Related
I'm writing a function that will find the number with max number of divisors but the function is not returning anything. Can someone point out my mistake?
This is the question
Write a C++ program that creates and integer array having 30 elements. Get input in this array (in main
function). After that, pass that array to a function called “Find_Max_Divisors” using reference pointer.
The function “Find_Max_Divisors” should find (and return) in the array that number which has highest
number of divisors. In the end, the main function displays that number having highest number of divisors.
#include <iostream>
using namespace std;
int main ()
{
int arr[30];
int* array = &arr[30];
cout << "Please enter values of the array" << endl;
for (int i=0; i<30; i++)
{
cin >> arr[i];
}
cout << "Number with most divisors in array is " << endl;
int Find_Max_Divisors (*array);
}
int Find_Max_Divisors (int p[])
{
int count=0, max_divisor, max_counter, prev=0, repeat=0, divisor;
for (int i=2; i<=30; i++)
{
if (p[i]%i==0)
{
count++;
}
if (count > prev)
{
prev = count;
divisor = p[i];
}
if (count==max_counter && max_counter!=0)
{
cout << p[i] <<" has maximum of "<< count <<" divisors.\n";
}
max_counter = prev;
max_divisor = divisor;
repeat++;
}
return count;
}
change
int Find_Max_Divisors (*array);
to
int value = Find_Max_Divisors(arr);
You can get rid of the array variable altogether.
It's quite possible you'll find you need to put your function before main, too.
Firstly, you declare an array that has 30 elements
int arr[30];
But here you make the pointer point to the out of arr.
int* array = &arr[30];
I guess you want to make pointer point to arr, if i am not wrong, you can do as:
int *array = &arr[0]; // or int * array = arr;
Then when you call the Find_Max_Divisors function, you should change to:
int return_value = Find_Max_Divisors(array);
One more thing, int this function:
for (int i=2; i<=30; i++)
When i=30, p[i] go to out of bount again. It should be:
for (int i=2; i< 30; i++)
you don't need pointers to do that this simple code can fix your problem just change the size of your array as you want i am testing with array of size 4 here
#include <iostream>
using namespace std;
int Find_Max_Divisors(int p[])
{
int count = 0, max = 0;
for (int i = 0; i < 4; i++) {
for (int j = 1; j < p[i] / 2; j++) {
if (p[i] % j == 0) {
count++;
}
}
if (count > max)
max = p[i];
}
return max;
}
int main()
{
int arr[30];
// int* array = &arr[30];
cout << "Please enter values of the array" << endl;
for (int i = 0; i < 4; i++) {
cin >> arr[i];
}
int value = Find_Max_Divisors(arr);
cout << "Number with most divisors in array is " << value << endl;
}
There are several mistakes in your code:
First, if your main function should know the funtions it calls, you should declare them previously. Just add a line Find_Max_Divisors (int p[]); Before the main function.
An array in C or C++ is a pointer, when you only call it by it's name. So call Find_Max_Divisors (arr) and get rid of that awful pointer-assignment.
In the last line just try to call the function, but never put it to stdout, you should change it to this:
cout << "Number with most divisors in array is " << Find_Max_Divisors(arr) << endl;
What you actually did with int Find_Max_Divisors (*array); was declaring a new variable and not calling a function.
This is the task that I have performed.
Write a C++ function which accepts an array of integers and the size of the array and finds :
a. Sum of the elements in the array
b. Average of the array elements
c. Minimum and maximum values in the array
In the main program, declare an array of 10 integers using dynamic memory allocation and call
the aforementioned function. Display the output of the function within the main. (Use call by
reference for output values).
//USER DEFINED FUNCTION " func "
void func(int arr[], int size, int *sum, int *avg, int *min, int *max)
{
*sum = 0;
*min = arr[0];
*max = arr[0];
*avg = 0;
//calculations for sum
for (int i = 0; i < size; i++)
{
*sum = *sum + arr[i];
}
//calculations for avg
*avg = *sum / size;
//calculations for minimum
for (int i = 0; i < size; i++)
{
if (*min > arr[i])
*min = arr[i];
}
//calculations for maximum
for (int i = 0; i < size; i++)
{
if (*max < arr[i])
{
*max = arr[i];
}
}
}
void main()
{
int *arr;
int size;
cout << "enter size of array " << endl;
cin >> size;
arr = (int*) calloc(size, sizeof(int));
for (int i = 0; i < size; i++)
{
cout << "enter element : " << endl;
cin >> arr[i];
}
int sum, avg, min, max;
func(arr, size, &sum, &avg, &min, &max);
cout << "sum is : " << sum << "\n avg is : " << avg << endl;
cout << "minimum is : " << min << endl;
cout << "the maximum is : " << max << endl;
getch();
}
Thats my code, its working fine and giving me desired results but is their any alternate for this as well because in the " func " body i am using *min,*max ,*avg because i have passed a value by pointer though i can simply pass value by reference and use " min " instead of " *min " . I want a suggestion on how to pass a value through pointer and yet dont use a dereference operator inside the body of user defined function like here its "func" .
You can use references to achieve what you need.
So your function declaration will change to
func(int arr[], int size, int &sum, int &avg, int &min, int &max)
And inside you can use the variables directly as min, max, avg etc.
In the main you will have to call as
func(arr, size, sum, avg, min, max);
Finally, I will suggest you to create local variables, do all the calculations in them and them finally assign the values to the references passed (This might be a bit optimized in most cases).
To reduce dereference-cluttering, use local variables for the computations and write to the parameters when you're done.
Example:
void sum(const std::vector<int>& numbers, int* result)
{
int total = 0;
for (auto i: numbers)
{
total += i;
}
*result = total;
}
This has a couple of other benefits in addition to readability:
It's faster, because there's no need to constantly read and write through an indirection. (References are just as bad as pointers in this regard.)
It leaves the out parameter unmodified if something throws an exception.
So the question is to Add selection sort function to grade program above. Program should display list of grades in sorted ascending order, we are giving the selection sort function and cant change it, my question is how would I call it from the main function
Here is my code`
#include <iostream>
using namespace std;
double average(double x[], int n);
double maximum(double x[], int n);
double minimum(double x[], int n);
int nAboveAvg(double x[], int n);
void sort(double x[], int npts);
int main()
{
double grades[50];
int ngrades;
cout<<"How many grades? (max = 50) ";
cin>>ngrades;
//create for loop to get grades from user
for(int i = 0; i<ngrades; i++)
{
cout<<"Enter grade ";
cin>> grades[i];
while(grades[i]< 0 || grades[i] > 100)
{
cout<<"Invalid grade- please enter again"<<endl;
cin>>grades[i];
}
}
//call the functions
double avg = average(grades, ngrades);
double max = maximum(grades, ngrades);
double min = minimum(grades, ngrades);
int nAbove = nAboveAvg(grades, ngrades);
//Calling the sort function
sor = sort(grades, ngrades);
//display results
cout << "Average = " << avg << endl;
cout << "# above average = " << nAbove << endl;
cout<<"Max value is = "<<max<<endl;
cout<<"Min value is = "<<min<<endl;
cout<<"Array sorted "<<sor<<endl;
}
void sort(double x[], int npts)
{
double min_value;
int min_index;
double temp;
for(int i= 0; i<npts - 1; i++)
{
for(int j = i + 1; j<npts; j++)
{
if(x[j] < min_value)
{
min_value = x[i];
min_index = j;
}
}
temp = x[min_index];
x[min_index] = x[i];
x[i] = temp;
}
return;
}
`
I think your problem is that you expect the "sort" function to return a value; it does not.
The "sort" function does not return a value, because it was defined with a "void" return value therefore trying to retrieve any data from the variable "sort" will not work (or should not, anyway).
Arrays are passed-in to functions by reference; This means that all of the changes done to the array within the sort function are are still there once the function returns; because of this, you should be outputting the "grades" array, not a non-existent return value.
EDIT: I believe that your problem is at the line:
cout<<"Array sorted "<<sor<<endl;
Trying something like this instead:
for (int i = 0; i < ngrades; ++i)
{
cout << grades[i] << " ";
}
cout << endl;
EDIT 2: Also, change the line:
sor = sort(grades, ngrades);
to just:
sort(grades, ngrades);
EDIT 3: It turns out that there are a few problems with the "sort" function. The first, and worst, problem is that the variable "min_value" is being used without being defined.
Once I changed this, the program would run, but the "sort" function did not work properly.
This brings me to the second problem: The variables "min_value" and "min_index" need to be reset for every iteration of "i".
The final problem is that, within the "j" loop, "min_value" is assigned to "x[i]", whereas it should be assigned to "x[j]":
min_value = x[i];
min_index = j;
should be:
min_value = x[j];
min_index = j;
I fixed the function and tested it to make sure that it works.
Here is the code.
void sort(double x[], int npts)
{
double min_value;
int min_index;
double temp;
for (int i = 0; i < npts - 1; i++)
{
min_value = x[i];
min_index = i;
for (int j = i + 1; j < npts; j++)
{
if (x[j] < min_value)
{
min_value = x[j];
min_index = j;
}
}
temp = x[min_index];
x[min_index] = x[i];
x[i] = temp;
}
return;
}
Dear StackOverflow community,
I am trying to write code that accepts a "primefactorized" array, each element originally describing their final multiplicational product.
The code I'm trying to write then reads this array and turns it to the exponentiation of prime numbers, each index of the array corresponding to the next prime number, and each element on the index the power to which it must be raised. I believe I have done so, but I cannot for some reason get my IO working. For some reason when I switched the inner for-loops last incrementation part to an "i++" instead of the correct "j++", it would display the loop.
Relevant snippet
// Next stage: Take the array and turn in into the form described earlier
for(unsigned int i = 0; i < sizeof(result); i++)
{
temppower = result[i];
tempcounter = 1; // counter to control the loop.
for(unsigned int j = 0; i < sizeof(result)-1; j++)
{
if(result[j]+1 == temppower)
{
tempcounter++;
result[j+1] = 0;
}
}
result[i] = tempcounter;
}
for(unsigned int i = 0; i < sizeof(result); i++)
{
cout << result[i] << " ";
}
cout << endl;
Full code
#include <iostream>
#include <cmath>
#include <climits>
using namespace std;
#include "fact.h"
/** eartosthenes constructs an up-to-n primes array of length len .
* #param n call-by-value, top value for construction of primes.
* #param &len call-by-reference, the finished size of the array of primes.
* #return int* pointer to the first element of the array of primes.
* Description:
* The eartosthenes method of calculating primes are efficient for relative low primes (up to 10 million or so).
* You can read about the method at http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
* You can use wolfram-alpha https://www.wolframalpha.com/ and run Prime(start)...Prime(end) to get the primes
* between start and end, e.g. Prime(1)...Prime(10) yield {2,3,5,7,11,13,17,19,23,29}.
*/
int * eratosthenes(int n, int & len){
// computes all prime numbers up to n
// returns the prime numbers as an array
// the len parameter will be set to the length of the array
bool *isPrime=new bool [n+1]; // construct [n+1] booleans
len=0;
// initialize every value from 1..n to true.
for(int i=2; i<=n; i++){
isPrime[i]=true;
}
// now we'll start at 2, and for every number of multiplicity 2.
// e.g. 2*{1,2,3,4...n} is then set to false, as they are dividable by 2.
// then we increment to 3, during the same.
for(int i=2; i<=n; i++){
if(isPrime[i]){
len++; // for each such iteration, we increase our desired length.
for(int j=2*i; j<=n; j+=i){
isPrime[j]=false; // set every(n) multiplicity of 2 to false.
}
}
}
// having used erathosthenes formula, we now construct our array.
int *result=new int[len];
// now we need to return the primes-filled array.
for(int i=0, j=2; i<len; i++){
// if it's not a prime, then we spin the value up.
while(!isPrime[j]) j++;
// when the while-loop no longer hold, we'll have the iterations desired prime
// we then set it, and the for-loop will continue to the next.
result[i]=j++;
}
delete [] isPrime; // always delete what you have allocated with new.
// we say these allocation are on the heap or free store (c-syntax)
return result;
}
#include "fact.h"
factrep new_factrep()
{
factrep result;
result = new int[len];
return result;
}
factrep primfact(int n)
{
factrep result;
result = new int[len];
int m; // still to factorize number
int f; // current factor
int index = 0; // index of factrep array
int temppower = 0; // index for the power
int tempcounter = 0; // counter to help the power determine its size
m=n;
f=2;
// 0-initialize the result array
for(unsigned int i = 0; i < sizeof(result); i++)
{
result[i] = 0;
}
// continue until nothing to factorize
while(m != 1){
// while the factor divides m, go on
while(m % f == 0){
if(m!=1)
{
m=m/f;
result[index] = f;
index++;
}
else
{
result[index] = f;
break;
}
}
// increment factor
f++;
}
// Next stage: Take the array and turn in into the form described within
// the exercise handout,
for(unsigned int i = 0; i < sizeof(result); i++)
{
temppower = result[i];
tempcounter = 1; // counter to control the loop.
for(unsigned int j = 0; i < sizeof(result)-1; j++)
{
if(result[j]+1 == temppower)
{
tempcounter++;
result[j+1] = 0;
}
}
result[i] = tempcounter;
}
for(unsigned int i = 0; i < sizeof(result); i++)
{
cout << result[i] << " ";
}
cout << endl;
return result;
}
factrep mult(factrep f1, factrep f2)
{
factrep result;
result = new int[len];
for(int i = 0; i < len; i++)
{
result[i] = f1[i]+f2[i];
}
return result;
}
int getint(factrep f)
{
int result = 0;
// int *temparray = new int[len];
for(int i = 0; i < len; i++)
{
result *= pow(primes[i],f[i]);
}
return result;
}
// these are our global variables
// so in our header we called extern
// which basically tells c++, that we'll define them in another file.
int *primes;
int len;
int main(){
// construct our primes array with maximum integer value
primes=eratosthenes(sqrt(INT_MAX),len);
// len now contains the length of the primes.
// TEST VALUES
// these are our test values.
int n=60;
int m=25;
int l=640;
// first check for non-negative content
if ( n < 0 || m < 0 || l < 0){
cout << "values must be positive (n > 0)" << endl;
return 1;
}
// construct 3 prime-factorized arrays by the values (60,25,640)
factrep fn=primfact(n);
factrep fm=primfact(m);
factrep fl=primfact(l);
// Verify that these are indeed constructed with those values
cout << getint(fn) << " " << getint(fm) << " " << getint(fl) << endl;
// multiply: fn = fn*fm, fm = fl*fl, fl = fn*fm
// 1500 = 60*25, 409600 = 640*640, 614400000 = 1500*409600
fn=mult(fn,fm);
fm=mult(fl,fl);
fl=mult(fn,fm);
// Verify that our functions work as expected by printing out their values now.
cout << getint(fn) << " " << getint(fm) << " " << getint(fl) << endl;
/* Expected output:
60 25 640
1500 409600 614400000
*/
// and again, if we construct something on the heap/free-store we better delete it again
// otherwise we might have a memory-leak on our hands.
delete [] primes;
delete [] fn;
delete [] fm;
delete [] fl;
return 0;
}
Update
The error was pointed out to me: I had put an i variable reference within the inner-most loop instead of the j variable I was using. (facepalm).
In the meantime this realization quickly helped me to solve my original problem which I will paste below in case anyone might run into a similar problem (primes[] is an array of primes, one per element, established outside of the factrep functions)
for(unsigned int i = 0; i < sizeof(result); i++)
{
temppower = primes[i];
tempcounter = 0; // counter to control the loop.
for(unsigned int j = 0; j < sizeof(result); j++)
{
if(result[j] == temppower)
{
tempcounter++;
}
}
result[i] = tempcounter;
}
Line 116 : A loop is endless.
for(unsigned int j = 0; i < sizeof(result)-1; j++)
i never changes in the inner loop where j is increasing, thus preventing your program from advancing further and printing anything.
I am learning pointers so I tried to implement this simple code of finding Max, min and Avg of student grades.
I only could found the avg BUT for the Max and the Min I got the first element of the *p.
here is my code If you please can tell me what is my mistake
#include <iostream>
using namespace std;
int main()
{
int *p;
int x;
cout << "Enter a number of student: ";
cin >> x;
p = new int[x];
for (int i = 0; i < x; i++)
{
cout << "Enter a grade: ";
cin >> *(p + i);
}
int sum = 0;
int max = 0;
int min = 0;
max = *p;
min = *p;
for (int i = 0; i < x; i++)
{
if (min > *p)
{
min = *p;
p++;
}
}
for (int i = 0; i < x; i++)
{
if (max < *p)
{
max = *p;
p++;
}
}
for (int i = 0; i < x; i++)
{
sum += *p;
p++;
}
int avg = sum / x;
cout << "avg is : " << avg << endl;
cout << "Max num is : "<< max
<< "\n Min num is : " << min << endl;
}
Note the changes
for (int i = 0; i < x; i++)
{
if (min > *(p+i))
{
min = *(p+i);//changed
}
}
for (int i = 0; i < x; i++)
{
if (max < *(p+i))
{
max = *(p+i);//changed
}
}
for (int i = 0; i < x; i++)
{
sum += *(p+i);//changed
}
You only advance the pointer, if *p is greater than the current max or min. Either advance it on every iteration (and back up the original state) or use p[i] to get the element of the iteration.
Your code is wrong on a number of levels. First of all, have a look at how you initialize the pointer p, which is supposed to point to the beginning of your array containing int elements :
p = new int[x];
This is all good. However, if you now take a look at the first loop...
for (int i = 0; i < x; i++)
{
if (min > *p)
{
min = *p;
p++;
}
}
You will notice that you keep incrementing p, which was supposed to point to the beginning of the array. This way, you can't possibly visit every element of the array when you run the second loop, because p does not point at the start of your array anymore! Thus, you invoked what some people call undefined behaviour by accessing an array out of its bounds.
However, you were able to properly reference the array in the loop where you actually write the elements to it - with the line cin >> *(p + i);.
Also, you should always remember to delete everything you newed. However, if you lose the pointer to what new returned, you will never be able to successfully delete it.
Furthermore, if you're programming in C++, you really should avoid using raw pointers, and - if you really need to - wrap them inside an unique_ptr (if you're using C++11). When it comes to "dynamic arrays", std::vector is most often the better way.
That's because you're doing p++, thus "losing the pointer".
In each for loop except for the first one, change *p to p[i], and get rid of the p++.
Also, at the end of the function, call delete p.
You could inline the calculation of max, min, and sum:
int sum = 0;
int max = 0;
int min = 0;
for (int i = 0; i < x; i++)
{
int g=0;
cout << "Enter a grade: ";
cin >> g;
if (g > max)
max = g;
if (g < min)
min = g;
sum += g;
}
Then you wouldn't need p = new int[x]