hi I am new to programming, I will like to know if my code are ok:

CALCULATE THE FACTORIAL OF A NUMBER PROVIDED BY THE USER.

  1. Data Counter as a Wholenumber
  2. Data Number as a Wholenumber
  3.   Data Factorial as a Wholenumber
    
  4.    Output  “Enter Number”
    
  5.    Input    Number
    
  6.    Counter =Number
    
  7.     Factorial=Number;
    
  8.      Loop until counter is equal to 1
    
  9.                Counter= Counter-1
    
  10. Factorial= Factorial * Counter
  11. Next Loop
  12. Output Factorial

LINE Number Factorial Counter Notes
1 0 0 0
2 0 0 0
3 0 0 0
4 0 0 0 Output
5 5 0 0 User Enters 5
6 5 0 5
7 5 5 5
8 5 5 5 Loop until counter is equal to 1
9 5 5 4
10 5 20 4
11 5 20 4 Back to Line 8
8 5 20 4
9 5 20 3
10 5 60 3
11 5 60 3 Back to Line 8
8 5 60 3
9 5 60 2
10 5 120 2
11 5 120 2 Back to Line 8
8 5 120 2
9 5 120 1
12 5 120 1 Output

The algorithm is correct, though two things stand out:

  1. You don't account for a number that's less than 1. In real code this can cause problems.

  2. The loop stops when counter is equal to 1, but due to the way the factorial and counter interact, you could stop the loop at 2 and still get a correct result. For this program it's not a big deal, but in complex loops you can benefit from not doing unnecessary work.

There's also the matter of factorial growth and potentially overflowing the number data type, but that's not really a concern for pseudocode. However, it couldn't hurt to recognize that when translated to real code, you have to deal with the limitations of the computer.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.