Need help displaying min/max values of integers entered by user - c++

I need help with a c++ program that:
"Prompts users for N integers and determines/displays the integer
with the highest and lowest value – use separate functions to return the highest and lowest value. N is a random number from 5 to 10 (both inclusive)."
This is what I have so far:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
void randNumGenerator();
void smallestNum(int);
void largestNum(int);
int smallNum;
int largeNum;
int randomNum;
int num[10];
int main()
{
smallestNum(smallNum);
largestNum(largeNum);
system("pause");
return 0;
}
void randNumGenerator()
{
srand(time(0));
randomNum = 5 + (rand() % 10);
for (int x = 1; x <= randomNum; x++) {
cout << "Enter an integer: ";
cin >> num[randomNum];
}
}
void smallestNum(int smallNum)
{
randNumGenerator();
smallNum = num[randomNum];
for (int i = 0; randomNum <= i; i++)
if (num[randomNum] < smallNum)
{
smallNum = num[randomNum];
}
cout << "The smallest integer is: " << smallNum << endl;
}
void largestNum(int largeNum)
{
randNumGenerator();
largeNum = num[randomNum];
for (int i = 0; i <= i; i++)
if (num[randomNum] > largeNum)
{
largeNum = num[randomNum];
}
cout << "The largest integer is: " << largeNum << endl;
}
But, my code is not working and I can't seem to figure out how to fix it. Any help would be appreciated, thanks!

There are several issues:
First, with randomNum = 5 + (rand() % 10);, you generate random numbers between 5 and 14, inclusive, which may exceed int num[10]. Use randomNum = 5 + (rand() % 6); to get values between 5..10.
In your loops for (int i = 0; randomNum <= i; i++), with random <= i, you exceed array bounds since randomNum can go up to 10 and num[10] is already out of bounds for int num[10]. Write ... randomNum < i instead.
The same problem with smallNum = num[randomNum]; it exceeds array bounds; use smallNum = num[0] instead.
BTW: I'd interpret your assignment such that you enter the numbers once and then find the smallest and largest number in two different functions. In your code, you enter the numbers twice...
And: It's useless passing the smallNum into the function that overrides its value then. I'd rather use a function like int smallestNum() { ... return smallNum; } instead.
Hope it helps.

Try this,
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
void randNumGenerator();
void smallestNum();
void largestNum();
void getInput();
int num[11];
int length;
int main(){
smallestNum();
largestNum();
return 0;
}
void randNumGenerator(){
int from = 5;
int to = 10;
srand(time(0));
length = from + (rand() % (to - from));
}
void getInput(){
for (int x = 1; x <= length; x++) {
cout << "Enter the integer num[" << x << "]: ";
cin >> num[x];
}
}
void smallestNum(){
cout << "Finding smallest integer\n";
randNumGenerator();
getInput();
int smallNum = num[1];
for (int i = 1; i <= length; i++)
if (num[i] < smallNum)
smallNum = num[i];
cout << "The smallest integer is: " << smallNum << endl;
}
void largestNum(){
cout << "Finding largest integer\n";
randNumGenerator();
getInput();
int largeNum = num[1];
for (int i = 1; i <= length; i++)
if (num[i] > largeNum)
largeNum = num[i];
cout << "The largest integer is: " << largeNum << endl;
}
With above code, I hope you will find your mistakes on your own :)

In addition to the first answer, this loop makes no sense:
for (int x = 1; x <= randomNum; x++) {
cout << "Enter an integer: ";
cin >> num[randomNum];
}
randomNum is the same every loop, so you just keep overwriting the same array value.
And...
for (int i = 0; i <= i; i++)
This loop is wrong. You are checking i <= i which will always evaluate true.

Related

Number of time the iterative function is called

Would like to seek a bit of help from StackOverflow. I am trying to print out the sequence of Fibonacci number and also the number of time the iterative function is called which is supposed to be 5 if the input is 5.
However, I am only getting 4199371 as a count which is a huge number and I am trying to solve the problem since four hours. Hope anyone who could spot some mistake could give a hint.
#include <iostream>
using namespace std;
int fibIterative(int);
int main()
{
int num, c1;
cout << "Please enter the number of term of fibonacci number to be displayed: ";
cin >> num;
for (int x = 0; x <= num; x++)
{
cout << fibIterative(x);
if (fibIterative(x) != 0) {
c1++;
}
}
cout << endl << "Number of time the iterative function is called: " << c1 << endl;
}
int fibIterative(int n)
{
int i = 1;
int j = 0;
for(int k = 1; k <= n; k++) {
j = i + j;
i = j - i;
}
return j;
}
First, initialize the variable
c1 = 0;
so that you will not get any garbage value get printed.
Secondly this:
if (fibIterative(x) != 0)
{
c1++;
}
will make 2*count - 1 your count. You don't need that.
Edit: I have noticed that you have removed extra c1++; from your first revision. Hence, the above problem is not more valid. However, you are calling the function fibIterative() again to have a check, which is not a good idea. You could have simply print c1-1 at the end, to show the count.
Thirdly,
for (int x = 0; x <= num; x++)
you are starting from 0 till equal to x that means 0,1,2,3,4,5 total of 6 iterations; not 5.
If you meant to start from x = 1, you need this:
for (int x = 1; x <= num; x++)
{ ^
cout << fibIterative(x) << " ";
c1++;
}

C++ Sort unable to resolve identifier begin and end?(Keeping arrays together)

I'm trying to sort my array pairs by int, but my sort is saying 'unable to resolve identifier' to pairs.begin(), pairs.end(), and compare_pairs_second(). I cannot figure out why but i'm probably doing something wrong?
Here is my code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <algorithm>
#include <iterator>
using namespace std;
main()
{
string name[10];//declaring an array name
int number[10];//declaring an array number
cout << "Please input 10 names \n";//output
for(int i = 0; i < 10; i++){//for statement
cin >> name[i];//inputting names in the array names
}
cout << "Please input their corresponding numbers \n";//output
for(int x = 0; x < 10; x++){
cin >> number[x];//inputting numbers
}//end for
int i = 0;//redeclaring i to be 0
int x = 0;//redeclaring x to be 0
for(int l = 0; l < 10; l++)//for statement
{
cout << name[i] << ": " << number[x] << "\n";
i++;//adding 1 to i so outputs all of array name
x++;//adding 1 to x so outputs all of array number
}//end for
pair<string, int> pairs[10];
int i = 0;
int x = 0;
for(int z = 0; z < 10; z++)
{
pairs[z] = make_pair(name[i], number[x]);
i++;
x++;
}
std::sort(pairs.begin(), pairs.end(), compare_pairs_second<std::less>());
int i = 0;
int x = 0;
for(int z = 0; z < 10; z++)
{
name[i] = pairs[z].first;
number[x] = pairs[z].second;
i++;
x++;
}
string search = "";
cout << "Enter a name to search for";
cin >> search;
size_t found = pairs.find(search);
if(found!=string::npos)
cout << search << pairs;
} //end main
UPDATE/EDIT:
I got my sort to work...to an extent. I deleted the line of code that was giving me errors, and it now sorts my number array, which is half of what I wanted. But now how do I keep the names with their respective numbers without using my pairs variable that I had prior to this fix?
Ex
array number[5]={5, 2, 9, 11, 27};
array name[5]={"Steve", "John", "Bob", "Larry", "Patric"};
Output after sorting:
John: 2 Steve: 5 Bob: 9 Larry: 11 Patric: 27
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <algorithm>
#include <iterator>
using namespace std;
main()
{
const int size = 10;
string name[10];//declaring an array name
int number[10];//declaring an array number
cout << "Please input 10 names \n";//output
for(int i = 0; i < 10; i++){//for statement
cin >> name[i];//inputting names in the array names
}
cout << "Please input their corresponding numbers \n";//output
for(int i = 0; i < 10; i++){
cin >> number[i];//inputting numbers
}//end for
sort(number,number+size);
int i;
int j;
int min;
int counter = 0;
for(i = 0; i < counter; i++)
{
min = i;
for(j = i+1; j < counter; j++)
{
if(name[j] < name[min])
{
string tempString = name[i];
name[i] = name[j];
name[j] = tempString;
int tempInt = number[i];
number[i] = number[j];
number[j] = tempInt;
}
}
}
for(i = 0; i < 10; i++)
{
cout << name[i] << ": " << number[i] << "\n";
};
} //end main
Current output sorts numbers but does not keep names with them.
pairs is raw array, not a STL container; you can't invoke method on it like pairs.begin() and pairs.end().
Since C++11 you could use std::begin() and std::end(), which are overloaded for supporting raw arrays. e.g.
std::sort(std::begin(pairs), std::end(pairs), compare_pairs_second<std::less>());

Counting different elements in an array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I got this really easy project however i got stuck in a simple issue.
User enters a number not that is larger than 99 and smaller than 1 000 000.
I am supposed to get the number of digits in that number and how many times each one occurs
E.g: 112233 = 6 digits and 3 different numbers
I was able to do the first part however my second part of part is not working.
Here is the part not working:
int getDiff(int CLP, int Num)
{
int counter = 0, i = 0, j = 0;
for (int x = CLP, i = 0; x >= 1; x /= 10, i++) {
PlateNumberArray[i] = x % 10;
cout << endl
<< "Test===>" << PlateNumberArray[i] << endl;
} // end of "x = CLP" for loop
while (i < Num) {
j = 0;
while (j <= Num) {
if (PlateNumberArray[i] == PlateNumberArray[j])
NumberCounter[i]++;
j++;
} //end of while(j <= i)
i++;
} //end of while(i < Num)
for (int i = 0; i < Num; i++)
counter += NumberCounter[i];
return counter;
}
if for example my input is 112233 the return value should be 3, however i am getting 12
if input is 1122 the return value should be 2, however i am getting 8
Here is the whole program i have written so far:
/*====================================================================================
Headers and namespace
======================================================================================*/
#include <iostream>
using namespace std;
/*====================================================================================
Prototypes list
======================================================================================*/
int getNum(int); //This function checks how many digits there are in a plate number
int getDiff(int, int); //This function checks how many different numbers are there in the plate number
/*====================================================================================
Global variables list
======================================================================================*/
int PlateNumberArray[6];
int NumberCounter[6];
/*====================================================================================
main Function
======================================================================================*/
int main()
{
//Declaring variables
int CLP;
//End of Vriables Declration
cout << endl
<< "=============================" << endl;
cout << "Enter your vehicle's plate number" << endl;
do {
cin >> CLP;
if (CLP >= 1000000)
cout << "Plate number can be no longer than 6 digits, please re-enter" << endl;
else if (CLP < 100 && CLP >= 0)
cout << "Plate number can not be less than 3 digits, please re-eneter" << endl;
else if (CLP < 0)
cout << "Plate number can not be a negative, please re-eneter" << endl;
} while (CLP >= 1000000 || CLP < 100);
int Num = getNum(CLP);
cout << getDiff(CLP, Num);
return 0;
}
/*====================================================================================
getNum Function
======================================================================================*/
int getNum(int CLP)
{
//Declaring variables
int Num;
//End of Vriables Declration
if (CLP > 99999)
Num = 6;
else if (CLP > 9999)
Num = 5;
else if (CLP > 999)
Num = 4;
else if (CLP > 99)
Num = 3;
return Num;
}
/*====================================================================================
getDiff Function
======================================================================================*/
int getDiff(int CLP, int Num)
{
int counter = 0, i = 0, j = 0;
for (int x = CLP, i = 0; x >= 1; x /= 10, i++) {
PlateNumberArray[i] = x % 10;
cout << endl
<< "Test===>" << PlateNumberArray[i] << endl;
} // end of "x = CLP" for loop
while (i < Num) {
j = 0;
while (j <= Num) {
if (PlateNumberArray[i] == PlateNumberArray[j])
NumberCounter[i]++;
j++;
} //end of while(j <= i)
i++;
} //end of while(i < Num)
for (int i = 0; i < Num; i++)
counter += NumberCounter[i];
return counter;
}
You need to reset j each time you increment i.

C++ Vector Subscript Issues

I was making an app that calculates the mean, median, and range of any integers, but I ran into the issue: Vector subscript out of range. I've looked at some other posts about this, and still haven't been able to fix it.
Here's my code:
#include <iostream>
#include <Algorithm>
#include <Windows.h>
#include <vector>
using namespace std;
int main() {
//Variables
int sze;
int mraw = 0;
double mean;
double median;
double range;
int fullnum = 0;
int lastnum = 1;
vector<int> med;
cout << "How many numbers do you have? ";
cin >> sze;
int *arr = new int[sze];
for (int i = 0; i < sze; i++) {
med.push_back(arr[i]);
}
//Getting numbers
for (int i = 0; i < sze, i++;) {
system("cls");
cout << "Enter number #" << i + 1 << ": ";
cin >> arr[i];
}
//Mean
for (int i = 0; i < sze; i++){
fullnum += arr[i];
}
mean = fullnum / sze;
//Median
sort(med.begin(), med.end());
int mvs = sze;
while (med.size() >= 2) {
med.erase(med.begin());
med.erase(med.begin() + med.size() - 1);
mvs--;
}
if (mvs == 2) {
mraw = med[1] + med[2];
median = mraw / 2;
}
else {
median = mvs;
}
//Range
vector<int> rnge;
for (int i = 0; i < sze; i++) {
rnge.push_back(arr[i]);
lastnum++;
}
sort(rnge.begin(), rnge.end());
int bigsmall[2];
bigsmall[1] = rnge[1];
bigsmall[2] = rnge[lastnum];
range = bigsmall[2] - bigsmall[1];
//Outputs
cout << "Mean: " << mean << "\nMedian: " << median << "\nRange: " << range;
system("cls");
return 0;
}
You have what would be an off-by-one error if lastnum was initialized to 0.
When rnge is empty, presumably lastnum is 0. This means access rnge[lastnum] is in error, as rnge is empty.
Applying an inductive argument shows that lastnum is the count of number of elements, and not the index of the last element. Thus, rnge[lastnum] is always out of range.
In actuality, you have initialized lastnum to 1, so your bug is actually off-by-two.

Run Time Check failure # 2 - Stack around variable 'ary' was corrupted. Why?

I'm new, don't know what I'm doing.
The compile warnings are on and do not show any warnings. Executable pops up and alerts of Run Time Check Failure #2.
Help would be appreciated as to why this is happening.
#include <iostream>
#include <string>
using namespace std;
class romanType {
public:
string strg;
void inputRoman(int ary[]);
//void CalculateRoman(int ary[]);
//void outputRoman(int total);
};
int main()
{
int M = 1000;
int D = 500;
int C = 100;
int L = 50;
int X = 10;
int V = 5;
int I = 1;
romanType numerals;
int ary[50];
cout << "This is to convert your input of Roman numerals to a positiver integer" << endl;
cout << "When prompted, do as you're told" << endl;
numerals.inputRoman(&ary[50]);
// numerals.CalculateRoman(&input[50]);
return 0;
}
void romanType::inputRoman(int ary[])
{
string strg;
int array_size;
int i;
cout << "Input the an appropriate Roman Numeral value" << endl;
cin >> strg;
array_size = strg.length();
for (i = 0; i < array_size; i++)
{
ary[i] = strg[i];
}
}
/*
void romanType::CalculateRoman(int ary[])
{
int total = 0;
int i;
for (i=0; i < 50 ; i++){
if (ary[i] < (ary[i + 1])){
total = total + (ary[i + 1] - ary[i]);
}
else {
total = total + ary[i];
}
}
cout << "Your conversion should equal " << total << endl;
}
*/`
&ary[50] is the address of 51st element of ary, which means it points just after the last element of ary. Change it to ary:
numerals.inputRoman(ary);