CompTIA Tech+ (FC0-U71)Software Development ConceptsHard
A senior developer asks a junior team member to write pseudocode for a simple algorithm. The algorithm should calculate the sum of numbers from 1 to 5. Which of the following pseudocode snippets correctly represents this algorithm?
- ASTART SET sum = 0 FOR i FROM 1 TO 5 sum = sum + i END FOR DISPLAY sum END
- BSTART SET sum = 0 WHILE sum < 5 DO sum = sum + 1 END WHILE DISPLAY sum END
- CSTART SET sum = 0 IF i < 5 THEN sum = sum + i END IF DISPLAY sum END
- DSTART SET sum = 1 + 2 + 3 + 4 + 5 DISPLAY sum END
Show answer & explanationAnswer & explanation
Correct answer: A. START SET sum = 0 FOR i FROM 1 TO 5 sum = sum + i END FOR DISPLAY sum END
Option A correctly uses a FOR loop to iterate a counter 'i' from 1 to 5, adding each 'i' to the 'sum' variable. This accurately calculates the sum of numbers from 1 to 5 (1+2+3+4+5 = 15).
Why the other options are wrong
- B. Incorrect. This WHILE loop would count up to 5, but it would set 'sum' to 5 (0+1+1+1+1+1) and not calculate the sum of numbers from 1 to 5 (which is 15). It also reuses 'sum' as both a counter and an accumulator incorrectly.
- C. Incorrect. This uses an IF statement, which only executes once based on a condition, not iteratively to sum numbers. The variable 'i' is also undefined.
- D. Incorrect. While it would produce the correct result for this specific case, it does not represent an algorithm for 'calculating' the sum of numbers 'from 1 to 5' in a general, iterative way; it's a hardcoded calculation.
Pseudocode
An informal high-level description of the operating principle of a computer program or other algorithm. It uses natural language and common programming constructs to outline logic, without strict syntax rules.
- High-level, informal description.
- Uses natural language and programming constructs.
- Focuses on logic, not syntax.
Memory trick: Pseudocode: 'Pseudo' means 'almost', so it's 'almost code'.