Trying to cout stars based on numbers - c++

I am trying a simple program that prints out stars according to number that has been entered, if the number is negative then program prints "Try Again!" and you need to enter numbers while you finish with 5 different positive numbers. Also the range should be from 1 to 30. I see that I am going deeper underground, feels like I am stuck here. Else after while is failing of course. Any tips? :(
#include <iostream>
#include <string>
using namespace std;
int main(){
int myNumber = 0;
char star='*';
bool flag = false;
int counter = 0;
while(!flag && counter <= 5){
if(myNumber < 0 && myNumber > 30){
cout << "Try Again!" << endl;
}
cout << "Enter 5 numbers: " << endl;
cout << "-> ";
cin >> myNumber;
if(myNumber >0 && myNumber <= 30){
flag = true;
}
for(int i = 0; i < myNumber; i++){
cout << star;
}
counter++;
}
return 0;
}
Expected output is as follows:
Enter 5 numbers:
-> 4
* * * *
-> 10
* * * * * * * * * *
-> 7
* * * * * * *
-> -5
Try again!
-> 5
* * * * *
-> 12
* * * * * * * * * * * *

There are several problems with this code:
While loops do not need else blocks. The condition in the while () clause is supposed to be enough to get it to stop.
break statements should be used inside of loops, not outside of loops.
totalNumbers is never changed, so it will never be larger than 5, so the while loop will never be stopped. Remember that the check for totalNumbers will be evaluated after every run inside the loop, to determine if it should run again.
You need a check after taking user input to ensure the input numbers are between 1 and 30
and others.
Some changes to make:
your cin command should be in the while loop
you need to change totalNumbers after each correct cin and star output so that it eventually halts the while loop
you need an if/else block inside the while loop, after cin, to verify the input is between 1 and 30.
you need a way to print a string of stars with a variable length; you could use a for-loop for that.

I am not too sure what you mean by, "and you need to enter numbers while you finish with 5 different positive numbers."
If you wanted to prompt the user for input (of non-negative numbers) and then print out n-number of asterisks for the number the user has input I would:
#include <iostream>
#include <string>
using namespace std;
int main(){
int myNumber = 0;
char star='*';
bool flag = false;
while(!flag){
if(myNumber < 0){
std::cout << "Try again!" << std::endl;
}
std::cout << "Enter number: ";
std::cin >> myNumber;
if(myNumber >0 && myNumber <= 30){
flag = true;
}
}
for(int i = 0; i < myNumber; i++){
std::cout << star;
}
}
Hope this helps in some way!

Related

How to reverse my input including the negative

This is my code that I have currently but it always outputs 0 I'm trying to get it to output the reverse of the input including the negative for example -123425 will be 524321-:
#include<iostream>
using namespace std;
int main() {
int number;
bool negative;
cout << "Enter an integer: ";
cin >> number;
while (number != 0) {
number % 10;
number /= 10;
}
if (number < 0) {
negative = true;
number = -number;
cout << number << "-";
}
else {
negative = false;
}
cout << number << endl;
return EXIT_SUCCESS;
}
You could convert the input to a std::string, then reverse its content with std::reverse.
#include <algorithm> // reverse
#include <cstdlib> // EXIT_SUCCESS
#include <iostream> // cin, cout, endl
#include <string> // string, to_string
using namespace std;
int main()
{
cout << "Enter an integer: ";
int number;
cin >> number;
auto str = to_string(number);
reverse(str.begin(), str.end());
cout << str << endl;
return EXIT_SUCCESS;
}
Reading to an int first - and not to a std::string - makes sure that we parse a valid integer from the input. Converting it to a std::string allow us to reverse it. This let us feed inputs like -042 and -0 to the program, and get 24- and 0 as a result, not 240- and 0-.
After the first loop
while (number != 0) {
number % 10;
number /= 10;
}
the variable number is equal to 0.
So the following if statement
if (number < 0) {
negative = true;
number = -number;
cout << number << "-";
}
else {
negative = false;
}
does not make sense.
Pay attention to that it can happen such a way that a reversed number can not fit in an object of the type int. So for the result number you should select a larger integer type.
Here is a demonstrative program that shows how the assignment can be done.
#include <iostream>
int main()
{
std::cout << "Enter an integer: ";
int n = 0;
std::cin >> n;
bool negative = n < 0;
const int Base = 10;
long long int result = 0;
do
{
int digit = n % Base;
if ( digit < 0 ) digit = -digit;
result = Base * result + digit;
} while ( n /= Base );
std::cout << result;
if ( negative ) std::cout << '-';
std::cout << '\n';
return 0;
}
Its output might look like
Enter an integer: 123456789
987654321-
I think trying to visualize the process of your program is a great way to see if your solution is doing what you expect it to. To this end, let's assume that our number is going to be 12345. The code says that while this is not equal to 0, we will do number % 10 and then number /= 10. So if we have 12345, then:
number % 10 --> 12345 % 10 --> 5 is not assigned to any value, so no change is made. This will be true during each iteration of the while loop, except for different values of number along the way.
number /= 10 --> 12345 /= 10 --> 1234
number /= 10 --> 1234 /= 10 --> 123
number /= 10 --> 123 /= 10 --> 12
number /= 10 --> 12 /= 10 --> 1
number /= 10 --> 1 /= 10 --> 0 (because of integer division)
Now that number == 0 is true, we proceed to the if/else block, and since number < 0 is false we will always proceed to the else block and then finish with the cout statement. Note that the while loop will require number == 0 be true to exit, so this program will always output 0.
To work around this, you will likely either need to create a separate number where you can store the final digits as you loop through, giving them the correct weight by multiplying them by powers of 10 (similar to what you are hoping to do), or cast your number to a string and print each index of the string in reverse using a loop.
Quite simple:
int reverse(int n){
int k = abs(n); //removes the negative signal
while(k > 0){
cout<<k % 10; //prints the last character of the number
k /= 10; //cuts off the last character of the number
}
if(n < 0) cout<<"-"; //prints the - in the end if the number is initially negative
cout<<endl;
}
int main(){
int n = -1030; //number you want to reverse
reverse(n);
}
If you don't want to use String or have to use int, here is the solution.
You want to check the negativity before you make changes to the number, otherwise the number would be 0 when it exit the while loop. Also, the modulus would be negative if your number is negative.
number % 10 only takes the modulus of the number, so you want to cout this instead of just leaving it there.
The last line you have cout << number << endl; will cout 0 since number has to be 0 to exit the while loop.
if(number < 0) {
number = -number;
negative = true;
}
while (number != 0) {
cout << number % 10;
number /= 10;
}
if (negative) {
cout << "-"<< endl;
}
EDIT: With a broader assumption of the input taking all int type values instead of the reversed integer being a valid int type. Here is a modified solution.
if(number < 0) {
negative = true;
}
while (number != 0) {
cout << abs(number % 10);
number /= 10;
}
if (negative) {
cout << "-"<< endl;
}
using namespace std;
int main()
{
int number,flag=1;
long long int revnum=0;
bool negative;
cout << "Enter an integer: ";
cin >> number;
if(number<0)
{ negative=true;
}
while (number > 0) {
revnum=revnum*10+number %10;
number /= 10;
}
if (negative)
{ revnum=(-revnum);
cout << revnum << '-'<<endl;
}
else
{ cout<<revnum<<endl;
}
return 0;
}
A few changes I did -
checking the number whether it's negative or positive
if negative converting it to positive
3.reversing the number with the help of a new variable revnum
4.and the printing it according to the requirement
To reverse the num-
revnum=revnum*10 + number%10
then num=num/10
like let's try to visualize
1.take a number for example like 342
2.for 1st step revnum=0 so revnum*10=0 and num%10=2 , so revnum will be 2
and the number now is num/10 so 34
4.next now rev = 2 the rev*10=20 and num%10=4 then rev*10 + num/10 =24
5.finally we get 243
Hope it helps :)
edit:-
just a small edit to solve the problem of the overflow of int , made revnum as long long int.

Reversing a number (C++)

I am brand new to C++, and am trying to make a simple program to determine if a user-entered integer is four digits, and if so, to reverse the order of said digits and print that output.
I have a (mostly) working program, but when I try, one of two things happens:
a) if line 16 is commented out and line 17 is active, then the program prints out an infinite number of reversed numbers and the IDE (in this case, repl.it) crashes; or
b) if line 17 is commented out and line 16 is active, then the program prints out one correct line, but the next line is "Your number is too short...again" (look at code below)
#include <iostream>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main() {
int n, reversedNumber, remainder;
bool loopControl;
char userFinalResponse;
reversedNumber=0;
cout<<"Input a 4 digit integer and press Return\n"<<endl;
cin>>n;
while (loopControl=true){
//if ((n>9999)||(n<1000))
if ((n>9999)||((n<1000)&&(n>0)))
{
cout<<"Your number is too short or too long. Please try again.\n"<<endl;
cin>>n;
loopControl=false;
} else {
while(n != 0)
{
remainder = n%10;
reversedNumber=reversedNumber*10+remainder;
n /= 10;
loopControl=true;
}//closing brace for reversal loop
cout<<"Your reversed number is "<<reversedNumber<<"\n"<<endl;
}//closing brace for else
}//closing brace for "while (loopControl>0){"
return 0;
}//closing brace for "int main() {"
You can try this:
int number = 1874 //or whatever you need
auto str = std::to_string(number);
if (str.length() == 4) {
std::reverse(str.begin(), str.end());
std::cout << str << std::endl;
}
I suggest you to give a look at the algorithm header that contains a lot of useful methods that can help you while developing programs.
According to the cpp tutorials = is the assignment operator, not the comparison operator. Because of this your while loop will never terminate. You can simply initialize loopControl to true, and then set it to false when it's okay to exit:
int n, reversedNumber, remainder;
bool loopControl = true; //Initialize to true
char userFinalResponse;
reversedNumber = 0;
cout << "Input a 4 digit integer and press Return\n" << endl;
cin >> n;
while (loopControl) {
//if ((n>9999)||(n<1000))
if ((n>9999) || ((n<1000) && (n>0)))
{
cout << "Your number is too short or too long. Please try again.\n" << endl;
cin >> n;
loopControl = true; //need to keep on looping
}
else {
while (n > 0)
{
remainder = n % 10;
reversedNumber = reversedNumber * 10 + remainder;
n /= 10;
loopControl = false; //Ok to exit
}//closing brace for reversal loop
cout << "Your reversed number is " << reversedNumber << "\n" << endl;
}
}

Counting iterations in Newton-Raphson's method

I'm working in a simple program that calculates the root of any given function using Newton-Raphson's method. In this program I have to print the found root and the number of iterations made. The program itself is fine, I can find the root of any given function but I can't count properly the number of iterations. It is always 5 over the max. number of iterations or 1 less than it. Here's the code in C++:
#include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;
double f(float x)
{
double function1;
function1 = exp(x)- 4*pow(x,2); // given function
return function1;
}
double derivative(float x)
{
double derivative1;
derivative1 = exp(x) - 8*x; // derivative of given function
return derivative1;
}
void newtonMethod(double x0, double error, int N)
{
double xNext, xPrevious, root;
int k;
xPrevious = x0;
for(int i = 0; i < N || f(xNext) > error; i++)
{
xNext = xPrevious - (f(xPrevious)/derivative(xPrevious)); // calculates the next value of x
xPrevious = xNext;
root = xNext;
k = i;
}
cout << endl;
cout << "Iterations made: " << k << endl;
cout << endl;
cout << endl;
cout << endl;
cout << "Root is: " << root << endl;
}
int main()
{
double x0, error;
int N; // max. number of iterations you can do
cout << "Enter x0: ";
cin >> x0;
cout << "Enter the error: ";
cin >> error;
cout << "Enter the max. number of iterations: ";
cin >> N;
newtonMethod(x0, error, N);
}
And I'm pretty sure the error is in this piece of code:
;i < N || f(xNext) > error;
If I run this program and put N = 100, it shows the right root but it prints "Iterations made = 99" but this is wrong. What do I do to print the right number of iterations made? For example, for the function in the program above (e^x - 4x²) it should stop in the fourth iteration if I enter x0 = 0.5 and error = 0.0001. How to fix it?
To answer your question, which was why the following piece of code does not work:
;i < N || f(xNext) > error;
It is simply because that, in a for loop condition, it is a continuing condition that is evaluated, and not a stopping condition.
In the above piece of code, what you are telling the compiler is: continue the loop as long as either i < N is true or f(xNext) > error is true. Therefore, when you input x0 = 0.5, error = 0.0001 and N = 100, what the loop does is that it will not stop until both criteria are false, i.e. when i reaches N AND the tolerance in f(x) is smaller than error.
Now, the solution is simply to swap the || operator to && operator. Like this:
i < N && f(xNext) > error;
but then, your xNext is not initialized. Because that your xNext and xPrevious are equal at the end of each loop, I would simply put xPrevious instead. In addition, as #Rathat has written, evaluating your tolerance in f(x) should take its absolute value, so:
i < N && abs(f(xPrevious)) > error;
Finally, you should output the number of iterations as k + 1 since you started with i = 0.
This should solve your problem.
thanks for all the answers. I found out what's wrong besides the logic behind the for condition that #yuxiangDev explained very well. Despite #RatHat code being totally right the error was in the math.h library I was using. I tried with <cmath> and it worked really well! lol.

How do I implement a percentage chance function in a class object in C++?

I have a homework assignment that requires me to calculate a percentage chance from an user input of the numbers 1 to 3. However, I'm not sure how to do this.
This is my code, not all of it though:
void SwingAtBall( Ball *tBall ) {
std::cout << "How hard do you want to hit the ball? Please enter a number between 1 to 3." << std::endl;
int tBallHit;
std::cin >> tBallHit;
if ( tBallHit > 3 || tBallHit < 1 ) {
std::cout << "That is not a valid value. Please enter a number between 1 to 3." << std::endl;
std::cin >> tBallHit;
}
}
// Prompt for 1 to 3. There is a (input * 15) percent chance the ball only goes 5 feet. Otherwise the ball is hit a random number between 0 and (input * 150). Print how far it went.
If my understanding is correct that there is an (input * 15) percent chance the ball will go 5 feet and an (100 - (input * 15)) percent chance it will go anywhere from 0 to (input * 150) feet, then the following code will calculate what you are looking for...
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int inp, chance1, dist1, dist2, dist_final;
do {
cout << "Enter integer between 1 and 3: ";
cin >> inp;
} while (inp < 0 || inp > 3);
dist1 = 5;
srand(time(0));
dist2 = rand() % (inp * 150);
chance1 = (inp * 15) / 100;
dist_final = chance1 * dist1 + (1 - chance1) * dist2;
cout << "It went this far: " << dist_final << endl;
// system("pause");
return 0;
}
There's a whole <random> header for things like this.
Simple percentages are easy, you can use integers for that. Pick either 0-99 or 1-100, and use that in a uniform_int_distribution. Sure, 15% is 3/20 so you could also use a uniform_int_distribution(1,20) but that's more obscure.
"0 to (input * 150)" is a uniform_int_distribution(0,input*150).

Giving the user the option to loop a for loop

I'm having trouble giving the user an option to loop a loop. This program works fine
#include <iostream>
using namespace std;
int main()
{
// goal is to calculate the sum of the first 10 terms of Leibniz's Series....
// calculated by 1 - 1/3 + 1/5 - 1/7 + 1/9 ..... - 1/19
int termNumber; // keeps track of term numbers
int numberOfTerms = 0;
cout << "Enter number of Terms";
cin >> numberOfTerms;
double sum = 0.0;
int sign = +1;
for (termNumber = 1; termNumber <= numberOfTerms; termNumber++)
{
sum += ( sign / (2.0 * termNumber - 1));
sign *= -1;
}
cout << "\n\n The sum is " << ( 4 * sum) << "\n\n";
} // end body of loop
I need to give the user an option to repeat the program if he would like so I thought I could put it in a do-while loop, but when I do that it only loops "enter number of terms" any way I try to format it. This is the best I have at the moment.
#include <iostream>
using namespace std;
int main()
{
// goal is to calculate the sum of the first 10 terms of Leibniz's Series....
// calculated by 1 - 1/3 + 1/5 - 1/7 + 1/9 ..... - 1/19
cout << "\nGiven a positive integer specifying some number of terms, this program\n approximates "
"pi using Leibniz' Formula and the given number of terms.\n\n" ;
cout << "Leibniz' formula is 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... = Pi / 4.\n\n";
char yes = 0;
double sum = 0.0;
do {
int termNumber; // keeps track of term numbers
int numberOfTerms = 0;
int sign = +1;
cout << "enter number of terms.\n";
cin >> numberOfTerms;
for (termNumber = 1; termNumber <= numberOfTerms; termNumber++)
{
sum += (sign / (2.0 * termNumber - 1));
sign *= -1;
}
}
while (yes = 1);
cout << "\n\n The sum is " << (4 * sum) << "\n\n";
cout << "would you like to go again? " << yes;
} // end body of loop
I would like to give them the option to try a different amount using term numbers where y/Y and n/N work.
Thanks for any help I may get.
You need a cin to set yes and your cout lines are in the wrong place. They need to be inside of your do while loop. And an == in your while
do {
int termNumber; // keeps track of term numbers
int numberOfTerms = 0;
int sign = +1;
cout << "enter number of terms.\n";
cin >> numberOfTerms;
for (termNumber = 1; termNumber <= numberOfTerms; termNumber++)
{
sum += (sign / (2.0 * termNumber - 1));
sign *= -1;
}
cout << "\n\n The sum is " << (4 * sum) << "\n\n";
cout << "would you like to go again? " << yes;
cin >> yes
}
while (yes == 1);
try that
Just my two cents but maybe you can combine both of your ideas and use functions. Put the code you have in the do part above into a function with a parameter of number of terms. Also use your for loop in the body of this function. Then on the outside of your for loop call another function that asks the user if they would like to continue and also ask a new number for the "terms" and pass that back into the first function if the user supplies a 'y' or 'Y' else if a 'n' or 'N' you can just stop the program
Have you learned to use
continue;
in a for loop? I think this fits your description, basically what
continue;
does is it returns to the beginning of the for-loop in this case in a certain scenario.
The problem with the do while loop is that the variable used in the while() statement must have been defined outside of the loop body, even though syntactically is belongs to the loop. This can be avoided when using a for loop instead, which allows the definition of such variables within the for statement. Here is an example.
inline double leibniz (int n) noexcept // function for Leibniz sum
{
double result=0;
for(int k=1,sign=1; n; --n,++++k,sign=-sign)
result += double(sign)/double(k);
return result;
};
int main()
{
// no loose variables defined outside loop
for(bool again=true; again; ) { // control variable only lives withing loop body
int n; // number of terms, only needed within loop body
std::cout<<"number of terms = ";
std::cin >> n;
std::cout<<"result = "<<leibniz(n)<<'\n'
<<"try again? (1/0)";
std::cin >>again;
}
}
Thanks everyone for the help.
I didn't know the continue; yet, but I learned about it.
The major problem was my cin and cout were not in the right spot like stated before. Redid the last line to while (yes == 'Y' || yes == 'y'); and now all works perfectly.
You guys are great!