What causes problems with this piece of code?
-
06-09-2019 - |
Question
I was just wondering why this certain problem happens to me. If you can help me, I will appreciate it.
Program factorial;
uses crt;
var
f, i: Integer;
begin
f:=1;
for i:=1 to 5 do
f:= f * i;
write(f);
readkey;
end.
Okay, That works fine and the result is 120. And it's true.
Now, here's the problem. If I asked the user to enter the value of the number, it won't work.
Program factorial;
uses crt;
var
i,r: Integer;
begin
write('Enter the number');
read(r);
for i:=1 to r do
r:= r * i;
write(r);
readkey;
end.
If I wrote 5, the output will be 600.
Solution
You are using the value r as the stopping condition of the loop and modifying the value in the loop.
Program factorial;
uses crt;
var
i,r, f: Integer;
begin
write('Enter the number');
read(r);
f := 1;
for i:=1 to r do
f:= f * i;
write(f);
readkey;
end.
OTHER TIPS
You reuse the r
variable. If you input 5
for r
your program will in effect one to many times. You should start with 1
as the first f
.
Program factorial;
uses crt;
var
i,r, f: Integer;
begin
write('Enter the number');
read(r);
f:=1
for i:=1 to r do
f:= f * i;
write(r);
readkey;
end.
try:
Program factorial;
uses crt;
var
i,r,x: Integer;
begin
write('Enter the number');
read(x);
r:=1
for i:=1 to x do
r:= r * i;
write(r);
readkey;
end.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow