So we were given a project involving two arrays (one a string and the other including values), and I decided to use movies and years. One of the parameters of the project is to display the maximum and minimum values along with their string. Now, the max works fine, but when I try to run min, it says it isn't initialized. What am I doing wrong?
#include <iostream>
#include <string>
using namespace std;
int avgYear(int arr[], int size);
int indexMin(int arr[], int size);
int indexMax(int arr[], int size);
int main()
{
int total = 0;
string name[] = {"Toy Story", "A Bug's Life", "Toy Story 2", "Monster's Inc.", "Finding Nemo", "The Incredibles", "Cars", "Ratatouille", "WALL-E", "Up"};
int year[] = { 1995, 1998, 1999, 2001, 2003, 2004, 2006, 2007, 2008, 2009};
for (int x = 0; x < 10; x++)
cout << name[x] << " " << year[x] << endl;
cout << "The average year of release was " << avgYear(year, 10) << endl;
cout << "The First Year of Release was " << name[indexMin(year, 10)] << " in " << year[indexMin(year, 10)] << endl;
cout << "The Last Year of Release was "<< name[indexMax(year, 10)] << " in " << year[indexMax(year, 10)] << endl;
return 0;
}
int avgYear(int arr[], int size)
{
int avg;
int total=0;
for (int x = 0; x < size; x++)
total += arr[x];
avg = total / size;
return avg;
}
int indexMin(int arr[], int size)
{
int iMin;
int min = arr[0];
for (int x = 1; x < size; x++)
if (arr[x] < min)
{
min = arr[0];
iMin = x;
}
return iMin;
}
int indexMax(int arr[], int size)
{
int iMax;
int max = arr[0];
for (int x = 0; x < size; x++)
if (arr[x] > max)
{
max = arr[x];
iMax = x;
}
return iMax;
}
If minimum value is arr[0] then iMin won't ever be initialized because if (arr[x] < min) will never return true.
You max function also has the same problem but works because max element is not at index 0.
int iMin = 0;
Should fix your problem. Also it's a good idea to develop a habit to always initialize your variables and fields. Value stored in an uninitialized variable is indeterminate, reading from it is undefined behaviour.
if you initialize years like this:
int year[] = { 2009, 2008, 2007, 2006, 2004, 2003, 2001, 1999, 1998, 1995};
and then, the min work fine, and the max is error.^_^
you must initialize the iMin and iMax, and the initial number need to be the same with arr index, like this:
// min
int nStartIndex = 0;
int iMin = nStartIndex;
int min = arr[nStartIndex];
// max
int nStartIndex = 0;
int iMax = nStartIndex;
int max = arr[nStartIndex];
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;
}
#include <iostream>
using namespace std;
int main()
{
int max, n[]={50,30};
int arrayLength = sizeof(n)/sizeof(int);
cout << "Length is"<< arrayLength<<endl;
for(int x=0; x<arrayLength; x++)
{
if (n[x]>n[x+1])
max = n[x];
else
max = n[x+1];
}
cout << "Max is : " << max;
how to find max in array
You can use std::max_element:
max = *std::max_element(n, n+arrayLength);
You can code up brute-force
int array_max = -1; // Or some very negative number.
for (int i = 0; i < arrayLength; ++i)
{
if (n[i] > array_max)
{
array_max = n[i];
}
}
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.
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
I'm trying to compare the values in an array after passing it to a function and return the subscript of the element with the greatest value to represent a month of the year(ex: Jan = 1, Feb = 2, ect.). I've fiddled around with my algorithm but I just can't seem to get it to work. I (think) I know what I should do. Can someone explain this to me simply? (beginner in programming). Here is my code below:
#include <iostream>
using namespace std;
//this program determines the most wet and dry months
//in a year and calculates the annual rainfall and monthly average
//function declarations
double calculateTotal(double [], int);
double calculateAvg(double, int);
int determineWetMonth(double [], int);
int determineDryMonth(double [], int);
int main()
{
const int SIZE = 12;
double months[SIZE];//array stores rainfall each month
//initialize array
for(int count = 0; count < SIZE; count++)
{
months[count] = 0;
}
//populate array
for(int i = 0; i < SIZE; i++)
{
int rain = 0;
cout << "Enter the rainfall for month: " << i+1 << endl;
cin >> rain;
months[i] = rain;
}
//call total function
double total = 0.0;
total = calculateTotal(months, SIZE);
//call average function
double avg = 0.0;
avg = calculateAvg(total, SIZE);
//call wet function
int highest = 0;
highest = determineWetMonth(months, SIZE);
//call dry function
int lowest = 0;
lowest = determineDryMonth(months, SIZE);
//display results
cout << "The total annual rainfall is: " << total << endl;
cout << "The average monthly rainfall is: " << avg << endl;
cout << "The WETTEST month is: " << highest << endl;
cout << "The DRYEST month is: " << lowest;
cin.get();
cin.get();
}
double calculateTotal(double anArray[], int size)
{
double theTotal = 0.0;
for(int j = 0; j < size; j++)
{
theTotal = theTotal + anArray[j];
}
return theTotal;
}
double calculateAvg(double someTotal, int amount)
{
double theAvg = 0.0;
theAvg = someTotal / amount;
return theAvg;
}
int determineWetMonth(double theArray[], int num)
{
int most = 0;
for(int k = 0; k < num; k++)
{
if(theArray[k] > theArray[0])
{
most = k+1;
}
}
return most;
}
int determineDryMonth(double ourArray[], int dec)
{
int least = 0;
for(int m = 0; m < dec; m++)
{
if(ourArray[m+1] < ourArray[m])
{
least = m+1;
}
}
return least;
}
You need to use the value of the largest/smallest value
int determineWetMonth(double theArray[], int num)
{
int most = 1;
for(int k = 1; k < num; k++)
{
if(theArray[k] > theArray[most-1])
{
most = k+1;
}
}
return most;
}
int determineDryMonth(double ourArray[], int dec)
{
int least = 1;
for(int m = 1; m < dec; m++)
{
if(ourArray[m] < ourArray[least-1])
{
least = m+1;
}
}
return least;
}
A C++ solution using algorithms:
#include <algorithm>
//...
int determineDryMonth(double* ourArray, int siz)
{
return std::distance(ourArray, std::min_element(ourArray, ourArray + siz));
}
int determineWetMonth(double* theArray, int num)
{
return std::distance(theArray, std::max_element(theArray, theArray + num));
}
The min_element returns a pointer to the smallest item in the range, and the distance function tells you how far away the start is from the returned pointer. In essence, you get the position of the smallest value.
For the wettest month, the only change is that the function to get a pointer to the largest value is std::max_element.