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.
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 findMax function returns max value from the array only if it is located at some index other than first index. I don't understand why because my findMin function that has almost the same code works perfectly fine.
void findMax(int array[5])
{
maximum = array;
for (i = 0; i < 5; i++)
{
if (*(array+i) > *maximum)
*maximum = *(array+i);
}
cout<<"Maximum element in the array is "<< *maximum << "\n" ;
}
This is my findMin fun that is working fine.
void findMin(int array[5])
{
minimum = array;
for (i = 0; i < 5; i++)
{
if (*(array+i) < *minimum)
*minimum = *(array+i);
}
cout<<"Minimum element in the array is "<< *minimum <<"\n";
}
The other answers have described how to do this more cleanly in C++. But to point out the actual bug: it's in this line.
*maximum = *(array+i);
You're not reassigning the maximum pointer to point to the maximum element, but rather you're never changing the pointer, but changing the value inside the array where maximum points to (i.e. array[0]). You meant this instead:
maximum = array + i;
The same issue is present in your findMin function as well.
First of all, as one of the comments on your question said this is mostly C way of doing things. In C++ you should use std::vector, std::min_element and std::max_element. It's easier and safer to use them instead of doing everything manually by yourself.
But, if you really want to do it yourself, try this code out, it should work:
void findMax(int array[])
{
maximum = array;
for (int i = 1; i < 5; i++)
{
if (*(array + i) > *maximum)
maximum = (array + i);
}
cout << "Maximum element in the array is " << *maximum << "\n";
}
void findMin(int array[])
{
minimum = array;
for (int i = 1; i < 5; i++)
{
if (*(array + i) < *minimum)
minimum = (array + i);
}
cout << "Minimum element in the array is " << *minimum << "\n";
}
This should work assuming that minimum and maximum are globally declared like this:
int * maximum;
int * minimum;
There are minmax_element tools for finding maximum and minimum, this is the most optimal variant of solving your problem - see the definition of the StdMinMax function.
But if you want to implement the logic yourself, I gave an example of a function, see the definition of the MinMax function
#include <iostream>
#include <algorithm>
void StdMinMax(int* arr, const unsigned int size)
{
std::pair<int*, int*> bounds = std::minmax_element(arr, arr + size); // or use auto bounds = ... ore auto [max, min] = ...
std::cout << "min : " << *bounds.first << " max : " << *bounds.second << std::endl;
}
void MinMax(int* arr, const unsigned int size)
{
std::cout << "Find max : " << std::endl;
auto currentMax = *arr;
for (int i = 1 ; i < size; ++i)
{
if (arr[i] > currentMax)
{
currentMax = arr[i];
}
}
std::cout << "Max : " << currentMax << std::endl;
std::cout << "Find min : " << std::endl;
auto currentMin = *arr;
for (int i = 1 ; i < size; ++i)
{
if (arr[i] < currentMax)
{
currentMin = arr[i];
}
}
std::cout << "Min : " << currentMin << std::endl;
}
int main()
{
const unsigned int size{5};
int array[size]{1, 3, 4, -11, 77};
StdMinMax(array, size);
MinMax(array, size);
return 0;
}
I need some help with a simple program. And no - its not my homework (I am learning Cpp for myself and maybe use it in future)
So yeah. I have a program, that reads arrays size 10, and then put numbers in it {2.56, 1.598, 0, 5.15, 0, 3.012, 10, 4.789, 2.569, 0}
The program should ignore the 0, and it does, but the problem is.. I need to get the number of the where the number is placed in array
(Smallest number is 1.598 and its 2 in the array)
Meanwhile I get number 8 on the biggest (should be 5 if zeros would be ignored)
and 1 on the smallest. How can I fix that ?
Heres the void of the biggest number :
void Biggest(float array[], int n, float &max, int &maxNr)
{
max = array[0]
for (int i = 1; i < n; i++){
if (array[i] == 0)
continue;
if (array[i] > max){
max = array[i];
maxNr = i;
}
}
}
Printing void :
void Print(float min, float max, double avg, int maxNr, int minNr)
{
ofstream info;
info.open("result1.txt");
info << "Biggest: " << max << " Number : " << maxNr << endl;
info << "Smallest: " << min << " Number : " << minNr << endl;
info << "Average: " << avg << endl;
info.close();
}
And all main.
int main(){
float array[100];
int n;
float max;
float min;
double avg;
int maxNr, minNr;
Reading(array, n);
Biggest(array, n, max, maxNr);
Smallest(array, n, min, minNr);
Average(array, n, avg);
Printing(min, max, avg, maxNr, minNr);
return 0;
}
First of all, array indexes start at 0, not 1.
If you want to get the position ignoreing zeros, you need to use a separate counter variable from the one used to index the array, so that you don't increment it when you skip over 0.
void Biggest(float array[], int n, float &max, int &maxNr)
{
max = array[0];
int position = 0;
for (int i = 0; i < n; i++){
if (array[i] == 0) {
continue;
}
if (array[i] > max){
max = array[i];
}
position++;
}
maxNr = position;
}
Arrays in most (all that I can think of) programming languages start at index zero. So simply change your for loop condition to be:
for (int i = 0; i < n; i++)
Because you want the loop to start at the first element in the array, i must be initialized to 0. That should fix the problem you are having with the array.
I am having some issues with an array expansion project and am trying to find where the issue is with getting my array to expand with all zeroes. Here are the requirements:
Array Expander. The program should have an array of integers. It will have a function that has two parameters, the integer array and the array’s size. This function will create a new array that is twice the size of the arguments array. The function should copy the contents of the argument array to the new array, and initialize the unused elements of the second array with 0. The function must return a pointer to the new array. The program will then display the contents of the new array.
Program must have the following functions
• int* expandArray(int[ ], int)
• void showArray(int [ ], int)
I am getting the program to build the first array without issues, however, the second array, while it displays the first array of numbers fine, displays the second array with an assortment of digits. I have been looking at this for hours and am at a loss with how to correct this to work correctly. Here is my code that I have so far:
//Include section
#include <iostream>
#include <cstring>
//Namespace Section
using namespace std;
//Function Prototype Section
int *expandArray(int[], int&);
void showArray(const int[], int);
//Main section: this is the entry point of the program, which controls the flow of execution
int main()
{
int arraySize = 7; //sets the size of the array at 7
int *array = new int[arraySize];
for (int c = 0; c < arraySize; ++c)
array[c] = c + 1;
//the following outputs the initial array of 7 to the user's screen; beginning at 1 and incrementing to 7
cout << "*********************************************************************" << endl;
cout << " The following is the initial array " << endl;
cout << "*********************************************************************" << endl;
cout << endl;
showArray(array, arraySize);
cout << endl;
cout << endl;
//the following outputs the initial array, plus expands the array by double, initializing the unused elements with zero
cout << "*********************************************************************" << endl;
cout << " The following is the expanded array " << endl;
cout << "*********************************************************************" << endl;
cout << endl;
showArray(array, arraySize * 2);
cout << endl;
cout << endl;
delete[] array;
system("PAUSE");
return 0;
}
int *expandArray(int array[], int &arraySize)
{
int *expandedArray;
expandedArray = new int[arraySize * 2];
for (int index = arraySize; index < (arraySize * 2); index++)
expandedArray[index] = 0;
arraySize *= 2;
delete[] array;
return expandedArray;
}
void showArray(const int arr[], int arraySize)
{
for (int index = 0; index < arraySize; index++)
cout << arr[index] << " " << endl;
}
I believe my issue is in the following section of the code, but unsure as to how to fix it:
int *expandArray(int array[], int &arraySize)
{
int *expandedArray;
expandedArray = new int[arraySize * 2];
for (int index = arraySize; index < (arraySize * 2); index++)
expandedArray[index] = 0;
arraySize *= 2;
delete[] array;
return expandedArray;
Any assistance would be greatly appreciated!
As I see it you forgot to to copy the contents of your initial array into expandedArray in the declaration of your function. You only set all elements with index in between arraySize and arraySize*2 to 0 but never actually copied the values of your argument.
I would include the following:
for(int i=0; i<arraySize; i++) expandedArray[i] = array[i];
right after having declared expandedArray dynamically. Note it is important that you include this piece of code before modifying arraySize as you would get out-of-bounds issues when accessing array[i].
The issue is that you're not copying the original array's contents into the new allocated array space.
A simple solution is to use new[] with brace initialization of 0, and then copy the original contents into the new array. The brace initialization will initialize all the space to 0, so you don't need to write two loop to set the newly allocated space to 0.
int *expandArray(int array[], int &arraySize)
{
int *expandedArray;
// allocate and initialize all entries to 0
expandedArray = new int[arraySize * 2]{0};
// copy old elements to new space
for (int index = 0; index < arraySize; index++)
expandedArray[index] = array[index];
// delete old space
delete [] array;
// double array size
arraySize *= 2;
return expandedArray;
}
int *arrayExpander(int arr[], int size)
{
int *expendedArray = new int[size * 2];
// move elements forom original array into the expandedArray
// initilize the rest of the elements to ZERO
for (int i = 0; i < size * 2; i++)
{
if (i < size)
{
// filling firt half
expendedArray[i] = arr[i];
}
else
{
// second half of the array
expendedArray[i] = 0;
}
}
return expendedArray;
}
int main()
{
int size = 5;
int arr[] = { 1,2,3,4,5 };
// Array pointer
int *arrPtr = arrayExpander(arr, size);
// Display
for (int i = 0; i < size * 2; i++)
{
cout << arrPtr[i] << " " << flush;
}
return 0;
}
Actually there are 2 errors in your code:
When you run your code it prints the first 7 elements of your array of type double correctly, but not the other 7. This is because they are not initialized, therefore they are returning garbage values.
Therefore in the function you have to initialize the other 7 elements to 0. The same goes for the first 7 elements and the first matrix.
I rectified the problem. Please have a good look at it:
//Include section
#include <iostream>
#include <cstring>
//Namespace Section
using namespace std;
//Function Prototype Section
int *expandArray(int[], int&);
void showArray(const int[], int);
int *expandedArray;
//Main section: this is the entry point of the program, which controls the flow of execution
int main()
{
int arraySize = 7; //sets the size of the array at 7
int *array = new int[arraySize];
for (int c = 0; c < arraySize; ++c)
array[c] = c + 1;
//the following outputs the initial array of 7 to the user's screen; beginning at 1 and incrementing to 7
cout << "*********************************************************************" << endl;
cout << " The following is the initial array " << endl;
cout << "*********************************************************************" << endl;
cout << endl;
showArray(array, arraySize);
cout << endl;
cout << endl;
//the following outputs the initial array, plus expands the array by double, initializing the unused elements with zero
cout << "*********************************************************************" << endl;
cout << " The following is the expanded array " << endl;
cout << "*********************************************************************" << endl;
cout << endl;
expandArray(array, arraySize);
showArray(expandedArray, arraySize);
cout << endl;
cout << endl;
delete[] array;
return 0;
}
int *expandArray(int array[], int &arraySize)
{
expandedArray = new int[arraySize * 2];
for (int c = 0; c < arraySize; ++c)
expandedArray[c] = c + 1;
for (int index = arraySize; index < (arraySize * 2); index++)
expandedArray[index] = 0;
arraySize *= 2;
delete[] array;
return expandedArray;
}
void showArray(const int arr[], int arraySize)
{
for (int index = 0; index < arraySize; index++)
cout << arr[index] << " " << endl;
}
//here is your solution bro..!!
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]