January 21, 2016 In-class activities

Problem 1

Write a function countdown() that takes a number and prints:

N
N-1
N-2
...
1
Liftoff!

where N is the number you give it.

Example:

countdown(3);
3
2
1
Liftoff!

One possible answer:

In [1]:
void countdown(int n) {
    for (int i = n; i > 0; i--) {
        printf("%s\n", i);
    }
    printf("Liftoff!");
}
|  Added method countdown(int)

In [2]:
countdown(10)
10
9
8
7
6
5
4
3
2
1
Liftoff!
In [3]:
countdown(3)
3
2
1
Liftoff!

Problem 2

Write a function volume() that takes an height, width, and length dimensions and returns the volume of a cube with those dimensions.

One possible answer:

In [4]:
double volume(double width, double height, double length) {
    return (width * height * length);
}
|  Added method volume(double,double,double)

In [5]:
volume(3, 4, 6)
|  Expression value is: 72.0
|    assigned to temporary variable $5 of type double

Out[5]:
72.0

Problem 3

Define a class to hold students. The constructor should take a name and a year of graduation. Add a method "status" that when called, says: "You are a junior" (or whatever). Assume that the year is 2016.

Student student1 = new Student("Milley Cyrus", 2018); Student student2 = new Student("Taylor Swift", 2012);

The status is one of:

  • not in college yet
  • firstyear
  • sophomore
  • junior
  • senior
  • graduated

The beginning of a solution:

In [6]:
class Student {
    String name;
    int year;
    Student(String name, int year) {
        this.name = name;
        this.year = year;
    }
    void status() {
        printf("You are crazy!");
    }
}
|  Added class Student

In [7]:
Student miley = new Student("Miley Cyrus", 2015);
|  Added variable miley of type Student with initial value Student@50675690

In [8]:
miley.status()
You are crazy!