2.9 - Implementing Selection and Iteration Algorithms

mg8mer

Introduction

Welcome to the FiveHive article for topic 2.9 of AP CSA! 

In this article, we will briefly cover the learning objective of 2.9 as shown in the AP® Computer Science A Course and Exam Description 2025.

2.9.A - Develop code for standard and original algorithms (without data structures) and determine the result of these algorithms. 

This topic doesn’t have anything to cover in terms of content. In essence, we’re mainly applying what we’ve been learning for the past 8 topics.

Thus in this article, you’ll mainly do a coding problem on your own.

Without further ado, let’s get started. Get excited you guys!

Standard Algorithms

In Java, using iteration, selection, or a combination of the two, you can implement algorithms to do things such as (CED):

  • Identify if an integer is or is not evenly divisible by another integer
  • Identify the individual digits in an integer
  • Determine the frequency with which a specific criterion is met
  • Determine a minimum or maximum value
  • Compute a sum or average

Practice

Write a method that takes some String and determines how many letters in that string are lexicographically smaller than the respective following letter in that String.

For example, let’s assume our string is “abs”. 

Your method should output 2. 

This is because when comparing a and b, a is indeed lexicographically smaller than b, because b comes after a.

Then with b and s, because s comes after b, b is lexicographically smaller than a.

And lastly, we don’t compare the last letter, which in this case is s, because nothing comes after, so you should NOT take it into consideration in your method.

Please try this on your own, then compare your solution to mine below!


Practice Canonical Solution


public static int numLexicoSmaller(String w)
{
    int counter = 0;
    for (int i = 0; i < w.length() - 1; i++)
    {
        if (w.substring(i, i+1).compareTo(w.substring(i+1, i+2)) < 0)
        {
        	counter++;
         }
    }
    return counter;
}