Issue with C++ code - c++

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.

Related

Preventing the subtraction of two random integers from equaling a negative integer?

Simple mathgame.cpp.
case(2) is the subtraction of two random integers, but the **results cant be less than 0.
** I need 'subOp' to only hold the values of 'ranNum1' - 'ranNum2' when they equal >= 0
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
// Initialize random number generator.
srand(time(0));
// Declares variable as a random integer between 0-12
// int ranNum1 = rand() % 13;
// int ranNum2 = rand() % 13;
int menuChoice = 0;
int userAns=0;
// String variable for the game menu
string mathMenu =
"\n\n\tMATH GAME SELECTION\n\t-------------------\n\t1) Addition\n"
"\t2) Subtraction\n\t3) Multiplication\n\t4) -EXIT-\n";
// Answer responses
string cAns = "\n\tCORRECT ANSWER!" , wAns = "\n\tWRONG ANSWER!";
// While the user doesnt request to exit...
while (menuChoice != 4)
{
int ranNum1 = rand() % 13;
int ranNum2 = rand() % 13;
switch (menuChoice)
{
case (0):
break;
case (1): { int addOp = ranNum1 + ranNum2;
cout << "\tWhat is " << ranNum1 << " + " << ranNum2 << " = [?]\n \tYour answer: ";
cin >> userAns;
if (userAns == addOp) {
cout << cAns; }
else{
cout << wAns << "\n\tThe correct answer was " << addOp; }
break; }
case (2): { int subOp = ranNum1 - ranNum2;
do {
cout << "\tWhat is " << ranNum1 << " - " << ranNum2 << " = [?]\n\tYour answer: ";
cin >> userAns;
if (userAns == subOp) {
cout << cAns;
}
else {
cout << wAns << "\n\tThe correct answer was " << subOp;
}
} while (subOp < 0);
break; }
case (3):{ int multOp = ranNum1 * ranNum2;
cout << "\tWhat is " << ranNum1 << " x " << ranNum2 << " = [?]\n \tYour answer: ";
cin >> userAns;
if (userAns == multOp) {
cout << cAns; }
else {
cout << wAns << "\n\tThe correct answer was " << multOp; }
break; }
//Error message/ validator for integers between 1-4.
default: cout << "\t**Invalid menu selection** \n\a";
}
//Error message/ validator for input other than integer.
cout << mathMenu << endl << " Please Select An Option (1-4): ";
while (!(cin >> menuChoice)) {
cin.clear();
cin.ignore(1000, '\n');
cout << "Please ONLY select the given options (1-4): \a";
}
cout << endl;
}
system("pause");
return 0;
}
I've tried several different loops and bools. How do I loop through the equation until the results will only equal >0?
You can make a conditional statement to check whether the second value is greater than the first one. If so, then swap between them.
if (ranNum1 < ranNum2)
std::swap(ranNum1, ranNum2);
int subOp = ranNum1 - ranNum2;
Now, the value of ranNum1 is always greater than ranNum2.

Repeat checker goes back to menu even after entering N to input

The goal is to create a five-in-one program for various math stuff. The individual blocks work. After selecting and using a block, the program should then send a prompt asking the user whether to go back to the menu or terminate the program, this also works.
However, the function which checks whether you've inputted "Y", "y", "N", or "n" does not work. Instead, it automatically returns you to the main menu even after inputting "N" or "n", which should terminate the program.
#include <iostream>
#include<cctype>
#include<cstdlib>
#include <ctime>
#include <bits/stdc++.h>
using namespace std;
bool Primecheck(int x){
// checks if prime is positive or nah
if (x <= 1)
return false;
// Check from 2 to n-1
for (int i = 2; i < x; i++)
if (x % i == 0)
return false;
return true;
}
void Repeatcheck(char repeat){
//checks whether you inputted anything other than Y, y, N, or n
while (repeat != 'Y' && repeat != 'y' && repeat != 'N' && repeat != 'n' ){
system("cls");
std::cout << "that's not an option, dumbass." << std::endl;
std::cout << "\n Return to main menu? Y/N" << std::endl;
cin >> repeat;
}
}
int main()
{
//Option selection
int OptSel;
//repeat selection
char repeat;
repeat = 'Y';
//Optsel 1
int prime, i, primed2=0, flag=0;
//Optsel 2
int j,rows;
//Optsel 3
int t1 = 0, t2 = 1, nextTerm = 0;
//Optsel 4
int factorialinput;
long factorial = 1.0;
do{
system("cls");
repeat = 'Y';
startoptsel:
std::cout << "\n----MATHS PROGRAM----" << std::endl;
std::cout << "\n wats poppin?" << std::endl;
std::cout << "1.) prime number checker" << std::endl;
std::cout << "2.) right triangle drawer" << std::endl;
std::cout << "3.) fibonacci" << std::endl;
std::cout << "4.) factorial" << std::endl;
std::cout << "5.) exit" << std::endl;
std::cin >> OptSel;
//check whether option seleccted is available.
if (!std::cin || OptSel <= 0 || OptSel > 5) {
system("cls");
std::cin.clear();
std::cin.ignore(1000, '\n');
std::cout << "\nThat's not an option, dumbass." << std::endl;
std::cout << "\nInput numbers from 1-5." << std::endl;
goto startoptsel;
}
if (OptSel == 1) {
system("cls");
primechecker:
std::cout << "\n----Prime number checker----" << std::endl;
std::cout << "Enter number: " << std::endl;
std::cin >> prime;
// auto filters everything as not prime below 1
primed2=prime/2;
for(i = 2; i <= primed2; i++){
if(prime % i == 0)
{
cout << "\n " << prime << " is not a prime."<<endl;
flag=1;
break;
}
}
if (flag==0)
cout << "\n " << prime << " is a prime."<<endl;
if (!cin) {
system("cls");
std::cin.clear();
std::cin.ignore(1000, '\n');
std::cout << "please input a number" << std::endl;
goto primechecker;
}
std::cout << "\n Return to main menu? Y/N" << std::endl;
cin>>repeat;
Repeatcheck(repeat);
}
if (OptSel == 2) {
system("cls");
triangledrawer:
cout << "\n----RIGHT TRIANGLE DRAWER----" << std::endl;
cout << "\nInput number of rows: ";
cin >> rows;
for(i=1;i<=rows;i++){
for(j=1;j<=i;j++)
cout<< ' ' << j;
cout<<endl;
}
if (!cin) {
system("cls");
std::cin.clear();
std::cin.ignore(1000, '\n');
std::cout << "please input a number" << std::endl;
goto triangledrawer;
}
std::cout << "\n Return to main menu? Y/N" << std::endl;
cin>>repeat;
Repeatcheck(repeat);
}
if (OptSel == 3){
system("cls");
fibonacciprinter:
cout << "\n----Fibonacci printer----";
cout << "\nEnter the number of terms: ";
cin >> prime;
cout << "Fibonacci Series: ";
for (int i = 1; i <= prime; ++i) {
// Prints the first two terms.
if(i == 1) {
cout << t1 << ", ";
continue;
}
if(i == 2) {
cout << t2 << ", ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
cout << nextTerm << ", ";
}
if (!cin) {
system("cls");
std::cin.clear();
std::cin.ignore(1000, '\n');
std::cout << "please input a number" << std::endl;
goto fibonacciprinter;
}
std::cout << "\n Return to main menu? Y/N" << std::endl;
cin>>repeat;
Repeatcheck(repeat);
}
if (OptSel == 4){
system("cls");
cout << "Enter a positive integer: ";
cin >> factorialinput;
cout << "Factorial of ";
if (factorialinput < 0)
cout << "Error! Factorial of a negative number doesn't exist.";
else {
for(int i = 1; i <= factorialinput; ++i) {
cout << i << " ";
factorial *= i;
}
cout << "= " << factorial;
}
std::cout << "\n Return to main menu? Y/N" << std::endl;
cin>>repeat;
Repeatcheck(repeat);
repeat = repeat;
}
if (repeat == 'n' || repeat == 'N'){
system("cls");
std::cout << "\nJob done? JOB DONE! Aight wrap it up lesgo." << std::endl;
return 0;
}
}while (OptSel != 5);
system("cls");
std::cout << "\nJob done? JOB DONE! Aight wrap it up lesgo." << std::endl;
return 0;
}
Rewriting the program to instead run when repeat = Y or y and removing the specific instance of terminating the program when N or n is entered instead results in the program terminating automatically no matter what is inputted when the Repeatcheck function is called.
#include <iostream>
#include<cctype>
#include<cstdlib>
#include <ctime>
#include <bits/stdc++.h>
using namespace std;
bool Primecheck(int x){
...
}
void Repeatcheck(char repeat){
while (repeat != 'Y' && repeat != 'y' && repeat != 'N' && repeat != 'n' ){
system("cls");
std::cout << "that's not an option, dumbass." << std::endl;
std::cout << "\n Return to main menu? Y/N" << std::endl;
cin >> repeat;
}
}
int main()
{
...
do{
...
}while (OptSel != 5 && repeat == 'Y' || repeat == 'y');
system("cls");
std::cout << "\nJob done? JOB DONE! Aight wrap it up lesgo." << std::endl;
return 0;
}

C++ How to call an if statement loop?

C++ code where a user enters 2 integers, then the program outputs how many numbers were multiples of 3 between those integers, including both numbers, and how many numbers were divisible by 5.
Here is my code. I think I am not calling the if statements correctly. Maybe I need a switch?
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int numb1, numb2;
int sentinel;
int counter = 0;
int mult3 = 0;
int mult5 = 0;
cout << "Enter an integer:";
cin >> numb1;
cout << "Enter another integer:";
cin >> numb2;
cout << endl;
sentinel = (abs(numb2-numb1)+1);
if(numb1 % 3 == 0 && counter <= sentinel) {
mult3++;
numb1++;
counter++;
}
else {
numb1++;
counter++;
}
cout << endl;
counter = 0;
if(numb1 % 5 == 0 && counter <= sentinel) {
mult5++;
numb1++;
}
else {
numb1++;
counter++;
}
cout << endl;
cout << mult3 << " " << "numbers are divisible by 3 in between your entered integers." << endl;
cout << mult5 << " " << "numbers are divisible by 5 in between your entered integers.";
cout << endl;
return 0;
}
A short version for your code is given below. Checkout the while loop(not ran, just from top of my head).
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int numb1, numb2;
int sentinel;
int counter = 0;
int mult3 = 0;
int mult5 = 0;
cout << "Enter an integer:";
cin >> numb1;
cout << "Enter another integer:";
cin >> numb2;
cout << endl;
while(numb1 <= numb2){
mult3 += (numb1%3)==0?1:0; // (numb1%3)?0:1
mult5 += (numb1%5)==0?1:0;
++counter;
++numb1;
}
cout << endl;
cout << mult3 << " " << "numbers are divisible by 3 in between your entered integers." << endl;
cout << mult5 << " " << "numbers are divisible by 5 in between your entered integers.";
cout << endl;
return 0;
}
You're not looping it at all, so this will only execute once.
while(counter < sentinel)
{
//run your tests and increment the appropriate variables if the numbers are divisible by 3 or 5
counter++;
}
start by evaluating the lowest of the 2 entered numbers + counter % 3 == 0
I got it. I had to use 3 separate while loops. One for <, one for >, and one for =. When I just had a <= and >=, the first loop would feed into the second. I took out the sentinel and the counter thanks to Avezan's help. Thanks everyone.

C++ program to display votes in percentage not showing correct result

I'm solving some C++ problems from ebooks. I made this C++ program but it isn't working properly. I've 2 problems:
Even after applying the forumla (votePercentage = firstAnswer/totalVotes*100;) it isn't showing the output, but only 0.
The program should display the bar chart, how am I suppose to do that? Any hints, reference or solution will be appreciated.
Here is my code:
/*
* 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.
*/
#include <iostream>
#include <string>
void startPoll (void);
void showPoll (void);
void pollCheck (void);
std::string pollQuestion, answer1, answer2, answer3;
int pollChoice, firstAnswer, secondAnswer, thirdAnswer;
int main (void)
{
int totalVotes = 1;
float votePercentage;
startPoll();
showPoll();
for(;;totalVotes++)
{
if (pollChoice == 1)
{
firstAnswer = firstAnswer + 1;
}
else if (pollChoice == 2)
{
secondAnswer++;
}
else if (pollChoice == 3)
{
thirdAnswer++;
}
else
{
std::cout << "==============*======*======*==============\n"
<< " RESULT \n"
<< "==============*======*======*==============\n"
<< "Question: " << pollQuestion << "\n"
<< "Total Votes: " << totalVotes << "\n";
votePercentage = (firstAnswer/totalVotes)*100;
std::cout << answer1 << ": " << firstAnswer << " votes. | " << votePercentage << "\n";
votePercentage = secondAnswer/totalVotes*100;
std::cout << answer2 << ": " << secondAnswer << " votes. | " << votePercentage << "\n";
votePercentage = thirdAnswer/totalVotes*100;
std::cout << answer3 << ": " << thirdAnswer << " votes. | " << votePercentage << "\n";
return 0;
}
std::cout << "\nEnter your vote again\nOR\nuse 0 to show the results.\n";
std::cin >> pollChoice;
}
std::cout << "Error: Something went wrong!\n";
}
void startPoll (void)
{
std::cout << "Enter your poll question:\n";
getline (std::cin, pollQuestion, '\n');
std::cout << "Enter answer 1:\n";
getline (std::cin, answer1, '\n');
std::cout << "Enter answer 2:\n";
getline (std::cin, answer2, '\n');
std::cout << "Enter answer 3:\n";
getline (std::cin, answer3, '\n');
}
void showPoll (void)
{
std::cout << "==============|======|======|==============\n"
<< " POLL \n"
<< "==============|======|======|==============\n"
<< pollQuestion << "\n"
<< "1. " << answer1 << "\n"
<< "2. " << answer2 << "\n"
<< "3. " << answer3 << "\n\n"
<< "Enter 1,2 or 3:\n\n";
std::cin >> pollChoice;
pollCheck();
}
void pollCheck (void)
{
if (pollChoice != 1 && pollChoice != 2 && pollChoice != 3)
{
std::cout << "Wrong choice entered! Please try again.\n\n";
return showPoll();
}
}
You need to take care that integer/integer = integer. In your case, changing
(firstAnswer/totalVotes)*100
to
(1.0*firstAnswer/totalVotes)*100
or
(firstAnswer*100.0/totalVotes)
should work. They all give a floating point result.
Well, the solution for the Bar Chart could be the following:(Not written by me) I think thats very self explaining because its really basic
void line (int n, char c)
{
// this is the loop for n
for (int i = 0; i < n; i++)
cout << c << endl;
}
Here is my solution, you can see how I made the bars work by reading the comments.
#include <iostream>
using namespace std;
int main()
{
int a = 0;
int b = 0;
int c = 0;
cout << "What is your favorite animal? 1 Cat, ";
cout <<"2 Dog, 3 Fish, 0 Count votes" << endl;
//Choice counter
while (true)
{
int choice;
cout << "Choice: ";
cin >> choice;
if(choice == 1)
a++;
else if(choice == 2)
b++;
else if(choice == 3)
c++;
else if(choice == 0)
break;
else
continue;
}
cout << endl << " 1: " << a << endl;
cout << " 2: " << b << endl;
cout << " 3: " << c << endl;
cout << endl << "1\t" << "2\t" << "3\t" << endl;
//Finds the max voted option
int max = 0;
if(a > b && a > c)
max = a;
else if(b > c && b > a)
max = b;
else if(c > a && c > b)
max = c;
/* If the max voted option is bigger than 10, find by how much
we have to divide to scale the graph, also making 10 bar
units the max a bar can reach before scaling the others too */
int div =2;
if(max > 10)
{
do
{
max = max/div;
if(max < 10)
break;
div++;
}while(true);
}else
div = 1;
//Sets the final number for the bars
a=a/div;
b=b/div;
c=c/div;
if(a==0)
a++;
if(b==0)
b++;
if(c==0)
c++;
//Creates the bars
while(true)
{
if(a>0)
{
cout << "[]" << "\t";
a--;
}else
cout << " ";
if(b>0)
{
cout << "[]" << "\t";
b--;
}else
cout << " ";
if(c>0)
{
cout << "[]" << "\t";
c--;
}else
cout << " ";
cout << endl;
if(a==0 && b==0 && c==0)
break;
}
}

Score component in beginner C++ program

I am doing an assignment where I am supposed to write a program to test the user's math skills. Here's the code i have right now:
using namespace std;
void addition()
{
int Value, Value2, Answer;
bool gotAnswer;
for (int i=1; i<=10; i++)
{
Value = 1 + (rand()%10);
Value2 = 1 + (rand()%10);
gotAnswer = false;
cout << Value << " + " << Value2 << " = ";
for (int a=1; (a<=3 && gotAnswer==false); a++)
{
cin >> Answer;
if (Answer==(Value+Value2))
{
cout << "CORRECT" << endl << endl;
gotAnswer = true;
}
else
{
cout << "WRONG Try again." << endl;
if (a==3)
{
cout << "You have missed 3 times. The answer is " << Value+Value2 << "." << endl << endl;
}
}
}
}
}
void substraction()
{
int Value, Value2, Answer;
bool gotAnswer;
for (int i=1; i<=10; i++)
{
Value = 1 + (rand()%10);
Value2 = 1 + (rand()%10);
gotAnswer = false;
cout << Value << " - " << Value2 << " = ";
for (int a=1; (a<=3 && gotAnswer==false); a++)
{
cin >> Answer;
if (Answer==(Value-Value2))
{
cout << "CORRECT" << endl << endl;
gotAnswer = true;
}
else
{
cout << "WRONG Try again." << endl;
if (a==3)
{
cout << "You have missed 3 times. The answer is " << Value-Value2 << "." << endl << endl;
}
}
}
}
}
void Multiplication()
{
int Value, Value2, Answer;
bool gotAnswer;
for (int i=1; i<=10; i++)
{
Value = 1 + (rand()%10);
Value2 = 1 + (rand()%10);
gotAnswer = false;
cout << Value << " x " << Value2 << " = ";
for (int a=1; (a<=3 && gotAnswer==false); a++)
{
cin >> Answer;
if (Answer==(Value*Value2))
{
cout << "CORRECT" << endl << endl;
gotAnswer = true;
}
else
{
cout << "WRONG Try again." << endl;
if (a==3)
{
cout << "You have missed 3 times. The answer is " << Value*Value2 << "." << endl << endl;
}
}
}
}
}
int main()
{
int number;
cout << "Enter the number for the problem type desired:"<<endl;
cout << " 1. Addition"<<endl;
cout << " 2. Subtraction"<<endl;
cout << " 3. Multiplication"<<endl;
cin >> number;
if (number == 1)
{
addition();
}
else if(number == 2)
{
substraction();
}
else if (number ==3)
{
Multiplication();
}
}
The program runs fine. However, there should be a score component where the user gets 10 points on the first try, 5 point on second try, and 0 on third try/wrong. I have no idea how to blend the score component in and the display at the end of 10 questions. Hints please?
All thanks in advance.
You should keep a score variable in each of your functions, add to the score variable as necessary and then return the score variable.
So those function are no longer going to be voids, they'll be ints. You can then get the score at the end and print it out.
I'm not going to write any code for you, since it is for an assignment :P