C++ Program To Find Smallest and Largest Number In Array - c++

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

Related

C++ getSmallest program

I keep getting function definition is not allowed where the '{' is after int getSmallest(int numbers[],int SIZE);. I am having trouble figuring out how to fix it and getting this program to compile.. This is what I have as of right now:
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
// Function prototypes
int getSmallest(int numbers[], int SIZE);
int main()
{
int count = 0;
int numbers[SIZE];
string inFile;
cout << "Enter input file name:";
cin >> inFile;
ifstream file(inFile);
//Reading from file
for (count = 0; count < SIZE; count++) {
cout << SIZE << "numbers read from file." << endl;
cout << "The smallest value is: " << getSmallest(numbers, SIZE) << endl;
}
}
int getSmallest(int numbers[], int SIZE)
{
smallest = numbers[0];
for (count = 1; count < SIZE; count++) {
if (numbers[count] < smallest) {
smallest = numbers[count];
}
return smallest;
}
}
The problem is in your function. Variable smallest and count are not defined ... you didn't specify type. You defined them in your main, but your function does not know anything about variables in main. Just about variables that you passed (numbers and SIZE). Try it like this:
int getSmallest(int numbers[], int SIZE)
{
int smallest = numbers[0];
for (int count = 1; count < SIZE; count++) {
if (numbers[count] < smallest) {
smallest = numbers[count];
}
return smallest;
}
}
*Note the int before smallest and count
I also noticed that this function returns immediately after one loop iteration. You should write that return statement outside for loop
int getSmallest(int numbers[], int SIZE)
{
int smallest = numbers[0];
for (int count = 1; count < SIZE; count++) {
if (numbers[count] < smallest) {
smallest = numbers[count];
}
}
return smallest;
}
Also, I don't know if that SIZE is defined anywhere in any header file, but it is not defined in your program.
You are also not reading from file. Maybe this link will help you understand how to read from file: http://www.cplusplus.com/doc/tutorial/files/

Function is not returning any value | C++

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.

Find the index of the minimum element in a subarray

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;
}

How do i find the maximum number in an Array using a function

In my c++ class, i'm supposed to use this " int mymaximum(int a[], int numberOfElements); " function to find the maximum number in an Array. The function should return the largest in this array.
This is the code I have so far without the function I need to use. Thanks in advance and sorry about the messy code, still learning.
#include <iostream>
using namespace std;
int main() {
int Array[] = {23,2,90,53,38};
int mymaximum = 0;
for(int i = 0; i < 5; i++){
if(Array[i] > mymaximum){
mymaximum = Array[i];
}
}
cout << "The Max is: " << mymaximum << "\n";
return 0;
}
Just wrap around the logic to find maximum in a function. Like this:
int mymaximum(int a[], int numberOfElements)
{
// moved code from main() to here
int mymaximum = 0;
for(int i = 0; i < numberOfElements; i++)
{
if(a[i] > mymaximum)
{
mymaximum = a[i];
}
}
return mymaximum;
}
Aso, in order to support negative numbers, modify your logic like this:
int mymaximum(int a[], int numberOfElements)
{
// moved code from main() to here
int mymaximum = a[0];
for(int i = 1; i < numberOfElements; i++)
{
if(a[i] > mymaximum)
{
mymaximum = a[i];
}
}
return mymaximum;
}
Note that now I initialize maximum with the first entry in the array!
In main() call your method like this:
int main() {
int Array[] = {23,2,90,53,38};
cout << "The Max is: " << mymaximum(Array, sizeof(Array) / sizeof(Array[0])) << "\n";
return 0;
}
I'll show the overall structure without solving the homework for you:
#include <iostream>
using namespace std;
int mymaximum(int a[], int numberOfElements) {
int ret = 0;
// compute the maximum and store in `ret'
...
return ret;
}
int main() {
int Array[] = {23,2,90,53,38};
cout << "The Max is: " << mymaximum(Array, sizeof(Array) / sizeof(Array[0])) << "\n";
return 0;
}
In case you're wondering, sizeof(Array) / sizeof(Array[0]) computes the size of the array so that you don't have to hard-code it here.
Just move your logic into the desired function as follows:
int mymaximum(int Array[], int numberOfElements)
{
int mymaximum = 0;
for(int i = 0; i < numberOfelements; i++){
if(Array[i] > mymaximum){
mymaximum = Array[i];
}
}
return mymaximum;
}
Put that above int main(), then inside main() replace the removed code with:
int mymaximum = ::mymaximum(Array, 5);
(The :: wouldn't be needed if either the local variable or the function had different names).
You should then apply the suggestion in sasha's comment to use [0] as the initial guess at a maximum.
Replace your for loop structure with this:
int max(0);
max = mymaximum(Array, 5);
In the function mymaximum use this code:
int max(a[0]);
for(auto i(1); i < numberOfElements; ++i)
if(a[i] > max)
max = a[i];
return max;

Swapping Pointers of Array

#include <iostream>
#include <cstdlib>
using namespace std;
void swapNum(int *q, int *p)
{
int temp;
temp = *q;
*q = *p;
*p = temp;
}
void reverse(int *ip, int const size)
{
for (int k = 0; k < size; k++)
{
if (k == (size/2))
{
int *q = &ip[k];
int *p = &ip[k+1];
swapNum(q,p);
break;
}
else
swap(ip[k], ip[size-k]);
}
}
int main()
{
const int size = 20;
int arr[size];
int *ip;
ip = arr;
cout << "Please enter 20 different numbers." << endl;
for (int i = 0; i < size; i++)
{
cout << "\nNumber " << i+1 << " = ";
cin >> ip[i];
}
reverse(ip, size);
cout << "I will now print out the numbers in reverse order." << endl;
for (int j = 0; j < size; j++)
{
cout << ip[j] << " ";
}
return 0;
}
When I try to run this program it crashes. I don't know what's wrong and the purpose of my program is to swap number of the array using pointers. I am recently introduced to this so I am not that familiar with it. But I think that I am swapping the address of the numbers instead of swapping the numbers in the address. Correct me if I am wrong.
You're accessing outside the array bounds in reverse() when you do:
swap(ip[k], ip[size-k]);
On the first iteration of the for loop, k is 0 and size-k is size. But array indexes run from 0 to size-1. So it should be:
swap(ip[k], ip[size-k-1]);
But I don't see a definition of swap in your program. I think it should actually be:
swapNum(&ip[k], &ip[size-k-1]);
Another improvement: Instead of handling size == k/2 specially and using break, just use size < k/2 as the bound test in the for loop.
swap(ip[k], ip[size-k]);
Your problem is there. size - k when k is 0 will lead to undefined behavior (accessing an array out of bounds). Your loop structure in reverse can be simplified:
for (int k = 0; k < size / 2; k++)
swapNum(&ip[k], &ip[size - k - 1]); // updated to use the address since your swap function takes pointers.
Function reverse is invalid
void reverse(int *ip, int const size)
{
for (int k = 0; k < size; k++)
{
if (k == (size/2))
{
int *q = &ip[k];
int *p = &ip[k+1];
swapNum(q,p);
break;
}
else
swap(ip[k], ip[size-k]);
}
}
For example when k is equal to 0 then you call
swap(ip[0], ip[size]);
However the array has no element with index size.
ALso you mess two functions std::swap and swapNum
This code snippet also is invalid
if (k == (size/2))
{
int *q = &ip[k];
int *p = &ip[k+1];
swapNum(q,p);
break;
}
When size is an even number (or an odd number) as in your code then you make incorrect swap. For example if size is equal to 20 then you should swap ip[9[ with ip[10]. However according to the code snippet above you swap ip[10] with ip[11].
You could use standard algorithm std::reverse
for example
#include <algorithm>
#include <iterator>
//...
std::reverse( std::begin( arr ), std::end( arr ) );
or
#include <algorithm>
//...
std::reverse( arr, arr + size );
If you want to write the function yourself then it could look as
void reverse( int a[], int size )
{
for (int k = 0; k < size / 2; k++)
{
int tmp = a[k];
a[k] = a[size-k-1];
a[size-k-1] = tmp;
}
}
Or if you want to use your function swapNum then
void reverse( int a[], int size )
{
for (int k = 0; k < size / 2; k++)
{
swapNum( &a[k], &a[size-k-1] );
}
}
EDIT: I removed qualifier const from the first parameter that was a typo.