Hayotiy misollar
Hayotiy misol
Massivlardan foydalanishning amaliy misolini ko‘rsatish uchun turli yoshlarning o‘rtacha qiymatini hisoblaydigan dastur yaratamiz:
Misol
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
float avg, sum = 0;
// Get the length of the array
int length = ages.length;
// Loop through the elements of the array
for (int age : ages) {
sum += age;
}
// Calculate the average by dividing the sum by the length
avg = sum / length;
// Print the average
System.out.println("The average age is: " + avg);
Bu misolda esa turli yoshlar orasidan eng kichigini topadigan dastur yaratamiz:
Misol
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
// Get the length of the array
int length = ages.length;
// Create a 'lowest age' variable and assign the first array element of ages to it
int lowestAge = ages[0];
// Loop through the elements of the ages array to find the lowest age
for (int age : ages) {
// Check if the current age is smaller than the current 'lowest age'
if (lowestAge > age) {
// If the smaller age is found, update 'lowest age' with that element
lowestAge = age;
}
}
// Output the value of the lowest age
System.out.println("The lowest age in the array is: " + lowestAge);
Sonlar ro‘yxati bilan ishlaydigan dastur yarating: manfiy qiymatlarni o‘tkazib yuboring, lekin nol uchrasa, butunlay to‘xtang:
Misol
int[] numbers = {3, -1, 7, 0, 9};
for (int n : numbers) {
if (n < 0) {
continue; // skip negative numbers
}
if (n == 0) {
break; // stop loop when zero is found
}
System.out.println(n);
}
Massivdagi eng katta va eng kichik qiymatlarni aniqlab boradigan dastur yarating:
Misol
int[] numbers = {45, 12, 98, 33, 27};
int max = numbers[0];
int min = numbers[0];
for (int n : numbers) {
if (n > max) {
max = n;
}
if (n < min) {
min = n;
}
}
System.out.println("Max: " + max);
System.out.println("Min: " + min);
Teatr qatoridagi o‘rindiq raqamlarini chiqaradigan dastur yarating: unda o‘rindiq raqami (indeks) ham, u yerda kim o‘tirgani (qiymat) ham ko‘rsatilsin:
Misol
String[] seats = {"Jenny", "Liam", "Angie", "Bo"};
for (int i = 0; i < seats.length; i++) {
System.out.println("Seat number " + i + " is taken by " + seats[i]);
}
W3Schools Pathfinder
Yutuqlaringizni kuzating – bu bepul!
