Skip to content

Lab 3: CodingBat Loops

Today's lab is about loops, strings, and arrays. The goal is to solve as many CodingBat problems as you can during the lab period. Make sure you log in to CodingBat for your submissions to be counted. Grading will be done directly from CodingBat. If you have not yet set up your CodingBat account, please see the Lab02 instructions.

Learning Objectives

After completing this lab, you should be able to:

  • Solve CodingBat problems that require looping over a string.
  • Solve CodingBat problems that require looping over an array.
  • Explain differences when looping over strings and arrays.

Tip

You need to solve at least five problems in each category (String-2 and Array-2). Solutions for the first two problems are provided below. You are welcome to submit that code if you would rather solve only three problems on your own. Or, if you would like additional practice, you are welcome to solve more than five problems. The choice is yours!

String-2 Problems

Solve any five problems from the String-2 category.

Example 1: doubleChar

Problem: Given a string, return a string with two of every character.

Solution: Create a new string, and append each character twice.

public String doubleChar(String str) {
    String result = "";
    for (int i = 0; i < str.length(); i++) {
        result += str.charAt(i);
        result += str.charAt(i);
    }
    return result;
}
Example 2: countHi

Problem: Count the number of times "hi" appears in a string.

Solution: At each index, look for the letter 'h' followed by the letter 'i'. Notice the loop stops at length() - 1, because the if statement looks at index i + 1.

public int countHi(String str) {
    int count = 0;
    for (int i = 0; i < str.length() - 1; i++) {
        if (str.charAt(i) == 'h' && str.charAt(i + 1) == 'i') {
            count++;
        }
    }
    return count;
}

Array-2 Problems

Solve any five problems from the Array-2 category.

Example 1: countEvens

Problem: Count the even integers in an array.

Solution: Increment a count variable each time an even value is found.

public int countEvens(int[] nums) {
    int count = 0;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] % 2 == 0) {
            count++;
        }
    }
    return count;
}
Example 2: bigDiff

Problem: Get the difference between the max and min values.

Solution: Find the min and max by starting with the first value and comparing with every other value in the array.

public int bigDiff(int[] nums) {
    int max = nums[0];
    int min = nums[0];
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] > max) {
            max = nums[i];
        }
        if (nums[i] < min) {
            min = nums[i];
        }
    }
    return max - min;
}

Extra Practice

The String-1 and Array-1 categories involve problems that don't require loops. You can solve problems in these two categories to become more familiar with strings and arrays in general.