Java Program for Even/Odd and Sum of N Natural Numbers
Check if a Number is Even or Odd in Java
Given an integer input, the objective is to determine whether a number is even or odd using Java programming.
An even number is completely divisible by 2, whereas an odd number leaves a remainder of 1 when divided by 2.
Example:
Input: Num = -5
Output: The number is Negative
Methods to Check Even or Odd
- Method 1: Using Brute Force
- Method 2: Using Nested if-else Statements
- Method 3: Using the Ternary Operator
Sum of First N Natural Numbers (Java)
Natural numbers are a sequence of positive numbers starting from 1. The sum of the first N natural numbers can be calculated using different methods.
Method 1: Using for Loop (Java)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Kindly Insert an Integer Variable: ");
int n = scanner.nextInt();
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("Sum of Natural Numbers = " + sum);
scanner.close();
}
}
Output:
Kindly Insert an Integer Variable: 3 Sum of Natural Numbers = 6
Method 2: Using Formula (Java)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Kindly Insert an Integer Variable: ");
int n = scanner.nextInt();
int sum = n * (n + 1) / 2;
System.out.println("Sum of Natural Numbers = " + sum);
scanner.close();
}
}
Output:
Kindly Insert an Integer Variable: 3 Sum of Natural Numbers = 6
Method 3: Using Recursion (Java)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Kindly Insert an Integer Variable: ");
int n = scanner.nextInt();
System.out.println("Sum of Natural Numbers = " + getSum(n));
scanner.close();
}
static int getSum(int n) {
if (n == 0)
return 0;
return n + getSum(n - 1);
}
}
Output:
Kindly Insert an Integer Variable: 3 Sum of Natural Numbers = 6