I've put my code below. Basically, I find the lowest number of an element in the array, and I also want it to find the index of the lowest element. It finds the index with a fairly low amount of elements, but for some reason it sometimes just seems to return random numbers for the index, and I have no idea why.
You are increasing the variable index in each iteration of the for loop
index++;
And the variable min is redundant.
The for loop can look the following way
for (i = 1; i < size; i++)
{
if ( array[i] < array[index] )
{
index = i;
}
}
cout << "The smallest number is " << array[index] << " and is found at index " << index;
Pay attention to that there is standard algorithm std::min_element() that performs the same task.
For example
#include <iterator>
#include <algorithm>
//...
auto min = std::min_element( array, array + size );
std::cout << "The smallest number is " << *min << " and is found at index " << std::distance( array, min ) << '\n';
you need just add an index var on out of your loop and set it to zero . then evry time your max item has changed , your index changes too.
#include<iostream>
using namespace std;
int main()
{
int min;
int array[100];
int size;
int i;
int index = 0;
cin >> size;
for (i = 0; i < size; i++)
{
cin >> array[i];
}
min = array[0];
index =0
for (i = 0; i < size; i++)
{
if (min > array[i])
{
min = array[i];
index =i
}
i++;
}
cout << "The smallest number is " << min << " and is found at index " << index;
return 0;
}
Related
I am trying to make program which finds max and min element of vector, and and outputs elements in the interval min max, but skips those that were specified in the vector.
For example:
in: 2 6 7
min is 2, max is 7
out: 3 4 5
But I have error message: vector subscript out of range
The code:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int size;
cout << "Enter size:" << endl;
cin >> size;
vector <int> vect;
vect.resize(size);
for (int j = 0; j < vect.size(); j++)
{
cout << "Enter " << j << " element: ";
cin >> vect[j];
cout << endl;
}
cout << "Your first vector: " << endl;
for (int j = 0; j < vect.size(); j++)
{
cout << vect[j] << " ";
}
cout << endl;
int min = *min_element(vect.begin(), vect.end());
int max = *max_element(vect.begin(), vect.end());
for(int j = min; j<max;j++)
{
if (vect[j] != j)
{
cout << j;
}
}
system("pause");
return 0;
}
You can use the std::find along with the computed min and max:
for (int i = min + 1; i < max; ++i)
if (std::find(vect.begin(), vect.end(), i) == vect.end())
std::cout << i;
This is not the most efficient solution (e.g. If you sort the vector, then you don't need to repeatedly call find).
Also, be careful when dereferencing the result of max/min_element if vect is empty. If you do that, you invoke undefined behaviour.
Note that there is a minmax_element that will give you both iterators at the same time, which is much nicer.
min and max will return min and max values of the vector. Instead checking with min and max, Check in range[0,vect.size()]
for(int j = 0; j<vect.size();j++)
{
if (vect[j] !=min && vect[j]!= max)
{
cout << j;
}
}
I have following problem to solve: given an array, I need to find the arithmetic mean between elements with indexes of first minimal and last maximum element (index boundaries are not inclusive).
For example, given {1, 5, 1, 9, 2, 7, 1, 3}, first minimal and last maximum elements are 1 and 9 respectively, their indexes are 0 and 3, so the answer would be an arithmetic mean of elements with indexes 1..2, i.e. arithmetic mean of 5 and 1, which is 3.
I know how to find the mean of the whole array but how to find the mean between the first min and last max element of the array?
#include <iostream>
using namespace std;
int main(){
setlocale(LC_ALL,"RUS");
cout << "Enter the array: ";
int k;
double Sum = 0;
double min = 0;
double max = 0;
const int n = 7;
double mass[8] = {0, 0, 0, 0, 0, 0, 0, 0};
for(k = 0; k <= n; k++){
cin >> mass[k];
}
for(int i = 0; i <= 7; i++){
if(mass[i] > max){
max = mass[i];
}
else if (mass[i] < min){
min = mass[i];
}
}
int i;
for(i = 0; i <= n; i++){
Sum = Sum + mass[i];
}
cout << Sum / 8;
return 0;
}
The answer should be 3.
I am assuming that you want a C++ program using C++ features. You current program is a C program that uses C++ I/O. Let me know if you want a C program that uses C features.
A C++ program means you should use std::vector but in case the assignment requires a C style array here is a version:
#include <iostream>
#include <algorithm>
#include <iterator>
#include <numeric>
int main() {
int size, *array;
std::cout << "How many elements? ";
std::cin >> size;
// create the array
array = new int[size];
if (array) {
// fill the array from the keyboard (could also use std::generate_n)
std::for_each(array, array+size, [index = 0](int& value) mutable {
std::cout << "Element " << ++index << "? ";
std::cin >> value;
});
// calculate the index of the max and min
auto minmax = std::minmax_element(array, array+size);
std::cout << "\nThe min " << *minmax.first << " is located at index " << std::distance(array, minmax.first);
std::cout << "\nThe max " << *minmax.second << " is located at index " << std::distance(array, minmax.second);
// calculate the average between the indexes
double average = std::accumulate(++minmax.first, minmax.second, 0.0, [count = 0](double average, int value) mutable {
std::cout << "\nAdding " << value << " to average";
return average + (value - average)/++count;
});
// print the result
std::cout << "\nAverage is " << average;
// delete the array
delete[] array;
}
}
And in case I am wrong and you are allowed to use std::vector here is a version:
#include <iostream>
#include <algorithm>
#include <iterator>
#include <numeric>
#include <vector>
int main() {
int size;
std::vector<int> array;
std::cout << "How many elements? ";
std::cin >> size;
// fill the array from the keyboard
std::generate_n(std::back_inserter(array), size, [index = 0, value = 0]() mutable {
std::cout << "Element " << ++index << "? ";
std::cin >> value;
return value;
});
// calculate the index of the max and min
auto minmax = std::minmax_element(array.begin(), array.end());
std::cout << "\nThe min " << *minmax.first << " is located at index " << std::distance(array.begin(), minmax.first);
std::cout << "\nThe max " << *minmax.second << " is located at index " << std::distance(array.begin(), minmax.second);
// calculate the average between the indexes
double average = std::accumulate(++minmax.first, minmax.second, 0.0, [count = 0](double average, int value) mutable {
std::cout << "\nAdding " << value << " to average";
return average + (value - average)/++count;
});
// print the result
std::cout << "\nAverage is " << average;
}
You need to think in terms of iterators, not values. Instead of recording the first minimal value, create an iterator that points the element one past it. Instead of recording the last maximal value, create an iterator that points to that value. You can then pass the range defined by these to iterators to std::accumulate to do the summation and then divide this by the std::distance of the same range to find the mean. But be aware that the number of elements between the min and max might be 0.
First, you need to find indexes.
Then loop through the array from first minimal to index of last maximum.
You can use the code below
#include <iostream>
using namespace std;
int main()
{
int array[] = { 1, 5, 2, 10, 2, 7, 1, 10};
int min = array[0];
int max = array[0];
int indexOfMin = 0;
int indexOfMax = 0;
int sum = 0;
float dist = 0;
float mean = 0;
int arrSize = sizeof(array)/sizeof(array[0]);
for (int i = 0; i < arrSize; i++){
if(array[i] >= max ){
max = array[i];
indexOfMax = i;
}
}
cout << "Max is at index [" << indexOfMax << "] : " << max << endl;
for (int i = 0; i < arrSize; i++){
if(array[i] == min){
continue;
}
if(array[i] < min){
min = array[i];
indexOfMin = i;
}
}
cout << "Min is at index [" << indexOfMin << "] : " << min << endl;
if(indexOfMin > indexOfMax){
indexOfMax++;
indexOfMin--;
for(int i = indexOfMax; i <= indexOfMin; i++){
sum += array[i];
}
dist = indexOfMin - indexOfMax + 1;
}else if(indexOfMin < indexOfMax){
indexOfMax--;
indexOfMin++;
for(int i = indexOfMin; i <= indexOfMax; i++){
sum += array[i];
}
dist = indexOfMax - indexOfMin + 1;
}
mean = sum/dist;
cout << "Sum: " << sum << " && dist: " << dist << endl;
cout << "Mean: " << mean << endl;
return 0;
}
Output:
Max is at index [7] : 10
Min is at index [0] : 1
Sum: 27 && dist: 6
Mean: 4.5
Output for int array[] = {1, 5, 1, 9, 2, 7, 1, 3} :
Max is at index [3] : 9
Min is at index [0] : 1
Sum: 6 && dist: 2
Mean: 3
Working on an assignment that requires me to put in some functions (finding max/min value, sum and average value of random numbers in an array), I've managed to complete all of them but for min value I'm getting a value of -2145379808. I'm not sure where I've messed up and I would appreciate the help.
Code so far:
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char** argv) {
{
cout << "Enter array size " << endl;
}
float avg;
float sum;
int size;
cin >> size;
int array[size];
int max = array [0];
int min = array [0];
srand((unsigned)time(NULL));
for (int i = 1; i < size + 1; i++)
{
array[i] = 1+rand()%100 ;
sum += array[i];
cout << "number " << i << " = "<< array[i] << endl;
}
for (int x = 1; x < size; x++){
if (array[x] > max){
max = array[x];
}
if (array[x] < min){
min = array[x];
}
}
cout << "\nmax = " << max << endl;
cout << "\nmin = " << min << endl;
cout << "\nsum = "<< sum << endl;
cout << "\navg = " << sum / size << endl;
return 0;
}
Setting max and min to the uninitialised element of array is never going to end well. On this note, you also need to initialise sum. You may as well remove avg since you don't use it.
You need to set max and min to the first element of array once you know what it is. Crudely, you could set max to std::numeric_limits<int>::min() and min to std::numeric_limits<int>::max().
Note also that the bounds of array are array[0] to array[size - 1]. Therefore you need to revisit the indexing in your loops.
Then once you have it working, bin it, and use std::vector<int>, and things like minmax_element: http://en.cppreference.com/w/cpp/algorithm/minmax_element
The problem is in following lines:
float avg;
float sum;
...
int max = array [0];
int min = array [0];
Because at this point the value at array [0] are garbage value.
To correct your code change this line as following (also include climits header file). Also, change loops index accordingly:
float avg = 0;
float sum = 0;
...
int max = INT_MIN;
int min = INT_MAX;
Following is corrected code(some changes made for optimization). See it working here:
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <climits>
using namespace std;
int main(int argc, char** argv) {
{
cout << "Enter array size " << endl;
}
float sum = 0;
int size;
cin >> size;
int array[size];
int max = INT_MIN;
int min = INT_MAX;
srand((unsigned)time(NULL));
for (int i = 0; i < size; i++)
{
array[i] = 1+rand()%100 ;
sum += array[i];
cout << "number " << i << " = "<< array[i] << endl;
if (array[i] > max){
max = array[i];
}
if (array[i] < min){
min = array[i];
}
}
cout << "\nmax = " << max << endl;
cout << "\nmin = " << min << endl;
cout << "\nsum = "<< sum << endl;
cout << "\navg = " << sum / size << endl;
return 0;
}
To insure your max and min are initialized correctly, C++ provides std::numeric_limits for all types. They each have max() and min() member functions to return the max and min value for the type. In any code you want to find a maximum and minimum, you want to first initialize your maximum to the minimum of the type and vice versa. That way any value will be larger than your min and smaller than your max.
You do that with std::numeric_limits similar to:
int min = std::numeric_limits<int>::max()
int max = std::numeric_limits<int>::min()
Let me know if you have more questions.
I am running the binary search algorithm in C++ but it gives me spurious results. For example, searching for the value 21 gives me a
"Value is Found"
message but my array consists only of numbers from 0 to 20.
Any help is greatly appreciated.
#include <iostream>
#include <iomanip>
using namespace std;
int binarySearch(const int [], int, int, int, int ); // function prototype
int main()
{
const int arraySize = 10;
int arr[ arraySize ];
int key;
for( int i = 0; i <= arraySize; i++) // generate data for array
arr[i] = 2*i;
cout << "The array being searched is: " << endl;
for (int j = 0; j<=arraySize; j++) // print subscript index of the array
{
cout << setw(5) << j << " ";
}
cout << endl;
for (int z = 0; z<=arraySize; z++) // print elements of the array below index
{
cout << setw(5) << arr[z] << " ";
}
cout << "\n" <<"Enter value you want to search in array " << endl;
cin >> key;
int result = binarySearch(arr, key, 0, arraySize, arraySize); // function call
if (result == 1) // print result of search
cout << "Key is found " << endl;
else
cout << "Key not found " << endl;
return 0;
} // end main function
int binarySearch(const int a[], int searchKey, int low, int high, int length)
{
int middle;
while (low <= high){
middle = (low + high) / 2;
if (searchKey == a[middle]) // search value found in the array, we have a match
{
return 1;
break;
}
else
{
if( searchKey < a[middle] ) // if search value less than middle element
high = middle - 1; // set a new high element
else
low = middle + 1; // otherwise search high end of the array
}
}
return -1;
}
You are invoking undefined behavior because your for loop conditions are <=arraySize. Change it to <arraySize. On making this change, the code works perfectly for sample inputs.
By writing int arr[ arraySize ]; you are creating an array of 10 elements (i.e., from 0 to 9), while in the for loops, you start from 0 and move until 10.
Live Demo
This is a console application on CodeBlocks 13.12.
I am getting a variety of errors when I run this Insertion Sort.
Sometimes it prints outrageously large values that weren't in the original array. Or sometimes it runs and sorts the array perfectly fine.
Can anybody please point out what could possibly be wrong? Sorry I'm a noob.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void insertionSort(int arr[], int size);
int main()
{
int size;
srand(time(NULL));
cout << "Specify the size of your array: ";
cin >> size;
int theArray[size]; // creates an array of a size the user chooses
cout << endl << "Your current array: {";
for (int i = 0; i < size; i++) //prints out the original array
{
theArray[i] = rand() % 10000;
cout << theArray[i];
if (i != size - 1) // to beautify output
{
cout << ", ";
}
if (i % 10 == 0 && i != 0)
{
cout << endl;
}
}
cout << "}" << endl << endl;
insertionSort(theArray, size);
}
void insertionSort(int arr[], int size)
{
int begin = clock(); // are for timing the sort
for (int i = 0; i < size; i++) //does the sorting
{
int j = i + 1;
int temp = arr[j];
while (arr[i] > arr[j])
{
arr[j] = arr[i];
arr[i] = temp;
j--;
i--;
}
}
int end = clock(); // are for timing the sort
cout << endl << "Your sorted array is: {";
for (int i = 0; i < size; i++) // prints out sorted array
{
cout << arr[i];
if (i != size - 1)
{
cout << ", ";
}
if (i % 10 == 0 && i != 0)
{
cout << endl;
}
}
cout << "}" << endl << endl << "Your sort took: " << end - begin << " milliseconds" << endl << endl;
}
Additionally to #marom's answer, in your while loop, you don't put limitations neither on i or j, hence you try to access arr[-1], arr[-2] and so on. Also, you go back to the beginning of the sorted array, since you decrement i. Have a look at this code, compiled with g++ 4.8.1 gives no errors. Also, try to use std::swap defined in header <utility> since c++11 or in header <algorithm> until c++11.
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <utility>
using namespace std;
void insertionSort(int arr[], int size);
int main()
{
int size;
srand(time(NULL));
cout << "Specify the size of your array: ";
cin >> size;
int theArray[size]; // creates an array of a size the user chooses
cout << endl << "Your current array: {";
for (int i = 0; i < size; i++) //prints out the original array
{
theArray[i] = rand() % 10000;
cout << theArray[i];
if (i != size - 1) // to beautify output
{
cout << ", ";
}
if (i % 10 == 0 && i != 0)
{
cout << endl;
}
}
cout << "}" << endl << endl;
insertionSort(theArray, size);
}
void insertionSort(int arr[], int size)
{
int begin = clock(); // are for timing the sort
for (int i = 0; i < size - 1; i++) //does the sorting
{
int j = i + 1;
int temp = arr[j];
while (j > 0 && arr[j] < arr[j - 1])
{
// ^^ this ensures that we don't try to access arr[-1]
swap(arr[j], arr[j-1]); //prefer std functions if they do the job you want
j--;//we don't go back
}
}
int end = clock(); // are for timing the sort
cout << endl << "Your sorted array is: {";
for (int i = 0; i < size; i++) // prints out sorted array
{
cout << arr[i];
if (i != size - 1)
{
cout << ", ";
}
if (i % 10 == 0 && i != 0)
{
cout << endl;
}
}
cout << "}" << endl << endl << "Your sort took: " << end - begin << " milliseconds" << endl << endl;
}
At least this is wrong:
void insertionSort(int arr[], int size)
{
int begin = clock(); // are for timing the sort
for (int i = 0; i < size; i++) //does the sorting
{
int j = i + 1;
When i is size-1 then j equals size and you get over the bounds of the array (valid values are from 0 to size-1 included). You need to limit your for loop to i < size-1
First advice : don't do all your printing or clock measure in your sort function. Keep that for your main program. Your sort function must remain clear and concise with no side effect.
Now, i find it better to split the code into 2 simple functions :
First, if arr is assumed already sorted up the index n-1
you want to insert the adequate element of the table at pos offset so that
arr will be sorted up to index n:
void insert(int arr[], int n){
int i=n, temp=arr[n];
while ( (arr[i-1]>temp) && (i>0) )
{
arr[i]=arr[i-1];
i--;
}
arr[i]=temp;
}
Now we just have to call our insertion for all offsets in arr except first one:
void insertionSort(int arr[], int size)
{
for(int n=1; n<size; n++) insert(arr,n);
}
As already mentioned by marom in his answer, when i = size - 1 you set j = size and access memory out of bounds, similarly, consider the case where j is set to the smallest element in the array, in that case you reach the left most position of the array by swapping the elements and decrementing, and eventually, i will become negative (since you do not put a bound to check if i becomes less than 0) and so will j and you will be accessing memory out of your bounds again.
Moreover, you are decrementing the value of i as well, which does not make sense, since by decrementing the value of i you are making extra runs for the external for loop.
So, your function shall look something like this ::
for (int i = 0; i < size - 1; i++) //changed the limit of for loop
{
int j = i + 1;
int temp = arr[j];
while ((j > 0) && (arr[j - 1] > arr[j])) //instead of working with the values of i, now we are doing everything with j
{
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}
}
Hope this helps!