C Program To Find Factorial of a Number using Recursion

Lets write a C program to find Factorial of a user input number using Recursion.

Factorial Definition: Factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n.

Important Note: By convention, Factorial of 0 is 1. i.e., 0! = 1.

Example: 5! = 5 x 4 x 3 x 2 x 1 which is equal to 120. i.e., 5! = 120.

Formula To Calculate Factorial of any positive integer number
We can calculate factorial of any number using this relationship:

num! = num * (num – 1)!

where num is a positive integer number.

Related Read:
C Program To Find Factorial of a Number
Recursive Functions In C Programming Language

Video Tutorial: C Program To Find Factorial of a Number using Recursion


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

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


Source Code: C Program To Find Factorial of a Number using Recursion

#include<stdio.h>

int fact(int);

int main()
{
    int num;

    printf("Enter a positive number to find its Factorial\n");
    scanf("%d", &num);

    printf("\nFactorial of %d is %d.\n", num, fact(num));

    return 0;
}

int fact(int num)
{
    if(num)
        return(num * fact(num - 1));
    else
        return 1;
}

Output 1:
Enter a positive number to find its Factorial
7

Factorial of 7 is 5040.

Output 2:
Enter a positive number to find its Factorial
8

Factorial of 8 is 40320.

Logic To Find Factorial of a Number using Recursion

We ask the user to enter a positive integer number and we pass this number to a function called fact().

Inside fact() function
Inside fact() function, we check if the number is non-zero, if true, we execute the code inside if block orelse(if num is zero), then the code inside else block gets executed.

Inside if block, we add the factorial of (num-1) to the value of num.

num * fact(num – 1)

and return the result to the calling function.

Inside else block, we simply return 1. Because factorial of 0 is 1. So when num is 0, we return 1.

Example:

numnum * fact(num-1)
55 * fact(4)
44 * fact(3)
33 * fact(2)
22 * fact(1)
11 * fact(0)

Value Returning – Control Shifting back.

FunctionReturn Value Result
1 * fact(0)return 1;1 * 1 = 1
2 * fact(1)12 * 1 = 2
3 * fact(2)23 * 2 = 6
4 * fact(3)64 * 6 = 24
5 * fact(4)245 * 24 = 120

Finally 120 will be returned to main() method where we call the fact() method.

Source Code: C Program To Find Factorial of a Number using Recursion and Ternary or Conditional Operator

#include<stdio.h>

int fact(int);

int main()
{
    int num;

    printf("Enter a positive number to find its Factorial\n");
    scanf("%d", &num);

    printf("\nFactorial of %d is %d.\n", num, fact(num));

    return 0;
}

int fact(int num)
{
    return( (num > 0) ? (num * fact(num - 1)) : 1 );
}

Output 1:
Enter a positive number to find its Factorial
5

Factorial of 5 is 120.

Output 2:
Enter a positive number to find its Factorial
6

Factorial of 6 is 720.

Know more about ternary operator or conditional operator, watch a separate video tutorial: Ternary Operator / Conditional Operator In C.

Memory Stack

Whenever there is a recursive function call, function instance and the memory associated with that function instance gets pushed into the stack. When any function instance returns a value, that function instance and memory associated with that function instance gets popped out or removed or gets deleted from the memory stack.

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

Recursive Functions In C Programming Language

Lets learn recursive functions in C programming language, with examples and illustrations of memory and function instances in the stack.

Stake is a Data Structure and we’ll be discussing it once we start teaching Data Structures using C topics. For now consider it as a memory stack and some organized structure to hold data, which follows LIFO rule. i.e., Last In, First Out

That is, the last instance which enters the stack is the one which leaves the stack first.

Related Read:
Function / Methods In C Programming Language

Recursive Function: A function calling itself, within it’s own function definition is called Recursive Function.

Types of Recursive Functions

There are 4 types of recursive functions:
1. Direct Recursive function.
2. In-direct Recursive function.
3. Tail Recursive function.
4. Non-tail Recursive function.

We’ll discuss each one in separate video tutorials.

In this video tutorial lets learn the very basic of how to write and use recursive functions and how to keep track of function instances and return data.

Requirements To Learn Recursion

1. You need to know basics of C programming language. If you’re a total beginner, then we do not advice you to start with recursive functions. Just go to this page C Programming: Beginner To Advance To Expert and start watching the C program video tutorials one by one, and in no time you’ll be an advance user and you can learn/understand Recursive functions.

2. If you know the basics, then grab a piece of paper and get a pen. Write down the program on the paper, and also write the function call instances and track the variable values. Write everything we’re explaining in this video tutorial. If you get any doubts, write it down too. Watch the video once again and check if your doubts are cleared. If its still not cleared, follow the next step.

3. Turn on your computer and your favorite C editor, and type the program. Don’t copy paste it. Write the code yourself. Better if you write it without looking at the source code we’ve posted below. Once you execute and get the results, edit/modify the source code and check for different results. Check if you can edit the program and clarify your doubts. If you still don’t understand, then use the comment section below and ask your doubts.

4. Even if you understood the concept well, please visit the comment section below and try to help other students understand it. By teaching, you learn more.

Video Tutorial: Recursive Functions In C Programming Language


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

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


Source Code: Recursive Functions In C Programming Language: Example

#include<stdio.h>

void natural(int);

int main()
{
    int num = 1;

    natural(num);

    return 0;
}

void natural(int num)
{
    if(num <= 3)
    {
        natural(num+1);
        printf("%d  ", num);
    }

    return;
}

Output:
3 2 1

Logic To Print natural numbers from 1 to 3 using Recursion

We call natural() function and pass num to it. Initial value of num is set to 1. Inside natural() function/method we check if the value of num is less than or equal to 3. If true, we call the method natural() and pass num+1 to it. Once num is greater than 3, return statement executes and the control transfers to the calling function and the remaining code in that function gets executed. In our program we have printf statement after the recursive function call. So our program prints the value of num and then transfers the control to the calling function.

SlnonumFunction Call
11main()
21nature(1+1)
32nature(2+1)
43nature(3+1)
54nature(4+1)

Each time the recursive call is executed, an instance of the function and memory associated with it is pushed or added to the stack. And for each time the return statement is executed, the function and the memory associated with it is popped or deleted from the stack.

Stack is a Data Structure used to store data in some organized way. For now just know that its a memory stack in your RAM. It’s like a basket which holds the data in particular order. The data is stored one upon another. So the one which gets inserted or pushed at the last is the one which gets popped out first. This concept is called LIFO. Which means, Last In, First Out.

5
4
3
2
1

So we have 5 numbers inside the stack. If we want to add 6 to it, it’ll sit at the top of 5. In above stack, if you want to pop out, the first number you can pop out is the last number present in the stack, which is 5. You can only pop out the items one by one in this order, from above stack: 5, 4, 3, 2, 1.

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

C Program To Find If a Point Lies Inside Triangle or Not

Write a function to compute the distance between two points and use it to develop another function that will compute the area of the triangle whose vertices are A(x1, y1), B(x2, y2), and C(x3, y3). Use these functions to develop a function which returns a value 1 if the point (x, y) lies inside the triangle ABC, otherwise returns a value 0.

3 triangles inside a triangle

Analyze Above Problem Statement

1. We need to define a function which calculates the distance between two points.

For Example: distance(x1, y1, x2, y2); This function takes values of 2 points (x1, y1) and (x2, y2) and returns the distance between these 2 points.

2. User will enter values for 3 points, which are 3 edges/points of the triangle: (x1, y1), (x2, y2) and (x3, y3). We need to make use of a function(check Step 1) to calculate the distance between them. Once we have the distances, which are nothing but 3 sides of the triangle, we can use it to find area of that triangle using Heron’s or Hero’s Formula.

We call the distance between points (x1, y1) and (x2, y2) as a.
We call the distance between points (x2, y2) and (x3, y3) as b.
We call the distance between points (x3, y3) and (x1, y1) as c.

Using 3 sides of the triangle and Heron’s formula we calculate the area of triangle and store it inside variable area.

Hint: Check the image above for all these points we’ve explained so far. It has all the markings, which will help you visualize the concept.

3. Next, user will enter values for a point(x, y) on the graph. We need to make use of distance function(see step 1) and area of triangle function(see step 2) to find the area of 3 triangles formed by connecting (x1, y1) and (x, y), (x2, y2) and (x, y), (x3, y3) and (x, y);

We store the area of these 3 triangles inside variables A, B and C.

4. Write a function which returns 1 if the point lies within the triangle and returns 0 if the point lies outside the triangle.

If area of triangle represented by points (x1, y1), (x2, y2) and (x3, y3) is equal to the sum of the 3 triangles formed by connecting these 3 points to (x, y), then the points lie inside the triangle else the point is outside the triangle.

i.e., area_of_main_triangle == A + B + C; then the point lies inside the main triangle else it lies outside the main triangle.

Hint: Check the image above once again and write it down on a piece of paper, so that you clearly understand all the markings.

Note: This C program is comparatively bigger, but most part of its logic is already covered in other videos. Nothing complicated here. Its very simple, easy and straightforward program. Just don’t get stressed by looking at the length of this program. Learn the code(and the logic) step by step. Consume this or understand this program bit by bit and in no time you’ll know the whole thing!

Related Read:
C Program To Calculate Distance Between Two Points
C Program To Calculate Area of a Triangle using Pointers

Video Tutorial: C Program To Find If a Point Lies Inside Triangle or Not


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

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


Source Code: C Program To Find If a Point Lies Inside Triangle or Not

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

void  calc(float x1, float y1, float x2, float y2, float x3, float y3,
          float x, float y, int *flag, float *area);
int   position(float area, float A, float B, float C);
float distance(float x1, float y1, float x2, float y2);
float calc_area(float a, float b, float c);

int main()
{
    float x1, y1, x2, y2, x3, y3, x, y;
    int   flag = 0;
    float area = 0;

    printf("Enter value for(x1, y1)\n");
    scanf("%f%f", &x1, &y1);

    printf("Enter value for(x2, y2)\n");
    scanf("%f%f", &x2, &y2);

    printf("Enter value for(x3, y3)\n");
    scanf("%f%f", &x3, &y3);

    printf("Enter point(x, y) to check if it lies inside the Triangle\n");
    scanf("%f%f", &x, &y);

    calc(x1, y1, x2, y2, x3, y3, x, y, &flag, &area);

    printf("\nArea of Triangle = %f\n", area);

    if(flag) printf("Point (%0.1f, %0.1f) lies within the Triangle\n", x, y);
    else     printf("Point (%0.1f, %0.1f) lies outside the Triangle\n", x, y);

    return 0;
}

void calc(float x1, float y1, float x2, float y2, float x3, float y3,
          float x, float y, int *flag, float *area)
{
    float A, B, C, a, b, c, d, e, f;

    a = distance(x1, y1, x2, y2);
    b = distance(x2, y2, x3, y3);
    c = distance(x3, y3, x1, y1);
*area = calc_area(a, b, c);

    d = distance(x1, y1, x, y);
    e = distance(x2, y2, x, y);
    f = distance(x3, y3, x, y);

    A = calc_area(d, a, e);
    B = calc_area(e, b, f);
    C = calc_area(f, c, d);

*flag = position(*area, A, B, C);
}

float distance(float x1, float y1, float x2, float y2)
{
    return( sqrt( pow((x2 - x1), 2) + pow((y2 - y1), 2) ) );
}

float calc_area(float a, float b, float c)
{
    float S;

    S = (a + b + c) / 2.0;

    return( sqrt(S * (S - a) * (S - b) * (S - c) ) );
}

int position(float area, float A, float B, float C)
{
    float res = area - (A + B + C);

    if(res < 0)
    {
        res *= -1;
    }

    if(res == 0 || res < 0.001 )
    {
        return(1);
    }
    else
    {
        return(0);
    }
}

Output 1:
Enter value for(x1, y1)
0 0
Enter value for(x2, y2)
10 0
Enter value for(x3, y3)
10 20
Enter point(x, y) to check if it lies inside the Triangle
5 2

Area of Triangle = 100.000000
Point (5.0, 2.0) lies within the Triangle

Output 2:
Enter value for(x1, y1)
0 0
Enter value for(x2, y2)
10 0
Enter value for(x3, y3)
10 20
Enter point(x, y) to check if it lies inside the Triangle
10 20.1

Area of Triangle = 100.000000
Point (10.0, 20.1) lies outside the Triangle

Output 3:
Enter value for(x1, y1)
0 0
Enter value for(x2, y2)
20 0
Enter value for(x3, y3)
10 30
Enter point(x, y) to check if it lies inside the Triangle
10 15

Area of Triangle = 300.000000
Point (10.0, 15.0) lies within the Triangle

Logic To Find If a Point Lies Inside Triangle or Not

We ask the user to enter values for 3 edges or points of the triangle. We call it (x1, y1), (x2, y2) and (x3, y3). We also ask the user to enter a point, to check if it lies inside or outside the Triangle. We store the value of point inside (x, y).

We pass the values of (x1, y1), (x2, y2), (x3, y3), (x, y) and the address of variables flag and area to a function called calc().

calc(x1, y1, x2, y2, x3, y3, x, y, &flag, &area);

Inside calc() function
Inside calc() function we call another function to find distance between user entered points (x1, y1), (x2, y2), (x3, y3) and (x, y). We pass values of 2 points to the function distance() to get back the value or the distance between these two points.

a = distance(x1, y1, x2, y2);

Similarly, we find the distance between points (x2, y2) and (x3, y3), (x3, y3) and (x1, y1). This gives us lengths of all 3 sides of the triangle.

    a = distance(x1, y1, x2, y2);
    b = distance(x2, y2, x3, y3);
    c = distance(x3, y3, x1, y1);

Inside distance() function
We use a simple formula to calculate distance between 2 points:

distance = sqrt( (x2 – x1)*(x2 – x1) + (y2 – y1)*(y2 – y1) );

C Program To Calculate Distance Between Two Points

Inside calc_area() function
When we know the values of all 3 sides of a triangle, we can easily calculate its area using Heron’s or Hero’s formula.

sqrt(S * (S – a) * (S – b) * (S – c) );

where a, b and c are sides of the triangle.
and S is semi-perimeter of the Triangle.

S is calculate using below formula:

S = (a + b + c) / 2.0;

C Program To Calculate Area of a Triangle using Pointers

Inside calc() function
Now we calculate the distance between the user entered point(x, y) and with all 3 points of the triangle (x1, y1), (x2, y2) and (x3, y3). And store the values inside variables d, e, f. We make use of the function distance() here to get the distance between the points.

Inside calc_area() function
Again we reuse the calc_area() function to calculate the area’s of 3 triangles formed by connecting (x1, y1), (x2, y2), (x3, y3) with (x, y).

Inside position() function
Now we have area of the entire triangle(with sides a, b, c). And area of 3 more triangles present inside the main triangle – according to our assumption, as per above image. It need not be like that. We store these 3 areas in variables A, B and C.

If area == A + B + C, then the point (x, y) lies inside the triangle orelse the point(x, y) lies outside the triangle.

Very Important Note:

Since variables *area, A, B, C and all the points on the graph are of type float. So the final result for *area == A + B + C will have a very small difference. i.e., up to 0.001

So whenever we check for if(*area == A + B + C) it returns false or 0. So we use different logic. If the point lies inside the triangle then A + B + C will be equal to the area of main triangle. So we subtract the value of main triangle with all the 3 triangles present inside, so the result should be either 0 or with a small difference less than 0.001.

So the difference can be positive or negative, so we multiple the result by -1 in case the result is less than 0. After that we check for the condition if res is equal to 0 or res is less than 0.001, then we return 1, indicating that the point lies inside the triangle. If there is a difference bigger than 0.001 then we return 0, indicating that the point (x, y) lies outside the triangle.

Source Code Which Matches Exactly To The Problem Statement

3 triangles inside a triangle
We’ve changed the variable names to match the problem statement. Rest everything is same – the logic and working etc. Only 4 variable names have been changed to match the problem statement.

Source Code: C Program To Find If a Point Lies Inside Triangle or Not

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

void  calc(float x1, float y1, float x2, float y2, float x3, float y3,
          float x, float y, int *flag, float *ABC);
int   position(float ABC, float APB, float BPC, float CPA);
float distance(float x1, float y1, float x2, float y2);
float calc_area(float a, float b, float c);

int main()
{
    float x1, y1, x2, y2, x3, y3, x, y;
    int   flag = 0;
    float ABC = 0;

    printf("Enter value for(x1, y1)\n");
    scanf("%f%f", &x1, &y1);

    printf("Enter value for(x2, y2)\n");
    scanf("%f%f", &x2, &y2);

    printf("Enter value for(x3, y3)\n");
    scanf("%f%f", &x3, &y3);

    printf("Enter point(x, y) to check if it lies inside the Triangle\n");
    scanf("%f%f", &x, &y);

    calc(x1, y1, x2, y2, x3, y3, x, y, &flag, &ABC);

    printf("\nArea of Triangle = %f\n", ABC);

    if(flag) printf("Point (%0.1f, %0.1f) lies within the Triangle\n", x, y);
    else     printf("Point (%0.1f, %0.1f) lies outside the Triangle\n", x, y);

    return 0;
}

void calc(float x1, float y1, float x2, float y2, float x3, float y3,
          float x, float y, int *flag, float *ABC)
{
    float APB, BPC, CPA, a, b, c, d, e, f;

    a = distance(x1, y1, x2, y2);
    b = distance(x2, y2, x3, y3);
    c = distance(x3, y3, x1, y1);
 *ABC = calc_area(a, b, c);

    d = distance(x1, y1, x, y);
    e = distance(x2, y2, x, y);
    f = distance(x3, y3, x, y);

  APB = calc_area(d, a, e);
  BPC = calc_area(e, b, f);
  CPA = calc_area(f, c, d);

*flag = position(*ABC, APB, BPC, CPA);
}

int position(float ABC, float APB, float BPC, float CPA)
{
    float res = ABC - (APB + BPC + CPA);

    if(res < 0)
    {
        res *= -1;
    }

    if(res == 0 || res < 0.001 )
    {
        return(1);
    }
    else
    {
        return(0);
    }
}

float distance(float x1, float y1, float x2, float y2)
{
    return( sqrt( pow((x2 - x1), 2) + pow((y2 - y1), 2) ) );
}

float calc_area(float a, float b, float c)
{
    float S;

    S = (a + b + c) / 2.0;

    return( sqrt(S * (S - a) * (S - b) * (S - c) ) );
}

Output 1:
Enter value for(x1, y1)
0 0
Enter value for(x2, y2)
10 0
Enter value for(x3, y3)
10 20
Enter point(x, y) to check if it lies inside the Triangle
5 2

Area of Triangle = 100.000000
Point (5.0, 2.0) lies within the Triangle

Output 2:
Enter value for(x1, y1)
0 0
Enter value for(x2, y2)
10 0
Enter value for(x3, y3)
10 20
Enter point(x, y) to check if it lies inside the Triangle
10 20.1

Area of Triangle = 100.000000
Point (10.0, 20.1) lies outside the Triangle

Output 3:
Enter value for(x1, y1)
0 0
Enter value for(x2, y2)
20 0
Enter value for(x3, y3)
10 30
Enter point(x, y) to check if it lies inside the Triangle
10 15

Area of Triangle = 300.000000
Point (10.0, 15.0) lies within the Triangle

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

C Program To Calculate Area of a Triangle using Pointers

Lets write a C program to calculate area of a Triangle when their sides are input by the user. Lets use pointers and functions.

Problem Statement

If the lengths of the sides of a Triangle are denoted by a, b and c, then area of Triangle is given by:

Heron's or Hero's Formula

where, s = (a + b + c) / 2. Write a function to calculate the area of triangle.

Here s is semi-perimeter of the Triangle.

Related Read:
Find Area of a Triangle Using Its Sides: C Program
Basics of Pointers In C Programming Language

Formula To Calculate Area of a Triangle When its Sides are Given

area = sqrt( S * (S – a) * (S – b) * (S – c) );

where a, b and c are lengths of sides of the Triangle.
S = (a + b + c) / 2.0;
S – Semi-perimeter.

Very Important Note:

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

Video Tutorial: C Program To Calculate Area of Triangle using Pointers


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

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


Source Code: C Program To Calculate Area of Triangle using Pointers

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

void cal_area(float, float, float, float*);
int  validate(float, float, float);

int main()
{
    float a, b, c, area;

    printf("Enter values of 3 sides of a Triangle.\n");
    scanf("%f%f%f", &a, &b, &c);

    if( validate(a, b, c) )
    {
        cal_area(a, b, c, &area);
        printf("Area of Triangle is %0.2f\n", area);
    }
    else
    {
        printf("Please enter valid values for sides of Triangle.\n");
    }

    return 0;
}

void cal_area(float x, float y, float z, float *A)
{
    float S;

     S = (x + y + z) / 2.0;

    *A = sqrt(S * (S - x) * (S - y) * (S - z));
}

int validate(float x, float y, float z)
{
    int flag = 0;

    if(x > y && x > z)
    {
        flag = ( x < (y + z) );
    }
    else if(y > z)
    {
        flag = ( y < (x + z) );
    }
    else
    {
        flag = ( z < (x + y) );
    }

    return(flag);
}

Output 1:
Enter values of 3 sides of a Triangle.
10
20
30
Please enter valid values for sides of Triangle.

Output 2:
Enter values of 3 sides of a Triangle.
50
30
0
Please enter valid values for sides of Triangle.

Output 3:
Enter values of 3 sides of a Triangle.
15
14
2
Area of Triangle is 12.53

Output 4:
Enter values of 3 sides of a Triangle.
14.6
14
0.7
Area of Triangle is 2.58

Output 5:
Enter values of 3 sides of a Triangle.
4
5
6
Area of Triangle is 9.92

In Output 1: the largest side is 30. So the other side is 10 and 20. Adding 10 and 20 gives 30, which is not greater than the largest side. So these three values can’t form a valid triangle.

In Output 2: we’ve a 0. No side of a Triangle can have a length of 0. So it’s a invalid Triangle.

Logic To Calculate Area of a Triangle using Pointers

We ask the user to enter/input values of 3 sides of a Triangle. We pass these three values along with the address of variable area to a function called cal_area().

Inside cal_area() function we calculate the semi-perimeter using below formula:

S = (x + y + z) / 2.0;

Note: While calculating Semi-perimeter make sure to divide by 2.0 and not by 2. Because sum of sides of triangle might be a floating point number. Division by integer will give integer value as result. So it’s always better to avoid division by integer value.

Calculate Area of Triangle using Heron’s or Hero’s Formula

To calculate Area of a Triangle when all 3 of its sides are known, we make use of Heron’s or Hero’s Formula:

*A= sqrt( S * (S – a) * (S – b) * (S – c) );

We are storing the result inside a pointer variable. Variable A has the address of variable area i.e., A = &area. *A is the value present at address A or &area.

When we modify the value present at an address it reflects everywhere in the program. Hence we are able to display the result of area inside main method, without literally returning any value from cal_area() funtion.

Logic To Validate The Sides of Triangle

A Triangle is said to be valid if the sum of two sides is greater than the largest of the three sides.

For Example:
If a, b and c are 3 sides of the Triangle. If c is the largest side. Then for the Triangle to be valid, value of (a+b) must be greater than c.

(a+b) > c

Triangle Valid or Not based On Sides: C Program

In function validate() we first find the largest side of the triangle and check if its value is less than the sum of other 2 sides of the triangle. If true we return 1 else we return 0.

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

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