Prime Number Program In C

Prime Number Program In C

Program to find whether a given number is Prime or Not


#include<stdio.h>

int main()
{
 /* Declaring variable for n=number, c=counter variable:holds 
 number of factor of 'n' */
 int n,c=0, i;
 
 // Inputting number
 printf("Enter number to check whether Prime or Not:");
 scanf("%d",&n);

 // Checking whether number valid or not
 if(n>0)
 {
  
 // Checking whether number is prime or not 
 for(i=1;i<=n;i++)
 {
  if(n%i==0)
    c=c+1;
 }
 
 if(c==2)
   printf("Prime Number");
 else
   printf("Not a Prime Number");
 }
 
 else 
   printf("Not a valid Number");

 return 0;
}

Program to print ( list ) all the prime number between 1 to n

#include<stdio.h>

int main()
{
 /* Declaring variable for n=number, c=counter variable:holds 
 number of factor of 'n' */
 int n,c, i,j;
 
 // Inputting number
 printf("Enter number till which you want to list prime number:");
 scanf("%d",&n);

 // Checking whether number valid or not
 
 if(n>0)
 {
  printf("List of Prime Numbers:");
 // Checking whether number is prime or not 
 for(i=1;i<=n;i++)
 {
  c=0;
  for(j=1;j<=i;j++)
  {
    if(i%j==0)
      c=c+1;
  }
 if(c==2)
   printf("%d ",i);
 }
 
 }
 else 
   printf("Not a valid Number");

 return 0;
}
Palindrome Program In C

Palindrome Program In C


C PROGRAM TO DETERMINE PALINDROME NUMBER

Back To Palindrome Program

#include<stdio.h>
int main()
{
  // variable for a=number, n=to copy number, d=digit, rev=reverse of number
  int a,n,d=0,rev=0;

  // Inputting number
  printf("Enter any number to determine whether it is Palindrome or not:");
  scanf("%d",&a);

  // copying number in n
  n=a;

  // Determining whether number is palindrome or not
  while(n!=0)
  {
    d=n%10;
    rev=rev*10+d;
    n=n/10;
  }
           
  // Displaying Whether number is palindrome or not
  if(a==rev)
    printf("Palindrome number");
  else
    printf("Not a Palindrome Number");

  return 0;
}


C PROGRAM TO PRINT(LIST) PALINDROME NUMBER FROM 10 TO n

Back To Palindrome Program

#include<stdio.h>
int main()
{
  /*declaring variable for num=user wish, i=acts as number, n=to copy number, 
  d=digit, rev=reverse of number */
  int num,n,d=0,rev,i;

  // Inputting number
  printf("Enter number till which you want to list Palindrome Number:");
  scanf("%d",&num);

  printf("List of Palindrome Number:");
  for(i=10;i<=num;i++)
  {
    // copying number in n
    n=i;
    rev=0;
    // Determining whether number is palindrome or not
    while(n!=0)
    {
       d=n%10;
       rev=rev*10+d;
       n=n/10
    }
           
    // Displaying Whether number is palindrome or not
    if(i==rev)
    printf("%d ",i);
  }

  return 0;
}

C PROGRAM TO FIND WHETHER A NUMBER IS PALINDROME OR NOT USING RECURSION

Back To Palindrome Program

#include<stdio.h>

// Declaring global variable r=reverse, d=digit
int r=0, d=0;

// Defining function with parameter n = number
int rev(int n)
{
/* Base condition : Any condition where a recursive function 
or method does not invoke itself. */
if(n==0)
return r;

// Continue calling function rev or function invoke itself
else
{
 // Extracting digit
 d=n%10;
 
 // Finding reverse
 r=(r*10+d);
 
 // function invoke itself
 rev(n/10);
}
}

int main()
{
// Declaring variable n = number
int n;

// Declaring variable "r" to hold the reverse number
int r;

// Inputting Number
printf("Enter the Number : ");
scanf("%d",&n);

// Calling function "rev" with actual parameter "n" passed to it
r=rev(n);

// Checking and Displaying if a Number is palindrome or Not
if(r==n)
printf("%d is a Palindrome Number ",n);

else
 printf("%d is not a Palindrome Number ",n);

return 0;
}


C PROGRAM TO ENTER A WORD AND CHECK WHETHER IT IS PALINDROME OR NOT USING STRING FUNCTION

Back To Palindrome Program


// palindrom - When word = reverse of word then it is called palindrome
// Example : madam - palindrome, Madam - not palindrome, MadaM - palindrome

#include<stdio.h>
#include<string.h>

int main()
{
 // Declaring variable str=string 
 char word[50], word1[50];
 
 // Inputing string
 printf("Enter any word : ");
 scanf("%s",&word);

 // Copying word to word1
 strcpy(word1,word);
 
 // checking if palindrome or not
 if(strcmp(word,strrev(word1))==0)
 {
  printf("Entered word is a palindrome ");
 }
 
 else
  printf("Entered word is not palindrome ");

 return 0;
}

PALINDROME PROGRAM IN C WITHOUT USING STRING FUNCTION

Back To Palindrome Program

#include<stdio.h>

int main()
{
 // Declaring variable str=string 
 char word[50], revword[50];
 
 /* Declaring variable i=to iterate loop, l=length, 
 c=count the number of matched character */
 int i, j, l=0, c;
 
 // Inputing string
 printf("Enter any word : ");
 scanf("%s",&word);

 // finding length
 while(word[l]!='\0')
 l++;
 
 // Reversing string
 j=0;
 for(i=l-1;i>=0;i--)
 {
  revword[j]=word[i];
  j++;
 }
 revword[j]='\0';
 
 //checking if palindrome or not
 c=0;
 for(i=0;word[i]!='\0';i++)
 {
  if(revword[i]==word[i])
  c++;
 }
 
 if(c==l)
 {
  printf("Word is a palindrome ");
 }
 
 else
  printf("Word is not palindrome ");
 
 return 0;
}
Leap Year Program In C

Leap Year Program In C

Leap Year Program In C using if-else

// Leap year program in c using if-else
#include<stdio.h>

int main()
{
 // Declaring variable for y=year
 int y;
 
 // Inputing year
 printf("Enter year to check leap year or not: ");
 scanf("%d",&y);
 
 // Determining and displaying whether leap year or not
 if(y%4==0)
 {
  if(y%100==0 && y%400!=0)
  printf("Century year, But not a leap year");
  else
  printf("Leap year");
 }
 else
 printf("Not a Leap Year");

 return 0;
}

Leap Year Program In C Using Ternary

// Leap year program in c using ternary
#include<stdio.h>

int main()
{
 // Declaring variable "y" to input year and "leap" to determine leap year
 int y,leap;
 
 // Inputting year
 printf("Enter any year : ");
 scanf("%d",&y);
 
 // Checking if leaf year or not
 leap=(y%400==0)?:(y%100!=0)?(y%4==0)?1:0:0;

 if(leap==1)
 printf("The given year is leap year");
 else
 printf("The given year is not leap year");

 return 0;
}

Insertion Sort Algorithm, Time Complexity And Program In C


INSERTION SORT IN C


In Insertion Sort we select a key i.e an element one by one from any given list of element ( array ) and then we insert it in its appropriate position. We can either scan the list from left to right or right to left to find an appropriate position. But usually we scan list from right to left because it is better in case of sorted and almost sorted arrays. Insertion sort is an efficient algorithm for sorting small number of elements. Though Insertion Sort is based on recursive idea, it is more efficient to implement this algorithm by bottom up approach i.e iteratively.  

Need Programming Help visit: Get Programming Help Online

Consider the elements to be sorted by insertion sort are : 89, 45, 68, 90, 29, 34, 17

As shown in Figure below, starting with A[1] and ending with A[n - 1], A[i] is inserted in its appropriate place among the first i elements of the array that have been already sorted (but, unlike selection sort, the elements are generally not in their final positions). 
Insertion Sort In C : Showing insertion of elements
Insertion Sort In C : Showing how elements are sorted
The above figure shows how elements 89, 45, 68, 90, 29, 34, 17  are sorted by insertion sort. A vertical bar separates the sorted part of the array from the remaining elements; the element being inserted is in bold.

Note : Refer to algorithm for better understanding.


INSERTION SORT ALGORITHM


InsertionSort(int a[ ], int n)

   for i=1 to n-1
       key = a[i]
       j = i-1

       while j>=0 and key < a[j]
           a[j+1]=a[j]; 
           j=j-1;
   
       a[j+1] =  key

Note : The operation of the algorithm can be understood with the help of above figure.

TIME COMPLEXITY OF INSERTION SORT


Time Complexity Of Insertion Sort - Best Case


  • The best case input in an array is such that the array is already sorted. 
  • In this case insertion sort has linear running time i.e O(n)


Time Complexity Of Insertion Sort - Worst Case


  • The worst case input in an array is such that the array is sorted in reverse order.
  • In this case insertion sort has quadratic running time i.e O(n2


Time Complexity Of Insertion Sort - Average Case

  • Input in this case is a random input.
  • In this case also insertion sort has quadratic running time i.e O(n2)
  • Insertion Sort is very efficient in sorting very small arrays.
  • Its impractical to sort very large arrays using insertion sort due to its time complexity of O(n2)

INSERTION SORT PROGRAM IN C


// Insertion sort program in c

#include<stdio.h> 

void InsertionSort(int a[],int n) ;

int main() 
{ 
 int a[20],i,n; 
 printf("Enter number of elements in array : "); 
 scanf("%d",&n);
  
 // Inputting elements
 for(i=0;i<n;i++) 
 { 
    printf("Enter number %d: ",i+1); 
    scanf("%d",&a[i]);
 } 
 
 // Displaying Elements before insertion sort
 printf("Items in the array are : "); 
 for(i=0;i<n;i++)
 { 
    printf("%d ",a[i]); 
 } 
 
 //Applying insertion sort
 InsertionSort(a,n); 
 
 // Displaying elements after insertion sort
 printf("\nElements after insertion sort : "); 
 for(i=0;i<n;i++) 
 { 
    printf("%d ",a[i]); 
 } 
 return 0; 
} 

void InsertionSort(int a[],int n) 
{ 
 int i,key,j; 
 
 for(i=1;i<n;i++) 
 { 
  key=a[i]; 
  j=i-1; 

  // Finding appropriate position to insert key
  while((key<a[j])&&(j>=0))  
  { 
   a[j+1]=a[j]; 
   j=j-1; 
  }
  
  // Inserting key
  a[j+1]=key; 
 } 
} 


More Informative Posts :
String Programs In C

String Programs In C

  1. Program to accept a string and print it
  2. Program to accept a character in the uppercase and print in lower case
  3. Program to accept a character in Lower case and print it in upper case
  4. Program to accept a character in any case and print in another case
  5. Program to accept a string and print it by using while loop
  6. Program to find length of a string using string function
  7. Program to find length of a string without using string function
  8. Program for Copy a String to another using String Function
  9. Program to find length of a string without using string function
  10. Program for Compare two String using String Function
  11. Program for Compare two String without using String Function
  12. Program for String Reverse with String Function
  13. Program for String Reverse without String Function
  14. Program for String Concatenation with String Function
  15. Program for String Concatenation without String Function
  16. Program to convert all characters in a string to lower case using string function
  17. Program to convert all characters in a string to lower case without using string function
  18. Program to convert all characters in a string to upper case using string function
  19. Program to convert all characters in a string to upper case without using string function
  20. Program to enter 5 string and print them with their length
  21. Program to accept a string and print each word of the string separately also print total number of words
  22. Program to accept a string and display vowels frequency( total number of vowels)
  23. Program to accept a string and display frequency of each vowel along with vowel
  24. Program to enter a word and check whether it is palindrome or not using string function
  25. Program to enter a word and check whether it is palindrome or not without using string function
Array Programs In C

Array Programs In C

  1. C Program to accept elements in an array and display it
  2. C Program to accept elements in an array and display sum of all the elements
  3. C Program to insert element in between an array. ( INSERTION )
  4. C Program to delete element from an array. ( DELETION )
  5. C Program to perform Transpose of a Matrix
  6. C Program to find Minimum element in an array
  7. C Program to find highest minimum temperature and lowest maximum temperature
  8. C Program to accept 10 numbers and print first five numbers in original order and print last five numbers in reverse order
  9. C Program showing Passing array to function. Program finds the average of 5 marks input by user
  10. C Program to initialize a character array and display the initialized character array in reverse order
  11. C Program to generate histogram of entered number
  12. C Program to enter values into a two-dimensional integer array of size (4 X 3) and then display it in matrix form
  13. Write a c program to enter values into a two-dimensional integer array of size (4 X 3) and then display the elements of the second row
  14. C Program to find the sum of elements that are greater than 5 within a two-dimensional array through a function receiving the array as arguments
  15. C Program To Accept 5 Student - Roll No, Marks in 3 Subjects of each student and Calculate Total, Average and Print it along with student roll Number
  16. C Programs to multiply two Matrices
  17. C Program to print a diagonal matrix with diagonal value enter by user
  18. C Program to print a anti diagonal matrix with diagonal value enter by user
  19. C Program to print the sum of diagonal values and anti-diagonal values of a matrix
Pointer Programs In C

Pointer Programs In C

Recursion Program In C

Recursion Program In C

Pattern Programs In C

Pattern Programs In C

  1. Program to print the given pattern :
    *
    * *
    * * *
    * * * *
    * * * * * 
  2. Program to print the given pattern :
    *
    * *
    * * *
    * * * *
    * * * * *
    * * * * * * ..... till n rows
  3. Program to print the given pattern :
    1
    1 2
    1 2 3
    1 2 3 4
    1 2 3 4 5 .... till n rows
  4. Program to print the given pattern :
    1
    2 2
    3 3 3
    4 4 4 4
    5 5 5 5 5 .... till n rows
  5. Program to print the given pattern :
    1 1 1 1 1
    2 2 2 2 2
    3 3 3 3 3
    4 4 4 4 4
    5 5 5 5 5
  6. Program to print the given pattern :
    5
    5 4
    5 4 3
    5 4 3 2
    5 4 3 2 1
  7. Program to print the given pattern :
    1 2 3 4 5
    1 2 3 4
    1 2 3
    1 2
    1
  8. Program to print the given pattern :
    5 4 3 2 1
    5 4 3 2
    5 4 3
    5 4
    5
  9. Program to print the given pattern :
            *
          * *
        * * *
      * * * *
    * * * * *
    
  10. Program to print the given pattern :
            1
          1 2
        1 2 3
      1 2 3 4
    1 2 3 4 5
  11. Program to print the given pattern :
            5
          4 5
        3 4 5
      2 3 4 5
    1 2 3 4 5
    
  12. Program to print the given pattern :
    1
    * *
    1 2 3
    * * * *
    1 2 3 4 5 .... till n rows
  13. Program to print the given pattern :
    1                 1
    1 2             1 2
    1 2 3         1 2 3
    1 2 3 4     1 2 3 4
    1 2 3 4 5 1 2 3 4 5
    
  14. Program to print the given pattern :
    1                 1
    1 2             2 1
    1 2 3         3 2 1
    1 2 3 4     4 3 2 1
    1 2 3 4 5 5 4 3 2 1
    
  15. Program to print the given pattern :
    1                 5
    1 2             5 4
    1 2 3         5 4 3
    1 2 3 4     5 4 3 2
    1 2 3 4 5 5 4 3 2 1
    
  16. Program to print the given pattern :
    1
    2 6
    3 7 10
    4 8 11 13
    5 9 12 14 15 ... till n rows
  17. Program to print the given pattern :
    ******** ********
    *******   *******
    ******     ****** 
    *****       *****
    ****         ****
    ***           ***
    **             **
    *               *
     
    *               *
    **             **
    ***           ***
    ****         ****
    *****       ***** 
    ******     ******
    *******   *******
    ******** ********
    
  18. Program to print the given pattern
     
          *
         ***
        *****
       *******
      *********
       *******  
        *****
         ***
          * 
    
  19. Program to print the given pattern :
    8 4 2 1
    4 2 1
    2 1
    1
  20. Program to print Pascal triangle :

Heap Sort Program In C

HEAP SORT

HEAP SORT IN C


Heap sort uses a binary heap, which is a complete binary tree.  

Binary Tree : A Binary Tree is a hierarchical structure  that is either empty or consists of an element, called the root, and two distinct binary trees, called the left subtree and right subtree.

 Example : 

Heap Sort : Binary Tree
Heap Sort : Binary Tree













Heap is a binary tree with the following properties : 
  • It is a complete binary tree.
  •  Each node is greater than or equal to any of its children.
Complete Binary Tree : A binary tree is complete if each of its levels is full, except that the last level may not be full and all the leaves on the last level are placed leftmost.

Example : 

Heap Sort : Complete Binary Tree
Heap Sort : Complete Binary Tree






Heap Example : 

Heap Sort : Heap
Heap Sort : Heap





Note : We represent heaps in level order, going from left to right. The array corresponding to the heap above is  : 
[45, 24, 32, 16,19,12, 21].

PSEUDOCODE TO ADD NODE IN HEAP


To add a new node to the heap, first add it to the end of the heap and then rebuild the tree as follows:

Let the last node be the current node;
while (the current node is greater than its parent) {
Swap the current node with its parent;
Now the current node is one level up;
}

Suppose we want to insert 3, 5, 1, 19, 11, 22. We assume that the heap is initially empty.

Heap Sort : Adding Node In Heap
Heap Sort : Adding Node In Heap


Now lets insert a new node 88 in the above heap.


Heap Sort : Rebuilding of Heap after adding a new node
Heap Sort : Rebuilding of Heap after adding a new node

PSEUDOCODE TO REMOVE ROOT FROM HEAP


Often you need to remove the max element, which is the root in a heap. After the root is removed, the tree must be rebuilt to maintain the heap property. The algorithm for rebuilding the tree can be described as follows:

Move the last node to replace the root;
Let the root be the current node;
while (the current node has children and the current node is smaller than one of its children) {
Swap the current node with the larger of its children;
Now the current node is one level down;
}

Heap Sort : Removing Root and Rebuilding Heap
Heap Sort : Removing Root and Rebuilding Heap


HOW HEAP SORT IS PERFORMED

  • First we take input in an array.
  • Then we insert these element in heap.
  • As we know that root of the heap is maximum element so we remove root and rebuild heap so that the next maximum element is at root. Rebuilding ensures that our tree is in the form of heap.
  • We store the root ( maximum element ) in decreasing order of array length. We could have used another array as well to store the root.


HEAP SORT PROGRAM IN C


// C Program ( Code ) for Heap sort
#include<stdio.h>

void insert(int a[], int n, int item);
int deleteheap(int a[],int n);

int main()
{
   int a[20],i,n,item;
   printf(" Enter number of elements in array : ");
   scanf("%d",&n);
   for(i=0;i<n;i++)
   {
     printf(" Enter number %d : ",i+1);
     scanf("%d",&a[i]);  
   }
 
   for(i=0;i<n;i++)
   {

     item=a[i];
     insert(a,i,item);
   }
   printf("\n Heap is : ");
   for(i=0;i<n;i++)
   {
     printf("%d ",a[i]);
   }


   for(i=n;i>=1;i--)
   { 
     item=deleteheap(a,i);
         
     // Stores item=Maximum element in decreasing order of array length
     a[i-1]=item;
   }


   printf("\n SORTED LIST IS!!!!\n");
   for(i=0;i<n;i++)
   {
     printf(" %d ",a[i]);
   }
 
 }
 
  // Used to Build Heap
  void insert(int a[], int n, int item)
  {
     int ptr,par,temp;
 
     ptr=n;
     while(ptr>=1)
     { 
       par=(ptr-1)/2;
 
       if(a[par]>=item)
       { 
         a[ptr]=item;
         return;
       }
       else
       {
         a[ptr]=a[par];
         ptr=par;
       }
    
       a[ptr]=item;
     }
 }
 
  /* Remove root which is the maximum element in Heap and rebuild heap 
     so that the next maximum element is at root. Rebuilding ensures 
     that our tree is in the form of heap.
     Returns item = a[0] wcich contains the root of the heap.
   */
  int deleteheap(int a[],int n)
  {
    int i=0,item,temp;
    
    // a[0] - contains the root of the heap
    item=a[0];
    a[0]=a[n-1];
    n=n-1;
    while(((a[i]<a[2*i+1])||(a[i]<a[2*i+2]))&&((2*i+1)<n))
    {
      if(a[2*i+1]>a[2*i+2])
      {
        temp=a[i];
        a[i]=a[2*i+1];
        a[2*i+1]=temp;
        i=2*i+1;
      }
 
      else
      {
        temp=a[i];
        a[i]=a[2*i+2];
        a[2*i+2]=temp;
        i=2*i+2;
      }
    }
    
    // Root of the heap is returned
    return item;
  }

HEAP SORT PROGRAM OUTPUT


Heap Sort : Heap sort code output
Heap Sort Output











More Informative Posts :
Different Types Of Errors In C

Different Types Of Errors In C

Errors are mistake that we programmer often commit. Errors also called as bugs causes the program to either run unexpectedly ( shows unexpected result ) or prevent the execution of a program. As programmer we are prone to make mistakes. So we should keep in mind the following different types of errors in c which we might commit :

TYPES OF ERRORS

SYNTAX ERROR IN C

  • Syntax Errors are basically compiler errors or compile-time errors which occurs when we do not follow the grammar of the programming language. 
  • It is detected when you compile the program by the compiler.

Syntax Errors occurs : 
  • Due to missing semicolon ( ' ; ' ). It is used as an terminating statement. So when you forget to place a semicolon or use any other alternative then it causes syntax error. 
       #include<stdio.h>
       int main()
       {
         int a=10 // Syntax error as semicolon is missing
         int b=100 : // Syntax error as using ':' instead of ';'
         return 0;
       }
    
  • It occurs when we use a variable which is not declared in program.
  •   #include<stdio.h>
      int main()
      {
         printf("Value of a : %d",a); // error as 'a' is not declared anywhere in program
         return 0;
      }
    
  • Error Occurs due to missing and unmatched parenthesis.
      // Syntax Error as ')' parenthesis is missing
      void sum( 
    
      // Syntax Error as '}' parenthesis is missing
      void product()
      { statement
    
      // Syntax Error due to unmatched parenthesis
      void a{}
    

SEMANTIC ERROR IN C

  • Semantic errors occurs when the statement written in the program are not meaningful to the compiler.
  • Semantic errors indicate an improper use of Java statements.
    Example : int a+b=c; // Semantic Error
    Correct one : int c=a+b;

    int a=+b; // Semantic Error
    Correct one : int a+=b; // Shorthand notation 

LOGICAL ERROR IN C

  • Logical errors are errors that shows unexpected results.
  • It occurs when you write a program that works, but does not do what you intend it to do.
    Example : Suppose you want to find the factorial of a number but instead of multiplying number you end up adding it.
    #include<stdio.h>
     int main()
     {
       int i;
       int factorial=1;
       
       for(i=1;i<=n;i++)
         factorial=factorial+i; // Logical Error. Correct statement : factorial=factorial*i;
    
       return 0;
     }
    

    Though the program would work fine and would not show any syntax or run time error. But the output which you were expecting will not be shown.

LINKER ERROR IN C

  • Linker Errors are errors that occurs when we do not include header files for the predefined functions used in a program and when we  misspell a standard c function.
    #include<stdio.h>
     int Main() // Linker error as 'main' is misspelled as 'Main'
     {
       printf("Hello : ");
       return 0;
     }
    

RUNTIME ERROR IN C

  • Run-time errors are errors that occurs during the execution of the program.
    Example :
    • When we divide a number by zero.
    • When input data is not in the correct format.
    //Runtime error program in c
    #include<stdio.h>
     int main()
     {
       int a=10,b=0,result;
       int number;
    
       result=a/b; // Runtime error
       scanf("%d",&number); // Error occurs when you input some other character instead of 'numbers'
    
       return 0;
     }
    
More Informative Posts :
C Program to add, subtract, multiply and divide two numbers

C Program to add, subtract, multiply and divide two numbers

The following programs takes input of two numbers from user and add, subtract and divide two numbers.

Sample Input / Output :

Enter any two number : 20
10

Sum = 30
Subtracted value = 10
Multiplied value = 200
Division value = 2

// C Program to add, subtract, multiply and divide two numbers
#include<stdio.h>

int main()
{
    int a, b;
    
    printf("Enter any two number : ");
    scanf("%d",&a);
    scanf("%d",&b);
    printf("Sum=%d",a+b);
    printf("\nSubtracted value=%d",a-b);
    printf("\nMultiplied value=%d",a*b);
    printf("\n Division value=%d",a/b);

    return 0;
}
Counting Sort Program In C

Counting Sort Program In C

COUNTING SORT

COUNTING SORT IN C


In the code for counting sort, we assume that the input is an array A[1 . . . n] and  we require two other arrays: the array B[1 . . . n] holds the sorted output, and the array C[0 . . . k] provides temporary working storage. Here k = maximum element present in array.

Consider following elements to be sorted using counting sort : 2, 5, 3, 0, 2, 3, 0, 3

So we have in array A[1 . . . 8 ] :
 2   5   3   0   2   3   0   3 

Now what we have to do is initialize the auxiliary array C[0 . . . k] with 0. Here k = 5.
So C[0 . . . 5] becomes :
 0   0   0   0   0   0 

Next step is to count the frequency of each element and store it in their respective index position i.e here frequency of 0 = 2. So we place '2' at index position '0'. Similarly we place each element and the array becomes C[0 . . . 5] :
 2   0   2   3   0   1 

Now we add the current index position with its previous index position and store it in the current index position i.e C[ i ] = C[ i ] + C[ i - 1 ] where 'i' starts from '1'.

So C[ 0 . . . 5 ] becomes : 
 2   2   4   7   7   8 

The final step is to place the elements in B[ 1 . . . 8 ] with reference to C[ 0 . . . 5 ] i.e  Now we treat elements in C[ 0 . . . 5 ] as index of B[ 1 . . . 8 ] and index of C[ 0 . . . 5 ] as elements of B[ 1 . . . 8 ]. So at index position '8' we have element '5' so we place '5' at index position of '8' of B[ 1 . . . 8 ] ( B[ 8 ] = 5 ) and we reduce the index position by '1' i.e 8-1 = 7. Now note that we have element '7'  in C[ 4 ] position but '4' is not present in the original array so we skip it and move to C[ 3 ] position, so we place '3' at index position '7' of B[ 1 . . . 8 ]. Similarly we place each element in B[ 1 . . . 8 ] and we get sorted array.

So the sorted array B[ 1 . . . 8 ]  is :
 0   0   2   2   3   3  3  5 



// Counting Sort algorithm
CountingSort(A,B,n,k)
   int C[0 . . . k ]
   for i=0 to k
      C[i]=0
   for j=1 to n
      C[A[j]] = C[A[j]] + 1;
   for i=1 to k
      C[i] = C[i] + C[i-1];
   for j=n downto 1
      B[C[A[j]]] = A[j];
      C[a[j]] = C[A[j]] - 1;


// Counting sort program in c

#include<stdio.h> 

void CountingSort(int a[], int sorted_array[], int max_element, int n);

int main() 
{ 
 int a[20],i,n; 
 int max_element, sorted_array[20];
 
 printf("Enter number of elements in array : "); 
 scanf("%d",&n);
  
 // Inputting elements
 for(i=1;i<=n;i++) 
 { 
    printf("Enter number %d: ",i+1); 
    scanf("%d",&a[i]);
 } 
 
 // Displaying Elements before counting sort
 printf("Items in the array are : "); 
 for(i=1;i<=n;i++)
 { 
    printf("%d ",a[i]); 
 } 
 
 // Finding Maximum element
 max_element=a[1];
 
 for(i=2;i<=n;i++)
 {
  if(a[i] > max_element)
  {
           max_element = a[i];
  }
 }
 
 //Applying counting sort
 CountingSort(a, sorted_array, max_element, n); 
 
 // Displaying elements after count sort
 printf("\nElements after count sort : "); 
 for(i=1;i<=n;i++) 
 { 
    printf("%d ",sorted_array[i]); 
 } 
    
 return 0; 
} 

void CountingSort(int a[],int sorted_array[],int max_element, int n)
{
 int aux_array[max_element];
 int i,j;
 
 // Initializing auxiliary array
        for(i=0;i<=max_element;i++)
 {
  aux_array[i]=0;
 }
 
        // Placing Frequency of each element in aux_array
 for(j=1;j<=n;j++)
 {
  aux_array[a[j]]=aux_array[a[j]]+1;
 }
 
        // Adding elements of current and previous index position
 for(i=1;i<=max_element;i++)
 {
  aux_array[i]=aux_array[i]+aux_array[i-1];
 }
 
        // Placing elements in sorted_array 
 for(j=n;j>=1;j--)
 {
  sorted_array[aux_array[a[j]]] = a[j];
  aux_array[a[j]] = aux_array[a[j]] - 1;
 }
}


 More Informative Posts :

Selection Sort Program In C

Selection Sort


SELECTION SORT IN C

We start Selection Sort by scanning the entire given list to find its smallest element and exchange it with the first element, putting the smallest element in its final position in the sorted list. Then we scan the list, starting with the second element, to find the smallest among the last n - 1 elements and exchange it with the second element, putting the second smallest element in its final position. Generally, on the ith pass through the list, which we number from 0 to n - 2, the algorithm searches for the smallest item among the last n - i elements and swaps it with A[i].


Consider the following element that is to be sorted using selection sort :  89, 45, 68, 90, 29, 34, 17.
The analysis of selection sort is straightforward. The input's size is given by the number of elements 'n' and the algorithm's basic operation is the key comparison A[j] < A[min]. The number of times it is executed depends only on the array's size.

Selection Sort In C : Showing how elements are sorted
Selection Sort In C : Showing how elements are sorted

The above figure shows how given elements 89, 45, 68, 90, 29, 34, 17 are sorted according to selection sort. Each line corresponds to one iteration of the algorithm i.e. a pass through the list tail to the right of the vertical bar. An element in bold indicates the smallest element found. Elements to the left of the vertical bar are in their final positions and are not considered in this and subsequent iterations. 

SELECTION SORT ALGORITHM

SelectionSort(int a[],int n)
   for i=0 to n-2
     min=i

     for j=i+1 to n-1
        if a[min] > a[j]
           min = j
   
     swap a[i] with a[min]

   

SELECTION SORT PROGRAM IN C

// Selection sort program in c

#include<stdio.h> 

void SelectionSort(int [],int); 
 

int main() 
{ 
 int a[20],i,n; 
 printf("Enter number of elements in array : "); 
 scanf("%d",&n);
  
 // Inputting elements
 for(i=0;i<n;i++) 
 { 
    printf("Enter number %d: ",i+1); 
    scanf("%d",&a[i]);
 } 
 
 // Displaying Elements before selection sort
 printf("Items in the array are : "); 
 for(i=0;i<n;i++)
 { 
    printf("%d ",a[i]); 
 } 
 
 //Applying selection sort
 SelectionSort(a,n); 
 
 // Displaying elements after selection sort
 printf("\nElements after selection sort : "); 
 for(i=0;i<n;i++) 
 { 
 printf("%d ",a[i]); 
 } 
 return 0; 
} 

void SelectionSort(int a[],int n) 
{ 
 int i,loc,j,min,temp; 
 for(i=0;i<=n-2;i++) 
 { 
   min = i;
 
   for(j=i+1;j<=n-1;j++) 
   {   
     // Finding minimum element
     if(a[min] >a[j])  
     { 
       min=j;  
     } 
   }
  
   //Swapping a[i] with a[min]
   temp=a[i]; 
   a[i]=a[min]; 
   a[min]=temp;
 } 
}

More Informative Posts :

Bubble Sort Program In C

Bubble Sort


BUBBLE SORT IN C

Back To Bubble Sort

Bubble Sort is a popular but inefficient sorting algorithm.  Bubble Sort is another brute-force application to the sorting problem that compares adjacent elements of the list and exchange them if they are out of order. By doing it repeatedly, we end up "bubbling up" the largest element to the last position on the list. The next pass bubbles up the second largest element, and so on until, after n - 1 passes, the list is sorted. Pass i (0 <= i <= n - 2) of bubble sort can be represented by the following diagram: 

Consider element to be sorted are : 89, 45, 68, 90, 29, 34, 17 

Bubble Sort In C : Swapping elements
Quick Sort In C : Showing how elements are sorted


First two passes of bubble sort on the given list 89, 45, 68, 90, 29, 34, 17 is shown in above figure.  A new line is shown after a swap of two elements is done. The elements to the right of the vertical bar are in their final positions and are not considered in  subsequent iterations of the algorithm.

BUBBLE SORT ALGORITHM


// Algorithm for Bubble Sort
BubbleSort(int a[],int n)
  for i=0 to n-2
    for j=0 to n-2-i
      if a[j] > a[j+1]
        swap a[j] with a[j+1]

BUBBLE SORT PROGRAM IN C


// Bubble sort program in c

#include<stdio.h> 

void bubblesort(int a[],int n);

int main() 
{ 
 int a[20],i,n; 
 printf("Enter number of elements in array : "); 
 scanf("%d",&n);
  
 // Inputting elements
 for(i=0;i<n;i++) 
 { 
 printf("Enter number %d: ",i+1); 
 scanf("%d",&a[i]);
 } 
 
 // Displaying Elements before bubble sort
 printf("Items in the array are : "); 
 for(i=0;i<n;i++)
 { 
 printf("%d ",a[i]); 
 } 
 
 //Applying bubble sort
 bubblesort(a,n); 
 
 // Displaying elements after bubble sort
 printf("\nElements after bubble sort : "); 
 for(i=0;i<n;i++) 
 { 
   printf("%d ",a[i]); 
 } 
 return 0; 
} 

void bubblesort(int a[],int n) 
{ 
  int i,j;
  for(i=0; i<=n-2; i++) 
  { 
    for(j=0;j<=n-i-2;j++) 
    { 
       // Swapping elements
       if(a[j]>a[j+1]) 
       { 
         int temp=a[j]; 
         a[j]=a[j+1]; 
         a[j+1]=temp; 
      } 
   } 
 } 
} 


More Informative Posts :

GOOD PROGRAMMING PRACTICES

GOOD PROGRAMMING PRACTICES


GOOD PROGRAMMING PRACTICES - FUNDAMENTALS

  • Every function should be preceded by a comment describing the purpose of the function.
  • Add a comment to the line containing the right brace, } that close every function, including the main(). This helps in determining that the function is ended.
  • Indent the entire body of each function. This indentation emphasizes the functional structure of a program and helps make program easier to read.
  • Set a convention for the size of indent you prefer and then uniformly apply that convention.
  • Choosing meaningful variable name helps make a program self-documenting i.e fewer comments are needed.
  • Multiple-word variable names can help make a program more readable.Separate the words with underscore eg : comp_psyche or good_programming_practices.
  • Place a space after each comma to make a program more readable.
  • Place spaces on either side of binary operator. This makes the operator stand out and makes the program more readable.
  • Although it is allowed that we can have multiple statement in a single line but to make program more readable there should be only one statement per line in a program.

GOOD PROGRAMMING PRACTICES - CONTROL STRUCTURES

  • Indent both body statement of an if...else statement.
  • If there are several level of indentation, each level should be indented with same additional amount of space.
  • When performing division by an expression whose value could be zero, explicitly test this case and handle it appropriately in your program ( such as printing an error message ) rather than allowing the fatal error to occur.
  • In a sentinel-controlled loop, the prompts requesting data entry should explicitly remind the user what the sentinel value is.
  • Too many levels of nesting can make a program difficult to understand. As a rule, try to avoid using more than three levels of nesting.
  • Limit the size of the control statement headers to a single line if possible.
  • Although the case clauses and the default case clause in a switch statement can occur in any order but its advisable to place the default clause at last.
  • In a switch statement when the default clause is last then the break statement is not required.

GOOD PROGRAMMING PRACTICES - FUNCTION

  • Familiarize yourself with rich collection of functions in C standard library.
  • Although It is not incorrect to do so but do not use the same names for a function's arguments and the corresponding parameters in function definition. This helps avoid ambiguity.
  • Choosing meaningful function names and meaningful parameter names makes program more readable and helps avoid excessive use of comments.
  • Parameter names are sometimes included in function prototype for documentation purposes. The compiler ignore these names.
  • Use only uppercase letters in the names of enumeration constants to make these constants stand out in a program and to indicate that enumeration constants are not variable.  

GOOD PROGRAMMING PRACTICES - ARRAY

  • Defining the size of each array as a symbolic constant make program more readable.
  • Use only uppercase letter for symbolic constant names. This makes these constants stand out in a program and reminds you that symbolic constants are not variable.
  • In multi-word symbolic constant names, separate the words with underscores for readability.
  • Strive for program clarity. Sometimes it may be worthwhile to trade off the most efficient use of memory or processor time in favor of writing clearer programs.
  • When passing an array to a function, also pass the size of the array. This helps make function reusable in many programs.

GOOD PROGRAMMING PRACTICES - STRING

  • When storing a string of characters in a character array be sure that the array is large enough to hold the largest string that will be stored.
  • Familiarize yourself with the various predefined string function. This helps in achieving task easily.
  • When using functions from the string-handling library, include the <string.h> header.

GOOD PROGRAMMING PRACTICES - POINTERS


  • Its preferable to include the letters Ptr in pointer variable names to make it clear that these variables are pointer and thus need to be handled appropriately.
  • Initialize pointer to prevent unexpected result.
  • If a variable does not change in the body of a function to which it is passed, the variable should be declared const to ensure that it is not accidentally modified.
  • Pass large objects such as structures using pointers to constant data to obtain the performance benefits of pass-by-reference.

GOOD PROGRAMMING PRACTICES - STRUCTURE AND UNION

  • Always provide a structure tag name when creating structure type. The structure type name is convenient for declaring new variables of the structure type later in the program.
  • Do not use spaces around  '->' and '.' operators. Omitting spaces helps emphasize that the expressions the operators are contained in are essentially single variable names.
  • Passing structure by reference is more efficient than passing structure by value.
  • Use typedef to help make a program more protable.
  • Capitalize the first letter of the typedef names to emphasize that they are synonyms for other types names.
  • Using typedef can help make a program more readable and maintainable.