Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to compute the cosine series using function. =1-x2/2!+x4/4!-x6/6!----

C Code Example — Function Programs

ADVERTISEMENT

C Program to compute the cosine series using function. =1-x2/2!+x4/4!-x6/6!----

Objective

Write a C program to compute the Cosine series: 1 - x2/2! + x4/4! - x6/6!...

Algorithm / Approach

  1. Create a cal_cos(x, n) function.
  2. Inside it, use a loop to iterate n times.
  3. Use the condition if (i % 2 == 0) to alternate between adding and subtracting the term from the sum.
  4. The term formula is pow(a, j) / fact(j), where j starts at 2 and increments.
main.c
#include<stdio.h>
#include<math.h>
float cal_cos(int, int);
int fact(int);
int main( ) 
{

 int x, n;
 printf("Enter the value of x : ");
 scanf("%d",&x);
 printf("Enter the value of n : ");
 scanf("%d",&n);
 float r = cal_cos(x, n);
 printf("Result = %f ",r);
 return 0;
}
float cal_cos(int a, int n) {
 int j =2 ;
 float sum = 1;
 for(i=1; i<=n; i++)
 {
  if(i%2 ==0)
  {
   sum = sum+pow(a,j)/(float)fact(j);
 }
 else
  {
   sum = sum-pow(a,j)/fact(j);
  }
 }
 return sum;
}

int fact(int x){
 int i, f=1;
 for(i=1; i<=x; i++){
  f = f*i;
 }
 return f;
}

Expected Output

Enter the Value of x : 3
 Enter the Value of n : 3
 Result = -1.250000

Explanation of the Program

  • The Cosine series (a Maclaurin series in calculus) calculates the exact value of a cosine angle using infinite polynomials.
  • Notice the explicit cast (float)fact(j). Because pow() and fact() both return integers in this specific code, dividing them would cause integer truncation. Casting forces floating-point division to preserve decimal accuracy.

Complexity

Time Complexity O(n^2)
Space Complexity O(1)
ADVERTISEMENT