"while" command in c++ - 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 << " ";
}

Related

How to place input value in arrays 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.

Exiting Loop using Enter(Return Key) C++

First of all thanks for answering and helping out...
Now i was making a program to let the user enter any number... and then use the program to point out the total number of 4's in the the number entered and i have now encountered a problem..
This is my first post here so please excuse me if i make any mistakes..
The Code
int main()
{
int T,i,j,l;
char N,p[10];
cin>>T;
while(T--) //The number of times a user can enter a new number
{
cout<<"\nEnter Numbers\n";
l=0;i=0;
do
{
N=getch(); //getch is used so that the enter key need not be pressed and the
//number looks like a whole and also so the each number is
//individually stored
p[i]=N; //here the number entered is stored in p
cout<<N; //to display the number obviously
l++;i++;
}while(N!=' '); //Now here between '' something has to be present so that the loop
//terminates as soon as the enter key is pressed right now as soon
//as the spacebar is hit the loop will terminate.
cout<<"\n";
j=0;
for(i=0;i<l;i++) //using l so that the loop runs accordingly
{
if(p[i]=='4')
{
j++; //for couting the number of 4's
}
cout<<p[i]<<"\n"; //wont be needing in the final program but here cout is just
// to check the output
}
cout<<"\n THERE ARE "<<j<<" FOURS\n";
}
}
Please not that i already have a solution for my program so please DO NOT provide a different code using some different logic... i really need this very same program to work.i know that this program can be made to work using string length but here i want the loop to terminate after the enter key is pressed.
Well if you want to stop getting input when the user presses enter instead of space you need to test against '\r', '\n' or '\r\n' depending on what OS you are using. That said you really should be using standard C++ if you are going to use C++. You could easily make your code like:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
int loops;
std::cout << "How many numbers to check: ";
std::cin >> loops;
std::cin.get(); // eat newline
for (int i = 0; i < loops; i++)
{
std::string numbers;
std::cout << "Enter numbers and press enter: ";
std::getline(std::cin, numbers);
auto numberOf4s = std::count(numbers.begin(), numbers.end(), '4');
std::cout << "Number of 4's entered: " << numberOf4s << std::endl;
}
return 0;
}
Live Example
You can to see check if N is equal to '\r'. So your while loop looks like
do
{
N=getch(); //getch is used so that the enter key need not be pressed and the
//number looks like a whole and also so the each number is
//individually stored
p[i]=N; //here the number entered is stored in p
cout<<N; //to display the number obviously
l++;i++;
}while(N!='\r');

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/)

Using an array of counters extract the integers from a file and count the number of responses?

#include <iostream>
#include <fstream>
#include <windows.h>
using namespace std;
void addRecordstoFile();
void readRecordsFromFile();
int main(){
addRecordstoFile();
readRecordsFromFile();
}
void addRecordstoFile(){
This adds the integers to the file but I want when it exits (when the user enters -1) not be displayed in the .txt file
int num=1;
char response;
ofstream outFile("numbers.txt",ios::out);
if (!outFile){
cerr<<"File was not opened correctly"<<endl;
exit(1);
}
cout<<"\t\t\tSurvey Response Analyzer"<<endl;
while(num!=-1){
cout<<"\n Enter a survey response from 1 to 10 (-1 to end): ";
cin>>num;
if(num<1 || num>10){
cout<<"\n Please enter a valid response from (1-10): ";
cin >>num;
}
outFile << num <<" ";
}
outFile.close();
cout<<"Saved to file..."<<endl;
system("pause");
}
This is where the major problem lies, I should extract the integers from the text file and place them in an array of counters to count the number of times the user enterred a number between 1 and 10. I am completely lost because I would need the size of the array to determine my loop.
void readRecordsFromFile(){
ifstream inFile("numbers.txt",ios::in);
if(!inFile){
cerr<<"File was not found";
exit (1);
}
How can I make an array of counters here without knowing the size of the array from the text file?
1. First query:
This adds the integers to the file but I want when it exits (when the
user enters -1) not be displayed in the .txt file
Replace
if (num < 1 || num > 10) {
cout<<"\n Please enter a valid response from (1-10): ";
cin >>num;
}
outFile << num <<" ";
with
if (num < 1 || num > 10) {
cout<<"\n Please enter a valid response from (1-10): ";
cin >>num;
} else {
outFile << num <<" ";
}
2. Second query:
I would need the size of the array to determine my loop
No you don't. You may use a while loop to check the end.
1st thing first, in your void addRecordstoFile() function, you could design your while loop as,
while(num!=-1){
cout<<"\n Enter a survey response from 1 to 10 (-1 to end): ";
cin>>num;
if(num<1 || num>10){
cout<<"\n Please enter a valid response from (1-10) ";
}
else{
outFile << num <<" ";
}
}
Next, for your void readRecordsFromFile() function, if your ultimate goal is only to count the number of appearances of the numbers entered, then you could use a 10 element counter array. and while reading from the file any digit you got, you just increase the element at the particular index of the counter array. say, you read 3 from the file, so you will just increase counter[3] as counter[3]++ to count the appearance of 3 in the file. Think about it.
while(/*end of file condition*/){
int a;
inFile>>a;
counter[a]++;
}
Hope it helped...
Well, the good news is you have tons of options to fix your issues. Here are some suggestions:
In order to avoid having the '-1' in the .txt file, I might change your loop to look like this:
while(num!=-1){
cout<<"\n Enter a survey response from 1 to 10 (-1 to end): ";
cin>>num;
if (num == -1) break; // will break out of loop before adding num!
if (num>0 && num<=10) outFile << num <<" "; // add only a valid number
// Note: if number is not 1 thru 10 or -1, loop simply repeats!
}
As for your second function, you have a variety of options, but I would suggest using a vector to contain the numbers. To use vectors, you need the library:
#include <vector>
Vectors are dynamic arrays -- you can add or delete elements to them as you wish. Your function might look like this:
void readRecordsFromFile(){
ifstream inFile("numbers.txt",ios::in);
if(!inFile){
cerr<<"File was not found";
exit (1);
}
vector <int> vNums; // a container for your int values
int inNum; // hold int for loading into vector
// Read each number to inNum, then add it to the vector
while (!inFile.eof()) {
inFile >> inNum; // load your input
vNums.push_back(inNum); // "push_back" adds an element
}
// Output the numbers... you may want to use a vector iterator for this
int x = 0;
while (x < vNums.size() ) {
cout << x+1 << " - " << vNums[x] << "\n";
x++;
}
}
Another option would be to use dynamic memory (new / delete), with linked lists. Here's a tutorial:
http://www.cprogramming.com/tutorial/lesson15.html
I think using a vector is a better solution, though! Best of luck.
return static_cast<double>(numerator/denominator);
Probably you prefer to cast each variable to double first and divide later. This is the difference:
If int: 2/4 == 0, so that static_cast<double>(numerator/denominator) returns 0.
If double (or float): 2./4. == 0.5, so that static_cast<double>(numerator) / static_cast<double>(denominator) returns 0.5.

Need program to multiply numbers user input when user is determining how many numbers they will input

I need to be able find the multiplication of all numbers entered by user. I know how to do this when I told the program how many numbers are going to be entered however in this program the users is telling the program how many numbers they are entering. I also need help making the average a floating point number. For example if user inputs 1, 1, 1, 1, and 0 average should be 0.8 not 0.
#include<iostream>
using namespace std;
int p, N = 0.0, sum =0;
float average = 0.0;
int main(){
cout<<"Enter the number of integers you want to enter: ";
cin>>N;
for (int i=0; i<N; i++) {
cout<<"enter a number: ";
cin>>p;
sum += p;
}
cout<<"The sum is "<<sum<<"\nThe average is "<<sum/N<<"\n";
system("pause");
}
To enable users to input different numbers of values, you can let users to input all numbers in one line separated by spaces. Use getline() to load all numbers and then pass them into vector<int>:
string str;
getline(cin, str);
// read all numbers, stored them in vector<int> numbers
vector<int> numbers;
istringstream ss(str);
int num;
while(ss >> num)
{
numbers.push_back(num);
}
// now you have all numbers, do whatever you want
cout << numbers.size() << " numbers in total" << endl;
// ... ...
Check out Ideone for the full code.