Longest and shortest words in a list


  • Find the length of the longest and shortest word in a list
  • How would your brain do it? (pretend that the words are hand-written so you can't just look at the one that juts out the farthest)
  • Assuming there is only a single longest and a single shortest word, report the actual longest and shortest words
  • If there are multiple longest or multiple shortest words, we have to think a little harder to solve the problem. At that point, how does your brain do it? One way is to look over the list a second time after you have the max/min lengths. This is not represented in the code below.


Test Case 1: 
Input: Brandon, Hannah, Paul, Steve (example of a list with several words of varying length)
Expected Output: 7
Actual: 7
Test Case 2:
Input: P, Q (example of list with words of only a single character)
Expected Output: 1
Actual: 1
Test Case 3:
Input: Paul (example of list with only one word)
Expected Output: 4
Actual: 4
#include <iostream>
#include <string>
using namespace std;
const int LIST_LEN = 11;
int main()
	// Look at first word
	string first_word;
	cout << "Give me your list: ";
	cin >> first_word;
	// Count letters of first word
	int count_letters_first_word = first_word.length();
	int max_len_so_far = count_letters_first_word;
	string longest_word_so_far = first_word;
	int min_len_so_far = count_letters_first_word;
	string shortest_word_so_far = first_word;
	for (int i = 1; i <= LIST_LEN; i++)
		// Look at next word
		string next_word;
		cout << "next word: ";
		cin >> next_word;
		// Count letters in next word
		int count_letters_next_word = next_word.length();
		// if next word had more letters, remember that next word instead of prev max word
		if (count_letters_next_word > max_len_so_far)
			max_len_so_far = count_letters_next_word;
			longest_word_so_far = next_word;
		if (count_letters_next_word < min_len_so_far)
			min_len_so_far = count_letters_next_word;
			shortest_word_so_far = next_word;
		// Repeat until no more words
	cout << "Max len so far is " << max_len_so_far << endl;
	cout << "That word was: " << longest_word_so_far << endl;
	cout << "Min len so far is " << min_len_so_far << endl;
	cout << "That word was: " << shortest_word_so_far << endl;
	return 0;
cs-142/longest-and-shortest-words-in-a-list.txt · Last modified: 2015/05/14 18:12 by cs142ta
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0