CSci 2101 Data Structures: Lab 3

Problem 1

In the following program fill in the code to print the pattern of alternating two characters (separated by spaces) repeated n times. For instance, for the characters and n defined in the program the result should be:
a ? a ? a ? a ? a ?
Change the characters and n to make sure that the program works right. Make sure to test it for n = 0.

public class LabThreeProbOne {
	public static void main(String[] args){
	    char c1 = 'a';
	    char c2 = '?';
	    int n = 5;

	    // your code goes here:

	}
}

Problem 2

In the following program fill in the code to count the number even elements of the array. Change the array to test the program. Comment out, but do not delete, your test cases.

public class LabThreeProbTwo {
	public static void main(String[] args){
	    int [] a = {1, 3, 6, 8, -7, 0, -8, 122, 3, 8, -8};

	    int count = 0; // the counter for even elements

	    // your code goes here:


	    // printing counter at the end:
	    System.out.println("the array has " + count + " even elements");
	}
}

Problem 3

Fill in the code to create and initialize an array of squares of integers from 1 to n in increasing order. I.e. if n = 3, the array will have 3 elements: 1, 4, 9. Make sure to test your program, it should work for any non-negative integer n.
Make sure to print out the array at the end of the program to test.

public class LabThreeProbThree {
	public static void main(String[] args){
	    int n = 3;
	    // fill in your code here:

	}
}

Problem 4

Write a program to find the smallest element of an integer array. Show all your test cases. Write this program using a 'for' loop and a 'for-each' loop.

*Problem 5: extra credit*

Write a program that demonstrates the difference between n++ and ++n. The program should evaluate two expression with the same starting values which differ only in replacing n++ by ++n. The printed results should show the difference.
This is a lab from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.