Calories counting loop - c++

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!

Related

How to input data from user into 2d array and cout to user c++

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.

Finding sum of User Inputed Values

I need help adding up several user inputed values using C++
double total; // Accumulates total
double price; // Gets next price from user
int numItems; // Number of items
int counter = 1; // Loop control counter
cout << "How many items do you have? ";
cin >> numItems;
cout << endl;
while (counter <= numItems) {
total = 0;
cout << "Enter the price of item " << counter << ": ";
cin >> price;
cout << endl;
total += price;
counter++;
}
cout << "The total price is: " << total << endl;
When I run my code, I end up getting the sum of only one value from the user
Yes, just as Chetan Ranpariya said:
total = 0; should be before while loop.

Confusing C++ Assignment

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.

C++ while loops on my program

#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

C++ While loop and Array

I have made a application where you enter in all the marks and it gives you the average and also makes it repeat itself but the problem is that
1) when ever the 'Finding average' line is executed, it gives me the
wrong value and also I use array to do so.
2)When ever I try to
iterate the application, the destructor is called and messes up my
application
and here is my code
#include <iostream>
#include <string>
using namespace std;
class Grade{
private:
int* ptr;
int number;
public:
Grade(const int hNumber){
number = hNumber;
ptr = new int[this->number];
}
Grade(const Grade& cpy){
ptr = new int[cpy.number];
}
void get_marks(){
for(int i = 0; i < number; ++i){
cout << "Enter Mark " << i << ": ";
cin >> ptr[i];
}
}
const int& operator [](const int access) const{
return ptr[access];
}
~Grade(){
cout << "Deleting memory" << endl;
delete [] ptr;
}
};
int main(){
//local variables
int sum = 0;
string name,subject;
int repeat;
char again = 'y';
//user interface
cout << "Welcome to Grade Marker" << endl;
cout << "Enter your name: ";
getline(cin,name);
while(again == 'y'){
cout << "Enter the subject name: ";
getline(cin,subject);
cout << "How many marks are being entered: ";
cin >> repeat;
//creating instance of grade
Grade grd(repeat);
grd.get_marks();;
//display info
cout << "The average mark is: ";
for (int i = 0; i < repeat; i++){
sum = ((sum + grd[i]) / repeat);
}
cout << sum << endl;
//looping the application
cout << "Would you like to enter another subject[y/n]: ";
cin >> again;
}
//good bye message
if (again == 'n' || again == 'no'){
cout << "Goodbye" << endl;
}
system("pause");
return 0;
}
and just to make it simple, the code section which I think gives me error are
cout << "Would you like to enter another subject[y/n]: ";
cin >> again;
}
//good bye message
if (again == 'n' || again == 'no'){
cout << "Goodbye" << endl;
}
and
//display info
cout << "The average mark is: ";
for (int i = 0; i < repeat; i++){
sum = ((sum + grd[i]) / repeat);
}
cout << sum << endl;
and thank you for your time
You are doing integer division, and in addition you do not reinitialize sum to 0 for each iteration. You can move sum declaration inside of the loop and just write:
float sum = 0;
for (int i = 0; i < repeat; i++){
sum += grd[i];
}
cout << "The average mark is: ";
cout << sum / repeat << endl;
std::cin.ignore() will help you here.
Adding...
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
...to the very end of your while-loop will clear out the input buffer up to the newline... You'll find that this will end the seemingly infinite loop.
See How do I flush the cin buffer? for more info.
Your while loop is calling the destructor because of scope. You are declaring the Grade grd every iteration you run the while loop. That means that your grd from the previous iteration is being redeclared again and again, hence the destructor being called. But that's normal. Did you want to save the Grade instances? In that case you'll need to make an array of Grade objects