C Program sum of first n natural nummbers
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
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: Using for Loop
In this method, we iterate from 1 to N, adding each number to the sum variable.
#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
Explanation:
To calculate the sum of the first N natural numbers:
- Initialize a variable sum to 0.
- Use a for loop to iterate from 1 to N.
- Add each iterated value to the sum variable.
- Print the final sum.
Method 2: Using Formula
We use the mathematical formula: Sum = N * (N + 1) / 2 to compute the sum efficiently.
#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
Explanation:
Using the formula N(N+1)/2, we can compute the sum in constant time:
- Substitute N with the given number.
- Compute the formula.
- Print the final sum.
This approach has a time complexity of O(1), making it highly efficient.
Method 3: Using Recursion
We use a recursive function that repeatedly adds numbers from N to 1.
#include <stdio.h> int getSum(int n) { if(n == 0) return 0; return n + getSum(n - 1); } int main() { int n; scanf("%d", &n); printf("%d", getSum(n)); return 0; }
Output:
5 Sum is 15
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.