Printing range of numbers and adding intervals

Aug 27, 2018 at 10:54am
I want to print a rang of numbers according to the intervals between them.
E.g minimum: 3, maximum: 12 and the interval is 3 should print something like 3,6,9,12.
However, i am struggling with the needed logic to achieve this aim.

Kindly assist

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
  #include <iostream>
using namespace std;

int main(int argc, const char * argv[]) {
    int min, max, intvr,add;

    cout<<"This program prints out the minimum, maximum and interval values"<<endl;
    cout<<endl;
    cout<<"enter mininum number: ";
    cin>>min;
    cout<<"enter maximum number: ";
    cin>>max;
    cout<<"enter interval number: ";
    cin>>intvr;
    cout<<endl;

    
   
    
    for(add=min; add<max; ++add)
    {
        cout<<add+intvr;
    }
cout<<endl;
}
Aug 27, 2018 at 12:02pm
In the example with max=12, you want to print the maximum value, so the condition should be add<=max. Also be sure to print a space after each value. I would change the for loop so that it iterates the actual values:
1
2
3
for (int val=min; val<=max; val+= intvr) {
    cout << val << ' ';
}
Aug 27, 2018 at 12:03pm
I think the pseudocode would be something like this:
-Get minimum number
-Get maximum number
-Get interval
-number is minimum
-As long as number is lower or equal to maximum number
----display number
----increment number by interval

Hope this helps

Edit: The only thing that you need to work on is your for loop I think, nothing big though:
1
2
3
4
for(add = min; add <= max; add += intvr)
{
    cout << add << ", ";
}
Last edited on Aug 27, 2018 at 12:06pm
Aug 27, 2018 at 12:32pm
The tutorial http://www.cplusplus.com/doc/tutorial/control/
has section: The for loop
The for loop is designed to iterate a number of times. Its syntax is:

for ( initialization; condition; increase ) statement;

The increase is
* an expression
* executed after the statement (i.e. the body of the loop)

The increase is not limited to be "plus one". Even the example in the tutorial uses "minus one".
Last edited on Aug 27, 2018 at 12:32pm
Topic archived. No new replies allowed.