C Program To Evaluate sin(x) = x – (x^3)/3! + (x^5)/5! + (x^7)/7! + ..

Write a C function to evaluate the series

sin(x) = x – x3/3! + x5/5! – x7/7! …

up to 10 terms.

Analyze Above Problem Statement

Sine series formula

1. In above sine series, observe the first term, which is x. Which can be written as x1/1!.

i.e., x = x1/1!;

2. Check the exponent and the number used to divide the value of x in each series. 1 followed by 3 which is followed by 5 and so on. If you observe closely they’re all odd numbers. Adding 2 to 1 gives you 3. Adding 2 to 3 gives you 5. Adding 2 to 5 gives you 7 and so on ..

So the sine series becomes:

sin(x) = x1/1! – x3/3! + x5/5! – x7/7! + x9/9! – x11/11! + x13/13! – x15/15! + x17/17! – x19/19!

Now we have all 10 terms in the sine series.

3. Now observe the sign. First term in the series is positive. Second term is negative. Third term is positive. Again the forth term is negative. So we can conclude that, first term starts with positive and then it’s an alternative between negative and positive.

4. Next we need to find factorial of each number which divides x in each series. i.e., 1, 3, 5, 7, 9, 11, 13, 15, 17, 19. (10 odd numbers)

Related Read:
Basics of Pointers In C Programming Language
Function / Methods In C Programming Language

Very Important Note:

Any address preceded by a * (Indirection operator) will fetch the value present at that address.

Video Tutorial: C Program To Evaluate sin(x) = x – (x^3)/3! + (x^5)/5! + (x^7)/7! + ..


[youtube https://www.youtube.com/watch?v=WF1UUdoZX5Q]

YouTube Link: https://www.youtube.com/watch?v=WF1UUdoZX5Q [Watch the Video In Full Screen.]


Source Code: C Program To Evaluate sin(x) = x – (x^3)/3! + (x^5)/5! + (x^7)/7! + ..

#include<stdio.h>
#include<math.h>

double factorial(int);
void   calc(float, float*);

int main()
{
    int   x;
    float radian, result = 0;

    printf("Enter value of x in degrees\n");
    scanf("%d", &x);

    radian = x * (3.14159 / 180.0); // Convert Degree To Radian

    calc(radian, &result);

    printf("Sin(%d) = %f\n", x, result);

    return 0;
}

void calc(float num, float *res)
{
    int count, n = 1, sign = 1;

    for(count = 1; (n <= 10); count += 2)
    {
       *res  +=  sign * ( pow(num, count) / factorial(count) );
        n    +=  1;
        sign *= -1;
    }
}

double factorial(int num)
{
    int    count;
    double sum = 1;

    for(count = 1; count <= num; count++)
    {
        sum *= count;
    }
    return(sum);
}

Output 1:
Enter value of x is degrees
0
Sin(0) = 0.000000

Output 2:
Enter value of x is degrees
30
Sin(30) = 0.500000

Output 3:
Enter value of x is degrees
45
Sin(45) = 0.707106

Output 4:
Enter value of x is degrees
60
Sin(60) = 0.866025

Output 5:
Enter value of x is degrees
90
Sin(90) = 1.000000

Check above output with the value present in below chart. If you further evaluate the values present in below chart, it matches with the output of our program:

Sine series values

Compound Assignment Operator

We are using compound assignment operator in this program.

 sum   *=  count;
 count +=  2
*res   +=  sign * ( pow(num, count) / factorial(count) );
 n     +=  1;
 sign  *= -1;

which is equal to writing:

 sum   =  sum * count;
 count =  count + 2;
*res   = *res + sign * ( pow(num, count) / factorial(count) );
 n     =  n + 1;
 sign  =  sign * -1;

Usually many advanced developers use such shorthand notations while writing the programs. So we need to at least understand their code while going through it on their git repository or a simple source file.

Compound Assignment Operators in C

Logic To Evaluate sin(x) = x – (x^3)/3! + (x^5)/5! + (x^7)/7! + ..

User enters value of x in degrees. We convert it to radian value using the formula:

radian = x * (3.14159 / 180.0);

C Program To Convert Degree To Radian

We pass the value of radian and address of another floating point variable result to a function calc();

Inside calc() function
Inside calc() function we iterate the for loop 10 times, as we need to find 10 terms in the series(according to the problem statement). We initialize the value of count(loop counter variable) to 1. For each iteration of for loop we increment the value of count by 2. For 10 iterations count value changes as follows: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19.

Inside for loop we calculate each series one by one:
*res += sign * ( pow(num, count) / factorial(count) );
sign *= -1;

We initialize the value of variable sign to 1. And then we alternate the sign from positive to negative, and negative to positive for each iteration.

We are making use of pow() builtin method to find num to the power of count. pow() is present in math.h library file, so we include it in the header of our program.

Calculate Power of a Number using pow(): C Program

We also call a method called factorial() to find factorial of the value present in variable count.

Inside factorial() function
Inside factorial() function we calculate the factorial of the passed number.

Factorial of a number is the product of all the numbers preceding it. For example, Factorial of 6 is 720 (1 x 2 x 3 x 4 x 5 x 6 = 720). Denoted by 6! = 720;

C Program To Find Factorial of a Number using Function

In general, n objects can be arranged in n(n – 1)(n – 2) … (3)(2)(1) ways. This product is represented by the symbol n!, which is called n factorial. By convention, 0! = 1.

Very Important Note

In factorial() function, variable sum has a return type of double. That is because int(integer) type variable can only hold up to 4 bytes of data. Where as double type variable can hold up to 8 bytes. Ofcourse these memory allocations are machine dependent, however on any machine double type variable holds more bytes than int type. So we prefer using double here as we’ll be calculating factorial for bigger numbers i.e., from 1 to 19. Since we’ll be returning value of sum from the factorial() function, we need to have a return type of double for the factorial() function too.

1.  1!  = 1.000000
2.  3!  = 6.000000
3.  5!  = 120.000000
4.  7!  = 5040.000000
5.  9!  = 362880.000000
6.  11! = 39916800.000000
7.  13! = 6227020800.000000
8.  15! = 1307674368000.000000
9.  17! = 355687428096000.000000
10. 19! = 121645100408832000.000000

Using sizeof() operator we can know the memory allocation for each data type: Sizeof Operator in C Programming Language.

Also note that the format specifier for double data type is %lf.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Calculate Sum, Average, Variance and Standard Deviation: C Program

Write a function that receives 5 integers and returns the sum, average and standard deviation of these numbers. Call this function from main() and print the results in main().

Analyze The Above Problem Statement

1. We need to write a function to calculate the results.
2. Our function receives 5 integers.
3. We need to calculate sum, average or mean and standard deviation inside the function.
4. Problem statement is asking us to return 3 values from the function, which is not possible. But we can work around and use pointers to make it work. So the problem statement is indirectly asking us to use pointers to return more than 1 value from the function.
5. We will not be using arrays in this program since the number of inputs is fixed to 5. We can take 5 variables to store the values entered/input by the user.

Note: Perfect code for above problem statement is present at the end of this blog post / article. In the video we’ve made some modifications to get accurate results for various user inputs. None-the-less, you can find the exact c source code for above problem statement at the end of this blog post.

Related Read:
Basics of Pointers In C Programming Language
Assignment Operators in C

Very Important Note:

Any address preceded by a * (Indirection operator) will fetch the value present at that address.

Video Tutorial: Calculate Sum, Average, Variance and Standard Deviation: C Program


[youtube https://www.youtube.com/watch?v=2CU6uSjyndA]

YouTube Link: https://www.youtube.com/watch?v=2CU6uSjyndA [Watch the Video In Full Screen.]


Source Code: Calculate Sum, Average, Variance and Standard Deviation: C Program

#include<stdio.h>
#include<math.h>

void stand_devi(float, float, float, float, float,
                float*, float*, float*, float*);

int main()
{
    float a, b, c, d, e;
    float sum = 0, avg = 0, sd = 0, vari = 0;

    printf("Enter 5 numbers\n");
    scanf("%f%f%f%f%f", &a, &b, &c, &d, &e);

    stand_devi(a, b, c, d, e, &sum, &avg, &vari, &sd);

    printf("\nSum = %0.2f\n", sum);
    printf("Mean / Average = %0.2f\n", avg);
    printf("Variance = %0.2f\n", vari);
    printf("Standard Deviation = %0.2f\n", sd);

    return 0;
}

void stand_devi(float a, float b, float c, float d, float e,
                float *sum, float *avg, float *v, float *sd)
{
    *sum = a + b + c + d + e;
    *avg = *sum / 5.0;

    *v   += pow( (a - *avg), 2 );
    *v   += pow( (b - *avg), 2 );
    *v   += pow( (c - *avg), 2 );
    *v   += pow( (d - *avg), 2 );
    *v   += pow( (e - *avg), 2 );

    *v   = *v / 5.0;
    *sd  = sqrt(*v);
}

Output:
Enter 5 numbers
50
-5
14
122
41

Sum = 222.00
Mean / Average = 44.40
Variance = 1885.84
Standard Deviation = 43.43

Logic To Calculate Sum, Average, Variance and Standard Deviation

We pass 5 floating point variables and address of 4 floating point variables to the function stand_devi().

Using below formula we calculate sum, average/mean, variance and standard deviation:

*sum = a + b + c + d + e;
*avg = *sum / 5.0;

*variance = ( (a – *avg) x (a – *avg) + (b – *avg) x (b – *avg) + (c – *avg) x (c – *avg) + (d – *avg) x (d – *avg) + (e – *avg) x (e – *avg) ) / 5.0;

*standard_deviation = sqrt(*variance);

Inside stand_devi() function we are calculating sum, average, variance and standard deviation and storing it inside the address of variables sum, avg, vari, sd. So value changes is reflected in the entire program and not just inside stand_devi() method.

C Program Source Code Which Matches the Problem Statement Exactly

#include<stdio.h>
#include<math.h>

void stand_devi(int, int, int, int, int,
                float*, float*, float*);

int main()
{
    int a, b, c, d, e;
    float sum = 0, avg = 0, sd = 0;

    printf("Enter 5 numbers\n");
    scanf("%d%d%d%d%d", &a, &b, &c, &d, &e);

    stand_devi(a, b, c, d, e, &sum, &avg, &sd);

    printf("\nSum = %0.2f\n", sum);
    printf("Mean / Average = %0.2f\n", avg);
    printf("Standard Deviation = %0.2f\n", sd);

    return 0;
}

void stand_devi(int a, int b, int c, int d, int e,
                float *sum, float *avg, float *sd)
{
    float v = 0; // Variance

    *sum = a + b + c + d + e;
    *avg = *sum / 5.0;

     v   += pow( (a - *avg), 2 );
     v   += pow( (b - *avg), 2 );
     v   += pow( (c - *avg), 2 );
     v   += pow( (d - *avg), 2 );
     v   += pow( (e - *avg), 2 );

     v   /= 5.0;

    *sd  = sqrt(v);
}

Output:
Enter 5 numbers
50
69
92
30
-60

Sum = 181.00
Mean / Average = 36.20
Standard Deviation = 52.29

Here we’re following all the things mentioned in the problem statement. We are taking 5 integer values and passing it to our user defined function. Inside the function we are calculating the sum, average and standard deviation and storing it at address of variables sum, avg, and sd. This modification or change is reflected everywhere in the program as we are modifying the value present at address. Addresses are unique and any changes made to the value present at a address reflects everywhere in the program. That’s how we are able to print the result i.e., values of sum, avg and sd inside main() function, after calling stand_devi() function.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert