0/30 Days Completed 0 Learning Days
Day 13 of 30 · Week 2 — Building Java Basics
Putting the basics together
1 Learn
Real programs mix everything: variables hold data, arrays hold lists, loops repeat, if decides, and methods keep it tidy.
Today's example finds the class topper and average using all of these together.
2 See the Code
Java
public class ClassReport {
static double average(int[] m) {
int total = 0;
for (int x : m) total += x;
return (double) total / m.length;
}
public static void main(String[] args) {
String[] names = {"Ananya", "Ravi", "Meena"};
int[] marks = {81, 93, 76};
int best = 0;
for (int i = 1; i < marks.length; i++) {
if (marks[i] > marks[best]) best = i;
}
System.out.println("Topper: " + names[best]);
System.out.println("Average: " + average(marks));
}
}- Two arrays share positions: names[i] goes with marks[i].
- The loop remembers the index of the highest mark.
- (double) total converts to decimal so the average keeps its fraction.
Output
Topper: Ravi Average: 83.33333333333333
3 Practice
- Add a method countPassed(int[] m) that returns how many marks are 35 or more.
Try it in your own Java setup or write it in the Practice Notebook.
4 Quick Check
1. Why do we write (double) total?
2. Which concept keeps the average code reusable?
Step 5
Answer and check the Quick Check above to unlock this.