A simple loop question

This is a discussion on A simple loop question within the C++ Programming forums, part of the General Programming Boards category; Hello all! I want a loop from A to B (B > A) including both endpoints A and B, with ...

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    42

    A simple loop question

    Hello all!

    I want a loop from A to B (B > A) including both endpoints A and B, with a given number of steps, for example (B-A)/steps. If I say

    Code:
    double A = 1.25f;
    double B = 7.12f;
    double step = 100f;
    
    for(double i = A; i < B; i += step) { }
    the endpoint B is excluded. What is the right way to do this?

    serge
    Last edited by serge; 05-03-2012 at 04:18 PM.

  2. #2
    ZuK
    ZuK is offline
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Code:
    #include <iostream>
    
    using namespace std;
    int main() {
        double A = 1.25;
        double B = 7.12;
        int steps = 10;
        double step = ( B - A )/( steps - 1);
     
        for(int i = 0; i < steps; ++i ) {
             cout << A + step * i << endl;
        }
    }
    Kurt
    Last edited by ZuK; 05-03-2012 at 04:48 PM. Reason: remove f from double literals

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple loop question
    By TonyG in forum C Programming
    Replies: 2
    Last Post: 06-01-2011, 04:36 AM
  2. Simple for loop question
    By benrogers in forum C Programming
    Replies: 2
    Last Post: 02-28-2011, 11:34 AM
  3. simple loop incrament question
    By aweida in forum C Programming
    Replies: 5
    Last Post: 09-27-2010, 10:40 PM
  4. simple for loop function question
    By felicityxiv in forum C Programming
    Replies: 7
    Last Post: 05-06-2006, 11:43 PM
  5. Please don't laugh...SIMPLE loop question!
    By the_lumin8or in forum C++ Programming
    Replies: 5
    Last Post: 03-31-2006, 12:08 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21