0% found this document useful (0 votes)
5 views

L08 Arrays

The document discusses arrays and loops in programming, specifically in the context of counting letter occurrences from user input until the word 'quit' is entered. It explains how to initialize arrays, use loops for counting, and emphasizes the importance of testing each part of the code. The methodology for solving the problem is broken down into steps, including decomposition and testing of individual components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

L08 Arrays

The document discusses arrays and loops in programming, specifically in the context of counting letter occurrences from user input until the word 'quit' is entered. It explains how to initialize arrays, use loops for counting, and emphasizes the importance of testing each part of the code. The methodology for solving the problem is broken down into steps, including decomposition and testing of individual components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Loops, Arrays and Programming

CS160 Spring 2012


Savitch Section 7.1

Arrays
• An array is a set of variables of the same type
accessed by their index

int[] day = new int[4];

31 28 31 30

day[0] day[2]
day[1] day[3]
2

1
Arrays (II)
• The previous example creates 4 integers.
– They are just accessed by their position
• E,g, day[0], day[1], …
– Each integer has its own value
• Arrays can be of any type
– int, double, char, boolean, String…
– Every element of an array has the same type
• Arrays are created using the new keyword
– type[] name = new type[size];
– The new command allocates a block of memory
• The length field of an array tells you how many elements it
has
– E.g., day.length == 4.
3

Loops + arrays: challenge problem


• Task: read words from input until the word
‘quit’ appears. Then print out how many times
each lowercase letter appeared.

• Question: where do you start? How do you


approach this problem?

2
Step 1: Decomposition
• What has to be done?
• Initialize counters! – another loop
– Read strings from terminal
– For each string, Nested
• For each character, loops
– Increment counter for that character

– Print out counts per character Another


loop

Steps 2-4:
• Tackle each step individually
– Initialize counters
• Declare the counters first
• But there are 26 of them…
• … so use an array!

int[] alpha_counter = new int[26];

3
Step 2 (continued)
– Still initializing counters…
• The counters count how often each letter appears
• So we need to initialize them to zero… all 26 of
them!
• So we use a loop… a for loop (26 iterations)

for(int i=0; i < 26; i++) {


alpha_counter[i] = 0;
}

Step 2 (yet again)


• So putting it together, we need to declare and
initialize a counter for every letter in the alphabet:

int[] alpha_counter = new int[26];


for(int i=0; i < 26; i++) {
alpha_counter[i] = 0;
}

4
Step 2 (one more time!)
• Actually, hard-coding ’26’ is a bad idea
– What if we want to include capitals later?
– What if we want to re-use this code?
• We want to initialize the whole array, and nothing more:

int[] alpha_counter = new int[26];


for(int i=0;
i < alpha_counter.length;
i++) {
alpha_counter[i] = 0;
}

Does it work?
• Did we declare and initialize the counters correctly?
– Never assume something is correct
– Test each step before moving on
• How?
– Method #1: Use the debugger
• Run the code (so far) step-by-step (F6)
• Check that the array has 26 elements
• Check that each is set to zero
– Method #2: Write the code to print counters
• Test it before you start counting letters

10

5
Printing the Counters

• So printing the counters is another loop:


– Why the trailing println()?

for(int i=0; i < 26; i++) {


System.out.print(alpha_counter[i]+” ”);
}
System.out.println();

11

Your First Test Code


• What should this print?
// Declare & Initialize Counters
int[] alpha_counter = new int[26];
for(int i=0; i < 26; i++) {
alpha_counter[i] = 0;
}

// Print Counters
for(int i=0; i < 26; i++) {
System.out.print(alpha_counter[i]+” ”);
}
System.out.println();
12

6
Running Your First Test
Class Letters {
public static void main(String[] args) {
// Declare and initialize counters
int[] alpha_counter = new int[26];
for(int i=0; i < 26; i++) {
alpha_counter[i] = 0;
}

// Print Counters
for(int i=0; i < 26; i++) {
System.out.print(alpha_counter[i]+” ”);
}
System.out.println();
}
}

13

Reading Strings & Counting Letters


• The next step has two parts:
– Read strings (until “quit”)
– Increment letter counters

• Decompose the (sub)problem


– Either read strings…
• Assuming you can count letters once you have them
– Or count letter instances
• Given a string (assume you can get strings somehow)

Don’t try to do two things at once!

14

7
One approach…
• We’ve already written a loop to read until “quit”
– Remember the Echo program?
• So let us start with that:

Scanner in_str = new Scanner(System.in);


String user_string = in_str.next();
while (!user_string.equals("quit")) {
System.out.println(user_string);
Put new code to count letters here!
user_string = in_str.next();
}

15

Wait! Stop! Test this First!


• How?
– Use a print statement to make sure you are
getting the right strings, or…
– Use the debugger!

Scanner in_str = new Scanner(System.in);


String user_string = in_str.next();
while (!user_string.equals("quit")) {
System.out.println(user_string);
user_string = in_str.next();
}
16

8
Counting Letters
• Given a string, we need to increment a counter
for every letter.
– Nested loop inside the get string loop

for(int i=0; i < user_string.length(); i++)


{
char letter = user_string.charAt(i);
OK, increment letter count here…
}

17

Counting Letters (II)


• Now increment the appropriate counter

for(int i=0; i < user_string.length(); i++)


{
char letter = user_string.charAt(i);
switch(letter) {
case ‘a’: alpha_counter[0]++; break;
case ‘b’: alpha_counter[1]++; break;
case ‘c’: alpha_counter[2]++; break;
// 23 more cases…
}

18

9
Counting Letters (alt)
• The previous code is clean but long.
• Java supports ASCII char subtraction
char first_char = ‘a’;
char second_char = ‘b’;
// z == 1
int z = second_char – first_char;

for(int i=0; i < user_string.length(); i++)


{
char letter = user_string.charAt(i);
int offset = letter – ‘a’;
if ((offset >= 0) && (offset < 26)) {
alpha_counter[offset]++;
}
19
}

Put it all together


Class Letters {
public static void main(String[] args) {

// Declare and initialize counters


int[] alpha_counter = new int[26];
for(int i=0; i < 26; i++) {
alpha_counter[i] = 0;
}

20

10
All together (II)
// count letters
Scanner in_str = new Scanner(System.in);
String user_string = in_str.next();
while (!user_string.equals("quit")) {
for(int i=0; i < user_string.length(); i++) {
char letter = user_string.charAt(i);
int offset = letter – ‘a’;
if ((offset >= 0) && (offset < 26)) {
alpha_counter[offset]++;
}
}
user_string = in_str.next();
}

21

All Together (III)


// Print Counters
for(int i=0; i < 26; i++) {
System.out.print(alpha_counter[i]+” ”);
}
System.out.println();
}
}

22

11
Done Yet? No!
• Test your program:
– Make up some input
– Count the letters by hand
– Double check your program’s results
• Make Hard Tests
– Include characters that aren’t letters
– Test the case where the first input is ‘quit’
– Test really long inputs
– ….
• Hint: it can be good to think of test cases first.

23

Methodology Review

1. Get a problem definition


– Designing hard test cases can help refine the
problem statements
2. Break the problem into pieces
– Attack each piece separately
– If a piece is big, break it up again
3. Test each piece before moving on
– This may require temporary code
– The debugger can help

24

12

You might also like