C and Java Programs for Even/Odd and Sum of N Natural Numbers
Check if a Number is Even or Odd in C
Given an integer input, the objective is to determine whether a number is even or odd using C 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 (C and 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 Brute Force
public class Main {
public static void main (String[] args) {
int n = 10;
int sum = 0;
for (int i = 1; i <= n; i++)
sum += i;
System.out.println(sum);
}
}
Output:
55
Method 2: Using Nested if-else Statements (Java)
public class Main {
public static void main (String[] args) {
int n = 10;
System.out.println(n * (n + 1) / 2);
}
}
Output:
55
Method 3: Using Recursion (Java)
public class Main {
public static void main (String[] args) {
int n = 10;
int sum = getSum(n);
System.out.println(sum);
}
static int getSum (int n) {
if (n == 0)
return 0;
return n + getSum(n - 1);
}
}
Output:
55
Explanation:
To calculate the sum recursively:
- Define a recursive function getSum() that calls itself.
- Base case: If n == 0, return 0.
- Otherwise, return n + getSum(n-1).
- Print the result.
While recursion simplifies the code, it has a time complexity of O(N) and uses extra memory due to function calls.