Reputation: 519
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.
Upvotes: 5
Views: 8699
Reputation: 155
There are Pascal variants that support step values for looping constructs. One is PascalABC.Net which is open source and is extensively used for teaching. The other is a commercial product, REMObjects Oxygene. Both allow the declaration of in-line variables.
Oxygene:
namespace ForLoopStep_Oxy;
begin
for counter := 1 to 10 step 2
writeLn(counter); // 1 3 5 7 9
for counter := 9 downto 0 step 2
writeLn(counter); // 9 7 5 3 1
end.
PascalABC.Net:
begin
for var i := 1 to 10 step 2 do
Writeln(i); // 1 3 5 7 9
Writeln;
for var j := 9 to 0 step -2 do
Writeln(j); // 9 7 5 3 1
Writeln;
for var k :='z' to 'a' step -2 do
Write(k); // zxvtrpnljhfdb
Writeln;
end.
Upvotes: 0
Reputation: 6477
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.
Upvotes: 6
Reputation: 31
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.
Upvotes: 1
Reputation: 10799
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.
Upvotes: 4