Question: Write a function that takes two numbers as input and returns their sum.
Ans:
package HelloWorld;
import java.util.*;
class PrimeN {
public static int sumN(int a, int b) {
int sum = a + b;
return sum;
}
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
int b = scan.nextInt();
int result = sumN(a, b); // yaha hamne ek result name ka int type ka variable banaya
System.out.println(result);
}
}
Question: Create a function that calculates the factorial of a given number using a loop.
Ans:
package HelloWorld;
import java.util.*;
class PrimeN {
public static int factorialN(int n) {
int f = 1;
for(int i = 1; i <=n; i++ ) {
f= f * i;
}return f;
}
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int result = factorialN(n);
System.out.println(result);
}
}
Question:
Comments
Post a Comment