3
votes

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.

3
Use the Odd() function or (counter and 1 <> 0) or (counter mod 2 <> 0) to get the odd numbers. Don't ever think of changing the loop counter inside the loop. - LU RD
So, how to get times of 3 (3,6,9,...) or times of N ? - S.Sakthybaalan
You can loop from 1 to 10 and test for Odd, no problem. - LU RD
No, that is OK to check odd no. or even no. But how to print multiplication of number N in a specific range ? For eg: multiplication of 5, from 5 to 60. (5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60). - S.Sakthybaalan
oh! Thank you for the suggestion - S.Sakthybaalan

3 Answers

4
votes

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.

3
votes

The for statement in Pascal does not support a step value, and you shouldn't alter the value of the index variable (this is a general principle for programming). Either test the index variable's value for the condition you are interested in (e.g., if odd(counter) then...), or re-code as a while or repeat...until loop, where you can have a 'pseudo-index' variable that you can manipulate as you feel necessary.

1
votes

I am not so familiar with pascal. But, I have a suggestion for you, what about using conditional to check the number if it divides into 2 with remaining of 1 (Like 5/2 and the remaining is 1) and then print it.

I hope it will help you.