Programming Basics SQL HTML CSS JavaScript Python C++ Java JavaFX Swing Problem Solving English English Conversations Computer Fundamentals Learn Typing

تحديات برمجيةالتحدي الثالث - حل التمرين الأول بلغة جافا

المطلوب

قم بتعريف دالة إسمها FindAll, مهمتها البحث في مصفوفة أحادية ( تتألف من أعداد صحيحة ) نمررها لها عن قيمة محددة أيضاً نمررها لها, و من ثم طباعة Index كل عنصر يملك هذه القيمة.
بعدها قم بتجربة هذه الدالة في البرنامج.


الحل بلغة جافا

public class Main {
// هنا قمنا بتعريف الدالة
public static void findAll(int[] arr, int x)
{
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == x)
{
System.out.println("'" + x + "' found at index " + i);
}
}
}
public static void main(String[] args)
{
// هنا قمنا بتجهيز القيم التي سنمررها للدالة
int[] array = {1, 2, 3, 2, 5, 2, 7, 2};
int value = 2;
// هنا قمنا بتجربة الدالة
findAll(array, value);
}
}
public class Main { // هنا قمنا بتعريف الدالة public static void findAll(int[] arr, int x) { for (int i = 0; i < arr.length; i++) { if (arr[i] == x) { System.out.println("'" + x + "' found at index " + i); } } } public static void main(String[] args) { // هنا قمنا بتجهيز القيم التي سنمررها للدالة int[] array = {1, 2, 3, 2, 5, 2, 7, 2}; int value = 2; // هنا قمنا بتجربة الدالة findAll(array, value); } }

سنحصل على النتيجة التالية عند التشغيل.

'2' found at index: 1
'2' found at index: 3
'2' found at index: 5
'2' found at index: 7