ibmi-brunch-learn

Announcement

Collapse
No announcement yet.

Loop from end to start

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Loop from end to start

    Hello,

    If I want to display the first 5 numbers I make my loop like this:

    Code:
    dcl-s i packed(3:0);
    dcl-s message varchar(50);
    dcl-s waitInput char(1);
    
    FOR i = 1 by 1 to 5;
          message = %char(i);
          dsply message '' waitInput;
    ENDFOR;

    I would like to display 5, 4, 3, 2 ,1

    I think my loop has a problem?

    Code:
    dcl-s i packed(3:0);
    dcl-s message varchar(50);
    dcl-s waitInput char(1);
    
    FOR i = 5 by 5 to 1;
        message = %char(i);
        dsply message '' waitInput;
    ENDFOR;

  • #2
    Does " BY 5 to 1" mean it increments 5 at a time ?

    Comment


    • #3
      You need to specify the initial value as 5 and then use down to (you can probably also do it by saying by -1 but I haven't checked.

      Code:
      FOR i = 5 downto 1 ;
         message = %char(i);
         dsply message ' ' waitInput;
      ENDFOR;
      By the way - the "message" field is not needed - much simpler to do it this way:
      Code:
      FOR i = 5 downto 1 ;
         dsply (  %char(i) )  ' ' waitInput;
      ENDFOR;
      By building the value to be displayed in parens the compiler treats it as the single field source for the display.

      This let's you do stuff like:
      Dsply ( 'This is loop ' + %char(i) );

      Comment


      • #4
        Originally posted by MFisher View Post
        Does " BY 5 to 1" mean it increments 5 at a time ?
        No, I don't think that I have to use `BY`....

        Comment


        • #5
          Originally posted by JonBoy View Post
          You need to specify the initial value as 5 and then use down to (you can probably also do it by saying by -1 but I haven't checked.

          Code:
          FOR i = 5 downto 1 ;
          message = %char(i);
          dsply message ' ' waitInput;
          ENDFOR;
          By the way - the "message" field is not needed - much simpler to do it this way:
          Code:
          FOR i = 5 downto 1 ;
          dsply ( %char(i) ) ' ' waitInput;
          ENDFOR;
          By building the value to be displayed in parens the compiler treats it as the single field source for the display.

          This let's you do stuff like:
          Dsply ( 'This is loop ' + %char(i) );
          Thank you, it is exactly what I wanted.

          Comment

          Working...
          X