pascal

Step value in Pascal programming


I want a programming code to print the odd numbers between a range to teach the students. Here I took the range as 1 to 10. So I want to print the odd numbers between 1 to 10.

I wrote this coding to print the odd numbers between 1 to 10

program printOdd1to10; {Prints odd numbers 1 - 10}

var counter : integer;
begin

   for counter := 1 to 10 do

      begin
        Writeln(counter); {prints new line}
        counter := counter + 2 {increment by value 2, like step 2}
      end;
        Readln;

end.

But when I run, it prints a long series of wrong answer. So, how to print like this pattern odd, even, times of 3(3,6,9...) numbers in pascal programming.


Solution

  • Following Jeff's answer, the best way to code your program is with 'while'.

    i:= 1;  // start with an odd number
    while i < 10 do
     begin
      writeln (i);
      i:= i + 2;  // or inc (i, 2)
     end;
    

    Incrementing i by 2 each time will ensure that i is always odd, so there's no need to check this.