Displaying only certain values in a loop

I've been writing a program that calculates the natural logarithm of 2 for the user. It prompts for the number of terms to calculate, and how many steps in between each value to display. I can't figure out how to only display certain values. Ex: If the user inputs 10 terms to compute and for the values to be displayed every 2 steps. Any help is appreciated.

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

const string PROGDESCRIPTION = "Program will approximate the natural logarithm of 2 ";
double UserPrompt(string prompt)
{
double terms;


cout << prompt;
cin >> terms;
while(terms >= 1)
{
return terms;
}

cout << "ERROR - Input must be positive and non-zero! Please Try again. " << endl;
cout << prompt;
cin >> terms;

return terms;
}


int main()
{
double numofterms, displaycount;
double numerator = 1;
double logarithm = 0;
cout << PROGDESCRIPTION << endl << endl << endl;

numofterms = UserPrompt("Enter the number of terms to compute: ");
displaycount = UserPrompt("Display value after every how many steps? ");

for(double x = 1; x <= numofterms; x += 1){
logarithm += numerator * 1 / x;

numerator = -numerator;
if(logarithm < 1)
cout << setprecision(10) << showpoint << logarithm << endl;
else
cout << setprecision(11) << showpoint << logarithm << endl;
}
Please use code tags to make it easier to read your code and point out line numbers.

First off, there is a problem with your UserPrompt function. Your while loop isn't doing anything the way it is written, and you can enter a negative number when you are asked to retry and it will go through just fine.
It should be written as:
1
2
3
4
5
6
while(terms < 1) {
  cout << "ERROR - Input must be positive and non-zero! Please Try again. " << endl;
  cout << prompt;
  cin >> terms;
}
return terms;


To get to your posted question:
To print after so many iterations, you can just keep a counter.
1
2
3
4
5
6
7
8
int printCounter = 0;
for(int i=1; i<=numofterms; i++) {
  printCounter++;
  if(printCounter >= displaycount) {
    cout << "print something..." << endl;
    printCounter = 0; //reset print counter
  }
}



Alternately, you could also skip the counter and just use mod.

1
2
3
4
5
for(int i=1; i<=numofterms; i++) {
  if((i % displaycount) == 0) {
    cout << "print something..." << endl;
  }
}
Last edited on
I'm having trouble getting the right output, tried both methods and it's still outputting five values each times the number of terms. For example I'm trying to get it so if the user inputs 6 terms with 2 steps each, it will only display the values every 2 steps, and display something like this:

0.5000000000
0.5833333333
0.6166666667

instead of:

1.0000000000
0.5000000000
0.8333333333
0.5833333333
0.7833333333
0.6166666667

Any help is appreciated I've been trying to figure this one out for a while and it's frustrating :\
Topic archived. No new replies allowed.