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.
Related
The function FindSubArrayMinimum is suppose to return the index of the minimum value in an array between the values (left,right). Instead of returning 1 as it should, it returns 7.
Here is my code:
#include <iostream>
using namespace std;
class Minimum {
int *array;
int arrayLen;
public:
Minimum(int *array, int arrayLen) {
}
void swap(int &a, int &b) {
int x;
x = a;
a = b;
b = x;
}
int findMinimum(int a, int b) {
if(a < b){
return a;
}else{
return b;
}
}
int findArrayMinimum(int a[], int arraySize) {
int min=a[0];
for(int i=0;i<arraySize-1;i++){
if(a[i] < min){
min = i;
}
}
return min;
}
int findSubArrayMinimum(int a[], int arraySize, int left, int right) {
int min = a[left];
for(int i=left;i<right+1;i++){
if(a[i] < min){
cout << min << endl;
min = i;
}
}
return min;
}
int findSubArrayMinimumAndSwap(int left, int right, int swapIndex) {
}
};
int main() {
int A[5] = {47, 7, 21, -1, 11};
Minimum min(A, 5);
cout << "Minimum of 7 and 11 is " << min.findMinimum(7, 11) << endl;
int x = 5, y = 7;
min.swap(x, y);
cout << "x = " << x << ", y = " << y << endl;
cout << "Minimum value is at position " << min.findArrayMinimum(A,5) << endl;
cout << "Minimum value between [1,2] is at position " <<
min.findSubArrayMinimum(A,5,1,2)<< endl;
return 0;
}
I cannot for the life of me figure out why it won't return the minimum index. Logically speaking it should work unless I'm missing something?
all of my other functions as all the ones I have finished I have working.
It is not true. In findArrayMinimum the loop should be
for(int i=0;i<arraySize;i++)
Or
for(int i=0;i<=arraySize-1;i++)
The initial value an the condition in the loop are also wrong. Should be int min=0 and if(a[i] < a[min])
Instead of returning 1 as it should, it returns 7.
findSubArrayMinimum is nice, except initial minimum value int min = a[left], should be int min = left and the condition in the loop should be if(a[i] < a[min]).
arraySize is odd in findSubArrayMinimum, it is not used.
Your do not need the separate implementation for findSubArray. You can do return findSubArrayMinimum(a, 0, arraySize - 1) in findSubArray.
If you would implement the tests with arrays of 0, 1, many elements, with the left, right, middle subarrays, you would discover all bugs in your code.
C++ is all about not re-inventing wheels.
#include <algorithm>
size_t findArrayMinimum(int a[], size_t arraySize) {
// Returns index of minimum element
return std::min_element(a, a + arraySize) - a;
}
In your findSubArrayMinumum you need min = a[i]; and not min = i; i is a index and a[i] is value.
I suggested you:
int findSubArrayMinimum(int a[], int arraySize, int left, int right) {
int index = left;
int min = a[left];
for(int i=left;i<right+1;i++){
if(a[i] < min){
min = a[min];
index = i;
}
}
return index;
}
int index = min.findSubArrayMinimum(A,5,1,3);
cout << "Minimum value between [1,2] is at position " << index <<
". and value is: " << A[index] << endl;
int findSubArrayMinimum(int a[], int arraySize, int left, int right) {
//The min is the index of minimum value since you are returning the index only
int min = left;
for(int i=left;i<=right;i++){
//since we have min = indexOfMin, then we need to compare the values
if(a[i] <= a[min]){
min = i;
}
}
//remember! You are returning the index of the minmum value!
return min;
}
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.
I am being tasked with writing a function that takes as parameters an array of doubles, the size of the array, and then 3 pass-by-reference parameters called min, max, and avg. My function must: process the array data to find the minimum value (min), maximum value (max), and calculate the average (avg), each of which gets assigned to the corresponding reference parameter so that the calling function will be able to see those values. I am fairly new to coding and am very confused in what my error is the main function included below, any help would be greatly appreciated.
#include <iostream>
using namespace std;
void normalizeMinMaxAvg(double data[], int size,double& min, double&
max, double& avg)
{
max = 0;
min = 0;
//int amount = size;
int count = 0;
int sum = 0;
int i;
avg = 0;
for (i=0; i < size; i++)
{
count++;
sum += i;
if ( i > max)
{
i=max;
}
else if (i < min)
{
i=min;
}
}
avg = sum/count;
}
int main ()
{
double data[]={10.0,0.0,20.0,30.0};
cout << normalizeMinMaxAvg (data, 4, min, max, avg);
return 0;
}
Just provide variables that can be passed to that function, and output these like follows:
int main ()
{
double data[]={10.0,0.0,20.0,30.0};
double min, max, avg;
normalizeMinMaxAvg (data, 4, min, max, avg);
cout << "min = " << min << "\n";
cout << "max = " << max << "\n";
cout << "avg = " << avg << "\n";
return 0;
}
Also inside your function use the data from the array to calculate min and max:
if ( data[i] > max)
{
max = data[i];
}
else if (data[i] < min)
{
min = data[i];
}
Few problems:
deal with the empty data array case first.
set min and max to the first element of the array (not to zero). Think about what if the numbers are all negative. Will max contain the right answer?
You want to find the maximum and minimum elements so you have to use the data contained in data
if ( data[i] > max){
max=data[i];
}
Same goes for the min case.
normalizeMinMaxAvg does not return so you cannot use it in a cout expression. You can print the parameters directly.
Here is a working version of your code.
void normalizeMinMaxAvg(double data[], int size,double& min, double&
max, double& avg)
{
if(size<=0)
return;
min= max = data[0];
int count = 0;
double sum = 0;
int i;
avg = 0;
for (i=1; i < size; i++)
{
count++;
sum += data[i];
if ( data[i] > max)
{
max=data[i];
}
else if (data[i] < min)
{
min=data[i];
}
}
avg = sum/(double)count;
}
int main ()
{
double data[]={10.0,0.0,20.0,30.0};
double min,max,avg;
normalizeMinMaxAvg (data, 4, min, max, avg);
cout<<min<<" "<<max<<" "<<avg<<endl;
return 0;
}
Your problem is that you're not accessing your array's data. Instead you're using your iteration variable i. Basically, on your normalizeMinMaxAvg function, you should do this on your for loop:
for (i=0; i < size; i++){
//count++; - no need for it, you already have size!
sum += data[i];
if ( max > data[i]){
max = data[i];
}
if (min < data[i]){
min = data[i];
}
}
avg = sum/size;
Also you need to declare your variables min, max and avg on your main() function in order to use them when you call your normalizeMinMaxAvg function.
There are a couple of issues with your code. You need to understand how passing arguments by reference works in C++.
void normalizeMinMaxAvg(double data[], int size,double& min, double& max, double& avg)
normalizeMinMaxAvg doesn't return anything - note the void return type - it modifies 3 already existing double variables, so if you are going to call it form main you have to define those variables.
int main()
{
double data[]={10.0,0.0,20.0,30.0};
double min = 0, max = 0, avg = 0; //variables defined and initialized here
//Note the '= 0' on all variables, it's important else they'll have random values
normalizeMinMaxAvg(data, sizeof(data)/sizeof(data[0]), min, max, avg);
//Your function has modified min, max, and avg, so you use them here
std::cout << min << ", " << max << ", " << avg << std::endl;
return 0;
}
Your normalizeMinMaxAvg function also has problems:
void normalizeMinMaxAvg(double data[], int size,double& min, double& max, double& avg)
{
if (size <= 0) //Nothing to do. Might want to add a return error code
return;
//0 is not a sensible value for init, what if all your values are negative?
min = data[0];
max = data[0];
avg = 0;
int sum = 0;
for (i=0; i < size; i++)
{
sum += data[i];
if ( data[i] > max) { //have to access your data by data[i]
max=data[i]; //NOT i=max, you're assigning to max
}
if (data[i] < min) {
min=data[i];
}
}
avg = sum/size;
}
Couple things I noticed:
The values are stored in data[] so you must use data[i] in your loop to check for min, max, and to compute the average.
Also, you want to initialize min to the maximum double value so that it will be replaced by the actual minimum from the data.
You need to be referencing the items in the array. So it should not just simply be i, that is just a number. It should be data[i]. This will refer to the ith element of the array data.
Three things:
You have to define min, max, avg in your main() function before passing them on.
You can't cout << function() if it doesn't return anything.
In normalizeMinMaxAvg for loop, you access i (index) instead of data[i] (the data under index i in array data).
So I'm getting a segmentation fault error in the beginning of the code. I've tried running some tests at the different points and the error seems to be when i allocate memory for the array. Ive just started learning about heap and stack memory so I'm not really sure if I'm doing something wrong there. Any help would be appreciated.
#include <iostream>
using namespace std;
//Function Prototypes
void sort(int A[], int n);
int findMin(int A[], int n, int j);
int swap(int& a, int& b);
double median(int A[], int n);
void output1(int median);
void output2(double median);
int main()
{
int size;
int array[size]; //Segmentaion fault here
int i = 0;
cout << "Enter the size of the list (< 1 to quit): ";
cin >> size;
while(size >= 1)
{
double element;
cout << "Enter element " << i+1 << ": ";
cin >> element;
array[i] = element;
i++;
while(i < size)
{
cout << "Enter element " << i+1 << ": ";
cin >> element;
array[i] = element;
i++;
}
sort(array, size);
median(array, size);
cout << "Enter the size of the list (< 1 to quit): ";
cin >> size;
}
delete [] array;
return 0;
}
void sort(int A[], int n)
{
int min;
for(int i = 0; i < n; i++)
{
min = findMin(A,n,i);
//min = findMinIndex(p, size, i);
//if(min )
swap(A[i],A[min]);
//swap(p[i],p[min]);
}
}
int findMin(int A[], int n, int j)
{
int minIndex = j;
for(int i = j+1; i < n; i++)
if(A[i]<A[minIndex])
minIndex = i;
return minIndex;
}
int swap(int& a, int& b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void output1(int median)
{
cout << "The median is " << median << "." << endl;
}
void output2(double median)
{
cout << "The median is " << median << "." << endl;
}
double median(int A[], int n)
{
if(n % 2 == 0)
{
int div1 = n / 2;
int num1 = A[div1];
int num2 = A[div1 -1];
double median = (num1 + num2) / 2;
output2(median);
}
else
{
int div2 = n - 1;
int median = div2 / 2;
output1(median);
}
}
Because you are not initialising size, the value in that variable could literally be anything. If it happens to be excessively large, say 106,840,406, then you won't be able to get an int[] of that size.
So basically, initialise your size variable to something sensible.
Segmentation Fault 11 equals to say "Index out of range"...
Index
0, 1, 2, 3, 4 ,5
Value 5, 6 ,1 ,9 ,8 ,7
Array length is 6, but its last index is 5.. for example, if we control a for cycle with 6 then we got Segmentation Fault 11...
An array in c++ has to be initialized at the with a fixed size. In your case, size is not initialized to any fixed integer value, which is illegal in c++ and will cause the compiler to produce an error message.
If you try the following line just before you initialize the array of size size, you can tell what the size originally is:
cout << size << endl;
I compiled your code with this line and got this int size before the compiler failed:
1995231824 (This differs for every compiler and computer, but every number will be as big and useless as this one)
Trying to have such a big array will naturally lead to a segmentation fault. That's why you would have to initialize the variable size to a fixed number. This will eliminate the segmentation fault.
Beginner in C++ here and learning arrays. The program below is supposed to return the smallest and largest number in an array using two separate functions. One for the largest and one for the smallest number. However, it is returning 0 all the time for function lastLowestIndex and I am unsure what I may be doing wrong.
Could someone ever so kindly advice and show me what is incorrect in that function and what can be done to correct it so that it returns the correct value? I am obviously not seeing and/or understanding what is incorrect.
Thank you so very much for your help and time in advance!!!
#include <iostream>
#include <cstdlib>
int lastLargestIndex(int [], int);
int lastLowestIndex(int [], int );
using namespace std;
int main()
{
const int N = 15;
int arr[N] = {5,198,76,9,4,2,15,8,21,34,99,3,6,13,61};
int location;
//int location2;
location = lastLargestIndex( arr, N );
cout << "The last largest number is:" << location << endl;
location = lastLowestIndex(arr, N);
cout << "The last smallest number is:" << location << endl;
// std::system ("pause");
return 0;
}
int lastLargestIndex( int arr[], int size )
{
int highNum = 0;
for( int i = 0; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
int lastLowestIndex(int arr[], int size)
{
int smallest = 0;
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
//cout << smallest << '\n';
return smallest;
}
However, it is returning 0 all the time for function lastLowestIndex and I am unsure what I may be doing wrong.
You got a logic error when you initialised smallest to 0 in function lastLowestIndex() - that way if (arr[i] < smallest) condition is not evaluated to true if all input is positive. Instead, you should initialise it to the first member of array arr. The function should look like this:
int lastLowestIndex(int arr[], int size)
{
int smallest = arr[0];
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
return smallest;
}
lastLowestIndex() initialises smallest to be 0, and then compares all elements of the array (which are positive, in your example) with it. All positive values are greater than zero, so smallest will remain zero.
Note that your logic is also not general for finding the maximum. Consider what the code will do if all elements of the array are negative.
You would be better off adopting a logic that does not make any assumptions about the array, other than its size and that it contains integral values. For example;
int lastLargestIndex( int arr[], int size )
{
int highNum = arr[0];
for( int i = 1; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
This doesn't exhibit the problems yours does, since it initialises highNum with the first element of the array, and iterates over the rest (if any). This does assume size is positive.
Your functions are also named in a misleading manner, since they (attempt to) return the maximum (or minimum) value in the array, but their name suggests they will return the index of that value. I'll leave resolving that little issue as an exercise.
This is the correct working code!
#include <iostream>
#include <cstdlib>
int lastLargestIndex(int [], int);
int lastLowestIndex(int [], int );
using namespace std;
int main()
{
const int N = 15;
int arr[N] = {5,198,76,9,4,2,15,8,21,34,99,3,6,13,61};
int location;
location = lastLargestIndex( arr, N );
cout << "The last largest number is:" << location << endl;
location = lastLowestIndex(arr, N);
cout << "The last smallest number is:" << location << endl;
// std::system ("pause");
return 0;
}
int lastLargestIndex( int arr[], const int size )
{
int highNum = -100001;
for( int i = 0; i < size; i++ )
{
if ( arr[i] > highNum )
{
highNum = arr[i];
}
}
return highNum;
}
int lastLowestIndex(int arr[], const int size)
{
int smallest = 100001;
for (int i = 0; i < size; i++)
{
if (arr[i] < smallest)
{
smallest = arr[i];
}
}
//cout << smallest << '\n';
return smallest;
}
Modifications done:
Replaced argument in function from int size to const int size, since N is declared as const int in main function
Replaced highNum with -100001
Replaced smallest with 100001