views:

128

answers:

3

Hi!

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.

+1  A: 

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.
KM
I think that's wrong. You don't keep the value in the loop, but overwrite it every time.
Peter Stuifzand
+1 for keeping the original indentation. Helpful while still poking at the original silliness.
Randolpho
@Peter Stuifzand, good catch. I hate programs that use single letter variables! makes it confusing
KM
+4  A: 

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.
Peter Stuifzand
I understand why you say that. But if you for example use 5 as the input, you will loop 5 times. The first for r will be 5, but should be 1. In effect this is multiplying one time to many.
Peter Stuifzand
Your first sentence is correct. I believe your 2nd and 3rd sentence is wrong.
dss539
His solution and your solution loop the same number of times. How does he have an off-by-one error in his loop?
dss539
His solution uses the value that was read from the user as the value to multiply with. His first example does this right, but the second example reuses the variable instead of declaring a new one.
Peter Stuifzand
@Peter, yes you are correct, but that is not an off-by-one error. That's why I was confused by what you said.
dss539
+10  A: 

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.
Vincent Ramdhanie
Just beat me :)
CiscoIPPhone
Doh, beat me too.
dss539