Wednesday, August 28, 2013

GCD and LCM Using Euclid's Algorithm



GCD LCM Using Euclids Algorithm

   #include <stdio.h>
   #include <conio.h>
   void main()
   {
     int num1, num2, gcd, lcm, remainder, numerator, denominator;
     clrscr();
     printf("Enter two numbers\n");
     scanf("%d %d", &num1,&num2);
     if (num1 > num2)
     {
       numerator = num1;
       denominator = num2;
     }
     else
     {
       numerator = num2;
       denominator = num1;
     }
     remainder = num1 % num2;
     while(remainder !=0)
     {
       numerator = denominator;
       denominator = remainder;
       remainder = numerator % denominator;
     }
     gcd = denominator;
     lcm = num1 * num2 / gcd;
     printf("GCD of %d and %d = %d \n", num1,num2,gcd);
     printf("LCM of %d and %d = %d \n", num1,num2,lcm);
   }    

Add without Add Operator


Add without ADD Operator

  #include<stdio.h>
  int main()
  {
      int a,b;
      int sum;
      printf("Enter any two integers: ");
      scanf("%d%d",&a,&b);
      //sum = a - (-b);
      sum = a - ~b -1;
      printf("Sum of two integers:%d",sum);
      return 0;
  }    

Subtract Without Using Subtract Operator



Subtract without subtract operator

   #include<stdio.h>
   int main()
   {
     int a,b;
     int sum;
     printf("Enter any two integers: ");
     scanf("%d%d",&a,&b);
     sum = a + ~b + 1;
     printf("Difference of two integers: %d",sum);
     return 0;
   }  

Swap using Bitwise Operator



Swap two numbers using bitwise operators

   #include <stdio.h>
   int main()
   {
     int i = 65;
     int k = 120;
     printf("\n value of i=%d k=%d before swapping", i, k);
     i = i ^ k;
     k = i ^ k;
     i = i ^ k;
     printf("\n value of i=%d k=%d after swapping", i, k);
     return 0;
   }  

Swap without using third variable



Swap Without using third variable

   #include <stdio.h>
   void main()
   {
     int a,b;
     printf("Enter number1: ie a");
     scanf("%d",&a);
     printf("Enter number2:ie b ");
     scanf("%d",&b);
     printf(value of a and b before swapping is a=%d,b=%d"a,b);
     a=a+b;
     b=a-b;
     a=a-b;
     printf("value of a and b after swapping is a=%d,b=%d"a,b);
   }  

Sieve of Eratosthenes For Generating Prime Numbers






An algorithm for making tables of primes. Sequentially write down the integers from 2 to the highest number n you wish to include in the table. Cross out all numbers >2 which are divisible by 2 (every second number). Find the smallest remaining number >2. It is 3. So cross out all numbers >3which are divisible by 3 (every third number). Find the smallest remaining number >3. It is 5. So cross out all numbers >5 which are divisible by 5 (every fifth number).
Continue until you have crossed out all numbers divisible by |_sqrt(n)_|, where |_x_| is the floor function. The numbers remaining are prime. This procedure is illustrated in the above diagram which sieves up to 50, and therefore crosses out composite numbers up to |_sqrt(50)_|=7. If the procedure is then continued up to n, then the number of cross-outs gives the number of distinct prime factors of each number.
The sieve of Eratosthenes can be used to compute the prime counting function as
 pi(x)=pi(sqrt(x))+1+x-|_1/2x_|-|_1/3x_|-|_1/5x_|-...+|_x/(2·3)_|+|_x/(2·5)_|+|_x/(3...5)_|+...-|_x/(2·3·5)_|+...
which is essentially an application of the inclusion-exclusion principle.

Euclid's GCD Algorithm


One of the earliest known numerical algorithms is that developed by Euclid (the father of geometry) in about 300 B.C. for computing the greatest common divisor (GCD) of two positive integers.
Let GCD(x,y) be the GCD of positive integers x and y. If x = y, then obviously
GCD(x,y) = GCD(x,x) = x
.
Euclid's insight was to observe that, if x > y, then
GCD(x,y) = GCD(x-y,y)
.
Actually, this is easy to prove. Suppose that d is a divisor of both x and y. Then there exist integers q1 and q2 such that x = q1d and y = q2d. But then
x - y = q1d - q2d = (q1 - q2)d. Therefore d is also a divisor of x-y.
Using similar reasoning, one can show the converse, i.e., that any divisor of x-y and y is also a divisor of x. Hence, the set of common divisors of x and y is the same as the set of common divisors of x-y and y. In particular, the largest values in these two sets are the same, which is to say that GCD(x,y) = GCD(x-y,y).
A Java method that implements Euclid's algorithm is as follows:

   int gcd(int K, int M) {
      int k = K;   // In order to state a simple, elegant loop invariant,
      int m = M;   // we keep the formal arguments constant and use 
                   // local variables to do the calculations.
      // loop invariant: GCD(K,M) = GCD(k,m)
      while (k != m) {
         if (k > m) 
            { k = k-m; }
         else 
            { m = m-k; }
      }
      // At this point, GCD(K,M) = GCD(k,m) = GCD(k,k) = k
      return k;
   }

As an example, suppose that we use this method to compute the GCD of 420 and 96. If we were to take a snapshot of the method's local variables immediately before the first loop iteration and immediately after each iteration, we'd get
When                         k     m
--------------------       ----- -----
Before 1st iteration        420   96
After 1st iteration         324   96
After 2nd iteration         228   96
After 3rd iteration         132   96
After 4th iteration          36   96
After 5th iteration          36   60 
After 6th iteration          36   24
After 7th iteration          12   24
After 8th iteration          12   12
A significant improvement in performance (in some cases) is possible, however, by using the remainder operator (%) rather than subtraction. Notice in the above that we subtracted m's value from k's four times before kbecame less than m. The same effect results from replacing k's value by k % m. (In this case, 420 % 96 is 36.) Using this approach forces us to change the loop condition, however, as here what will eventually happen is that one of k or m will become zero. (Indeed, k == m is impossible to arrive at unless K == M.) Note that GCD(x,0) = GCD(0,x) = x. (After all, x's greatest divisor is itself, which is also a divisor of zero.)
Our new method is as follows:

   int gcd(int K, int M) {
      int k = K;   // In order to state a simple, elegant loop invariant,
      int m = M;   // we keep the formal arguments constant and use 
                   // local variables to do the calculations.
      // loop invariant: GCD(K,M) = GCD(k,m)
      while (k !=0  &&  m != 0) {
         if (k > m)
            { k = k % m; }
         else
            { m = m % k; }
      }
      // At this point, GCD(K,M) = GCD(k,m) = max(k,m)
      return Math.max(k,m);
   }

Using this version of the method, we get the following snapshots:
When                         k     m
--------------------       ----- -----
Before 1st iteration        420   96
After 1th iteration          36   96
After 2nd iteration          36   24
After 3rd iteration          12   24
After 4th iteration          12    0
Notice that the number of loop iterations has been cut in half. Further code-simplification improvements are possible, however, by ensuring that k ≥ m. We can achieve this by replacing, on each iteration, k's value by m's and m's by k % m. This way, no if statement is needed:

   int gcd(int K, int M) {
      int k = Math.max(K,M);
      int m = Math.min(K,M);
      // loop invariant: k ≥ m ∧ GCD(K,M) = GCD(k,m)
      while (m != 0) {
         int r = k % m;
         k = m;
         m = r;
      }
      // At this point, GCD(K,M) = GCD(k,m) = GCD(k,0) = k
      return k;
   }

Using this version of the method, we get the following snapshots:
When                         k     m
--------------------       ----- -----
Before 1st iteration        420   96
After 1th iteration          96   36
After 2nd iteration          36   24
After 3rd iteration          24   12
After 4th iteration          12    0

Backtracking


Backtracking Algorithms

 Solution Spaces

Backtracking is a refinement of the brute force approach, which systematically searches for a solution to a problem among all available options. It does so by assuming that the solutions are represented by vectors (v1, ..., vm) of values and by traversing, in a depth first manner, the domains of the vectors until the solutions are found.
When invoked, the algorithm starts with an empty vector. At each stage it extends the partial vector with a new value. Upon reaching a partial vector (v1, ..., vi) which can’t represent a partial solution, the algorithm backtracks by removing the trailing value from the vector, and then proceeds by trying to extend the vector with alternative values.
ALGORITHM try(v1,...,vi) 
   IF (v1,...,vi) is a solution THEN RETURN (v1,...,vi) 
   FOR each v DO 
      IF (v1,...,vi,v) is acceptable vector  THEN 
        sol = try(v1,...,vi,v) 
        IF sol != () THEN RETURN sol 
      END 
   END 
   RETURN () 
If Si is the domain of vi, then S1 × ... × Sm is the solution space of the problem. The validity criteria used in checking for acceptable vectors determines what portion of that space needs to be searched, and so it also determines the resources required by the algorithm.
The traversal of the solution space can be represented by a depth-first traversal of a tree. The tree itself is rarely entirely stored by the algorithm in discourse; instead just a path toward a root is stored, to enable the backtracking.
                     •
            |------------------|
v1 :     |-•||--------S-------•|-|-
      |-----|-----------1-----|------|
v2 :|•----|•|S||--•|-  |•----|•|S||--•|-
    |----|||||2-----|  |----|||||2-----|
   ... ...... ... ... ... ... ...... ... ... ...

 Traveling Salesperson

The problem assumes a set of cities, and a salesperson which needs to visit each city exactly once and return to the base city at the end. The solution should provide a route of minimal length.
The route (a, b, d, c) is the shortest one for the following one, and its length is 51.
do-----12-|co
 | ||| ||| |
 |   |||   |
15|20   9|18
ao|  -----|o
   10      b
The traveling salesperson problem is an NP-hard problem, and so no polynomial time algorithm is available for it. Given an instance = (V, E) the backtracking algorithm may search for a vector of cities (v1, ..., v||) which represents the best route.
The validity criteria may just check for number of cities in of the routes, pruning out routes longer than ||. In such a case, the algorithm needs to investigate |||| vectors from the solution space.
bo----
 |   ----
 |    ---ao
 |-----
co-
                         •
        |---------------------------------|
  |----a------|    |----b------|    |-----c-----|

|-a-| |b--| |c-| |-a-| |b--| |c--||-a-| |-b-| |c--|

a b ca b c a b c a b c a b ca b c a b c a b ca b c
On the other hand, the validity criteria may check for repetition of cities, in which case the number of vectors reduces to ||!.
    •|
 |-------|
|a| b-| c-|

b c ac|a|b|

c b ca b a

 The Queens Problem

Consider a by chess board, and the problem of placing queens on the board without the queens threatening one another.
|-|-o|-|-o|-|-o|-|--|
|-|--|-|--|-|--|-|--|
|-|--|o|-o|o|--|-|--|
|o|-o|o|-o|o|-o|o|o-|
|-|--|o|-o|o|--|-|--|
|-|-o|-|-o|-|-o|-|--|
|o|--|-|-o|-|--|o|--|
| |  | | o| |  | |o
|-|--|-|-o|-|--|-|--|
--------------------
The solution space is {123, ..., n}n. The backtracking algorithm may record the columns where the different queens are positioned. Trying all vectors (p1, ..., pn) implies nn cases. Noticing that all the queens must reside in different columns reduces the number of cases to n!.
For the latter case, the root of the traversal tree has degree n, the children have degree 1, the grand children degree 2, and so forth.
             ||-||
             ||-||
     |-------------------|
    1          2         3
   •|-||     ||•||     ||-•|
   ||-||     ||-||     ||-||
  |----|    |----|    |----|
|1,2||1,3||2,1||2,3||3,1|-3,2-|
|••|||•|•||••|||-••||•|•|-|••-|
--|----|----|-- -|----|----|---
1,2,3 1,3,2  2,1,3  2,3,1 3,1,2 3,2,1
|•||||•||||-•|||-•|||-|•|-||•-|
|-••||-••||•|•||•|•||••||-••|-|
--------------- ---------------
Checking for threatening positions along the way my further reduce the number of visited configurations.
             ||-||
             ||-||
     |-------------------|
    1          2         3
   •|-||     ||•||     ||-•|
   ||-||     ||-||     ||-||
  |----|    |----|    |----|
|1,2||1,3||2,1||2,3||3,1|-3,2-|
|••|||•|•||••|||-••||•|•|-|••-|
-------|------- ------|--------
     1,3,2            3,1,2
     |•|||          |-|•|-
     |-••|          |••||-
     -----           -----

Convex Hull (Graham’s Scan)

The problem asks to construct the shortest polygon which encloses a given set of points on a plan. Intuitively, the polygon can be determined by placing a rubber around the set.
 •
  |---
 |   ----
 |•     ---
 |         ---
•|-----•     ----
       ----------•
Determine an extreme point with the largest coordinate. Sort the points in order of increasing angles, relatively to the extreme point.
  •
b  ---
     ----
   •--  ----
  c   --------
 •----d-•--------
e       ---------•
                a
Traverse the points in the sorted order, adding them to the partial solution upon making a turn of less than 180 degrees, and backtracking when making a larger turn.
  b
 •|-
  |----
  |c  ----
  •      ----
       •d   ---
•e            ---a
                •         b
 •|--
  ||||-
  |c -----
  •----  ----
 e    -•d   ----
•              -•a         b
 •|--
  | ----
  •c  |||-
    --| d|---
 e-----•  - ----
•    ||||-     -•a         b
 •|--
  | ----
  •c-  ----
    --- d ---
 e     •     ---
•              -•a        •b
  |---
  |  ---
  •c   ----
        d ----
•e     •     ----
                •a        •b
  |---
  ||||---
  •c -  ---
 ||||-  d  ---
•e     •     ----
                •a        •b-
  |---
  |  ----
  •c    ----
       •d  ---
•e            ---a
                •       •b-
   ----
   c  ----
  •      ---
       •d  ----
•e            ---a
                •         b
 •--
 ||-|--
 | c  ----
 |•      ----
 e     •d   ---
•             ---a
                •         b
 •---
 |  ---
 | c   ---
 |•     d----
 e||   •    ----
•---------------•a
The algorithm requires O(n log n) time for sorting the points, and O(n) time to select an appropriate subset.

 Generating Permutations

A permutation can be obtained by selecting an element in the given set and recursively permuting the remaining elements.
             {
              ai,P(a1,...,ai-1,ai+1,...,aN)  if N > 1
P(a1,...,aN) =  aN                         if N = 1
                    --|--|--|-|
                    |a|b-|c-d-|
    a|------------b------------c-------------d
--|--|--|-|  ---|-|--|--| ---|--|-|--|  --|--|--|-|
|-|b-|c-d-|  |a-|-|c-|d-| |a-|b-|-|d-|  |a|b-|c-|-|
At each stage of the permutation process, the given set of elements consists of two parts: a subset of values that already have been processed, and a subset that still needs to be processed. This logical seperation can be physically realized by exchanging, in the i’th step, the i’th value with the value being chosen at that stage. That approaches leaves the first subset in the first i locations of the outcome.
                    --|--|--|-|
                    |a|b-|c-d-|
--|--|------------|--------------------------|--|-|
a||b |c d |  |b a |c |d | |c||b |a|d |  |d|b |c |a|
-----|--------------------------|----   -----------
--|--|--|-|  ---|-|--|--| ---|--|-|--|
b-|a-|c-d-|  |b-|c|a-|d-| |b-|d-|c|a-|
      ---|--|------------|--|-|
      |b-|c-a-|d-|  b-|c-|d-|a|
                         |
                    b-|c-|d-|a|
                    |-|--|--|-|
permute(i) 
   if i == N  output A[N] 
   else 
      for j = i to N do 
         swap(A[i], A[j]) 
         permute(i+1) 
         swap(A[i], A[j])

Transpose of a Matrix



Transpose A Matrix

   #include <stdio.h>
   #include <conio.h>
   int main()
   {
     int m, n, i, j;
     int mat[10][10], trans[10][10];
     printf(" Enter the number of rows and columns of matrix ");
     scanf(" %d %d ", &m, &n);
     printf(" Enter the elements of matrix \n ");
     for( i = 0 ; i < m ; i++ )
     {
       for( j = 0 ; j < n ; j++ )
       {
         scanf(" %d ", &mat[i][j] );
       }
     }
     for( i = 0 ; i < m ; i++ )
     {
       for( j = 0 ; j < n ; j++ )
       {
         trans[j][i] = mat[i][j];
       }
     }
     printf(" Transpose of entered matrix :-\n ");
     for( i = 0 ; i < n ; i++ )
     {
       for( j = 0 ; j < m ; j++ )
       {
         printf(" %d\t ", trans[i][j] );
       }
       printf(" \n ");
     }
     getch();
     return 0;
   }  

Swap two Numbers



Swap Two Number

  #include <stdio.h>
  int main()
   {
     int x, y, temp;
     printf("Enter the value of x and y\n");
     scanf("%d", &x, &y);
     printf("Before Swapping\n x = %d\ny = %d\n",x,y);
     temp = x;
     x = y;
     y = temp;
     printf("After Swapping\n x = %d\ny = %d\n",x,y);
     return 0;
  }  

Swap String



Swap String

   #include<stdio.h>
   #include<string.h>
   #include<malloc.h>
   #include<conio.h>
   main()
   {
     char first[100], second[100], *temp;
     printf("Enter the first string ");
     gets(first);
     printf("Enter the second string ");
     gets(second);
     printf("\nBefore Swapping\n");
     printf("First string: %s\n",first);
     printf("Second string: %s\n\n",second);
     temp = (char*)malloc(100);
     strcpy(temp,first);
     strcpy(first,second);
     strcpy(second,temp);
     printf("After Swapping\n");
     printf("First string: %s\n",first);
     printf("Second string: %s\n",second);
     getch();
     return 0;
   }  

Strong Number



Strong Number

  void strong_number()
  {
    int num,i,p,r,sum=0,save_num;
    printf("\n Enter a number");
    scanf("%d",&num);
    save_num=num;
    while(num)
    {
        i=1,p=1;
        r=num%10;
    while(i<=r)
      {
        p=p*i;
        i++;
      } //while
        sum=sum+p;
        num=num/10;
    } //while
    if(sum==save_num)
      printf("%d is a Strong number", save_num);
    else
      printf("%d is not a Strong number", save_num);
  }  

Sort a Given Number of String



Sort A Given Number Of Strings

   #include <stdio.h>
   #include <conio.h>
   #include <string.h>
   main()
   {
     char str[4][10];
     int i;
     clrscr();
     for( i = 0; i < 4; i++ )
     {
       printf(“ \nEnter name %d: ”, i+1 );
       scanf(“ %s ”, str[i] );
     }
     printf(“\n Original Order\n”);
     for(i = 0; i < 4; i++ )
     printf(“ %s\t ”, str[i] );
     for(i = 0; i < 4; i++ )
     {
       for(j = i + 1; j < 4; j++ )
       if( strcmp(str[i], str[j]) > 0 )
       {
         strcpy( temp, str[i] );
         strcpy( temp, str[i], str[j] );
         strcpy( str[j], temp );
       }
     }
     printf(“\n Sorted Order\n”);
     for( i = 0; i < 4; i++ )
     printf(“ %s\t ”, str[i]);
     getch();
   }    

Selection Sort



Selection Sort

   #include <stdio.h>
   main()
   {
     int A[20], N, Temp, i, j;
     printf(" ENTER THE NUMBER OF TERMS...: ");
     scanf("%d",&N);
     printf("\n ENTER THE ELEMENTS OF THE ARRAY...:");
     for(i=1; i<=N; i++)
     {
       scanf("\n\t\t%d", &A[i]);
     }
     for(i=1; i<=N-1; i++)
       for(j=i+1; j<=N;j++)
     if(A[i]>A[j])
     {
       Temp = A[i];
       A[i] = A[j];
       A[j] = Temp;
     }
     printf("THE ASCENDING ORDER LIST IS...:\n");
     for(i=1; i<=N; i++)
       printf("\n %d",A[i]);
   }  

Recursive Binary Search



Recursive Binary Search

   #include<stdio.h>
   int main()
   {
     int a[10],i,n,m,c,l,u;
     printf("Enter the size of an array: ");
     scanf("%d",&n);
     printf("Enter the elements of the array: " );
     for(i=0;i<n;i++)
     {
       scanf("%d",&a[i]);
     }
     printf("Enter the number to be search: ");
     scanf("%d",&m);
     l=0,u=n-1;
     c=binary(a,n,m,l,u);
     if(c==0)
       printf("Number is not found.");
     else
       printf("Number is found.");
     return 0;
   }
   int binary(int a[],int n,int m,int l,int u)
   {
     int mid,c=0;
     if(l<=u)
     {
       mid=(l+u)/2;
       if(m==a[mid])
       {
         c=1;
       }
       else if(m<a[mid])
       {
         return binary(a,n,m,l,mid-1);
       }
       else
       return binary(a,n,m,mid+1,u);
     }
     else
       return c;
   }  

Reverse of a Number


Reverse Number

  #include <stdio.h>   \n main()
  {
     int n, reverse = 0;
     printf("Enter a number to reverse:\n");
     scanf("%d",&n);
     while (n != 0)
    {
        reverse = reverse * 10;
        reverse = reverse + n%10;
        n = n/10;
    }
     printf("Reverse of entered number is = %d\n", reverse);
     return 0;
  } 

Random Number Genrator



Random Number Generator

   #include<stdio.h>
   #include<conio.h>
   #include<stdlib.h>
   main()
   {
     int n, max, num, c;
     printf("Enter the number of random numbers you want ");
     scanf("%d",&n);
     printf("Enter the maximum value of random number ");
     scanf("%d",&max);
     printf("%d random numbers from 0 to %d are :-\n",n,max);
     randomize();
     for ( c = 1 ; c <= n ; c++ )
     {
       num = random(max);
       printf("%d\n",num);
     }
     getch();
     return 0;
   }  

Pascal Triangle



Pascal Triangle

   #include<stdio.h>
  long fact(int);
  int main()
  {
     int line,i,j;
     printf("Enter the no. of lines: ");
     scanf("%d",&line);
     for(i=0;i<line;i++)
    {
       for(j=0;j<line-i-1;j++)
       printf(" ");
       for(j=0;j<=i;j++)
       printf("%ld ",fact(i)/(fact(j)*fact(i-j)));
       printf("\n");
    }
   return 0;
   }
  long fact(int num)
  {
     long f=1;
     int i=1;
     while(i<=num)
     {
       f=f*i;
       i++;
     }
    return f;
  }  

String Palindrome

 #include<stdio.h>
  #include <string.h>
  main()
  {
     char a[100], b[100];
     printf("Enter the string to check if it is a palindrome\n");
     gets(a);
     strcpy(b,a);
     strrev(b);
     if( strcmp(a,b) == 0 )
       printf("Entered string is a palindrome.\n");
     else
       printf("Entered string is not a palindrome.\n");
       return 0;
  } 

Matrix Multiplications



Matrix- Matrix Multiplication

   #include <stdio.h>
   main()
   {
     int m1[10][10],i,j,k,m2[10][10],mult[10][10],r1,c1,r2,c2;
     printf("Enter number of rows and columns of first matrix (less than 10)\n");
     scanf("%d%d",&r1,&c1);
     printf("Enter number of rows and columns of second matrix (less than 10)\n");
     scanf("%d%d",&r2,&c2);
     if(r2==c1)
     {
       printf("Enter rows and columns of First matrix \n");
       printf("Row wise\n");
       for(i=0;i<r1;i++)
       for(j=0;j<c1;j++)
       scanf("%d",&m1[i][j]);
       printf("First Matrix is :\n");
       for(i=0;i<r1;i++)
       {
         for(j=0;j<c1;j++)
         printf("%d  ",m1[i][j]);
         printf("\n");
       }
       printf("Enter rows and columns of Second matrix \n");
       printf("Row wise\n");
       for(i=0;i<r2;i++)
       for(j=0;j<c2;j++)
       scanf("%d",&m2[i][j]);
       printf("Second Matrix is:\n");
       for(i=0;i<r2;i++)
       {
         for(j=0;j<c2;j++)
         printf("%d  ",m2[i][j]);
         printf("\n");
       }
       printf("Multiplication of the Matrices:\n");
       for(i=0;i<r1;i++)
       {
         for(j=0;j<c2;j++)
         {
         mult[i][j]=0;
         for(k=0;k<r1;k++)
         mult[i][j]+=m1[i][k]*m2[k][j];
         printf("%d\  ",mult[i][j]);
         }
         printf("\n");
       }
     }
     else
     {
       printf("Matrix multiplication cannot be done");
     }
     return 0;
   }    

Roots of a Quadratic Equation



Find The Roots Of A Quadratic Equation

   #include <stdio.h>
   #include <conio.h>
   #include <math.h>
   void main()
   {
     float a, b, c, d, realp, imgp, r1, r2;
     clrscr();
     printf(" Enter the 3 numbers\n ");
     scanf(" %f %f %f " ,&a, &b, &c);
     if ( a == 0 || b == 0 || c == 0 )
     {
       printf(" Error input only non zero numbers\n ");
     }
     else
     {
       d = b * b - 4 * a * c;
       if ( d == 0 )
       {
         printf(" Roots are equal\n ");
         r1 = r2 = - b / ( 2 * a );
         printf(" Root1 = %f, Root2 = %f ", r1, r2 );
       }
       else if(d>0)
       {
         printf( "Roots are real & distinct\n" );
         r1 = ( - b + sqrt ( fabs ( d ) ) ) / ( 2 * a );
         r2 = ( - b - sqrt ( fabs ( d ) ) ) / ( 2 * a );
         printf(" Root1 = %f, Root2 = %f", r1, r2);
       }
       else
       {
         printf(" Roots are imaginary\n ");
         realp = - b / ( 2 * a );
         imgp = sqrt ( fabs ( d ) ) / ( 2 * a );
         printf(" Root1 = %f + i%f, Root2 = %f - i%f ",realp, imgp, realp, imgp);
       }
     }
     getch();
   }  

Largest among N Digits

     #include<stdio.h>
   #include<conio.h>
   void main()
   {
     int max_num(int a[],int n);
     int max,i,n;
     int a[50];
     clrscr();
     printf("Enter n number:");
     scanf("%d",&n);
     printf("Enter the numbers:");
     for(i=0;i<n;i++)
     scanf("%d",&a[i]);
     max=max_num(a,n);
     printf("The largest number is %d",max);
     getch();
   }
   int max_num(int a[],int n)
   {
     int i,m=0;
     for(i=0;i<n;i++)
     {
       if(a[i]>m)
         m=a[i];
     }
     return m;
   } 

Inverse of a Matrix



Inverse of the Matrix

   #include<stdio.h>
   #include<math.h>
   float detrminant(float[][], float);
   void cofactors(float[][], float);
   void trans(float[][], float[][], float);
   main()
   {
     float a[25][25], n, d;
     int i, j;
     printf("Enter the order of the matrix:\n");
     scanf("%f", &n);
     printf("Enter the elemnts into the matrix:\n");
     for (i = 0; i < n; i++)
     {
       for (j = 0; j < n; j++)
       {
         scanf("%f", &a[i][j]);
       }
     }
     d = detrminant(a, n);
     printf("\nTHE DETERMINANT IS=%2f", d);
     if (d == 0)
       printf("\nMATRIX IS NOT INVERSIBLE\n");
     else
       cofactors(a, n);
   }
   float detrminant(float a[25][25], float k)
   {
     float s = 1, det = 0, b[25][25];
     int i, j, m, n, c;
     if (k == 1)
     {
       return (a[0][0]);
     }
     else
     {
       det = 0;
       for (c = 0; c < k; c++)
       {
         m = 0;
         n = 0;
         for (i = 0; i < k; i++)
         {
           for (j = 0; j < k; j++)
           {
             b[i][j] = 0;
             if (i != 0 && j != c)
             {
               b[m][n] = a[i][j];
               if (n < (k - 2))
                 n++;
               else
               {
                 n = 0;
                 m++;
               }
             }
           }
         }
         det = det + s * (a[0][c] * detrminant(b, k - 1));
         s = -1 * s;
       }
     }
     return (det);
   }
   void cofactors(float num[25][25], float f)
   {
     float b[25][25], fac[25][25];
     int p, q, m, n, i, j;
     for (q = 0; q < f; q++)
     {
       for (p = 0; p < f; p++)
       {
         m = 0;
         n = 0;
         for (i = 0; i < f; i++)
         {
           for (j = 0; j < f; j++)
           {
             b[i][j] = 0;
             if (i != q && j != p)
             {
               b[m][n] = num[i][j];
               if (n < (f - 2))
                 n++;
               else
               {
                 n = 0;
                 m++;
               }
             }
           }
         }
         fac[q][p] = pow(-1, q + p) * detrminant(b, f - 1);
       }
     }
     trans(num, fac, f);
   }
   void trans(float num[25][25], float fac[25][25], float r)
   {
     int i, j;
     float b[25][25], inv[25][25], d;
     for (i = 0; i < r; i++)
     {
       for (j = 0; j < r; j++)
       {
         b[i][j] = fac[j][i];
       }
     }
     d = detrminant(num, r);
     inv[i][j] = 0;
     for (i = 0; i < r; i++)
     {
       for (j = 0; j < r; j++)
       {
         inv[i][j] = b[i][j] / d;
       }
     }
     printf("\nTHE INVERSE OF THE MATRIX:\n");
     for (i = 0; i < r; i++)
     {
       for (j = 0; j < r; j++)
       {
         printf("\  %2f", inv[i][j]);
       }
       printf("\n");
     }
   }  

Insertion Sort

#include<stdio.h>
   void main()
   {
     int A[20], N, Temp, i, j;
     clrscr();
     printf("ENTER THE NUMBER OF TERMS...: ");
     scanf("%d", &N);
     printf("\n ENTER THE ELEMENTS OF THE ARRAY...:");
     for(i=0; i<N; i++)
     {
       gotoxy(25,11+i);
       scanf("\n\t\t%d",&A[i]);
     }
     for(i=1; i<N; i++)
     {
       Temp = A[i];
       j = i-1;
       while(Temp<A[j] && j>=0)
       {
         A[j+1] = A[j];
         j = j-1;
       }
       A[j+1] = Temp;
     }
     printf("\nTHE ASCENDING ORDER LIST IS...:\n");
     for(i=0; i<N; i++)
       printf("\n%d", A[i]);
     getch();
   } 

Floyd Triangle

#include <stdio.h>
  int main()
  {
     int n, i, c, a = 1;
     printf("Enter the number of rows of Floyd\'s triangle to print:\n");
     scanf("%d", &n);
     for (i = 1; i <= n; i++)
    {
        for (c = 1; c <= i; c++)
         {
            printf("%d ",a);
            a++;
        }
         printf("\n");
    }
   return 0;
  } 

Fibonacci Series

#include <stdio.h>
    #include <conio.h>
    void main()
    {
          int a,b,c,i,n;
          clrscr();
          a=0;
          b=1;
          printf("\n Enter n for how many times generate series");
          scanf("%d",&n);
          printf("\n FIBONACCI SERIES \n");
          printf("\t%d\t%d",a,b);
          for(i=0;i<n;i++)
         {
             c=a+b;
             a=b;
             b=c;
             printf("\t%d",c);
         }
         getch();
    }; 

Factorial

 #include <stdio.h>
  #include <conio.h>
  long int factorial(int n);
  void main()
  {
     int n;
     clrscr();
     printf("Enter the number:\n");
     scanf("%d",&n);
     printf("Factorial of %d is %ld",n,factorial(n));
     getch();
  }
  long int factorial(int n)
  {
     if(n<=1)
     {
        return(01);
     }
     else
     {
        n=n*factorial(n-1);
        return(n);
     }
  }      

Counting Digit in a Number

     #include<stdio.h>
   int main()
   {
     int num,count=0;
     printf("Enter a number: ");
     scanf("%d",&num);
     while(num)
     {
       num=num/10;
       count++;
     }
     printf("Total digits is:%d",count);
     return 0;
   } 

Counting Frequencies Of Elements Of Array

       #include <stdio.h>
   #include <conio.h>
   #include <stdlib.h>
   #define S 6
   main()
   {
     int a[S], freq[S];
     int i, j, k,n = S;
     clrscr();
     for(i = 0; i < S; i++)
     {
       printf(" \n Enter a[%d] element: ", i);
       scanf(" %d ", &a[i]);
       freq[i] = 1;
     }
     printf(" Original Array\n ");
     for(i = 0; i < S; i++)
     printf(" %d   ", a[i]);
     /* Main Logic Starts Here */
     for(i = 0; i < n; i++)
     for(j = i + 1; j < n; j++)
     {
       if(a[i] == a[j])
       {
         for(k = j; k < n; k++)
         a[k] = a[k+1];
         freq[i]++;
         n--;
       }
     }
     printf(" \nArray with freq\n ");
     printf(" \nElement  Freq\n ");
     for(i = 0; i < n; i++)
     printf("%d  %d\n ", a[i], freq[i]);
     getch();
   } 

Copy a String without using String Function

      #include<stdio.h>
  void stringCopy(char[],char[]);
  int main()
  {
      char str1[100],str2[100];
      printf("Enter any string: ");
      scanf("%s",str1);
      stringCopy(str1,str2);
      printf("After copying: %s",str2);
      return 0;
  }
  void stringCopy(char str1[],char str2[])
  {
      int i=0;
      while(str1[i]!=\'\u0000\')
      {
          str2[i] = str1[i];
          i++;
      }
      str2[i]=\'\u0000\';
  }

Permutation and Combinatins

#include <stdio.h>
  #include <conio.h>
  main()
  {
      int n , r, ncr( int , int);
      long npr( int , int);
      long double fact( int);
      printf(" Enter value of n & r \n");
      scanf("%d %d",&n , &r);
      if( n>= r)
      {
          printf( "%d C %d is %d \n", n,r,ncr( n , r));
          printf("%d P %d is %ld", n,r,npr( n, r));
      }
      else
      {
          printf("WRONG INPUT?? enter the correct input");
      }
  }
  long double fact( int p)
  {
      long double facts = 1;
      int i;
      for( i = 1; i<= p; i++)
      facts = facts * i;
      return( facts);
  }
  int ncr ( int n, int r)
  {
      return( fact( n) / (fact( r) * fact(n- r) ) ) ;
  }
  long npr( int n , int r)
  {
      return( fact( n) / fact( n- r));
  } 

Bubble Sort of an Array

#include <stdio.h>
 void bubble_sort(long [], long);
 int main()
 {
      long array[100], n, c, d, swap;
      printf("Enter number of elements:");
      scanf("%ld", &n);
      printf("Enter %ld longegers\n", n);
      for (c = 0; c < n; c++)
      scanf("%ld", &array[c]);
      bubble_sort(array, n);
      printf("Sorted list in ascending order:n");
      for ( c = 0 ; c < n ; c++ )
      printf("%ld\n", array[c]);
      return 0;
 }
 void bubble_sort(long list[], long n)
 {
      long c, d, t;
      for (c = 0 ; c < ( n - 1 ); c++)
       {
           for (d = 0 ; d < n - c - 1; d++)
            {
                if (list[d] > list[d+1])
                 {
                      t = list[d];
                      list[d] = list[d+1];
                      list[d+1]= t;
                }
           }
      }
 } 

Binary Search in an Array

int BinarySearch(int *array, int number_of_elements, int key)
 {
      int low = 0, high = number_of_elements-1, mid;
      while(low <= high)
      {
          mid = (low + high)/2;
          if(array[mid] < key)
          {
                  low = mid + 1;
          }
          else if(array[mid] == key)
          {
                  return mid;
          }
          else if(array[mid] > key)
          {
                  high = mid-1;
          }
      }
      return -1;
 }
 int main()
 {
      int number_of_elements;
      scanf("%d",&number_of_elements);
      int array[number_of_elements];
      int iter;
      for(iter = 1;iter < number_of_elements;iter++)
      {
          if(array[iter]< array[iter - 1])
          {
                 printf("Given input is \n not sorted\n");
 return 0;
          }
      }
      int key;
      scanf("%d",&key);
/* Calling this functions searches for the key and returns its index. It returns -1 if key is not found.*/
      int index;
      index = BinarySearch(array,number_of_elements,key);
     if(index==-1)
     {
              printf("Element not found\n");
     }
     else
     {
             printf("Element is at index %d\n ",index);
     }
     return 0;
 } 

Armstrong Number

 void main()
 {
     int n,b=0,t;
     clrscr();
     printf("Enter the no");
     scanf("%d",&n);
     t=n;
     while(n>0)
     {
             a=n%10;
             b=b+a*a*a;
             n=n/10;
     }
     if(b==t)
     {
             printf("Armstrong no");
     }
      else
     {
             printf("Not an armstrong no");
     }
     getch();
 } 

Adding Two Complex Numbers


  #include <stdio.h>
  #include <conio.h>
  #include <stdlib.h>
  struct complex
  {
      int real;
      int img;
  };
  int main()
  {
      struct complex a, b, c;
      printf(" Enter a and b where a + ib is the first complex number. ");
      printf("\n a = ");
      scanf(" %d ", &a.real);
      printf(" b = ");
      scanf(" %d ", &a.img);
      printf(" Enter c and d where c + id is the second complex number. ");
      printf("\n c = ");
      scanf(" %d ", &b.real);
      printf(" d = ");
      scanf(" %d ", &b.img);
      c.real = a.real + b.real;
      c.img = a.img + b.img;
      if ( c.img >= 0 )
          printf(" Sum of two complex numbers = %d + %di ", c.real, c.img);
      else
          printf(" Sum of two complex numbers = %d %di ", c.real, c.img);
      getch();
      return 0;
  } 

Software's to be used for C/C++ Programming