Gyakorlati alapok
Elemi programozási tételek egy 10 elemű tömbön
Maximumkiválasztás
A maximumkiválasztás során megkeressük a tömb legnagyobb elemét. Fontos szempont, hogy int maximum értéke kezdetben legyen 0. Értéke akkor lesz felülírva, ha tömb i-dik eleme (tomb[i]) nagyobb nála, ezáltal a for ciklus végére garantáltan a maximumérték kerül bele.
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rnd = new Random();
int tomb[] = new int[10];
int maximum = 0;
for(int i = 0; i < tomb.length; i++) {
tomb[i] = rnd.nextInt(50) + 1;
System.out.print(tomb[i] + " ");
if(tomb[i] > maximum){
maximum = tomb[i];
}
}
System.out.println("\n" + maximum);
}
}
Végeredmény (például):
21 47 11 38 5 49 20 11 5 23
49
Ha esetleg nemcsak a maximumra, hanem annak indexére (maxIndex) is kíváncsiak vagyunk, a kódot csak kis mértékben kell módosítanunk:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rnd = new Random();
int tomb[] = new int[10];
int maximum = 0;
int maxIndex = 0;
int i;
for(i = 0; i < tomb.length; i++) {
tomb[i] = rnd.nextInt(50) + 1;
System.out.print(tomb[i] + " ");
if(tomb[i] > maximum){
maximum =
tomb[i];
maxIndex = i;
}
}
System.out.println("\nA maximum (" + maximum + ") a(z) "
+ (maxIndex + 1) + ". helyen található.");
}
}
Végeredmény (például):
3 45 3 44 13 26 29 42 1 33
A maximum (45) a(z) 2. helyen található.