C Program to check if a Number Is Positive Or Negative Even or Odd
Check if a Number is Even or Odd in C
Given an integer input, the objective is to write a code to Check if a Number is Even or Odd in C Language.
An even number is completely divisible by 2, while an odd number has a remainder of 1 when divided by 2.
For Instance,
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
C Program to Find the Sum of First N Natural Numbers
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: Iterative Approach
This method uses a loop to add numbers from 1 to N iteratively.
#include <stdio.h> int main() { int n, sum = 0; scanf("%d", &n); for(int i = 1; i <= n; i++) sum += i; printf("Sum is %d", sum); return 0; }
Output:
5 Sum is 15
Method 2: Using Formula
The mathematical formula for the sum of first N natural numbers is: Sum = N * (N + 1) / 2.
#include <stdio.h> int main() { int n; scanf("%d", &n); int sum = n * (n + 1) / 2; printf("The sum is %d", sum); return 0; }
Output:
6 The sum is 21
Method 3: Recursive Approach
Recursion is used to break the problem into smaller subproblems, reducing the number by 1 in each step.
#include <stdio.h> int getSum(int sum, int n) { if(n == 0) return sum; return n + getSum(sum, n - 1); } int main() { int n, sum = 0; scanf("%d", &n); printf("%d", getSum(sum, n)); return 0; }
Output:
5 Sum is 15