How can I make the program display only cars that have 5 seats, for now no matter what, it shows all cars that I write infos about them, for example if I write in the console that there are 3 cars and give information about them and say that one has 2 seats and the others have 5 after I run the program it still displays all 3 of them. Any idea of how can I display only cars with 5 seats? Can I somehow use the quicksort() function ?
#include <iostream>
using namespace std;
struct Car
{
int no_seats;
int year;
char brand[20];
char color[20];
float horse_power;
};
void read_cars(Car C[], int &n)
{
int i;
cout << "Number of parked cars "; cin >> n;
for(i=1; i<=n; i++)
{
cout << "Brand " ; cin >> M[i].brand;
cout << "The year it was made in " ; cin >> M[i].year;
cout << "Color " ; cin >> M[i].color;
cout << "Power " ; cin >> M[i].horse_power;
cout << "Number of seats " ; cin >> M[i].no_seats;
}
}
void display_cars(Car C[], int n)
{
int i;
for(i=1; i<=n; i++)
{
cout << "Brand " ; cout << M[i].brand << endl;
cout << "The year it was made in " ; cout << M[i].year << endl;
cout << "Color " ; cout << M[i].color << endl;
cout << "Power " ; cout << M[i].horse_power << endl;
cout << "Number of seats " ; cout << M[i].no_seats << endl;
}
}
int main()
{
Car C[50];
int n;
read_cars(M, n);
display_cars(M, n);
return 0;
}
You need to add a condition in the loop:
void display_cars(Car C[], int n)
{
int i;
for(i=1; i<=n; i++)
{
if(M[i].no_seats == 5) // <- like this
{
cout << "Brand " ; cout << M[i].brand << endl;
cout << "The year it was made in " ; cout << M[i].year << endl;
cout << "Color " ; cout << M[i].color << endl;
cout << "Power " ; cout << M[i].horse_power << endl;
cout << "Number of seats " ; cout << M[i].no_seats << endl;
}
}
}
Other notes:
Your n can only go up to 49 - remember that. That also means that you are wasting an element at M[0] (yes arrays are zero based in C++).
Prefer to use std::vector<Car> C over an array of fixed size. A std::vector grows as you push_back more and more elements into it - and it keeps track of the number of contained elements, so you do not need to pass the size of the vector around. C.size() would tell you the number of elements.
void display_cars(const std::vector<Car>& C)
{
std::cout << "There are " << C.size() << " cars in the vector\n";
for(const Car& a_car : C) // a range based for-loop
{
if(a_car.no_seats == 5) // a_car will be a reference to each car in the loop
{
// use "a_car" to display info about one particular car
}
}
}
Related
I am trying to add up all the values that have been stored into array b and have it display under the "total column" and don't know how to only have the scores add together.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int array[5][4];
int sum = 0;
cout<<"Enter grades for 4 exams for the 5 students \n";
for(int i=0;i<5;i++)
{
for(int b=1;b<=4;b++)
{
cout <<setw(8)<< "enter student "<< i << "'s grade for exam " << b << '\n';
cin >> array[i][b];
}
}
cout <<"ID"<<setw(11)<<"score 1"<<setw(11)<<"score 2"<<setw(11)<<"score 3"<<setw(11)<<"score 4"<<setw(11)<<"total"<<setw(11)<<"letter"<<endl;
cout <<"--------------------------------------------------------------------------------------------------------------\n";
for(int i=0;i<5;i++)
{
cout << i<< " ";
for(int b=1;b<=4;b++)
{
sum = sum + array[b];
cout <<setw(10)<<array[i][b]<<sum;
}
cout <<'\n';
}
cout <<"--------------------------------------------------------------------------------------------------------------\n";
return 0;
}
To be more specific around line 28
for(int i=0;i<5;i++)
{
cout << i<< " ";
for(int b=1;b<=4;b++)
{
sum = sum + array[b];
cout <<setw(10)<<array[i][b]<<sum;
}
cout <<'\n';
Arrays indexes start at 0, not 1. You are correctly looping through your array's 1st dimension, but not its 2nd dimension. You need to change the inner for loops from for(int b=1;b<=4;b++) to for(int b=0;b<4;b++)
Also, to handle the total column, you simply need to reset sum to 0 on each iteration of the 1st dimension, and then print the result after the iteration of the 2nd dimension.
Try this:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int array[5][4];
cout << "Enter grades for 4 exams for the 5 students \n";
for(int i = 0; i < 5; i++)
{
for(int b = 0; b < 4; b++)
{
cout << "Enter student " << i+1 << "'s grade for exam " << b+1 << '\n';
cin >> array[i][b];
}
}
cout << "ID" << setw(11) << "score 1" << setw(11) << "score 2" << setw(11) << "score 3" << setw(11) << "score 4" << setw(11) << "total" << setw(11) << "letter" << endl;
cout << "--------------------------------------------------------------------------------------------------------------\n";
for(int i = 0; i < 5; i++)
{
cout << setw(2) << left << i+1 << right;
int sum = 0;
for(int b = 0; b < 4; b++)
{
sum = sum + array[i][b];
cout << setw(11) << array[i][b];
}
cout << setw(11) << sum << '\n';
}
cout << "--------------------------------------------------------------------------------------------------------------\n";
return 0;
}
Online Demo
I was given a task to write an example of derived class. But In my program, something strange is happening with the roll numbers.
Also, when this program is compiled in g++.
When I used char [] and gets() to store the strings and input values into them, it didn't allow me to enter the value for collname.
When I use string and cin, I get some strange values while asking for marks.(Check the attached image).
#include<iostream>
#include<conio.h>
using namespace std;
class uni
{
private:
int rollno[100], i, flag;
int intermarks[100];;
int theorymarks[100];
void settheorymarks();
protected:
int numstud;
void setintermarks();
void issurno();
public:
void prepres();
void showres(string collname);
};
class college : public uni
{
private:
string collname;
public:
college(int N)
{
numstud = N;
issurno();
}
void enter_marks();
void disp();
};
void uni::issurno()
{
for (i = 0; i < numstud; i++)
rollno[i] = 1024+i;
cout << "Roll numbers issued!" << endl;
}
void uni::settheorymarks()
{
cout << "Enter theory marks for: " << endl ;
for(i = 0; i < numstud; i++)
{
cout << i+1 << ".) Roll number: " << rollno << " : ";
cin >> theorymarks[i];
}
cout << endl << endl << "Theory marks recorded!" << endl;
}
void uni::setintermarks()
{
cout << "Enter inter marks for: " << endl ;
for(i = 0; i < numstud; i++)
{
cout << i+1 << ".) Roll number: " << rollno << " : ";
cin >> intermarks[i];
}
cout << endl << endl << "Internal marks recorded!" << endl;
}
void uni::prepres()
{
settheorymarks();
}
void uni::showres(string colnam)
{
cout << "College: " << colnam << endl;
cout << "__________________________Result___________________________" << endl;
cout << "s. No.\tRoll no\tInternal\tTheory" << endl;
for(i = 0; i < numstud; i++)
cout << i+1 << "\t" << rollno[i] << '\t' << intermarks[i] << "\t" << theorymarks[i] << endl;
cout << endl << "End of result!" << endl;
}
void college::disp()
{
showres(collname);
}
void college::enter_marks()
{
cout << "Enter the college name: ";
cin >> collname;
setintermarks();
prepres();
}
int main()
{
int n;
cout << "Enter number of stufents: ";
cin >> n;
college c(n);
c.enter_marks();
c.disp();
return 0;
}
I feel that I've made a stupid mistake somewhere.
PS: In school, I was forced to use turbo C++ (One of the oldest compilers).
You just forget the [i] after rollno in the two lines like:
cout << i+1 << ".) Roll number: " << rollno[i] << " : ";
There are a few other things I would ask you to improve if I was your supervisor/teacher:
always use expressive variable and method names. Avoid any abbreviations.
why is there the arbitray offset of 1024 in rollno? If this is just "obfuscation" remove it...
Unclear: why is setintermarks called inside enter_marks but settheorymarks in prepres ?
typo in "stufents"
I need help in a simple way of solving a part of my code that i cant seem to make it work.The point of my "assignment" is that everything must try to be in one class.Now the problem i am having is at a part of my code where it is suppose to "print" the n number of products meaning that it displays what you have inputted in the void get() part,but the problem i cant seem to resolve is it only prints the last name,amount,weight of the product and not everything written.
class Class
{
public:
string name;
int n, amount;
float weight;
void market()
{
cout << "Give the number of products you want to get at Market : " << endl;
cin >> n;
}
void get()
{
for (int i = 0; i < n; i++)
{
cout << "Give product name,amount and weight : " << endl;
cin >> name >> amount >> weight;
}
}
void print()
{
cout << "\nProduct display:\n" << endl;
for (int i = 0; i < n; i++)
{
cout << name << " - " << amount << " , " << weight << " kg" << endl;
cout << "------------------------" << endl;
}
};
};
The main part.
int main()
{
Class market;
market.market();
market.get();
market.print();
}
You're actually overwriting name, amount and weight. You have to make use of something similar to std::vector:
class Class {
public:
std::vector<string> names;
// Same for others
When you get them from std::cin you have to push them into the vector:
names.push_back(name);
amounts.push_back(amount);
weights.push_back(weight);
When printing you loop over the vectors:
for (int i = 0; i < n; i++) {
cout << names[i] << " - " << amounts[i] << " , " << weights[i] << " kg" << endl;
cout << "------------------------" << endl;
}
You must use a std::vector<TYPE> (example 1), or array for holding multiple data in a single variable (example 2).
Example 1
Since you've been coding in C++ programming language, it's highly recommended to use std::vector<> for best results.
Consider the class example (read comments too):
int count = 0; // PRIVATE SECTION
char ask;
std::vector<std::string> name;
std::vector<int> amount;
std::vector<float> weight;
std::string tName; // temp variables
int tAmount;
float tWeight;
public:
void market()
{
cout << "WELCOME!" << endl; // nothing's required with vector
}
void get()
{
do {
cout << "Give product name, amount and weight : " << endl;
cin >> tName >> tAmount >> tWeight; // getting temporary variables
name.push_back(tName); // assigning
amount.push_back(tAmount);
weight.push_back(tWeight);
count++;
cout << "Add more? (Y/n): "; // add more? Go on if yes...
cin >> ask;
} while (ask == 'Y' || ask == 'y');
}
void print()
{
cout << "\nProduct display:\n"
<< endl;
for (int i = 0; i < count; i++)
{
cout << name[i] << " - " << amount[i] << " , " << weight[i] << " kg" << endl;
cout << "------------------------" << endl;
}
}
Sample Output
WELCOME!
Give product name, amount and weight :
ABC 12 55.5
Add more? (Y/n): y
Give product name, amount and weight :
SSD 33 43.2
Add more? (Y/n): n
Product display:
ABC - 12 , 55.5 kg
------------------------
SSD - 33 , 43.2 kg
------------------------
Example 2
You can do the same thing just with few modifications, but having static number isn't considered dynamic. You can use arrays for your program as stated below.
Rather than:
string name;
int n, amount;
float weight;
Consider const int MAX = 1024; and use (class variables must be visible only inner the class and nowhere else):
private: // declare on top of the class ("private:" is by default and redundant)
string name[MAX];
int n, amount[MAX];
float weight[MAX];
Edited & working example class:
void get()
{
for (int i = 0; i < n; i++)
{
cout << "Give product name,amount and weight : " << endl;
cin >> name[i] >> amount[i] >> weight[i];
}
}
void print()
{
cout << "\nProduct display:\n"
<< endl;
for (int i = 0; i < n; i++)
{
cout << name[i] << " - " << amount[i] << " , " << weight[i] << " kg" << endl;
cout << "------------------------" << endl;
}
}
Sample Output
Give the number of products you want to get at Market :
2
Give product name,amount and weight :
ABC 25 102
Give product name,amount and weight :
BDE 22 333
Product display:
ABC - 25 , 102 kg
------------------------
BDE - 22 , 333 kg
------------------------
I'm new to coding. I wrote the below code in C++ and I am not allow to use array.
You will create a console C++ program that uses a nested loop to enter each archer's individual end scores and then displays the total score for each archer.
I am stuck at how to calculate the total end score:
#include <iomanip>
using namespace std;
int main()
{
int Rounds = 4;
int Archers = 3;
int endScore ;
int average;
for (int a = 1; a <= Archers ; a++)
{
cout << endl << "Number " << a << " score" << endl;
int tEndScore = 0 ;
for(int i=1; i <=Rounds ; i++)
{
cout << "Round " << i << " : " ;
cin >> endScore;
while(cin.fail())
{
cout << endl << "not enter an integer " << endl ;
cout << "Please enter an integer ";
cin >> endScore;
}
tEndScore += endScore;
}
cout << endl << "The total score for 4 ends of Archer Number " << a << " is " << tEndScore << endl;
average =(double) tEndScore/Rounds;
cout << setiosflags(ios::fixed) << setprecision(2) << endl << "The average score of 4 ends of Archer Number " << a << " is " << average << endl;
}
}
This is the result after running. It will only use the last value I entered as tEndScore:
You need to shift tEndScore =+ endScore; this line inside the second for loop as
for(int i=1; i <=Rounds ; i++)
{
...
...
tEndScore += endScore;
}
And it will be a good practice (And mandatory for your code...) to initialize the tEndScore for each player as
for (int a = 1; a <= Archers ; a++)
{
tEndScore = 0;
endScore = 0;
average = 0;
...
...
}
You need to replace totalEndScore to tEndScore and totalRounds to Rounds.
Does anybody have a simple solution to terminate a for loop that inputs values for a vector when a specific value is placed into the vector, but does not store that specified value into the vector?
I have created a random number generator that creates "n" unique values for a vector of size "n". However, when I run my code, the word "done" pops up and the program crashes.
Here is the code:
int main()
{
int i = 0;
vector<int> playerIndex;
vector<int> randGenNum;
vector<string> players;
vector<string> team1;
vector<string> team2;
vector<string> team3;
vector<string> team4;
cout << "Welcome to the Team Selector. \n" << endl;
cout << "A random team of two will be generated for you all." << endl;
cout << "When you are finished entering player names, enter the word \"done\". " << endl;
cout << "Enter the name of the players: \n" << endl;
for(string name; cin >> name;){
players.push_back(name);
if(name == "done"){
players.erase(players.end() - 1);
break;
}else{
playerIndex.push_back(i);
i++;
}
}
cout << "\n";
cout << "Player names: \n";
for(int a=0; a < players.size(); a++){
cout << a + 1 << " - " << players[a] << endl;
}
srand(time(0));
int b =0;
int randNum;
while(b < players.size()){
randNum = 1 +(rand()%players.size());
if(find(randGenNum.begin(), randGenNum.end(), randNum)!= randGenNum.end()){
while(find(randGenNum.begin(), randGenNum.end(), randNum)!= randGenNum.end()){
randNum = 1 +(rand()%players.size());
}
randGenNum.push_back(randNum);
b++;
}else{
randGenNum.push_back(randNum);
b++;
}
}
cout << "\n" <<"This is a test" << endl;
for (int c=0; c < players.size(); c++){
cout << "Generated #: " << randGenNum[c] << endl;
}
int totalPlayers = players.size();
int firstPlayer = randGenNum[0];
int secondPlayer = randGenNum[1];
int thirdPlayer = randGenNum[2];
int fourthPlayer = randGenNum[3];
int fifthPlayer = randGenNum[4];
cout << "\n";
cout << "Team 1 is: " << players[firstPlayer] << " and "<< players[secondPlayer] << "\n" << endl;
cout << "Team 2 is: " << players[thirdPlayer] << " and " << players[fourthPlayer] << "\n" << endl;
return 0;
}
Problem
players.end() - 1 is not a valid iterator.
Solutions 1:
Check the item before adding it to the vector.
for(string name; cin >> name;) {
if(name != "done")
{
players.push_back(name);
playerIndex.push_back(i);
i++;
}
}
Solutions 2:
Use std::vector::pop_back().
for(string name; cin >> name;){
players.push_back(name);
if(name == "done"){
players.pop_back();
break;
}else{
playerIndex.push_back(i);
i++;
}
}