Giving the user the option to loop a for loop - c++

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!

Related

Trying to cout stars based on numbers

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!

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.

Getting an infinite loop in Babylonian Algorithm for square roots in C++

I have thoroughly searched for this topic all over the internet, and the threads are either dead, or use a different method than what is described in my book.
For example, http://www.geeksforgeeks.org/square-root-of-a-perfect-square/ . This doesn't work for me because my algorithm needs to loop until it reaches 1% of the last "guess".
Here is the question from the text.
The Babylonian algorithm to compute the square root of a number n is as follows:
Make a guess at the number (you can pick n/2 as your initial guess).
Compute r = n / guess
Set guess = (guess + r) / 2
Go back to step 2 for as many iterations as necessary. The more that steps 2 and 3 are repeated, the closer guess will become to the
square root of n.
Write a program that inputs an integer for n, iterates through the
Babylonian algorithm until guess is within 1% of the previous guess,
and outputs the answer as a double.
I have written the following code:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int n;
double r, guess(4), lastGuess;
cout << "Enter a number to find the square root of: ";
cin >> n;
do
{
r = n / guess;
lastGuess = guess;
guess = ( guess + r ) / 2;
// cout <<"Guess: " << guess << endl;
// cout <<"Last Guess: " << lastGuess << endl;
cout << "Guess : " << guess << endl;
cout << "Last Guess 1% = " << lastGuess + ( lastGuess * 0.01 ) << endl;
cout << "r = " << r << endl;
} while( guess >= lastGuess * 0.01 );
cout << r;
return 0;
}
The program computes the right answer for r, but the loop doesn't terminate despite guess being greater than 1% added to lastGuess.
This program produces the following output when inputting 144 as n.
....
r = 12
Guess : 12
Last Guess 1% = 12.12
r = 12
Guess : 12
Last Guess 1% = 12.12
r = 12
Guess : 12
Last Guess 1% = 12.12
r = 12
Guess : 12
Last Guess 1% = 12.12
....
The root (r) is correct (12). The guess is LESS than lastGuess (12 < 12.12), which should return a false to the condition, correct?. Why is the loop not ending?
If you want to add 1% you need to multiply by 1.01, not 0.01.
while( guess >= lastGuess * 1.01 );
By the way, this iterates while guess is growing by more than 1%. You should also allow for the opposite, that it may have shrunk by more than 1%. The approximation could approach the answer from either direction. (It will approach positive roots from the right and negative roots from the left.)
While printing your lastGuess you are using
lastGuess + ( lastGuess * 0.01 )
But while checking loop condition you are using
lastGuess*0.01
So in loop condition use the same equation which you are using for printing lastGuess value.
To properly exit the loop, use something similar to this.
void f(int N)
{
double x = N / 4;
double prev = 0.0f;
while(1)
{
x = 0.5 * (x + N / x);
if (prev == x)
break;
prev = x;
printf("val: %f\n", x);
}
printf("SQRT(%d) = %f\n", N, x);
}
I had the same problem in my book. This is what I wrote and it works perfect.
#include <iostream>
using namespace std;
int main()
{
double guess, root, previousGuess;
int number;
cout << "Enter a number to find the Babylonian square root.\n";
cin >> number;
cout << "You want to find the square root of " << number << ".\n";
cout << "Enter a guess for the square root.\n";
cin >> guess;
do
{
root = number / guess;
previousGuess = guess;
guess = (guess + root ) / 2;
} while(guess < 0.99*previousGuess || guess > 1.01*previousGuess);
cout << "The answer is " << guess << ".\n";
return 0;
}

Simple while loop not terminating (beginner)

Here's what I want my program to do. Prompt the user to input 10 integers. Then my program adds up the even integers, adds up the odd integers, then displays both sums. Simple beginner's exercise. To do this, I'm using a while loop with a control variable. Here is the entirety of my code:
#include <iostream>
using namespace std;
int main()
{
int evenSum = 0;
int oddSum = 0;
int num;
int control = 0;
cout << "Enter 10 integers: " << endl;
cin >> num;
while (control <= 10)
{
if (num%2 == 0)
{
evenSum = evenSum + num;
}
else
{
oddSum = oddSum + num;
}
control++;
cin >> num;
}
cout << "The sum of the even integers is " << evenSum << endl;
cout << "The sum of the odd integers is " << oddSum << endl;
return 0;
}
To test this code, I'm using as input the first 10 positive integers, 1-10. However, I'm having a couple headaches. First, control never passes from the while loop, i.e. the program never gets to the point where it displays the evenSum and outSum variable values. I'm having a hell of a time figuring out why the while loop never terminates. As I've written it, the while condition will become false as soon as control = 11, and the control variable is incremented at the end of the while body, so it should not keep going. Yet it does.
My second headache (probably related) is that the sum of the even numbers in my input should be 30, and the sum of the odd numbers should be 25. However, while my program gets the oddSum correct, it only sums the evens up to 20, so it is not counting the last number (10) for some reason.
I have walked through this program carefully several times on paper. Also, I've had it display the variable values as it goes, so I can track what it is doing with each while loop. Eventually, it just stops displaying output, but without ever actually terminating. And it sums the evens and odds correctly, just without adding that last number.
It seems to me there is at least one off-by-one error here, possible 2 that are compounding each other. But I have tried adjusting my various values and it's nothing doing. My other thought is that I'm suspicious of the way I have set up my input stream. I.e. I'm unsure of what value will be assigned to num in the final iteration of the while loop.
Can anyone shed some light on either of these problems?
Read at the top of your loop (after checking the count)
// cin >> num;
while (control <= 10)
{
cin >> num;
if (num%2 == 0)
{
evenSum = evenSum + num;
}
else
{
oddSum = oddSum + num;
}
control++;
// cin >> num;
}
Try to trace the code execution. Manually. That is the best way to learn how computers think.
You’ll realize, that the loop condition is broken. You start counting from 0, continue up to 10 including, stop at 11. 0..10, that’s 11 numbers!
Furthermore, you are reading input once at the beginning and then once at the end of each iteration. That makes 12 reads.
When trying to read more input than supplied, the program blocks and waits for more input. A program in infinite loop is active, it consumes all your CPU resources. In this case the program is blocked and uses close to no resources.
ask to enter numbers inside the loop,its easy to understand when to input particular number
int control = 1;
while (control <= 10)
{
cout << "Enter integer at position:"+Control << endl;
cin >> num;
if (num%2 == 0)
{
evenSum = evenSum + num;
}
else
{
oddSum = oddSum + num;
}
control++;
}
I could not see an error. Only the issue that you have to put 11 numbers instead of 10. Have you tried to type 11 numbers?
hey i am also a beginner but i tried to answer your question. you could also use compound assignment i.e. += instead of repeating evenSum and oddSum twice.
#include <iostream>
using namespace std;
int main()
{
int evenSum = 0;
int oddSum = 0;
int num;
int control = 0;
cout << "Enter 10 integers: " << "\n";
while (control <= 9 )
{
cin >> num;
if (num % 2 == 0)
{
evenSum += num;
}
else
{
oddSum += num;
}
control++;
}
cout << "The sum of the even integers is: " << evenSum << "\nThe sum of the odd integers is: " << oddSum << "\n";
return 0;
}

Is there a way to not include a negative number in an average, when entering a negative number is how you terminate the program?

Sorry about last time for those who saw my previous thread. It was riddled with careless errors and typos. This is my assignment:
"Write a program that will enable the user to enter a series of non-negative numbers via an input statement. At the end of the input process, the program will display: the number of odd numbers and their average; the number of even numbers and their average; the total number of numbers entered. Enable the input process to stop by entering a negative value. Make sure that the user is advised of this ending condition."
And here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number, total1=0, total2=0, count1=0, count2=0;
do
{
cout << "Please enter a number. The program will add up the odd and even ones separately, and average them: ";
cin >> number;
if(number % 2 == 0)
{
count1++;
total1+=number;
}
else if (number >= 0)
{
count2++;
total2+=number;
}
}
while (number>=0);
int avg1 = total1/count1;
int avg2 = total2/count2;
cout << "The average of your odd numbers are: " << avg1 << endl;
cout << "The average of your even numbers are " << avg2 << endl;
}
It seems to be working fine, but when I enter a negative number to terminate the program, it includes it with the rest of the averaged numbers. Any advice to get around this? I know it's possible, but the idea escapes me.
Your main loop should be like this:
#include <iostream>
for (int n; std::cout << "Enter a number: " && std::cin >> n && n >= 0; )
{
// process n
}
Or, if you want to emit a diagnostic:
for (int n; ; )
{
std::cout << "Enter a number: ";
if (!(std::cin >> n)) { std::cout << "Goodbye!\n"; break; }
if (n < 0) { std::cout << "Non-positve number!\n"; break; }
// process n
}
After here:
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
Immediately check if the number is negative
if(number < 0) break;
Now you wouldn't need to use your do-while loop in checking if the number is negative. Thus, you can use an infinite loop:
while(true) {
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
if(number < 0) break;
// The rest of the code...
}
ADDITIONAL:
There is something wrong in your code. You aren't showing the user how much the number of even and odd numbers are, and the total number of numbers entered.
ANOTHER ADDITIONAL: You should use more meaningful variable names:
int totalNumEntered = 0, sumEven = 0, sumOdd = 0, numEven = 0, numOdd = 0;
Of course I am not limiting you to these names. You can also use other similar names.
FOR THE INTEGER DIVISION PROBLEM:
You must cast your expression values to the proper type (in this case, it is float). You should also change the averages variables' types to float:
float avg1 = float(total1) / float(count1);
float avg2 = float(total2) / float(count2);
Immediately after cin >> number, check for < 0, and break if so. Try to step through the program line by line to get a feel for the flow of execution. Have fun learning, and good luck!