3.3 Longest word
You have an array of words that make up a sentence. Write a program to first loop through the array and build a sentence by adding each word followed by a space. Then, find and display the longest word in the array.
words = ["The", "black", "cat", "jumped", "over", "the", "tall", "fence"]
Sentence: The black cat jumped over the tall fence Longest word: jumped
set words to ["The", "black", "cat", "jumped", "over", "the", "tall", "fence"]
set sentence to empty string
loop for length of words array
add word at current position to sentence
add space to sentence
print "Sentence:", sentence
set longest_word to first word in words array
loop from position 1 to length of words array - 1
if length of word at current position > length of longest_word
set longest_word to word at current position
print "Longest word:", longest_word
words = ["The", "black", "cat", "jumped", "over", "the", "tall", "fence"]
# Build the sentence manually
sentence = ""
for i in range(len(words)):
sentence = sentence + words[i] + " "
print("Sentence:", sentence)
# Assume the first word is the longest
longest_word = words[0]
# Loop through the rest of the array
for i in range(1, len(words)):
if len(words[i]) > len(longest_word):
longest_word = words[i]
print("Longest word:", longest_word)
# Array storing the words of the sentence
words = ["The", "black", "cat", "jumped", "over", "the", "tall", "fence"]
# Build the sentence manually by adding each word followed by a space
sentence = ""
for i in range(len(words)):
sentence = sentence + words[i] + " "
# Display the sentence
print("Sentence:", sentence)
# Assume the first word is the longest
longest_word = words[0]
# Loop through the rest of the array
for i in range(1, len(words)):
# If the current word length is greater than the current longest word
if len(words[i]) > len(longest_word):
# Update the longest word
longest_word = words[i]
# Display the longest word
print("Longest word:", longest_word)
Extension
Update the program so that when it displays the longest word, it also shows the number of characters in that word. This gives extra information about the result and helps the user understand how the program decided which word was the longest.
Sentence: The black cat jumped over the tall fence Longest word: jumped (length 6)