C and Python 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 Python)
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 (Python)
n = 10
sum = 0
for i in range(1, n + 1):
sum += i
print(sum)
Output:
55
Method 2: Using Formula (Python)
n = 10
sum = n * (n + 1) // 2
print(sum)
Output:
55
Method 3: Using Recursion (Python)
def getSum(n):
if n == 0:
return 0
return n + getSum(n - 1)
n = 10
print(getSum(n))
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.