I'm a freshman college CS student, and I can't seem to figure this problem out. It basically wants me to ask the user for the amount of students in a particular class, and then continuously loop asking for the students names. After all that is done, I have to find out which name that was entered will be first, alphabetically, and which name will be last, alphabetically.
My code so far does everything up until I have to sort through the names, as well as displaying the names incorrectly. It only displays the latest name entered, not both names at once.
#include <iostream>
#include <string>
using namespace std;
int main () {
int studentCount;
string studentName;
cout << "Hello fellow educator!" << endl;
cout << "I will be helping you with your line-up for today." << endl;
cout << "Please enter the number of students in your class: ";
cin >> studentCount;
cout << endl;
cout << endl;
if (studentCount < 1 || studentCount > 25) {
cout << "Please try again." << endl;
cout << "Try putting in a number between 1 and 25." << endl;
cout << endl;
}
for (int count = 1; count <= studentCount; count++) {
cout << "Please enter a student's name: ";
cin >> studentName;
}
cout << "the names are " << studentName; // Just testing the string
return 0;
}
As you collect names, Store the names in a data structure.If you keep adding all names to a single string, then, it can be stored as one concatenated string but we want different names(strings).
So, Lets take vector as our datastructure.
int main () {
int studentCount;
string studentName;
vector<string> attendanceBook;
for (int count = 1; count <= studentCount; count++) {
cout << "Please enter a student's name: ";
studentName.clear();
cin >> studentName;
attendanceBook.push_back(studentName);
}
std::sort(attendanceBook.begin(),attendanceBook.end());
cout<<"First: "<<name.front<<endl<<"Last: "<<name.back();
So this is the completed code, after hours of work, and it runs and does everything properly. It's simple, I know, but to a college freshman only having been exposed to the surface of Java, this is complicated to me. :) I knew there was a way of doing this without vectors or arrays.. Thanks to everyone who tried their best to help me. I'll be sure to come back in the future.
#include <iostream>
#include <string>
using namespace std;
int main () {
int studentCount;
string studentNames;
string first;
string last;
cout << "Hello fellow educator!" << endl;
cout << "I will be helping you with your line-up for today." << endl;
cout << "Please enter the number of students in your class: ";
cin >> studentCount;
cout << endl;
cout << endl;
while (studentCount < 1 || studentCount > 25) {
cout << "Please try again." << endl;
cout << "Try putting in a number between 1 and 25: ";
cin >> studentCount;
}
for (int count = 0; count < studentCount; count++) {
cout << "Please enter the name for student number " << count + 1 << ":";
cin >> studentNames;
if (count == 1) {
first = studentNames;
last = studentNames;
}
else {
if (studentNames < first) {
first = studentNames;
}
else if (studentNames > last) {
last = studentNames;
}
}
}
cout << "The first student in line is " << first << "." << endl;
cout << "The last student in line is " << last << "." << endl;
return 0;
}
First, you need to make an array of string instead of a single string to avoid overwriting.
After that, sort them lexicographically and print them.
EDIT:
Have a look at the code given below:
#include <iostream>
#include <string>
#include <algorithm> /* Used to sort the string lexicographically */
#define LIMIT 50 /* I'm considering that you are not providing more than 50
names at once to a program*/
using namespace std;
int main () {
int studentCount; /* Count number of the students */
string studentName[LIMIT]; /* Array of string */
cin >> studentCount; /* Input number of student */
/* Keep on asking until the correct value of studentCount is not provided */
while (studentCount < 1 || studentCount > 25) {
cout << "Please try again." << endl;
cout << "Try putting in a number between 1 and 25." << endl;
cin >> studentCount;
}
cout <<"Please enter a student's name: ";
for (int count = 0; count < studentCount; count++) {
cin >> studentName[count]; /* I started the count value from 0 to n-1
because the index of an array starts from 0 */
}
/* Now, time to sort the array of string lexicographically */
sort(studentName, studentName+studentCount);
/* Print the names of the student */
cout << "Names of the students : " << endl;
for(int i=0; i< studentCount; i++) {
cout << studentName[i] << endl;
}
return 0;
}
This code will keep on asking until correct value of studentCount is not received. You can even change the upper limit of the program by changing the value of LIMIT from 50 to something else you may need.
Related
So I am fairly new to 2d arrays in c++ and I know im doing something wrong but im not sure what.
#include <iostream>
using namespace std;
int main(){
string favBands[10][2];
cout << "Welcome to the favorite band printer outer!" << endl;
int count = 1;
string band;
string song;
for(int i = 0; i < 10; i++){
for(int j = 1; j < 2; j++){
cout << "Enter your number " << count << " band:\n" << endl;
count += 1;
cin >> band;
favBands[i][j] = band;
cout << "Enter " << favBands[i][j] << "'s best song:\n" << endl;
cin >> song;
favBands[i][j] = song;
}
}
}
I want to ask the user to enter their 10 favorite bands and then ask for their favorite song from that band in a pair. So for example:
Enter your number 1 favorite band:
Black Eyed Peas (user input)
Enter your favorite Black Eyed Peas song:
Boom Boom Pow (user input)
I am able to do all of this but the problem comes when I try to print the array to the user. I think my problem may lie in how i input the user data into my array but im not sure how to fix it. Thanks!
You will only need one for loop. see we are storing data for 10 users. and for every user we are taking two data at index 0 and index 1. So we don't need second for loop. please observe code and ask if you still have any confusion. I will be happy to figure it out as well.
#include <iostream>
using namespace std;
int main(){
string favBands[10][2];
cout << "Welcome to the favorite band printer outer!" << endl;
int count = 1;
string band;
string song;
for(int i = 0; i < 10; i++)
{
cout << "Enter your number " << count << " band:\n" << endl;
count += 1;
cin >> band;
favBands[i][0] = band;
cout << "Enter " << favBands[i][0] << "'s best song:\n" << endl;
cin >> song;
favBands[i][1] = song;
}
}
Allow me to suggest using two separate arrays instead of a 2D array, one for bands and one for songs, and then cout'ing the song, like so:
#include <iostream>
using namespace std;
int main() {
string favBands[10];
string favSongs[10];
cout << "Welcome to the favorite band printer outer!" << endl;
int count = 1;
string band;
string song;
for (int i = 0; i < 10; i++) {
cout << "Enter your number " << count << " band:\n" << endl;
count += 1;
cin >> band;
favBands[i] = band;
cout << "Enter " << favBands[i] << "'s best song:\n" << endl;
cin >> song;
favSongs[i] = song;
cout << "Your favorite song by " << favBands[i] << " is " << favSongs[i] << ".\n";
}
}
Although both bands and songs are strings, 2D arrays aren't really best suited for this type of problem.
So i am still a beginner at this and still practising. Basically i need to make a program that continues to asks the user to enter any number other than 5 until the user enters the number 5.
I have that done but i could't figure out how to check if the user entered a repeating number.For example:
1
2
3
3 - The program should end
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main() {
cout << setw(15) << setfill('*') << "*" << endl;
cout << "Number 5" << endl;
cout << setw(15) << setfill('*') << "*" << endl;
int num;
cout << "Enter a number: ";
cin >> num;
if (num == 5) {
cout << "\nWhy did you enter 5? :) " << endl;
_getch();
exit(0);
}
for (int i = 1; i < 10;i++) {
cin >> num;
if (num == 5) {
cout << "\nWhy did you enter 5? :) " << endl;
_getch();
exit(0);
}
}
cout << "Wow, you're more patient then I am, you win." << endl;
_getch();
}
The previous answer does not meet the requirement in the linked article, which the querist himself seemed to not grasp:
★★ Modify the program so that it asks the user to enter any number other than the number equal to the number of times they've been asked to enter a number. (i.e on the first iteration "Please enter any number other than 0" and on the second iteration "Please enter any number other than 1"m etc. etc. The program must behave accordingly exiting when the user enters the number they were asked not to.)
This variant complies:
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 10; i++)
{
cout <<"Please enter any number other than " <<i <<": ";
int num;
cin >>num;
if (num == i)
return cout <<"Hey! you weren't supposed to enter " <<i <<"!\n", 0;
}
cout <<"Wow, you're more patient then I am, you win.\n";
}
You could add all inputted numbers to a vector, and whenever you get a new number, check if it's already in the vector. Include these headers:
#include <vector>
#include <algorithm> // for std::find
Make the vector like this
std::vector<int> pastEntries;
Do the check like this:
if (std::find(pastEntries.begin(), pastEntries.end(), num) != pastEntries.end()) {
std::cout << "\nWhy did you enter " << num << "? :) " << endl;
...
And when the number was not found, add it to the vector like this (you can put this after the if block):
pastEntries.push_back(num);
Alternatively, you can use std::set:
std::set<int> pastEntries;
Insert into the set like this:
pastEntries.insert(num);
And find the number in the set like this:
if (pastEntries.find(num) != pastEntries.end()) {
Or insert the number while finding out whether it has already been inserted like this:
if (!pastEntries.insert(num).second) {
Question:
Create a program that first asks the user to enter the number of items he/she has eaten today and then to enter the number of calories for each item. It then calculates the number of calories he/she has eaten for the day and displays the value.
#include <iostream>
using namespace std;
int main()
{
int numberOfItems;
int count; // loop counter for the loop
int caloriesForItem;
int totalCalories;
cout << "How many items did you eat today? ";
cin >> numberOfItems;
cout << "Enter the number of calories in each of the " << numberOfItems << " items eaten:" >> endl;
while (caloriesForItem)
{
cout << "Please enter item calories:";
cin >>caloriesForItem;
count == numberOfItems;
}
cout << "Total calories eaten today = " << totalCalories;
return 0;
}
In the end I'm not sure how I would make it read and calculate as it says it must be a while loop.
You have all of your pieces already. You have a count for your loop, a totalCalories tracker, and a variable to hold the current items caloriesForItem. Every iteration of your loop must increase the count, and every iteration must retrieve a new value for caloriesForItem. You can add this each time to totalCalories.
#include <iostream>
using namespace std;
int main()
{
int numberOfItems;
int caloriesForItem;
// These two variables need to have a start value
int count = 0;
int totalCalories = 0;
cout << "How many items did you eat today? ";
cin >> numberOfItems;
cout << "Enter the number of calories in each of the " << numberOfItems << " items eaten:" >> endl;
// Loop for as many times as you have items to enter
while (count < numberOfItems)
{
cout << "Please enter item calories:";
// Read in next value
cin >> caloriesForItem;
// Add new value to total
totalCalories += caloriesForItem;
// Increase count so you know how many items you have processed.
count++;
}
cout << "Total calories eaten today = " << totalCalories;
return 0;
}
You were pretty close though.
(I added comments in the appropriate places to explain whats going on.)
Lastly I want to add that you pretty much can convert any for loop to a while loop using this themplate:
for( <init_var>; <condition>; <step> ) {
// code
}
becomes
<init_var>;
while( <condition> ) {
// code
<step>;
}
Example:
for(int i = 0; i < 10 i++) {
cout << i << endl;
}
becomes
int i = 0;
while(i < 10) {
cout << i << endl;
i++;
}
Take a look at this code:
#include <iostream>
using namespace std;
int main()
{
int numberOfItems, caloriesForItem, totalCalories=0;
cout << "How many items did you eat today? ";
cin >> numberOfItems;
cout << "Enter the number of calories in each of the " << numberOfItems << " items eaten:" << endl;
while (numberOfItems--)
{
cout << "Please enter item calories:";
cin >> caloriesForItem;
totalCalories += caloriesForItem;
}
cout << "Total calories eaten today = " << totalCalories;
return 0;
}
It's a sufficient way to do what you wanted, if you don't understand, let me know!
I made this program that asks users to enter the grade of some students, determine whether they pass or fail and then determine how many pass and how many fail the exam. Here's my code:
#include <iostream>
using namespace std;
int main ()
{
int passing = 0;
int failing = 0;
int mid_grade;
int final_grade;
int student = 5;
while (student > 0)
{
cout << "Enter mid-term grade: ";
cin >> mid_grade;
cout << "Enter final grade: ";
cin >> final_grade;
double total_grade = (double)mid_grade*3/10 + (double)final_grade*7/10;;
cout << "The total grade is: " << total_grade << endl;
student --;
if (mid_grade < 4 || final_grade < 4 || total_grade < 10)
{
// cout << "Fail." << endl;
failing++;
}
else
{
// cout << "Pass!" << endl;
passing++;
}
}
cout << passing << " student passed" << endl;
cout << failing << " student failed" << endl;
return 0;
}
what I want to do now is to tell my program to read the mid-term and the final grade in a text file I made then calculate the total grade (like I did in the above code), then show the grades on the screen, determine who pass and fail the exam and the total number of students who pass/fail the exam.
Here's what my text file looks like:
Mid-term Final
8 5
9 6
10 11
15 17
9 20
11 19
Alright so this should help. I put some notes. You need to create a text file in the same directory /src called grades.txt
should look like this
10 9 8 7 4 3 4 5 5 9
You will need to change things. But this should give you a good starting point or where you should be going. Hope this helps.
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
int passing = 0;
int failing = 0;
int mid_grade = 0; //Always initilize your variables!!!
int final_grade = 0;
int student = 5;
//Create a variable to open the file
ifstream inFile; inFile.open("src\\grades.txt");
while (student > 0)
{
cout << "Enter mid-term grade: ";
inFile >> mid_grade;
cout << mid_grade << endl;
cout << "Enter final grade: ";
inFile >> final_grade;
cout << final_grade << endl;
cout << "student number" << student << endl; //Notice it goes backwards you have to fix it.
double total_grade = ((double)mid_grade*3)/10 + ((double)final_grade*7/10);
cout << "The total grade is: " << total_grade << endl;
student --;
cout << endl;
if (total_grade < 7)
{
// cout << "Fail." << endl;
failing++;
}
else
{
// cout << "Pass!" << endl;
passing++;
}
}`enter code here`
cout << passing << " student penter code hereassed" << endl;
cout << failing << " student failed" << endl;
return 0;
}
I'd read the file, skip the 1st line, then read the rest, line by line, using stringtokenizer to get the two values to work with.
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
double Donor = 0.0;
int totalRaised = 0;
cout << "Enter amount donated by first donor [or -1 to stop]:" << endl;
cin >> Donor;
while (Donor != -1)
{
cout << "Enter amount donated by next donor [or -1 to stop]:" << endl;
cin >> Donor;
totalRaised = totalRaised + Donor;
}
cout << "Total amount of money raised: " << totalRaised << endl;
system("pause");
return 0;
}
This is my code and my goal is to have the user put the input in and when done enter in -1 and display the total amount enter from the user but my problem when I run this code I do not get the correct value. Could someone point me in the right direction and explain how to make the program run correctly. Thank you.
while (Donor != -1)
{
cout << "Enter amount donated by next donor [or -1 to stop]:" << endl;
totalRaised = totalRaised + Donor;
cin >> Donor;
}
see if it works.
you have to add the first input which was before the while loop and then go for the next input