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

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

المطلوب

قم بتعريف دالة إسمها Factorial(), عند استدعاءها نمرر لها عدد, فترجع ناتج قيمة الـ Factorial له.
بعدها قم بتجربة هذه الدالة في البرنامج.


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

public class Main {
public static int factorial(int n)
{
int f = 1;
for (int i = 1; i <= n; i++)
{
f *= i;
}
return f;
}
public static void main(String[] args)
{
int x = 5;
System.out.println(x + "! = " + factorial(x));
}
}
public class Main { public static int factorial(int n) { int f = 1; for (int i = 1; i <= n; i++) { f *= i; } return f; } public static void main(String[] args) { int x = 5; System.out.println(x + "! = " + factorial(x)); } }

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

5! = 120