VERY NEWWWW programmer. needs help with fof

So my teacher mentions about using the for loop, setw(), and setfill() to make a table like the following. However, I do not understand that how to use a setw()and seetill in a for loop. I just want to know that how the following code uses for loop to make the output becomes nice-formatted. Thanks!
Example:

4 5 6 7

______________________

12| xxx

24| xxx

36|

48|

60|

72|

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
  #include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    char ans;
    int low,high,step;
    long int value;
    double r,n,m,result;

    do
    {
    cout<<"Please enter the total value of the loan: ";
    cin>>value;
    cout<<"Please enter the lowest interest rate you wish to pay: ";
    cin>>low;
    cout<<"Please enter the highest interest rate you wish to pay: ";
    cin>>high;
    cout<<"Please enter the step size between interest rates: ";
    cin>>step;
    cout<<endl<<setw(5)<<"|";
    for(int i=low;i<=high;i+=step)
        cout<<setw(9)<<i;
    cout<<endl<<setw(78)<<setfill('-')<<"-"
       <<endl<<setfill(' ');

    for(int i=1;i<16;i++)
    {
        if(i==7)
          break;
        n=i*12;
        cout<<setw(3)<<n<<setw(2)<<"|";
        for(int j=low;j<=high;j+=step)
        {
            if(j==high+1)
                continue;
            r=(double)j/100;
            m=pow(1+r,n);
            result=(value*r*m)/(m-1);
            cout<<setw(9)<<result;
        }
        cout<<endl;
    }

    cout<<endl<<"Do you want to do this again? ";
    cin>>ans;
    }while(ans=='Y' || ans == 'y');
    return 0;
}
a) read this:
http://www.programming4beginners.com/tutorial/chapter12/alignment
http://www.programming4beginners.com/tutorial/chapter12/nested-loops

b) setfill will replace the 'blanks' in front of ouput with the given character ('-'). So

setw(78)<<setfill('-')<<"-"

will print out '-' character 79 times.
Last edited on
OMG THESE TWO links are so helpful!!! THANKS KEVIN Q-Q
Topic archived. No new replies allowed.