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

C Program To Shift Variable Values Circularly To Right

Given three variables x, y, z write a function to circularly shift their values to right. In other words if x = 5, y = 8, z = 10, after circular shift y = 5, z = 8, x = 10. Call the function with variables a, b, c to circularly shift values.

Analyze The Above Problem Statement

1. We need to write a function which receives 3 numbers.
2. Inside the function we need to swap the values of 3 variables circularly to the right.

i.e., value of x to y, value of y to z, and value of z to a.

Related Read:
Basics of Pointers In C Programming Language
Swap 2 Numbers Using a Temporary Variable: C

Very Important Note:

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

Video Tutorial: C Program To Shift Variable Values Circularly To Right


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

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


Source Code: C Program To Shift Variable Values Circularly To Right

#include<stdio.h>

void shift_right(int*, int*, int*);

int main()
{
    int x, y, z;

    printf("Enter 3 numbers\n");
    scanf("%d%d%d", &x, &y, &z);

    printf("Before shifting right: x = %d, y = %d and z = %d\n", x, y, z);

    shift_right(&x, &y, &z);

    printf("After shifting right: x = %d, y = %d and z = %d\n", x, y, z);

    return 0;
}

void shift_right(int *a, int *b, int *c)
{
    int temp;

    temp = *c;
    *c   = *b;
    *b   = *a;
    *a   = temp;
}

Output 1:
Enter 3 numbers
5
8
10
Before shifting right: x = 5, y = 8 and z = 10
After shifting right: x = 10, y = 5 and z = 8

Output 2:
Enter 3 numbers
2
3
1
Before shifting right: x = 2, y = 3 and z = 1
After shifting right: x = 1, y = 2 and z = 3

Logic To Shift Variable Values Circularly To Right

We ask the user to enter 3 numbers and store it inside the address of variables x, y and z. Now we pass these 3 address to the function shift_right();

Inside shift_right() function
Inside shift_right() function we shift the value present at *c to a temp variable. Then, we shift the value of *b to *c, then the value of *a to *b, and then we shift the value present in temp to *a. This shifts the values of variables x, y and z circularly to the right.

*a has the value present at the address &x;
*b has the value present at the address &y;
*c has the value present at the address &z;


int temp;

temp = *c;
*c = *b;
*b = *a;
*a = temp;

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

Pointer To A Pointer In C Programming Language

Lets write C program to learn the concept of pointer pointing to another pointer. It’s also called as Multiple Indirection or double pointer concept.

Note: We could go any level deep. For Example, a pointer can point to a pointer which is pointing to another pointer, which is pointer to a pointer pointing to another pointer and so on.

But only 2 concepts hold practical usage in our programs:
1. The pointer concept.
2. Pointer to Pointer concept.

Related Read:
Basics of Pointers In C Programming Language

Very Important Note:

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

Example:

int num = 5;
int *ptr1, **ptr2;

ptr1 = &num;
ptr2 = &ptr1;

According to above code, ptr1 holds the address of variable num. So *ptr1 should fetch the value present at the address num. If you print out the *ptr1 you’ll get 5 as the result.

Similarly, ptr2 holds the address of pointer variable ptr1. *ptr2 fetches the value present at the address ptr1 – which is address of num. If we print out *(*ptr2) it prints out the value present at num, which is 5.

Video Tutorial: Pointer To A Pointer In C Programming Language


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

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


Source Code: Pointer To A Pointer In C Programming Language

#include<stdio.h>

int main()
{
    int num = 5;
    int *ptr1, **ptr2;

    ptr1 = &num;

    printf("Num = %d\n", num);
    printf("Address of Num, using variable num = %d.\n", &num);
    printf("Address of Num, using pointer ptr1 = %d.\n", ptr1);
    printf("Value present at Address %d is %d.\n\n", ptr1, *ptr1);

    ptr2 = &ptr1;

    printf("Address of pointer variable ptr1 = %d\n", ptr2);
    printf("Value present at address %d is %d, 
           which in turn holds the value %d.\n", ptr2, *ptr2, **ptr2);

    return 0;
}

Output:
Num = 5
Address of Num, using variable num = 6356728.
Address of Num, using pointer ptr = 6356728.
Value present at Address 6356728 is 5.

Address of pointer variable ptr1 = 6356724
Value present at address 6356724 is 6356728, which in turn holds the value 5.

Homework: Do it on your own

According to above program

int ***ptr3;
ptr3 = &ptr2;

printf("%d", ***prt3);

What will be the output?

Note: Take pen and paper. First know the value present at ptr3. Next check the result for *ptr3. Then check for **ptr3 and then finally ***ptr3.

Hint:
ptr3 holds address of ptr2.
i.e., ptr3 = &ptr2;

*ptr3 can be writte an *(&ptr2).

*(&ptr2) will fetch the value present at address &ptr2, which is address of pointer variable ptr1.
i.e., *(&ptr2) = &ptr1.

Next, *(&ptr1) will fetch the value present at &ptr1, which is address of num.
i.e., *(&num) which is equal to 5.

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

Basics of Pointers In C Programming Language

In today’s video tutorial lets learn basics of pointers in C programming language. Think of it as base of a building. If you can hold these basic concepts strong your building will be safer.

Topics Covered

1. What are pointers?
2. How to declare pointers.
3. How to access the value present at the address stored in pointer variable.
4. Using Address of operator.
5. Using Indirection operator.

What are pointers?

A pointer is a variable which refers to or points to an address in your computers memory.

Definition: A pointer variable is a variable which holds the address of another variable.

And since pointer variable is also a variable, it also has a unique address associated with it.

Operators

& is called “address of” operator.
* is called Indirection or “value at address” operator.

Video Tutorial: Basics of Pointers In C Programming Language


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

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


Source Code: Basics of Pointers In C Programming Language

#include<stdio.h>

int main()
{
    int num = 5;
    int *ptr; // pointer variable

    ptr = &num; // both hold address of num

    printf("Value of num = %d\n", num);
    printf("Address of num = %d\n", &num);
    printf("Address of ptr = %d\n", &ptr);
    printf("Value of ptr = %d\n", ptr);
    printf("Access value of num from ptr = %d\n", *ptr);
    printf("Access value of num from num = %d\n", *(&num));

    return 0;
}

Output:
Value of num = 5
Address of num = 6356732
Address of ptr = 6356728
Value of ptr = 6356732
Access value of num from ptr = 5
Access value of num from num = 5

Note: Whenever you declare and initialize a variable, for example, int num = 5; Your program does the following tasks:
1. Reserves space in your computers memory depending upon the data type.
2. Associates the name num with this memory location.
3. Stores the number 5 in this memory location.

Declaration of pointer variable

General Syntax
data_type* pointer_variable_name;

OR

data_type *pointer_variable_name;

Example:

int *ptr1;

int* ptr2;

Both these declaration are valid.

Rules for constructing pointer variable are same as that of regular variables: Rules for Constructing Variable Names: C

Assigning value to pointer variable

General Syntax
pointer_variable_name = &another_variable;

Example:

ptr = &num;

This stores the address of variable num as value of pointer variable ptr.

Declaring and Assigning value to pointer variable

Example:

int num = 5;
int *ptr;  // Declaration of pointer variable

ptr = &num;  // Assigning value to pointer variable

Note: While assigning address to pointer variable do not include * in front of pointer variable.

Values and addresses

num will have 5.
&num will have address of num.
&ptr will have address of ptr.
ptr will have address of num.
*ptr will have value of num.

Call by Value and Call by reference

Call by Value Example: C Program To Swap Two Numbers using Function
Call by Reference Example: C Program To Swap Two Numbers using Pointers

Note: Address can’t be negative values. So we can use %u as format specifier, which means unsigned integer.

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