Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to calculate sum of series using predefined function
In C programming, calculating the sum of mathematical series is a common task. This program demonstrates how to calculate the sum of the series: 1 - n²/2! + n?/4! - n?/6! + n?/8! - n¹?/10! using the predefined pow() function from the math.h library.
Syntax
double pow(double base, double exponent);
Algorithm
The algorithm to calculate the sum of series using predefined function −
- Step 1: Read the value of n from user
- Step 2: Initialize factorial = 1, sum = 1, and loop counter
-
Step 3: For each even power from 2 to 10:
- Calculate factorial for current power
- Use
pow()to calculate n raised to current power - Apply alternating signs (negative for powers 2, 6, 10)
- Add/subtract the term to/from sum
- Step 4: Display the final sum
Example
Following is the C program to calculate sum of series using the predefined pow() function −
Note: To compile this program, you may need to link the math library using
-lmflag:gcc program.c -lm
#include <stdio.h>
#include <math.h>
int main() {
int i, n = 5, num;
long int fact = 1;
double sum = 1.0;
printf("Enter the n value: ");
scanf("%d", &num);
for(i = 1; i <= n; i++) {
fact = fact * i;
if(i % 2 == 0) {
if(i == 2 || i == 6 || i == 10)
sum += -pow(num, i) / fact;
else
sum += pow(num, i) / fact;
}
}
printf("Sum is %.6f
", sum);
return 0;
}
Output
Enter the n value: 10 Sum is 367.666656
How It Works
The program implements the series calculation by −
- Starting with sum = 1 (first term of the series)
- Computing factorial incrementally for each term
- Using
pow(num, i)to calculate powers of n - Applying alternating signs based on the position in series
- The series approximates the mathematical function cos(?n)
Key Points
- The
pow()function requires themath.hheader file - Factorial is calculated iteratively to avoid repeated calculations
- The series uses only even powers (2, 4, 6, 8, 10) with alternating signs
- Using
doublefor sum ensures better precision for floating-point calculations
Conclusion
This program efficiently calculates the sum of a mathematical series using the predefined pow() function. The approach demonstrates how to combine loops, conditionals, and math library functions to solve complex mathematical problems in C.
