Write a pseudocode to calculate the factorial of a number (Hint: Factorial of 5, written as 5! = × × 1).
To calculate the factorial of a number, we need to multiply all integers from 1 up to that number. The pseudocode for calculating factorial is as follows:
Step 1: INPUT a number to n Step 2: SET fact = 1, counter = 1 Step 3: WHILE counter <= n, REPEAT steps 4 to 5 Step 4: fact = fact × counter Step 5: counter = counter + 1 Step 6: PRINT fact
In this pseudocode, we first accept the number from the user for which factorial needs to be calculated. We initialize two variables: fact to store the result (initialized to 1) and counter to keep track of iterations (initialized to 1).
The WHILE loop continues until the counter becomes greater than the input number n. Inside the loop, we multiply the current value of fact with the counter and store it back in fact. After each iteration, the counter is incremented by 1. For example, if n = 5, the loop runs 5 times. In first iteration: fact = = 1. In second: fact = = 2. In third: fact = = 6. In fourth: fact = = 24. In fifth: fact = = 120. Thus, 5! = 120.
Explanation
The textbook demonstrates pseudocode structure in Example 4.8, showing the use of SET for initialization, WHILE loops for iteration, INPUT for user input, and PRINT for output. Following this pattern, the factorial pseudocode uses a counter-controlled loop to multiply numbers from 1 to n, accumulating the product in the 'fact' variable.
Solution Steps
Step 1: Accept input number n
Step 2: Initialize fact = 1 and counter = 1
Step 3: Use WHILE loop with condition counter <= n
Step 4: Multiply fact by counter and store in fact
Step 5: Increment counter by 1
Step 6: Display the final factorial value