C program for prime number

To understand better please read the following post first, it will clear your concept of prime number What is prime number and Why 1 is not a prime number?


#include<stdio.h>

int main(){
    int n, i,check;
    printf("Enter a positive number\n");
    scanf("%d",&n);
    for(i=2;i<=n/2;i++){

        if(n%i==0) {
            check = 1;
            break;
        }
    }

    if(check==1)
        printf("\n%d is not a prime number\n",n);
    else
        printf("\n%d is a prime number\n",n);

    return 0;
}

Logic: The above program takes an integer n to check whether it is prime and use two control variables i & check Since every number is divisible by 1 so we started from i = 2. And i will be up to n/2. Why n/2 and why not n Because if we divide n, by any number between n/2 and n it will give us a remainder. For example if we divide 12 by 7(12÷2 < 7) it will remain 5, in case of 9 it will remain 3. That makes if(n%i==0) false every time. So if we take n it just increase time complexity.

Then we divide n with 2 to n/2 if it divide without any remainder, we set check = 1 And show it as not a prime.

Another one


#include<stdio.h>
int main(){
    int min, max, i,count;

    printf("Enter the first end point\n");
    scanf("%d",&min);
    printf("Enter the second end point\n");
    scanf("%d",&max);
    printf("\n\n");
    for(i=min;i<=max;i++){
        for(count=2;count<=i;count++){
            if(i%count==0) break;
        }
        if(count==i) printf("%d\n",count);
    }

    return 0;
}


Here we also use the same logic to find out the prime number from an interval.


Why 1 is not a prime number?

We know that the prime numbers are 2, 3,5, 7, 11, 13, … … …, it starts from 2 because One is not a prime number.

Why one is not a prime number?

It explanation is on the following.

The fundamental theorem of arithmetic Or Factorization Theorem: The fundamental theorem of arithmetic states that every positive integer (except the number 1) can be represented in exactly one way apart from rearrangement as a product of one or more primes (MathWorld)

From the definition we got two factors

  1. product of one or more primes
  2. can be represented in exactly one way

Lets consider 12, the factors of 12 are 1, 2, 3, 4,6 and 12. So if we represent 12 as the product of primes then 12= 2x2x3
But we can not take 1x2x2x3(Extra 1 is multiplied)
Or we can’t take 1x1x2x2x3 (Extra two 1’s is multiplied)
or even we can’t take 1x1x1x2x2x3 (Extra three 1’s is multiplied). Though all these makes 12.

Thus we can represent 12 in many ways if take ‘1’ as a prime number. We cant take these because it violates our second factor "can be represented in exactly one way". So excluding the ‘1’ we represent 12 in exactly one way as a product of three primes(2,2,3).

More example 14=2x7 not (1x2x7 or 1x1x2x7)
51 =3x17 not (1x3x17 or 1x1x317)
So to maintain The fundamental theorem of arithmetic Or Factorization Theorem formula we apart ‘1’ from series of prime numbers.

But, is ‘1’ is a compound number? Nope!! as we know that compound number are those which can be represent as the product of integer number. Example 24 is a compound number as it can be written as 4x6.

So what is ‘1’ actually? According to mathematician we can define it as “Unit Number”


If anyone wish to see the Bangla version of this post See it here

Matrix addition and subtraction in C using arrays

Consider 4 matrices, A, B,C and D, we are going to add A and B and keep on C. (A+B = C). And will subtract B from A and keep it on D.(A-B=D).

First we need to check that the number of rows of matrix A is equal to the number of rows of matrix B, Also we should perform the same check in case of column. But in our program we assume that number of rows of A and B are equal, as well as the column of A is equal to column of B. Then we goes

c[00]=a[00]+b[00], c[01]=a[01]+b[01]… and so on.
d[00]=a[00]-b[00], c[01]=a[01]-b[01]… and so on.

Lets coding this simple Program.


#include<stdio.h>

int main(){
    int a[10][10],b[10][10],c[10][10],d[10][10], row, col,i,j;

    printf("Enter the rows number of both matrices\n");
    scanf("%d",&row);
    printf("Enter the columns number of both matrices\n");
    scanf("%d",&col);


        printf("Enter the elements of matrix A\n");
        for(i=0;i<row;i++){
            for(j = 0;j < col;j++){
                printf("Enter the element at [%d%d] : ",i,j);
                scanf("%d",&a[i][j]);
            }
            printf("\n");

        }

        printf("Enter the elements of matrix B\n");
        for(i=0;i<row;i++){
            for(j = 0;j < col;j++){
                printf("Enter the element at [%d%d] : ",i,j);
                scanf("%d",&b[i][j]);
            }
            printf("\n");

        }

        printf("The addition of A and B is \n\t\t");
        for(i=0;i<row;i++){
            for(j = 0;j < col;j++){
                c[i][j]=a[i][j] + b[i][j];
            }
        }
        //printing addition
        for(i=0;i<row;i++){
            for(j = 0;j < col;j++){
                printf(" %d ",c[i][j]);
            }
            printf("\n\t\t");
        }


        printf("\nThe subtraction of A and B is \n\t\t");
        for(i=0;i<row;i++){
            for(j = 0;j < col;j++){
                d[i][j]=a[i][j] - b[i][j];
            }
        }

        //printing subtraction
        for(i=0;i<row;i++){
            for(j = 0;j < col;j++){
                printf(" %d ",d[i][j]);
            }
            printf("\n\t\t");
        }



    return 0;
}




C program to find sum of diagonal elements in a matrix

Row-major order and Column-major order: In computing, row-major order and column-major order describe methods for arranging multidimensional arrays in linear storage such as memory. The difference is simply that in row-major order, consecutive elements of the rows of the array are contiguous in memory; in column-major order, consecutive elements of the columns are contiguous.(Wiki)

C Supports Row-major order: That means if we represents a two dimensional matrix in C, At first It will traverse the first row then second row and so on.

Square Matrix: We know that square matrix is a matrix whose ROW and COLUMN are equal. If a square matrix of size n then ROW = COLUMN = n. Now see a square matrix. On which we will manipulate the main diagonal elements, elements above main diagonal, elements bellow the main diagonal.

two dimensional matrix in c

From the above image we can see that the indexes of all the diagonal elements follow a general rule, that is ROW = COLUMN, here [00], [11], [22] and [33].

Above the main diagonal we have [01], [02], [03], [12], [13] and [23]. Now notice carefully that, all these indexes follows ROW < COLUMN.

Now we have those elements which are bellow the main diagonal these are, [10], [20], [21], [30], [31], and [32]. in these case ROW > COLUMN. Now lets start with code……

#include <stdio.h>

int main(){
    int mat[10][10], array_size, row=0, col=0, diagonalSum=0, aboveSum=0, bellowSum=0;

    printf("Enter the array size\n");
    scanf("%d",&array_size);
    printf("Enter the elements of matrix\n");

    for(row=0;row<array_size;row++){
        for(col = 0;col<array_size;col++){
            printf("Enter the element at [%d%d] : ",row,col);
            scanf("%d",&mat[row][col]);
        }
        printf("\n");

    }
    // Sum of diagonal element ROW = COLUMN
    printf("The diagonal elements are \t");
    for(row=0;row<array_size;row++){
        for(col = 0;col<array_size;col++){
            if(row==col){
                printf(" %d, ",mat[row][col]);
                diagonalSum += mat[row][col];
            }
        }
    }

    printf("\nAnd the sum is %d\n\n",diagonalSum);

    // Sum of elements above diagonal  ROW < COLUMN
    printf("The elements above diagonal are \t");
    for(row=0;row<array_size;row++){
        for(col = 0;col<array_size;col++){
            if(row<col){
                printf(" %d, ",mat[row][col]);
                aboveSum += mat[row][col];
            }
        }
    }

    printf("\nAnd the sum is %d\n\n",aboveSum);

    // Sum of elements bellow diagonal  ROW > COLUMN
    printf("The elements bellow diagonal \t");
    for(row=0;row<array_size;row++){
        for(col = 0;col<array_size;col++){
            if(row>col){
                printf(" %d, ",mat[row][col]);
                bellowSum += mat[row][col];
            }
        }
    }

    printf("\nAnd the sum is %d\n\n",bellowSum);

    return 0;
}



Matrix multiplication in C with explanation

We should have basic knowledge on the representation of two dimensional matrix in C. Here is three two dimensional matrix a, b and c. a for matrix A, b for matrix B, and c for matrix C. which holds the multiplication result. i, j, k are control variable and sum is needed to hold the summation of the consecutive two products.

#include <stdio.h>
int main()
{

   int a[2][2] = {3,4,2,7};
   int b[2][2] = {6,8,5,9};
   int c[2][2], i, j, k, sum;

   printf("Matrix A is : \n\t\t");
   for(i=0;i<2;i++){
    for(j=0;j<2;j++){
        printf("%d \t",a[i][j]);    }
    printf("\n\t\t");
   }

   printf("\nMatrix B is : \n\t\t");
   for(i=0;i<2;i++){
    for(j=0;j<2;j++){
        printf("%d \t",b[i][j]);
        }
    printf("\n\t\t");
   }

   printf("\nMultiplication of matrix A and B\n\t\t");
   for(i=0;i<2;i++){
    for(j=0;j<2;j++){
        sum = 0;
        for(k=0;k<2;k++){
            sum = sum + a[i][k] * b[k][j];
             }
        c[i][j]=sum;
    }
   }
     printf("\nMatrix A*B is : \n\t\t");
    for(i=0;i<2;i++){
    for(j=0;j<2;j++){
        printf("%d \t",c[i][j]);
      }
    printf("\n\t\t");
   }

return 0;
}

Traversing a matrix

Let us consider the traversing of matrix A, we use here two for loop. One is nested in another, now consider for the first time printf("%d \t",a[i][j]); at the first time i and j enter the loop with value i=0 and j=0; so it represent the first element of matrix A with a[0][0]=3, After the first iteration j increase it's value by j =1 and the inner loop is also true in this case so it point a[0][1] = 4; At the next iteration j= 2 so the for loop is false as 2 is not greater than 2. so it execute the next line printf("\n\t\t"); which prints a new line and two tab after printing a[0][0]=3 and a[0][1] =4,

Now lets talk about the outer loop, for(i=0;i<2;i++) by this time i = 1 and then it enter the inner loop for(j=0;j<2;j++) again it runs two times and results a[1][0]=2 and a[1][1]=7.

Graphical Representation of matrix multiplication

Matrix Multiplication

It uses three for loops, the control variables are i, j, k, at the first iteration all these control variables including sum are zero so,
sum = sum + a[i][k] * b[k][j]
=> 0+a[i][k] * b[k][j]
=> 0+ a[0][0]=3 * b[0][0]= 6
=> 3*6=18
so sum =18, At the next iteration k=1, and still i=0 also j=0 therefore

sum = sum + a[i][k] * b[k][j]
=> 18+a[0][1]*b[1][0]
=>18+4*5
=>18+20
=38

At the next iteration k gets 2 so it becomes false and go to the upper loop (control variable j) and brings j=1, and still i=0, and sum initialize with 0;

sum = sum + a[i][k] * b[k][j]
=> 0 + a[i][k] * b[k][j]
=> 0 + a[0][0]=3 * b[0][1]= 8
=> 3*8=24,

At the next iteration k=1, therefore

sum = sum + a[i][k] * b[k][j]
=> 24+a[0][1]*b[1][1]
=> 24+4*9
=> 24+36=60.

And thus 47, 97 comes correspondingly.

Exception

From the above program we can see that the column of matrix A and the row of matrix B are equal 2=2,This rule must be maintain in matrix multiplication

Column number of first matrix must be equal to the row number of the second matrix

Now lets try with another programm

#include <stdio.h>
int main()
{

   int a[12][12], b[12][12] ,c[12][12], rowa, cola, rowb,colb, i, j, k, sum;

   printf("Row of the first matrix\n");
   scanf("%d",&rowa);
   printf("Column of the first matrix(a) \n");
   scanf("%d",&cola);

    printf("Enter the elements of first matrix\n");
    for (  i = 0 ; i < rowa ; i++ ){
        for ( j = 0 ; j < cola ; j++ ){
      scanf("%d", &a[i][j]);
        }
    }

   printf("Row of the second matrix\n");
   scanf("%d",&rowb);
   printf("Column of the second matrix(b) \n");
   scanf("%d",&colb);

   if(cola != rowb){
        printf("The row number of the second matrix(b) should be %d\n",cola);
        printf("Column of first matrix must be equal to the number of row of the second matrix.\n");
        printf("Run the program again.\n");
   }

   else{
        printf("Enter the elements of second matrix\n");
        for (  i = 0 ; i < rowb ; i++ ){
            for ( j = 0 ; j < colb ; j++ ){
            scanf("%d", &b[i][j]);
            }
        }

      printf("\nMultiplication of matrix A and B\n\t\t");
        for(i=0;i<rowa;i++){    // rowa ...?  [1]
            for(j=0;j<colb;j++){  // colb...?  [2] 
            sum = 0;
                for(k=0;k<rowb;k++){// rowb...?  [3] 
                    sum = sum + a[i][k] * b[k][j];
                }
            c[i][j]=sum;
        }
    }
    printf("\nMatrix A*B is : \n\t\t");
    for(i=0;i<rowa;i++){
    for(j=0;j<colb;j++){
        printf("%d \t",c[i][j]);
      }
    printf("\n\t\t");
   }
   }
return 0;
}

  1. The number of row of the product matrix is equal to the row of the first(a) matrix
  2. The number of column of the product matrix is equal to the second(b) matrix
  3. The iteration number is equal to row of the second matrix (rowb) or the column of the first matrix (cola), since both are equal.

How to convert a while loop to a for loop in c

The basic structure of for loop is as following

for(initialization; condition; adjustment){
        statement(s);
      }

So the fo loop has four parts,

  1. Initialization: We need to assign a value for the control variable.
  2. condition: We have to use a conditional expression here. The compiler execute/iterate the for loop until it get 0 or false
  3. adjustment: Adjust the control variable (by increment or decrement ) so that the condition get 0 or false
  4. statement(s): Any type of simple or compound statement(s)

The basic structure of while loop is as following

while(condition){
        statement(s);
      }

We can see that the while loop has only two parts

  1. Condition
  2. statement(s)

So if we wish to use the while loop as the for loop we need to construct it as the following

initialization;
while( condition){
        statement(s);
      adjustment;
       }

Now lets see a program using both for loop and while loop. See the factorial finding program using both for loop and while loop

#include<stdio.h>
int main(void){

int count;

printf("Using for loop\n\n");
for(count = 1;count<=5; count++){
        printf(" \t count is %d\n",count);
        }


printf("\n Using for loop\n\n");
count = 1;
while(count<=5 ){
        printf("\t count is %d\n",count);
        count++;
        }

return 0;
}


Difference between while loop and if statement

The basic structure of while loop is as following

while(condition){
        statement;
      }

The basic structure of if statement is as following

if(condition){
        statement;
      }

So, seeing their structure, it seems that they are same. But no,,, they are not same. if the condition of if is true, the if statement will execute. Otherwise not. Once the condition is true it will execute and will iterate. Where as the while loop will iterate until it get a false or '0'

#include <stdio.h>
int main()
{
    char ch;
    printf("Press any key without N/n to continue the program\n");
    ch = getch();
    while((ch != 'N') && (ch != 'n')){
        printf("\a");
        ch = getch();
    }
    return 0;

}

The above program will not stop till you pressed N or n. As soon as you pressed the N or n the condition will false and the while stop iterating

#include <stdio.h>
int main()
{
    char ch;
    printf("Press n\n");
    ch = getch();
    if(ch == 'n'){
        printf("\a You pressed n\n");
        ch = getch();
    }
    printf("Then you pressed %c\n",ch);
    return 0;

}

To understand better, do as I state, After executing the program, press n, the condition will true, so the statement, You pressed n will show on display. Again press n, that means again the condition is true, but it will not iterate and execute the last statement Then you pressed ...


Factorial program in c using for loop, while loop and function.

Wikipedia define factorial as following

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.

Math is Fun gives the following definition

The factorial function (symbol: !) means to multiply a series of descending natural numbers.

Example
4! = 4 × 3 × 2 × 1 = 24
7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040
1! = 1 0! = 1, because the following reason.

We can rearrange one thing only one way, as 0 is also an entity so we can rearrange it in one way.
Also we can prove it mathematically with the help of Combination
Let us consider n is the number of different people, if we choose a team consisting with n people then we can only choose it one time, so

Now lets start coding using for loop

#include<stdio.h>
int main(){

    int n,i;
    float fact=1;
    printf("Enter your n\n");
    scanf("%d",&n);
    
    if(n <0 ) printf("\aPlease enter a positive number\n");
    else if((n == 1) || (n == 0)){
        printf("\aThe factorial is 1\n");
    }
   else{
            for(i=1;i<=n;i++){
            fact =fact*i;
            }
        printf("\aThe factorial is %.2f\n",fact);
       }

    return 0;
}

Using while loop

#include<stdio.h>

int main(){

    int n,i=1;
    float fact=1;
    printf("Enter your n\n");
    scanf("%d",&n);
    if(n <0 ) printf("\aPlease enter a positive number\n");
    else if((n == 1) || (n == 0)){
        printf("\aThe factorial is 1\n");
    }
   else{
           while(i<=n){
            fact =fact*i;
                i++;
            }
          printf("\aThe factorial is %.2f\n",fact);
       }

    return 0;
}

Using user defined function

#include<stdio.h>

float factorial( int n){
    if((n == 1) || (n == 0) ) return 1;
    else return n*factorial(n-1);
}

int main(){

    int n;
    printf("Enter your n\n");
    scanf("%d",&n);
    if(n <0 ) printf("\aPlease enter a positive number\n");
    else  printf("\aThe factorial is %.2f\n",factorial(n));

    return 0;
}

Taylor and Maclaurin Series

Lets try with Taylor and Maclaurin Series. We start by supposing that ƒ is any function that can be represented by a power series:

Let’s try to determine what the coefficients cn must be in terms of ƒ. To begin, notice that if we put x = a in Equation 1, then all terms after the first one are 0 and we get

ƒ(a) = c0

If we differentiate the series in equation 1 term by term...

Here we just convert the degree in radian as we know that
1800 = πc

And the substitution of x = a in equation 2

ƒ'(a) = c1

Now we differentiate both sides of Equation 2 and obtain

Again we put x = a in Equation 3. The result is

ƒ''(a) = 2c2

Let’s apply the procedure one more time. Differentiation of the series in Equation 3 gives

ƒ'''(a) = 2.3c3 = 3!c3

By now you can see the pattern. If we continue to differentiate and substitute x = a, we obtain

Solving this equation for the nth coefficient cn, we get

This formula remains valid even for n = 0 if we adopt the conventions that 0! = 1 and ƒ(0) = ƒ.

Thus we have proved the following theorem.
THEOREM: If ƒ has a power series representation (expansion) at a, that is, if

Substituting this formula for cn back into the series, we see that if ƒ has a power series expansion at a, then it must be of the following form.

This equation is called the Taylor series of the function ƒ at a (or about a or centered at a). For the special case a = 0 the Taylor series becomes

This case arises frequently enough that is is given the special name Maclaurin series.

EXAMPLE 1: Find the Maclaurin series for sin x and prove that it represents sin x for all x.
Solution: We arrange our computation in two columns as follows:

Since the derivatives repeat in a cycle of four, we can write the Maclaurin series as follows:

See the C program to find out sin(x)

EXAMPLE 2: Find the Maclaurin series for cosx and prove that it represents cosx for all x.
Solution: We arrange our computation in two columns as follows:

See the C program to find cos(x)

Collected from Calculus Website, by Kiryl Tsishchanka


C program For Trigonometric ratio.

Lets try with the library function to calculate the trigonometric ratio. Here use the built in function. The C library function double cos(double x) returns the cosine of a radian angle x. Correspondingly the sin(x) and tan(x)

Here we just convert the degree in radian using 1800 = πc (Radian)


// Using Library function
#include<stdio.h>
void main(){
    float tempt, degree;
    printf("Enter the number \(In degree\)\n");
    scanf("%f",&degree);
    tempt = degree;
    degree = degree * 3.14159265359 / 180;
    printf("sin\(%.2f\) = %1.2f\n",tempt, sin(degree));
    printf("cos\(%.2f\) = %1.2f\n",tempt, cos(degree));
    printf("tan\(%.2f\) = %1.2f\n",tempt, tan(degree));


}

Now try with Taylor and Maclaurin Series Following are these equations.. we will transform them in our program.

#include<math.h>
#include<stdio.h>
double  factorial(int num){
        double fact =1;
        int i;
        for(i=1;i<=num;i++){
            fact = fact*i;
        }

        return fact;
}

void main(){
    double tempt, x,sum=1.0;
    int term,counter;
    int  sign =-1.0;
    printf("Enter the term number till you want to calculate the value\n");
    scanf("%d",&term);
    printf("Enter the value of x\n");
    scanf("%lf",&x);
    tempt=x;

//ex
    for(counter=1;counter <= term ; counter++){
        sum = sum + ((pow(x,counter))/(factorial(counter)));
    }
 printf("So the Taylor series of ex around %.1lf is %.15lf \n",tempt,sum);

//sinx
x = x * 3.14159265359 / 180;
sum = x;
for(counter=3;counter<=term;counter+=2){
   sum = sum + (sign * (pow(x,counter))/factorial(counter));
}
printf("The Taylor series of sin(x) around %.1lf is %.15lf \n",tempt,sum);


// cosx
 sum = 1.0;
 sign = -1.0;
 for(counter=2;counter <= term ; counter += 2){
        sum = sum + (sign *(pow(x,counter))/factorial(counter));
        sign = sign * (-1);
    }
 printf("The Taylor series of cos(x) around %.1lf is %.15lf \n",tempt,sum);


}


Explanation

Here we use a user defined function factorial which takes an integer value to calculate it's factorial and the function also return a double type integer.

Here we use some variables
x = the variable of Taylor series.
sum = to hold the value of cos, sin and ex
tempt = to hold the value of x, as we change the value of x into radian.
term = Number of term of Taylor series.
counter = loop counter.
sign = to make negative number.


ex

We initialize the sum with 1, and the series of ex also start with 1 then just use it's corresponding arithmetic expression

sin(x)

Again we initialize the sum with 1 since the series of cos(x) start with 1, the counter variable start with 2 and each time it increases by 2, as the series goes. and the sign variable also changes its negativity after each iteration.

cos(x)

Notice that the sin(x) series start with x so again we initialize the sum with x and goes as like the Taylor series.


1's and 2's complement

1’s Complements: Just replaces each one with ‘0’ and each zero with ‘1’. For example: 100101 it’s 1’s complement is 011010

2’s Complements: When we add an extra one with the 1’s complements of a number we will get the 2’s complements. For example: 100101 it’s 1’s complement is 011010 and 2’s complement is 011010+1 = 011011 (By adding one with 1's complement)

Why we need the complements of a number

One reason of it is to represent the negative number. In binary system we use ‘1’ for negative number and ‘0’ for positive number. We represent the sign of a number using an extra bit at the extreme left of the number. For example 0,101 is +5 and 1,011 is -3.

And the most important reason is that, if we can evolve only one convention for representing positive and negative numbers which would allow us to use one basic procedure for both addition and subtraction. If the procedure is same, we could use a single electronic circuit to implement both addition and subtraction. A convention for representing negative numbers which allows this is the ‘complement representation’ of numbers.

2’s Complement

With n bits we can represent 2n number. For example if we take 4 bits then 24 = 16, so with 4 bits we can represents 16 different numbers(0 to 15 here.)

1's and 2's complements

From the above image we can see that we have divided the total range (0-15) into two parts. one is 0001(1) to 0111(7) and another is 1001(9) to 1111(15). Now we use the first seven combinations of 4 bits for representing positive numbers 1 to 7 (See the above image). And we reserve the other seven combinations for representing the negative number -1 to -7. This images actually as the following…

Let’s see with formula

The 2’s complement of a binary number x, which has n bits, is given by (2n-x).. Of the n bits of the complement representation (n-1) bits represent the magnitude. That is 4 bits for the whole system {0000 through 1111(15)} and (n-1) = 4-1 = 3 bits represents the magnitude {000 through 111(8)} Consider the number +3 whose binary representation is 0011. it has four bits. Hence the 2’s complement of +3 is (24-3) which is 13 (1101) (See on the image). Thus 0011’s 2’s complement is 1101

From the above two images we see that the code 1111, which is normally represents 15, is assigned to -1. So 24-1 = 15. Similarly the binary equivalent of 4(0100) is assigned to 12(1100). And 24-4 = 12

1’s Comppement

If we notice the circular image we can see that 0001(1) points to the 1110(-2), Similarly 0110(6) points to 1001(-7). The amazing thing is that 1110(-2) is the 1’s complements of 0001(1) and 1001(-7) is 1’s complement of 0110(6). So the normal thinking is that if we want to find the 1’s complements of 165 is -166, we can say without any doubt. Just increment it by one and make its sign negative.

Are you thinking what about 8!!
Yeah that’s right. Lets see what about the 8(1000) 2’s complements

1’s complements of 8(1000) is 0111, and 2’s complement is 0111+1 = 1000. Which is equivalent 8.


C program for Bitwise Operation.

To know more about Bitwise operation please read the Bitwise Operator in C. It explains how these bitwise operator work in C

#include <stdio.h>
void main(void)
{
    int i=165,j=281;
    printf("Bitwise AND operation of %d and %d is %d \n", i,j, i&j);
    printf("Bitwise OR operation of %d and %d is %d \n", i,j, i|j);
    printf("Bitwise XOR operation of %d and %d is %d \n", i,j, i^j);
    printf("2 bits right shift of %d is %d \n", i, i>>2 );
    printf("3 bits left shift of %d is %d \n", i, i<<3);
    printf("NOT operation of %d is %d \n", i, ~i);

}


Bitwise Operator in C

In the C programming language, operations can be performed on a bit level using bitwise operators.

Following are the six bitwise operators provided by C for bit manipulation
Symbol Operator
& bitwise AND
| bitwise inclusive OR
^ bitwise exclusive OR
<< left shift
>> right shift
~ bitwise NOT (one's complement) (unary)

To understand these operation lets ahead with two example..
We know that in C, integer consumed 2 bytes or 16 bit memory. So the binary representation of 165 and 281 as the following

(165)10 = (10100101)2

(281)10 = (100011001)2

But in C when it consumed 16 bits, it will like the following..

165 = 0000000010100101

281 = 0000000100011001

These extra bits(0's) are added to make it 16 bit integer number. Now the operation take place as..

Now remains the shift operations, yeah..
You will clear by seeing the following two images of Right shift (>>) and Left Shift (<<)

Right Shift >>

To understand the operation we shifted it by 2 bits. All the bits of the number (165) shifted to right by 2 bits.

Left Shift

To understand it we shifted the number by 3 bits, all the bits of the number (165) shifted to left by 3 bits

NOT operation

We first complement each bit of the number (i.e., replace '1' by '0' and '0' by '1') To know more about 1's and 2's Complement

bitwise not operator
See the C program With All the bitwise operation

C program and flowchart to find the largest of three numbers

Following is the flowchart to find out the largest of three number

And following is the C code


#include <stdio.h>
void main(void)
{
    int A,B,C;
    printf("Enter 3 integer number \n");
    scanf("%d",&A);
    scanf("%d",&B);
    scanf("%d",&C);
    if(A>B){
        if(A>C){
            printf(" %d is the Greatest Number \n",A);
        }
        else{
            printf("%d is the greatest Number \n",C);
        }
    }
    else{
            if(B>C){
                printf("%d is the greatest Number \n",B );
            }
            else{
                printf("%d is the greatest Number \n", C);
            }
    }
}




To check if it is Leap Year with C

#include <stdio.h>
void main(void)
{
    int year;
    printf("Enter a year to check if it is Leap Year\n");
    scanf("%d",&year);
    if(year%400==0) /* Why  mod 400 */
        printf("%d is a Leap Year\n",year);
    else if(year%100==0) /*  Why  mod 100  */
        printf("%d is not a Leap Year\n",year);
    else if(year%4==0)
        printf("%d is a Leap Year\n",year);
    else
        printf("%d is not a Leap Year\n",year);

}


The reason for leap year

Who invented Leap Years?

Julius Caesar introduced Leap Years in the Roman empire over 2000 years ago, but the Julian calendar had only one rule: any year evenly divisible by 4 would be a leap year. This led to way too many leap years, but didn't get corrected until the introduction of the Gregorian Calendar more than 1500 years later.

Which Years are Leap Years?

In the Gregorian calendar 3 criteria must be taken into account to identify leap years:

  1. The year is evenly divisible by 4;
  2. If the year can be evenly divided by 100, it is NOT a leap year, unless;
  3. The year is also evenly divisible by 400. Then it is a leap year.

Example

The year 1600 was a leap year. The years 1700, 1800, 1900 were not leap years. However, the year 2000 was a leap year. The years 2100, 2200, 2300 will not be leap years. The year 2400 will be a leap year. The year 2500 will not be a leap year.

But Why??

Because of the following reasons

It takes the Earth approximately 365.242199 days – or 365 days, 5 hours, 48 minutes, and 46 seconds – to circle once around the Sun. This is called a tropical year. So we are 5 hours, 48 minutes, and 46 ahead than calender, this makes after four years.........

We found that we are ahead 23 hours, 15 Mins and 4 Seconds. And we count it as one day(24 hours) and this makes February 29 days instead of 28 days.

Now notice that it also got some error since we are considering 23 Hours 15 Minutes and 4 seconds as a day. So calendar now ahead by..

From the above we can see that the calendar is now ahead by 0 hours, 44 minutes and 56 seconds after each four years to make an extra days(February -29). So for 1 year the calender is ahead by 0/4 = 0 years, 44/4=11 minutes and 56/4=14 Seconds. And for 100 years…

After 100 years, As the calendar is ahead by 18 hours, 43 Minutes and 20 seconds So don't count the 100 years as the leap year, though it is divisible by 4

It has also a problem!

Since calendar was ahead by 18 hours, 43 Minutes and 20 seconds we give to the calender 24 hours(By letting February in 28 days). Again we are ahead by ...6 hours 17 Minutes and 40 seconds...

This causes after 100 years, what will happen after 400 years!!

So after 400 years we are ahead by 25 hours 10 minutes and 40 seconds This makes the 400th a leap year.

You may ask that we are still ahead by 1 hour 10 minutes and 40 seconds. Yeah that's right! But this has trivial effect on tropical year as it divide among each year of 400 years!!! Gotcha??

Here the C Program to find Leap year

What is Modulo operation?

In computing, the modulo operation finds the remainder of division of one number by another (sometimes called modulus).

Given two positive numbers, a (the dividend) and n (the divisor), a modulo n (abbreviated as a mod n) is the remainder of the division of a by n .

For instance, the expression "5 mod 2" would evaluate to 1 because 5 divided by 2 leaves a quotient of 2 and a remainder of 1.

While "9 mod 3" would evaluate to 0 because the division of 9 by 3, has a quotient of 3 and leaves a remainder of 0; there is nothing to subtract from 9 after multiplying 3 times 3.

Modulus operator in c

The following example of modulo operation will explain itself better, For example you are given some hours, Let’s consider 772 hours and you are told to find out the extra days which do not make a day. Then you will do it by the following arithmetic division

So there are 32 days and 4 hour. Now you find your result 4(The extra days which do not make a day) But in programming we can do by just one command “772 mod 24” which evaluates 4.

See a program to find out the odd-even number with modulus operator

Find out Odd and Even number using C

C program tofind out odd or even number using modulus operator


#include <stdio.h>

void main(void)
{
int i;
printf("Enter an integer\n");
scanf("%d",&i);       
if(i%2==0)/* Modulo operator  Here it produce 0 for every even Number */
{
        printf("This is an even number.\n");
}

else
{
    printf("This is an odd Number\n");
}