This lab gives an example of the programming expertise needed for this course.
Getting started
Start up NetBeans and create a project for a Java Application. Use the names of your choice.
Delete the default main
method
and replace it with the following:
public static void main(String[] args) { java.util.Random g = new java.util.Random() ; int X[] = new int[1000 + g.nextInt(10)] ; for (int i = 0; i<X.length; ++i) { X[i] = g.nextInt(10) ; } System.out.println(exceeds(X, 3)) ; System.out.println(exceeds(X, 7)) ; System.out.println(exceeds(new int[]{}, 2015)) ; }
Writing the missing method
This program is missing the exceeds
method.
A correct exceeds
method takes two arguments.
The first is an array of integers, and the second is an integer.
The exceeds
method returns the number of elements
in the array that are greater than the second argument.
When run, this problem should print three numbers. The first should be close to 600, the second should be close to 200, and the third should be 0.
Show the lab instructor the result of your program’s execution.
For those who prefer an alternative
Here are some alternate entry points for those with more experience with C, C++, Python, or Processing.
Processing
Because Processing is an extension of Java, the implementation
of exceeds
is the same as in Java (ignoring the
public static
method modifier required in Java).
If you want to use the Processing IDE,
start with the following program and add exceeds
.
void setup() { noLoop() ; } void draw() { java.util.Random g = new java.util.Random() ; int X[] = new int[1000 + g.nextInt(10)] ; for (int i = 0; i<X.length; ++i) { X[i] = g.nextInt(10) ; } println(exceeds(X, 3)) ; println(exceeds(X, 7)) ; println(exceeds(new int[]{}, 2015)) ; }
C
Start with the following main
routine.
Because C and C++ don’t have an operator for determining the size
of an array,
the exceeds
function requires an additional argument
that gives the size of the array.
#include <time.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { int X[1010], xSize, i ; srand(time(NULL)) ; xSize = 1000 + rand()%10 ; for (i = 0; i<xSize; ++i) { X[i] = rand()%10 ; } fprintf(stdout, "%d\n", exceeds(X, xSize, 3)) ; fprintf(stdout, "%d\n", exceeds(X, xSize, 7)) ; fprintf(stdout, "%d\n", exceeds(X, 0, 2015)) ; return (EXIT_SUCCESS); }
Python
Start with the following Python program and add the exceeds
function.
This program uses the common Python list rather than the much rarer
(and more difficult)
array
class.
import random def main(): g = random.Random() x = [g.randint(0, 9) for e in range(g.randint(1000, 1009))] print(exceeds(x, 3)) print(exceeds(x, 7)) print(exceeds([], 2015)) if __name__ == "__main__": main()