#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
Related
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'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.
I have a problem with my code, every time I loop it with the answer 'y'(Yes) it loops to infinity?
I'm trying to make a loan calculator and every time the user is done calculating with a transaction and wants to reset, and do another calculation if he enters in a value 'y', and if he enters 'n' the program will end.
Here's my code so far:
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
char ans = 'y';
do {
string name;
int Months;
int n;
double LoanAmount, Rate, MonthlyInterest, TotalLoanAmount, MonthlyAmortization, OutstandingBalance;
cout << fixed << showpoint;
cout << "Enter Name of Borrower: ";
getline(cin, name);
cout << "Enter Loan Amount: ";
cin >> LoanAmount;
cout << "Enter Number of Months to Pay: ";
cin >> Months;
cout << "Enter Interest Rate in Percent(%): ";
cin >> Rate;
cout << setprecision(2);
MonthlyInterest = LoanAmount * Rate;
TotalLoanAmount = LoanAmount + (MonthlyInterest * Months);
cout << "Monthly Interest: " << MonthlyInterest << endl
<< "Total Loan Amount with interest: " << TotalLoanAmount << endl;
cout << setw(100)
<< "\n\tSUMMARY OF OUTSTANDING INSTALLMENT" << endl
<< "\tName of Borrower: " << name
<< "\n\nMonth\t\tMonthly Amortization\t\tOutstanding Balance"
<< "\n";
for(n = 1; n <= Months; n++) {
MonthlyAmortization = TotalLoanAmount / Months;
OutstandingBalance = TotalLoanAmount - MonthlyAmortization;
cout << n << "\t\t" << MonthlyAmortization << "\t\t\t" << n - 1 << OutstandingBalance << endl;
}
cout << "\nEnd of Transaction";
cout << "Do you want to compute another transaction?[y/n]?" << endl;
cin >> ans;
}
while(ans == 'y');
}
After your cin>>ans, add these two lines :
cin.clear();
cin.sync();
That usually fixes a lot of the infinite looping problems I get with cin.
Also, I would recommend against initializing ans as 'y' when you declare it. I don't think this is causing you problems but it's an uncessesary thing.
You seem to expect pressing y and enter to register as only 'y'. If you want to get the input of just one character have a look at std::cin.get(char)
I am kinda new to C++, and I have encountered a problem in building a simple c++ addition calculator. Here is the code:
#include <iostream>
#include <string>
#include <climits>
using namespace std;
int main()
{
int number;
int total = 0;
int x = 0;
int z = 5;
cout << "Please enter the number you want to add" << endl;
while(x < 5 && z != 0){
cin >> number;
if (!cin){
cout << "Enter a valid number. " << "You have" << z << "tries left before this program terminate." << endl;
cin.clear();
z--;
}
else{
total = total + number;
x++;
}
}
cout << "The total number is " << total << endl;
return 0;
}
When I run the application and then I input a non-integer, it shows "you have _ tries left" altogether. How do I make the application so that it will give the user a chance to input a something?
One simple solution would be to add
std::string junk;
cin >> junk;
just after cin.clear(). This will extract the junk and put it in junk, and just skip over it.
You could use ignore(). I don't know how many junk characters you'll have, but you could try something like
cout << "Enter a valid number. " << "You have" << z << "tries left before this program terminate." << endl;
while (!cin.eof())
cin.ignore();
cin.clear();