This program outputs terms in a Jugglers Series based on user input of first term, number of terms to calculate and terms per line
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
//prototype
int ValidateInput (string Prompt);
int main()
{
//local variables
long long int firstTerm;
int termsToCalc;
int termsPerLine;
int count;
//tells user what program does
cout << "Program will determine the terms in a Juggler Series" << endl << endl;
//calls user function to read in the frist term
firstTerm = ValidateInput ("Enter the first term: ");
cout << endl;
//calls user function to read in the number of terms to calculate (after the first)
termsToCalc = ValidateInput ("Enter the number of terms to calculate (after the first): ");
cout << endl;
//calls user function to read in the number of terms to display per line
termsPerLine = ValidateInput ("Enter the terms to display per line: ");
cout << endl;
cout << "First " << termsToCalc << " terms of Juggler series starting with " << firstTerm << endl << endl;
count = 1;
do
{
if ((count % termsPerLine) == 0)
{
cout << "\n";
}
//the term is even take it to the power of 1/2 and increase the count 1
if (firstTerm % 2 == 0 )
{
firstTerm = pow(firstTerm , 0.5);
cout << setw(16) << firstTerm << endl;
count++;
}
//the term is odd take it to the power of 3/2, and increase the count 1
else
{
firstTerm = pow(firstTerm, 1.5);
cout << setw(16) << firstTerm << endl;
count++;
}
}
//continue looping until the terms to calculate is no longer less than or
// equal to the count
while (count <= termsToCalc);
return 0;
}
int ValidateInput (string Prompt)
{
//local variable
int number;
//prompts user for first term, and reads in number
cout << Prompt;
cin >> number;
//user input must be positive, a while loop will check user input and
//continue to check until the term is positive.
while (number <=0)
{
cout << "Error - Enter a positive number" << endl;
cin >> number;
}
//returns number to main function
return number;
}
This is the current printout
This is how I would like it to look
I can not figure out how to edit the output statement to make this display correctly
After removing the endls and moving the new line statement to the end I now get the correct print out but with an extra term
First of all, remove the endls from these:
cout << setw(16) << firstTerm << endl; // -> cout << setw(16) << firstTerm;
And perhaps move this part:
if ((count % termsPerLine) == 0)
{
cout << "\n";
}
to the end of the loop. So it becomes:
count = 0;
do {
if (firstTerm % 2 == 0 ) {
firstTerm = pow(firstTerm , 0.5);
cout << setw(16) << firstTerm;
} else {
firstTerm = pow(firstTerm, 1.5);
cout << setw(16) << firstTerm;
}
if ( (count + 1) % termsPerLine == 0) {
cout << "\n";
}
count++;
} while (count < termsToCalc);
Related
So I've been reading a C++ Primer that has all kinds of examples and test scenarios inside that are good to make sure each new chapter has been correctly learnt and that there's no other way to improve that actually coding.
The C++ Primer asked for this "Practice Problem" to be attempted and is as follows:
Write a program that provides the option of tallying up the results of a poll with 3 possible values. The first input to the program is the poll question; the next three inputs are the possible answers. The first answer is indicated by 1, the second by 2, the third by 3. The answers are tallied until a 0 is entered. The program should then show the results of the poll—try making a bar graph that shows the results properly scaled to fit on your screen no matter how many results were entered.
So I was curious as to how the author wanted me to make sure that the results fit the screen resolution regardless of "how many results were entered" and after entering the main syntax for the loops that input the data and display. I was curious what the best way to go about this and slapped together a very, VERY simple work around that'll divide by a 1:10 ratio dependant on the highest result input (up to 1000/100)
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Variable decleration
string Question;
int tally1 = 0, tally2 = 0, tally3 = 0;
int input = 1;
int resultRatio;
//Question input and text fluff
cout << "Please enter a poll that has 3 answers: ";
getline(cin, Question, '?');
cout << "Your question is: " << Question << "?" << endl;
cout << "When results are complete for specified poll answer, enter 0 to input results" << endl;
while (1) //Tally 1 answer input.
{
cout << "Please enter the tallies for answer A: ";
cin >> input;
tally1 = tally1 + input;
if (input != 0)
{
cout << "A's current tallies: " << tally1 << endl;
continue;
}
cout << endl;
break;
}
while (1) //Tally 2 answer input.
{
cout << "Please enter the tallies for answer B: ";
cin >> input;
tally2 = tally2 + input;
if (input != 0)
{
cout << "B's current tallies: " << tally2 << endl;
continue;
}
cout << endl;
break;
}
while (1) //Tally 3 answer input.
{
cout << "Please enter tallies for answer C: ";
cin >> input;
tally3 = tally3 + input;
if (input != 0)
{
cout << "C's current tallies: " << tally3 << endl;
continue;
}
cout << endl;
break;
}
// Ratio in which total tallies should be divded by before bar chart display
if (tally1 >= 10 || tally2 >= 10 || tally3 >= 10)
{
resultRatio = 10;
}
else if (tally1 >= 100 || tally2 >= 100 || tally3 >= 100)
{
resultRatio = 100;
}
else if (tally1 >= 1000 || tally2 >= 1000 || tally3 >= 1000)
{
resultRatio = 1000;
}
else
{
resultRatio = 1;
}
//Simple bar chart to display all the results in a ratio that'll fit the screen thanks to resultRatio division
cout << "All results have been entered, here is the barchart (Results displayed are divided by " << resultRatio <<"):";
cout << endl << "A:" << "(" << tally1 << "votes )";
for (int i = tally1 / resultRatio; i > 0; i--)
{
cout << "o";
}
cout << endl << "B:" << "(" << tally2 << "votes )";
for (int i = tally2 / resultRatio; i > 0; i--)
{
cout << "o";
}
cout << endl << "C:" << "(" << tally3 << "votes )";
for (int i = tally3 / resultRatio; i > 0; i--)
{
cout << "o";
}
cout << "\nHere is the full bar graph on input results";
return 0;
}
I was trying to figure out this task, but so far have been unsuccessful. I think I understand the logic behind it, I just don’t know how to nest loops so it works (if that makes sense). I would very much appreciate your help!
Task:
"Create an application in which a user enters full numbers until they enter number 0 (zero). The application should print out how many even numbers have been entered, how many odd numbers, sum of even numbers and sum of odd numbers, and total sum of numbers."
my code so far:
#include <iostream>
using namespace std;
void main() {
do {
int input1;
cout << "Type in a number";
cin >> input1;
} while (input1 != 0);
cout << "Type in a number";
cin >> input1;
if (input1 % 2 == 0)
{
int even = 0;
while (input1 % 2 == 0 )
cout << even;
even++;
}
else
{
int odd = 0;
while (odd != 0)
{
cout << odd;
odd++;
}
}
}
system("pause");
}
Note: I did not try to do the third part of the task, since the second one won't work :/ I figured out first part, and I did it with do while loop. Thanks again.
Try this:
int oddCount = 0;
int evenCount = 0;
int oddSum = 0;
int evenSum = 0;
int in;
do
{
std::cout << "Type in a number:";
std::cin >> in;
if (0 == in)
break;
if ( in % 2 == 0 )
{
evenCount++;
evenSum += in;
}
else
{
oddCount++;
oddSum += in;
}
} while ( true );
std::cout << "Odd count: " << oddCount << std::endl;
std::cout << "Even count: " << evenCount << std::endl;
std::cout << "Odd sum: " << oddSum << std::endl;
std::cout << "Even sum: " << evenSum << std::endl;
std::cout << "Total sum: " << oddSum + evenSum << std::endl;
Take a look at this piece of code:
#include <iostream>
using namespace std;
int main() {
int input;
int total_sum = 0, odd_sum = 0, even_sum = 0;
int odd_count = 0, even_count = 0;
do {
cout << "Type in a number: ";
cin >> input;
total_sum += input;
if (input % 2 == 0)
{
even_count++;
even_sum += input;
}
else
{
odd_count++;
odd_sum += input;
}
} while (input != 0);
cout << "Total Sum: " << total_sum << endl;
cout << "Even sum: " << even_sum << endl;
cout << "Odd sum: " << odd_sum << endl;
cout << "Even Count: " << even_count << endl;
cout << "Odd Count: " << odd_count << endl;
return 0;
}
See how input is declared outside of the loop. if it was inside it, then you essentially create it each time you enter the loop. that would be fine if you did not want to use its values outside of the loop (like in the loops condition).
Also, notice that the values you need to calculate can be updated within that same loop.
I am working on a project that involves creating a menu screen, and integrating three programs into one that can be selectively launched from the menu screen.
I thought making individual programs first before piecing them together with switch case and functions would be easy (I don't know class/objects). I keep running into a brick wall and a host of syntax/logical errors, so I deleted everything and now I'm back to square one-- with three distinct programs. This is very daunting-- how do proceed? :/
#include <iostream>
using namespace std;
int main ()
{
int x;
cout << "Enter the amount of money you have ";
cin >> x;
if (x >= 20) {
cout << "You can buy Comic Book $1 or Sports Journal $3 or Science Book $15 or Third Volume Series $20";
} else if (x >= 15 && x < 20) {
cout << "You can buy Comic Book $1 or Sports Journal $3 or Science book $15";
} else if (x >= 3 && x < 15) {
cout << "You can buy Comic Book $1 or Sports Journal $3";
} else if (x >= 1 && x < 3) {
cout << "You can buy Comic Book $1";
} else if (x <= 0) {
cout << "You cannot afford anything";
}
return 0;
}
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
int numclass; //number of classes
int numStudents; //number of students
int numTests; // Number of tests per student
double sectiontotal; //Accumulator for Class total scores
double total; // Accumulator for total scores
double average; //Average test score
double totalaverage = 0;
ofstream outfile;
outfile.open("Gradesinfo.txt");
// Set up numeric output formatting.
cout << fixed << showpoint << setprecision(1);
// Get the number of students.
cout << "This program gives average of test scores per student, per class, and for the whole institution for upto 2 students in upto 2 different classes in 3 subjects\n";
// Determine each student's average score.
cout << "Enter the number of classes";
cin >> numclass;
cout << "Enter the number of students per class";
cin >> numStudents;
cout << "Enter the number of tests";
cin >> numTests;
for (int section = 1; section <= numclass; section++) {
sectiontotal = 0; //Initialize class accumulator
totalaverage = 0;
for (int student = 1; student <= numStudents; student++) {
total = 0; // Initialize the accumulator.
for (int test = 1; test <= numTests; test++) {
double score;
cout << "Enter score " << test << " for ";
cout << "student " << student << ": ";
cin >> score;
if (score >= 0 && score <= 100) {
total += score;
} else {
cout << "Enter value from 1 - 100" << endl;
test = test - 1;
}
}
average = total / numTests;
totalaverage += average;
cout << "The average score for student " << student;
cout << " is " << average << ".\n\n";
outfile << "The average score for student " << student;
outfile << " is " << average << ".\n\n";
}
cout << "The total average for class " << section << " is: " << totalaverage / numStudents << endl;
outfile << "The total average for class " << section << " is: " << totalaverage / numStudents << endl;
sectiontotal += totalaverage;
}
cout << "The total average for the institution is: " << sectiontotal / numclass;
outfile << "The total average for the institution is: " << sectiontotal / numclass;
outfile.close();
return 0;
}
#include<cstdlib>
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream instream;
ofstream outstream;
instream.open("Grades.txt");
if (instream.fail()) {
cout << "The input file failed to open\n";
exit(1);
}
int next, largest, smallest;
largest = 0;
smallest = 0;
while (instream >> next) {
if (largest < next) {
largest = next;
} else {
smallest = next;
}
}
cout << "The highest grade is: " << largest << endl;
instream.close();
system("pause");
return 0;
}
I think you are shooting yourself on the foot. go 1 step after the other, please do take this as reference:
create a main file as entry point for the app, note the prototype and implementation of the functions printA and printB
#include <iostream>
using namespace std;
void printA();
void printB();
int main()
{
int x = 1;
cout << "Enter the option:\n";
while (cin >> x)
{
if (x <= 0)
{
break;
}
switch (x) {
case 1:
printA();
break;
case 2:
printB();
break;
default:
cout << "Invalid";
}
}
return 0;
}
void printB()
{
cout << "B";
}
void printA()
{
cout << "A";
}
create a new file fooA.cpp and paste there the implemented function printA
do the same for the printB in another file.
remove those implementations from main.cpp
you are done!
After the user is prompted to make a selection and they enter 3 they are then asked to enter a name from a list given. If they enter a name that is not on the list the program needs to output a statement saying that the name entered is not on the list
The program ends up breaking on Line 105 when an element that is not inside the array is entered.
I have tried everything I could think of and the program works fine if I remove the error trapping.
The issue is inside the int SpecTime function
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
double FastSkier(double [], string[], int); //Function for finding fastest skier
double AvgTime(double[], int); //Function for finding Average
int SpecTime(double[], string[], int); //Function for finding the time of the name entered
int SkiAndTime(double[], string[], int); //Function to list all Skiers and their times
int main()
{
const int Size = 5; //size of arrays
string name[Size] = { "Leela" , "Sarah" , "Anna" , "Keesha" , "Heidi" }; //array for Skier names
double time[Size] = { 2.03 , 2.40 , 1.85 , 1.90 , 2.50 }; //array for Skier times
int choice;
for (int count = 1;; count++)
{
cout << "Enter 1 to find the fastest Skier" << endl;
cout << "Enter 2 for the average time of the Skiers" << endl;
cout << "Enter 3 to find the time of a specific Skier \n";
cout << "Enter 4 to display all Skiers and their times \n";
cout << "Enter any other number to end the program \n";
cout << "\n";
cin >> choice;
if (choice == 1)
FastSkier(time, name, Size);
else if (choice == 2)
AvgTime(time, Size);
else if (choice == 3)
SpecTime(time, name, Size);
else if (choice == 4)
SkiAndTime(time, name, Size);
else
return 0;
}
system ("pause");
return 0;
}
double FastSkier(double time[], string name[], int Size)
{
int Loc; //location of data within array, value determined by for-loop
int count; //Counter
double fastest=time[0]; //variable to find fastest time for Skier, initialized at first value of time
for (count = 1; count < Size; count++) //cycles through all values of time comparing each one to find the lowest value
{
if (time[count] < fastest)
Loc = count-1; //subtract 1 from count to adjust for array index
}
cout << "\n";
cout << "The fastest Skier is " << name[Loc] << " with a time of " << fixed << setprecision(2) << time[Loc] << endl;
cout << "\n";
return 0;
}
double AvgTime(double time[], int Size)
{
int Loc; //location of data within array, acts as a counter in this function
double Avg; //Average
double sum = 0; //sum of all values within time[]
for (Loc = 0; Loc < Size; Loc++)
sum += time[Loc];
Avg = sum / Size;
cout << "\n";
cout << "The average time for Skiers is " << fixed << setprecision(2) << Avg << endl;
cout << "\n";
cout << "\n";
return 0;
}
int SpecTime(double time[], string name[], int Size)
{
string Skier; //Name of Skier entered by user
int Loc=0;
bool List = true;
cout << "Skiers \n";
for (int Loc = 0; Loc < Size; Loc++) //For-loop used to output and display all names of Skiers
{
cout << " " << name[Loc] << endl;
}
cout << "Enter the name of the Skier to view their time \n";
cin >> Skier;
for (int Loc = 0;; Loc++) //For-loop used to find the desired Skier's time
{
cout << Loc << " beginning of loop" << endl;
if (Skier == name[Loc])
{
cout << Loc << " in correct" << endl;
cout << Skier << " has the time " << fixed << setprecision(2) << time[Loc] << endl;
cout << "\n";
break;
}
if(Loc = Size)
{
cout << Loc << " in error" << endl;
cout << "The name you entered is not a current competitor in this competition \n";
cout << "\n";
break;
}
cout << Loc << " end of loop" << endl;
}
/*if (Skier != name[Loc]) //error trap for inputted names that are not listed
{
cout << "The name you entered is not a current competitor in this competition \n";
cout << "\n";
//break;
}*/
return 0;
}
int SkiAndTime(double time[], string name[], int Size)
{
cout << "Skiers Times" << endl;
cout << "\n";
for (int All = 0; All< Size; All++)
cout << name[All] << " " << fixed << setprecision(2) << time[All] << endl;
cout << "\n";
return 0;
}
One error is this:
if(Loc = Size)
This should be:
if(Loc == Size)
The second error is this:
if (Skier == name[Loc])
On the last iteration of the loop, Loc goes beyond the bounds of your array. Since you are checking this condition first, the value of Loc has already gone past the last entry.
Also, why are you writing a loop for this that has no stop condition defined in the for? It should be simply:
for (int Loc = 0; Loc < Size; Loc++)
or this:
bool found = false;
for (int Loc = 0; Loc < Size && !found; Loc++)
Then the entire loop is much simpler:
bool found = false;
for (int Loc = 0; Loc < Size && !found; Loc++) //For-loop used to find the desired Skier's time
{
cout << Loc << " beginning of loop" << endl;
if (Skier == name[Loc])
{
cout << Loc << " in correct" << endl;
cout << Skier << " has the time " << fixed << setprecision(2) << time[Loc] << endl;
cout << "\n";
found = true;
}
}
if ( !found )
{
cout << Loc << " in error" << endl;
cout << "The name you entered is not a current competitor in this competition \n";
cout << "\n";
}
Notice that there is no longer a break statement in the loop. The reason is that the found flag is set to true, and the loop condition includes a check for this flag.
In reality, there is no need for this loop at all. The std::find function takes care of this:
#include <algorithm>
//...
string* ptrSkier = std::find(name, name + Size, Skier);
if ( ptrSkier == &name[Size] )
{
// not found
}
else
{
// found the name
// the ptrSkier points to the skier found
// to get the position of the found name:
size_t Loc = std::distance(name, ptrSkier);
// rest of code here using Loc
//...
}
First: what PaulMcKenzie said.
Second: Your check for a valid competitor is incorrect. The fact that a single entry doesn't match the given name doesn't mean the name isn't somewhere else in the list.
You need to search the entire list for the name given, and only then decide if it's there or not. Start with a boolean variable, name_found, initially set to false. Then iterate through all names, and mark it true if you find the right one. Only when you get to the end of looping, and find that name_found is still false, can you conclude that the given name isn't there.
I was wanting to get some tips on how to get my program to output a desired number of columns by the user. For example, if the user enters 2 for termsPerLine, then the program should print the values generated by the Juggler series in two columns, or if the user enters 3 for termsPerLine, 3 columns and so forth. The output variable is firstTerm. Any assistance would be great.
#include <string>
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int ValidateInput(string Prompt);
int main()
{
int count;
double Odd;
double Even;
long long int firstTerm;
int noOfTerms;
int termsPerLine;
cout << "Program will determine the terms in a Juggler Series" << endl << endl;
firstTerm = ValidateInput("Enter the first term: ");
noOfTerms = ValidateInput("Enter the number of terms to calculate (after first): ");
termsPerLine = ValidateInput("Enter the terms to display per line: ");
cout << "First " << noOfTerms << " terms of JUGGLER SERIES starting with " << firstTerm << endl;
count = 1;
do
{
if (firstTerm % 2 == 0 )
{
firstTerm = pow(firstTerm , 0.5);
cout << setw(16) << firstTerm << endl;
count++;
}
if (firstTerm % 2 != 0 )
{
firstTerm = pow(firstTerm, 1.5);
cout << setw(16) << firstTerm << endl;
count++;
}
}
while (count <= noOfTerms);
cout << endl;
system("Pause");
return 0;
}
int ValidateInput( string Prompt)
{
int num;
cout << Prompt << endl;
cin >> num;
while ( num <= 0 )
{
cout << "Enter a positive number" << endl;
cin >> num;
}
return num;
}
Try this at the top of the loop:
if ((count % termsPerLine) == 0)
{
cout << "\n";
}
or this at the bottom of the loop:
if ((count % termsPerLine) == termsPerLine)
{
cout << "\n";
}
just Fix your loop as:
for (count = 1; count <= numOfTerm; count++)
{
if(firstTerm % 2 == 0)
firstTerm = pow(firstTerm, 0.5);
else
firstTerm = pow(firstTerm, 1.5);
if(count % termPerLine != 0)
cout << setw(15) << firstTerm;
else
cout << setw(15) << firstTerm << endl;
};