How to place input value in arrays c++? - c++

New to c++. I want to take the input values in scoreCurrent and place them into different arrays depending on whether they're above the average or below the average. I tried looking for solutions from different websites and youtube but none worked so far. How do I do this?
I apologize if my whole code is a mess and thank you in advance.
#include <iostream>
using namespace std;
int main()
{
// student count
int students, upperLimit;
cout<<"Enter no. of students: ";
cin>>students;
// upper limit
do
{
cout<<"Enter the upper limit: ";
cin>>upperLimit;
if(upperLimit<5)
{
cout<<"Invalid upper limit."<<endl;
continue;
}
break;
}while(true);
// student scores
int scoreCurrent, scoreTotal;
float average=0;
int belowAve(students), aboveAve(students);
for(int index=1; index<=students; index++)
{
cout<<"Enter score for student no. "<<index<<": ";
cin>>scoreCurrent; // take this and place it into an array
// condition invalid
if(scoreCurrent>upperLimit || scoreCurrent<0)
{
int current=index-1;
cout<<"Invalid score."<<endl;
index=current;
scoreCurrent=0;
}
scoreTotal+=scoreCurrent;
average=(float) scoreTotal/(float) students;
if(scoreCurrent>average)
{
// scoreCurrent values are placed in belowAve array;
}
if(scoreCurrent>average)
{
// scoreCurrent values are placed in aboveAve array;
}
}
// display
cout<<"Average: "<<average<<endl;
cout<<"Scores above or equal average: "<<belowAve<<endl;
cout<<"\nScores below average: "<<aboveAve<<endl;
return 0;
}

My guess is that scorecurrent is an array (and index the offset in scorecurrent)? If you think that this will work
std::cin >> scoreCurrent;
then the problems are:
where in scorecurrent will the input be placed (you don't use index)?
(if you want to give scores for all indices) when does the input stop?
Apart from the argument that a vector is better (which it is, because you don't need to specify its size and can just push_back()) I think this solution is a very elegant way to solve your problem.
It uses a lambda function to iterate over all elements of a (fixed-sized) array. There is also another, more traditional solution where the >> operator of std::cin is overloaded for arguments of array types.

Related

"while" command in c++

In c++, I have to write a code to get the user's desired numbers in each line with "while" command and when the user enter number -1 at the end, I have to display the largest number, the largest number other than the previous number, and the number of row with the largest number entered. For example user's numbers is:
4
7
11
5
-1
and result is:
11(the biggest number)
7(the biggest number after 11)
3(the row that the user has entered the largest number)
This is my own code:
#include <iostream>
using namespace std;
int main()
{
int price;
int max=0;
cin>>price;
while(price!=-1)
{
while(price>max)
{
max=price;
}
cin>>price;
}
cout<<max;
return 0;
}
I can find the largest number, but not the other two variables. Please reply ASAP.
I don't want to spoon feed you the code. I will help you with the logic instead.
Take input and store it in an array.
Then use a sorting algorithm (there are tons of them, another opportunity for you to learn) to sort the array (or the vector)
Print the array
View the code only when you learn how to do it on your own:
std::vector<int> vec;
int input = 0;
while (input != -1) {
std::cin >> input;
vec.push_back(input);
}
std::sort(vec.begin(), vec.end());
for (auto& element : vec) {
std::cout << element << " ";
}

Program exits before executing rest of the program

I am trying to create a students program but it stops after I put the 4th name, it doesn't allow me to put the grades neither shows the list at the end...
#include<iostream>
using namespace std;
int main()
{
string name[4];
double g1[4],g2[4],avg[4];
int cont;
for(cont=1;cont<=4;cont++)
{
cout<<"STUDENT "<<cont<<"\n";
cout<<"Name: ";
cin>>name[cont];
cout<<"First Grade: ";
cin>>g1[cont];
cout<<"Second Grade: ";
cin>>g2[cont];
avg[cont]=(g1[cont]+g2[cont])/2;
}
cout<<"STUDENTS LIST"<<"\n";
cout<<"--------------"<<"\n";
for(cont=1;cont<=4;cont++)
{
cout<<name[cont]<<" "<<avg[cont]<<"\n";
}
}
string name[4]; is an array with 4 elements. Valid indices are 0,1,2 and 3. Your loops skips the first element and accesses the array out-of-bounds on the last iteraton. That causes undefined behavior. Anything could happen.
The two loops for(cont=1;cont<=4;cont++) is wrong because you can only use indice 0, 1, 2, 3 for 4-element arrays.
You should use for(cont=0;cont<4;cont++) instead and change cout<<"STUDENT "<<cont<<"\n"; to cout<<"STUDENT "<<(cont+1)<<"\n";.
Another option is to add one more elements to each arrays. First elements of the arrays won't be used then, but this may contribute for readability for you.

How would I go on as to "return" string arrays between functions?

Hey so I was experimenting what I knew and realized when I tried passing a string value with return it wasn't supported, any idea? Sorry if my code is noob style (I only have 2 months of experience), I was planning on splitting the code between functions but I can't seem to do it because returning my array of strings cant be done with return :( Here's the code:
#include <iostream>
#include <math.h>
#include <sstream>
using namespace std;
int itemlist=0;
int c=0;
int r = 0;
int itemlistdec()
{
cout<<"How many items would you like to input?";
cin>>itemlist;
return itemlist;
}
int main() {
itemlistdec();
string item[4][itemlist];//declares item and that columns equal to itemlist whose content is declared right above
for (int c=0;c<itemlist;c++)
{
for (int r=0;r<3;r++) //DETERMINES WHERE EACH RECORD GOES
{
if (r==0)
{
cout<<"Please enter the name of the item ";
}
if (r==1)
{
cout<<"Please input the buying price\n";
}
if (r==2)
{
cout<<"Please input the selling price\n";
}
cin>>item[r][c];
}
}
int calc[3][itemlist];//declaring calc and itemlist
for (int r = 0;r<itemlist;r++)
{
istringstream(item[1][r])>>calc[0][r]; //TAKES BUYING PRICE INTO INT ARRAY FOR CALCULATION
}
for (int r = 0;r<itemlist;r++)
{
istringstream(item[2][r])>>calc[1][r]; //TAKES SELLING PRICE INTO INT ARRAY FOR CALCULATION
}
for (int fart = 0;fart<itemlist;fart++)
{
calc[2][fart] = calc[1][fart] - calc[0][fart]; //REPEATS CALCULATION FOR PROFIT UNTIL ITEMLIST IS REACHED
}
for (int r = 0;r<itemlist;r++)
{
stringstream ss;
ss<<calc[2][r]; //CONVERTS BOTH PROFIT VALUES INTO STRINGS
item[3][r] = ss.str();
}
cout<<"______________________________________________\n"; //DISPLAYS OUTPUT IN TABLE FORM
cout<<"Item\t\tBuying Price\t\tSelling Price\t\tProfit\n";
for (int c=0;c<itemlist;c++)
{
for (int r=0;r<4;r++)
{
cout<<item[r][c]<<"\t\t";
if (r==1)
{
cout<<"\t";
}
if (r==2)
{
cout<<"\t";
}
if (r==3)
{
cout<<"\n";
}
}
}
return 0;
}
I think you can use vector, it's very powerful. Like that:
std::vector<std::vector<std::string> > mySecondVector;
std::vector<std::string> myFirstVector;
myFirstVector.push_back("MyString");
mySecondVector.push_back(myFirstVector);
mySecondVector[i][j]; // to access
And for add, access to an element watch on http://www.cplusplus.com/reference/vector/vector/
Returning an array is a bit goofy. you have to return it as a pointer, and as soon as you do that you lose all size information. You have this handled by itemlist hanging around as a global variable, but global variables impose their own set of limitations. For one, you can never have more than one of these arrays (unless they are all the same size) because multiple arrays would be storing their length in the same spot.
First you have to flip the orientation of the array to get the constant size on the right-most index. Frankly because of locality (all of the data with respect to one item is in the same memory region, so if you load one part of an item into cache you probably load all of it. This almost always results in a much faster program) it's probably better that way, anyway. Then you've probably noticed you can't just return string[][] or anything that looks like it without the compiler barking at you, so you have to play games defining custom data types that you can return.
typedef string (*arrayPtr)[4];
Now you could try
arrayPtr itemlistdec()
{
cout << "How many items would you like to input?";
cin >> itemlist;
string item[itemlist][4];
//load the array
return item;
}
And itemlist knows how big the array is, but you get a new snag. Item goes out of scope on you and is no longer valid. Even more fun, string item[itemlist][4]; isn't even legal C++ because itemlist isn't a constant value. It works as a convenience in some C++ compilers, but not all.
So how about this? Dynamic allocation of the array will make it outlive itemlistdec, but now you'll have to delete the array manually when you are done with it.
arrayPtr itemlistdec()
{
cout << "How many items would you like to input?";
cin >> itemlist;
arrayPtr item = new string[itemlist][4];
//load the array
return item;
}
Now we've got something that works. We can make it a bit more readable (and less at the same time, because a reader has to track down just what an array is in order to know how to use it) by
typedef string (array)[4];
typedef array (*arrayPtr);
arrayPtr itemlistdec()
{
cout << "How many items would you like to input?";
cin >> itemlist;
arrayPtr item = new array[itemlist];
//load the array
return item;
}
This does not extend to variable length on both dimensions or if you absolutely must have the constant on the inside index. For that case you need this bastich:
string ** itemlistdec()
{
cout << "How many items would you like to input?";
cin >> itemlist;
string** item = new string*[4]; // 4 can be any number, but you also have to
// use it in place of 4 in the for loop
for (size_t index = 0; index < 4; index++)
{
item[index] = new string[itemlist];
}
//load the array
return item;
}
Doable, but you now have picked up a bunch of memory management duties. All of the allocated memory must be released with delete[]. In the string ** case, you have to run through the left-most index and delete[] all of the right-most arrays before deleting the left-most.
You can eliminate this with vector<vector<string>>, but in this case it's ugly. Great trick, but doesn't fit the overall program goal.
vector<vector<string>> itemlistdec()
{
int itemlist;
cout << "How many items would you like to input?";
cin >> itemlist;
vector<vector<string>> item(4, vector<string>(itemlist));
for (int c=0;c<itemlist;c++)
{
cout<<"Please enter the name of the item ";
cin>>item[0][c];
cout<<"Please input the buying price\n";
cin>>item[1][c];
cout<<"Please input the selling price\n";
cin>>item[2][c];
}
return item;
}
Note I'm returning the local vector and counting on move semantics to move the vector on return rather than copying it. Also note that you don't need a global itemlist anymore because the vector knows how big it is. You can even add stuff to it later if you want. And also note I ditched the inner for loop on the input. It's not needed.
This works better than the array options, but I still don't like it. Item is calling out for its own class so we can take advantages of the goodies that object oriented programming brings. We can also the correct data types for all of the member variables. That way we can catch bad input as the user enters it and get rid of an extra integer array used by the calculation.
class Item
{
public:
void read(istream & in)
{
// ignoring possibility of total failure of cin here.
cout<<"Please enter the name of the item ";
in >> name;
cout<<"Please input the buying price\n";
while (!(in >> buyPrice)) // loop until we read an integer from the user.
{
in.clear();
cout<<"Invalid. Please input the buying price\n";
}
cout<<"Please input the selling price\n";
while (!(in >> sellPrice))
{
in.clear();
cout<<"Invalid. Please input the selling price\n";
}
return in;
}
// calc logic method goes here.
// output method goes here.
private:
string name;
int buyPrice; // no screwing around with the calc array. numbers are
//read in as numbers or the input fails
int sellPrice;
};
vector<Item> itemlistdec()
{
int nrItems = 0;
cout << "How many items would you like to input?";
cin >> nrItems;
vector<Item> itemlist(nrItems);
for (Item& item : itemlist)
{
item.read(cin);
}
return itemlist;
}
Note I'm not checking validity of all input, just that valid integers were used. Probably sufficient, but ehhhh.... I have accidentally closed stdin by mistake. Not a fun thing to debug. Anyway, you have worse problems if stdin is going down.

Trying to develop a program to identify numbers that are smallest and greatest

Good evening everyone, i am attempting to write code that will determine when a number is largest and smallest.. I have asked some tutors I know for help and they have been stumped on this as well. I can not use functions or arrays or breaks. :/ Which I understand makes the process more difficult.. My professor has stated
"The only decisions staments allowed inside the loop are to determine the largest and smallest value. This means you are not allowed to use a decision to determine if the first number was entered. This is going to require you to prime your loop. We cover priming the loop in the next section but for this assignment it means get the first number before the loop begins. We will also assume that at least one number is going to be input."
I don't understand how he expects us to do something we have not learned yet, but regardless.. This is how far I have gotten on the assignment..
We have to have the user input a value to determine how many values will be input...
I keep receiving an error message after I input how many values I would like to check,
"the variable "num" is being used without being initialized.." But num is in the int!!!
Then have the software basically identify the largest and smallest... Hopefully this makes sense to someone.. If you have any questions, or if I need to clarify anything please let me know, I will do so to the best of my ability..
#include <iostream>
using namespace std;
int main ()
{
int number;
int max=0;
int num;
int min=0;
{ cout << "How many numbers do you want to enter" ;
cin >> number;
for (int i=0; num!=number; i++)
{
cout<<"Enter a num "; /* This is where they are supposed to place in a number, press enter, another number, press enter, until their enter presses = number*/
cin>>num;
if (num>max)
max=num;
if (num<min)
min=num;
}
cout<<"largest number is: "<<max << endl;
cout<<"smallest number is: "<<min << endl;
}
}
This:
for (int i=0; num!=number; i++)
has undefined behavior, num doesn't have a value when this is first evaluated. You meant i != number (or, even better, i < number).
It would be better to use some other way of stopping, i.e. stop when a non-number is entered for instance.
Update: Just to clarify: there are other issues as well, such as min not being initialized in a way that make as many numbers as possible smaller than it. I would probably have gone for min = INT_MAX; or something like that. See <climits> for that constant.
int min=0;
you should change that to
int min=std::numeric_limits<int>::max();
Otherwise, the if the number you entered is greater than 0, it will not be assigned to min.
the variable "num" is being used without being initialized..
Give num a value, you have not given it a value before your loop starts. But that loop concept itself is wrong, try this.
for (int i=0; i < number; i++)
There is two problem in your code, first your min must be a great number like maximum integer, and the second is your for loop should loop on i. I commented lines that you need to change :)
#include <iostream>
#include <limits>
using namespace std;
int main ()
{
int number;
int max=0;
int num;
int min=std::numeric_limits<int>::max(); // change min to maximum integer possible in c++
{
cout << "How many numbers do you want to enter" ;
cin >> number;
//for (int i=0; num !=number; i++) change this line
for (int i=0; i<number; i++) //to this line
{
cout<<"Enter a num "; /* This is where they are supposed to place in a number, press enter, another number, press enter, until their enter presses = number*/
cin>>num;
if (num>max)
max=num;
if (num<min)
min=num;
}
cout<<"largest number is: "<<max << endl;
cout<<"smallest number is: "<<min << endl;
}
}

C++ array program

I'm very confused when it comes to arrays and I've got a mini-project on using them but i'm stuck at a certain part in my program and I don't know what to do next, can anyone help?
the question is:
"Write a C++ program that reads 5 integers from the screen (provided by the user) and determines the largest integer. You MUST use an array to store the 5 integers.
The following shows a sample output of the program.
Enter 5 integers: 15 36 -8 92 56
The largest integer is 92 "
what i've got so far:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int userIntegers[5];
cout<<"Enter 5 integers: ";
cin>>userIntegers[0];
//system("pause");
return 0;
}
Here is the thing you have to do. You need to use a FOR or WHILE loop to get the certain number of user input and store them in array.
int userIntegers[5];
int largest = 0;
cout<<"Enter 5 integers: ";
for (int i=0; i<5; i++) //Use for loop upto how many numbers you need to get as input.
{
cin>>userIntegers[i];//get the input from user and store it in array at the index
/*If the input is the larger than prev largest or For special case to handle if all the values entered is less than zero.*/
if(largest < userIntegers[i] || largest == 0)
{
largest = userIntegers[i];//Assign the largest number to the variable.
}
}
cout<<"Largest Integer is: "<<largest;
or you can do more easily (using isstringstrem and INT_MIN):
int maxnumber = INT_MIN; // for being sure to have at lest one number above
int number;
string s;
cout<<"Enter 5 integers: ";
cin >> s;
std::istringstream steam( s );
while(steam >> number) {
if (number > maxnumber) {
maxnumber = number;
}
}
EDIT:
If you need an array #Sridhar seem have your answer (but think about using INT_MIN http://www.cplusplus.com/reference/climits/)