Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
This program looks at each character of a sentence.
DECLARE Sentence : STRING
DECLARE Index : INTEGER
DECLARE Found : INTEGER
Sentence ← "Ice Cream And Apples"
Found ← 0
FOR Index ← 1 TO LENGTH(Sentence)
IF LCASE(SUBSTRING(Sentence, Index, 1)) = 'a'
THEN
Found ← Found + 1
ENDIF
NEXT Index
OUTPUT FoundHow many times does the loop run, and what is output? Why is LCASE used?
DIV is the whole part of a division and MOD the remainder. ROUND(Value, Places) rounds to a number of decimal places, and RANDOM() returns a number from 0 to 1. LENGTH(Text) counts the characters, SUBSTRING(Text, Start, Length) takes a piece starting at Start (position 1 is the first character), UCASE and LCASE change the case.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Step 1. The passes. "Ice Cream And Apples" has 20 characters, counting the three spaces. The loop runs 20 times.
Step 2. The count. The letter a appears in Cream, in And (as A) and in Apples (as A). LCASE turns both capital A letters into a, so all three are counted. The output is 3.
Why LCASE. Without it, 'A' = 'a' is FALSE, and the program would count only 1.
Answer: 20 passes, output 3.
Log in to join the discussion.
Loading…