Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Thursday 28 March 2013

C Code To Check Whether A No. Is Palindrome Or Not

A Palindrome number is a number, which when reversed in order of digits, produces the same number a the original one. Some examples of Palindrome numbers are: 11, 121, 1331. 14641, 15101051, 989, 5225 etc. The C program for the same is very simple. First we will reverse the original number and then check it with the original number. If found same, number is palindrome, otherwise not.

A Simple Algorithm for the same will be:
  1. Input number from user, 'num'.
  2. Apply Logic on 'num', produce reversed number 'rev'.
  3. If num == rev, print 'num' is Palindrome.
  4. Otherwise print 'num' is not Palindrome.

C Program To Check Whether A Number Is Palindrome Or Not:


/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>

void main()
{
 int a,b,c,d;
 clrscr();
 printf("Enter a number: ");
 scanf("%d",&a);
 b=a;
 d=0;

 while(a!=0)
 {
  d = d*10;
  c = a%10;
  a = a/10;
  d = d+c;
 }

 if(d==b)
 printf("\nThe number %d is plaindrome",b);

 else
 printf("\nThe number %d is not Palindrome",b);

 getch();
}


Program Output:


Palindrome Number C Code


Please Comment If You Liked This Post !! 


Sunday 17 March 2013

Selection Sort Algorithm And C Code

In computer science, a selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar Insertion sort. Selection sort is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.
The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.


Complexity:


Worst case performanceО(n2)
Best case performanceО(n2)
Average case performanceО(n2)



Step-by-step example:



Selection Sort Algorithm And C Code

Here is an example of this sort algorithm sorting five elements:
64 25 12 22 11

11 25 12 22 64

11 12 25 22 64

11 12 22 25 64

11 12 22 25 64
(Nothing appears changed on this last line because the last 2 numbers were already in order.)
Selection sort can also be used on list structures that make add and remove efficient, such as a linked list. In this case it is more common to remove the minimum element from the remainder of the list, and then insert it at the end of the values sorted so far. For example:
64 25 12 22 11

11 64 25 12 22

11 12 64 25 22

11 12 22 64 25

11 12 22 25 64

Algorithm & Pseudo Code For Selection Sort:

/* Double-Click To Select Code */

/* a[0] to a[n-1] is the array to sort */
int i,j;
int iMin;
 
/* advance the position through the entire array */
/*   (could do j < n-1 because single element is also min element) */
for (j = 0; j < n-1; j++) {
    /* find the min element in the unsorted a[j .. n-1] */
 
    /* assume the min is the first element */
    iMin = j;
    /* test against elements after j to find the smallest */
    for ( i = j+1; i < n; i++) {
        /* if this element is less, then it is the new minimum */  
        if (a[i] < a[iMin]) {
            /* found new minimum; remember its index */
            iMin = i;
        }
    }
 
    /* iMin is the index of the minimum element. Swap it with the current position */
    if ( iMin != j ) {
        swap(a[j], a[iMin]);
    }
}

C Program For Selection Sort:

/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>

int smallest(int arr[],int k,int n);
void sort(int arr[],int n);

void main()
{
 int arr[20],i,n,j,k;
 clrscr();
 printf("\nEnter the number of elements in the array: ");
 scanf("%d",&n);

 printf("\nEnter the elements of the array");
 for(i=0 ; i < n ; i++)
 {
  printf("\n arr[%d] = ",i);
  scanf("%d",&arr[i]);
 }

 sort(arr,n);
 printf("\nThe sorted array is: \n");
 for(i=0 ; i < n ;  i++)
 printf("%d\t",arr[i]);
 getch();
}

int smallest(int arr[],int k,int n)
{
 int pos=k,small=arr[k],i;
 for(i=k+1;i<n;i++)
 {
  if(arr[i]<small)
  {
   small=arr[i];
   pos=i;
  }
 }
 return pos;
}


void sort(int arr[],int n)
{
 int k,pos,temp;
 for(k=0 ; k < n ; k++)
  {
   pos=smallest(arr,k,n);
   temp=arr[k];
   arr[k]=arr[pos];
   arr[pos]=temp;
  }
}
 

Output Of Program:


Selection Sort Algorithm And C Code


Please Comment If You Liked This Post !! 

This article uses material from the Wikipedia article Selection_sort which is released under the Creative Commons Attribution-Share-Alike License 3.0


Insertion Sort Algorithm And C Code

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as Quicksort, heapsort, or Merge sort. However, insertion sort provides several advantages:
  • Simple implementation
  • Efficient for (quite) small data sets
  • Adaptive (i.e., efficient) for data sets that are already substantially sorted: the time complexity is O(n + d), where d is the number of inversions
  • More efficient in practice than most other simple quadratic (i.e., O(n2)) algorithms such as selection sort or bubble sort; the best case (nearly sorted input) is O(n)
  • Stable; i.e., does not change the relative order of elements with equal keys
  • In-place; i.e., only requires a constant amount O(1) of additional memory space
  • Online; i.e., can sort a list as it receives it


Step-by-step example:

The following table shows the steps for sorting the sequence {3, 7, 4, 9, 5, 2, 6, 1}. In each step, the item under consideration is underlined. The item that was moved (or left in place because it was biggest yet considered) in the previous step is shown in bold.
3 7 4 9 5 2 6 1
3 7 4 9 5 2 6 1
7 4 9 5 2 6 1
4 7 9 5 2 6 1
3 4 7 9 5 2 6 1
3 4 5 7 9 2 6 1
2 3 4 5 7 9 6 1
2 3 4 5 6 7 9 1
1 2 3 4 5 6 7 9

Algorithm/Pseudo-Code:


 for i ← 1 to i ← length(A)-1
   {
     //The values in A[ i ] are checked in-order, starting at the second one
     // save A[i] to make a hole that will move as elements are shifted
     // the value being checked will be inserted into the hole's final position
     valueToInsert ← A[i]
     holePos ← i
     // keep moving the hole down until the value being checked is larger than 
     // what's just below the hole <!-- until A[holePos - 1] is <= item -->
     while holePos > 0 and valueToInsert < A[holePos - 1]
       { //value to insert doesn't belong where the hole currently is, so shift 
         A[holePos] ← A[holePos - 1] //shift the larger value up
         holePos ← holePos - 1       //move the hole position down
       }
     // hole is in the right position, so put value being checked into the hole
     A[holePos] ← valueToInsert 
   }

Here is the C Code for Insertion Sort:



/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>

void sort(int arr[],int n); //Function Prototype

void main()
{
 int arr[20],i,n,j,k;
 clrscr();
 printf("\nEnter the number of elements in the array: ");
 scanf("%d",&n);

 printf("\nEnter the elements of the array");
 for(i=0 ; i < n ; i++)
 {
  printf("\n arr[%d] = ",i);
  scanf("%d",&arr[i]);
 }

 sort(arr,n);

 printf("\nThe sorted array is: \n");
 for(i=0;i<n;i++)
 printf("%d\t",arr[i]);
 getch();
 }

void sort(int arr[],int n)
{
 int k,j,temp;
 for(k=1 ; k < n ; k++)
 {
  temp=arr[k];
  j=k-1;
  while((temp < arr[j]) && (j>=0))
  {
   arr[j+1]=arr[j];
   j--;
  }
  arr[j+1]=temp;
 }
}


Output:


Insertion Sort Algorithm And C Code




This article uses material from the Wikipedia article Insertion_sort which is released under the Creative Commons Attribution-Share-Alike License 3.0


Saturday 16 March 2013

Linear Search In An Array C Code

As I have already described what are Arrays and their basic creation C code, in this post, we'll learn how to perform Linear Search In An Array, its Algorithm And C Code.

In computer sciencelinear search or sequential search is a method for finding a particular value in a list, that consists of checking every one of its elements, one at a time and in sequence, until the desired one is found. Linear search is the simplest search algorithm; it is a special case of brute-force search. Its worst case cost is proportional to the number of elements in the list; and so is its expected cost, if all list elements are equally likely to be searched for. Therefore, if the list has more than a few elements, other methods (such as binary search or hashing) will be faster, but they also impose additional requirements.

Here is the C Code for Linear Search:


/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>
void main()
{
 int arr[10],num,i,n,found=0,pos=-1;
 clrscr();
 printf("Enter the number of elements in the array: ");
 scanf("%d",&n);

 printf("\nEnter the elements: \n");
 for(i=0;i<n;i++)
 {
  printf("arr[%d] = ",i);
  scanf("%d",&arr[i]);
 }

 printf("\nEnter the number that has to be searched: ");
 scanf("%d",&num);

 for(i=0;i<n;i++)
 {
  if(arr[i]==num)
  {
   found=1;
   pos=i;
   printf("\n %d is found in the array at position = %d",num,i);
   break;
  }
 }
 if(found==0)
 printf("\ %d does not exist in the array",num);
 getch();
}


Output:

Linear Search C Code

Please Comment If You Liked This Post !! 

This article uses material from the Wikipedia article Linear Search which is released under the Creative Commons Attribution-Share-Alike License 3.0


Binary Search In An Array Algorithm And C Code

As I have already described what are Arrays and their basic creation C code, in this post, we'll learn how to perform Binary Search In An Array, its Algorithm And C Code.

In computer science, a binary search or half-interval search algorithm finds the position of a specified value (the input "key") within a sorted array. In each step, the algorithm compares the input key value with the key value of the middle element of the array. If the keys match, then a matching element has been found so its index, or position, is returned. Otherwise, if the sought key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the input key is greater, on the sub-array to the right. If the remaining array to be searched is reduced to zero, then the key cannot be found in the array and a special "Not found" indication is returned.
A binary search halves the number of items to check with each iteration, so locating an item (or determining its absence) takes logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.

Algorithm/Pseudo-code:

Recursive Algorithm

A straightforward implementation of binary search is recursive. The initial call uses the indices of the entire array to be searched. The procedure then calculates an index midway between the two indices, determines which of the two subarrays to search, and then does a recursive call to search that subarray.

Each of the calls is tail recursive, so a compiler need not make a new stack frame for each call. The variables imin and imax are the lowest and highest inclusive indices that are searched.
int binary_search(int A[], int key, int imin, int imax)
{
  // test if array is empty
  if (imax < imin):
    // set is empty, so return value showing not found
    return KEY_NOT_FOUND;
  else
    {
      // calculate midpoint to cut set in half
      int imid = midpoint(imin, imax);
 
      // three-way comparison
      if (A[imid] > key)
        // key is in lower subset
        return binary_search(A, key, imin, imid-1);
      else if (A[imid] < key)
        // key is in upper subset
        return binary_search(A, key, imid+1, imax);
      else
        // key has been found
        return imid;
    }
}

It is invoked with initial imin and imax values of 0 and N-1 for a zero based array.
The number type "int" shown in the code has an influence on how the midpoint calculation can be implemented correctly. With unlimited numbers, the midpoint can be calculated as "(imin + imax) / 2"

C Code For Binary Search:

/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>
void main()
{
 int arr[10], num, i, n, found=0, pos=-1, beg, end, mid;
 clrscr();

 printf("Enter the number of elements in the array: ");
 scanf("%d",&n);
 printf("\nEnter the elements: \n");
 for(i=0 ; i < n ; i++)
 {
  printf("arr[%d] = ",i);
  scanf("%d",&arr[i]);
 }

 printf("\nEnter the number that has to be searched: ");
 scanf("%d",&num);

 beg=0;
 end=n-1;
 while(beg<=end)
 {
  mid=(beg end)/2;
  if(arr[mid]==num)
  {
   printf("\n %d is present in the array at position = %d",num,mid);
   found=1;
   break;
  }

  if(arr[mid] > num)
  end = mid-1;

  else if(arr[mid] < num)
  beg = mid+1;
 }

 if(beg > end && found==0)
 printf("\n %d does not exist in the array",num);
 getch();
}

This Code Is Quite Easy. First we take the no. of elements from the user and then user enter them. Then user inputs the element that has to be searched. Then we begin the searching. If the element to be found is the middle element, the element is shown, other wise for the two conditions, arr[mid] > num or arr[mid]  < num, the search iterates, either till the element is found or until the array gets terminated.  


Output:

Binary Search C Code


Please Comment If You Liked This Post !! 

This article uses material from the Wikipedia article Binary search algorithm which is released under the Creative Commons Attribution-Share-Alike License 3.0


Sunday 10 March 2013

Delete An Element From Any Array C Code

As I have already described what are Arrays and their basic creation C code, in this post, we'll learn how to delete any element from any position from an 1-D array. Deleting an element does not affect the size of array. However, its necessary to check if the deletion operation is not outside the size of the array. For example, if the array contains 5 elements and you want to delete the 6th element, it won't be possible.

NOTE:- If you want to delete an element from any Array, then the total number of elements will be reduced by one, that is, you can say that the 'Deleted' Element will be replaced by other elements and the whole array has to be shifted.

Here is the C Code for Deleting An Element From Any Position Of An 1-D Array:

/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>

void main()
{
 int arr[100],n,pos,i,temp;
 clrscr();
 printf("Enter the number of elements in the Array: ");
 scanf("%d",&n);
 printf("\nEnter %d elements:\n\n",n);

 for(i=0 ; i<n ; i  )
 {
  printf(" Array[%d] = ",i);
  scanf("%d",&arr[i]);
 }
 
 printf("\nEnter the Position in the Array for Deletion: ");
 scanf("%d",&pos);
 pos = pos-1;
  
 printf("\nOld Array: ");  
 for(i = 0; i < n; i  )
 {
  printf("%4d", arr[i]);
 }
 
 temp = arr[pos];
 for(i=pos ; i<n ; i  )
 {
  arr[i] = arr[i 1];
 }
  
 if(pos>n)
 {
  printf("Insertion Outside The Array ");
 }
 
 n=n-1;
 
 printf("\n\nNew Array:");  
 for(i = 0; i < n; i  )
 {
  printf("%4d", arr[i]);
 }
 
 getch();
}


Output of Program:

Delete An Element From Any Array C Code

Please Comment If You Liked This Post !! 


Insert An Element In An Array And C Code

As I have already described what are Arrays and their basic creation C code, in this post, we'll learn how to insert an element in the Front of an 1-D array. Let me explain you by this example:
Let we have an array Arr[10] having four elements initially  Arr[0] = 1, Arr[1] = 2, Arr[2] = 3, Arr[3] = 4 and you want to insert a number 59 at first location, that is, at Arr[0] = 59. So we have to move elements one step below so after insertion Arr 1] = 1 which was Arr[0] initially, and Arr 2] = 2, Arr 3] = 3 and Arr[4] = 4. Array insertion does not mean increasing its size i.e array will not be containing 11 elements, but instead inserting an element.

NOTE:- If you want to insert an element into a full Array, that is, all elements are already present in the array, then element will be inserted but the last element will be terminated. 


Here is the C Code for Inserting An Element In The Beginning Of An 1-D Array:



/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>

void main()
{
 int arr[100],n,num,i;
 clrscr();
 printf("Enter the number of elements in the Array: ");
 scanf("%d",&n);
 printf("\nEnter %d elements:\n\n",n);

 for(i=0 ; i<n ; i++)
 {
  printf(" Array[%d] = ",i);
  scanf("%d",&arr[i]);
 }
 
 printf("\nEnter the Number to be Inserted At the Front: ");
 scanf("%d",&num);
 
 printf("\nOld Array: ");  
 for(i = 0; i < n; i++)
 {
  printf("%4d", arr[i]);
 }
 
 for(i=n ; i>=0 ; i--)
 {
  arr[i+1] = arr[i];
 }
 arr[0] = num;
 n=n+1;
 
 printf("\n\nNew Array:");  
 for(i = 0; i < n; i+)
 {
  printf("%4d", arr[i]);
 }
 
 getch();
}


Output of Program:

Insert Element In Array C Code


Please Comment If You Liked This Post !!



Introduction to Arrays and C Code

In computer science, an array data structure or simply an array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. An array is stored so that the position of each element can be computed from its index tuple by a mathematical formula.

For example, an array of 10 integer variables, with indices 0 through 9, may be stored as 10 words at memory addresses 2000, 2004, 2008, … 2036, so that the element with index i has the address 2000 + 4 × i.


One-dimensional arrays

A one-dimensional array (or single dimension array) is a type of linear array. Accessing its elements involves a single subscript which can either represent a row or column index.
As an example consider the C declaration int anArrayName[10];
Syntax : datatype anArrayname[sizeofArray];
For Example, int Arr[25]; will make an array of type 'int', name 'Arr' and size=25.

Multidimensional arrays

For a two-dimensional array, the element with indices i,j would have address B + c · i + d · j, where the coefficients c and d are the row and column address increments, respectively.
More generally, in a k-dimensional array, the address of an element with indices i1i2, …, ik is
B + c1 · i1 + c2 · i2 + … + ck · ik.
For example: int a[3][2];
This means that array a has 3 rows and 2 columns, and the array is of integer type. Here we can store 6 elements they are stored linearly but starting from first row linear then continuing with second row. The above array will be stored as a11, a12, a13, a21, a22, a23.

Compact layouts

Often the coefficients are chosen so that the elements occupy a contiguous area of memory. However, that is not necessary. Even if arrays are always created with contiguous elements, some array slicing operations may create non-contiguous sub-arrays from them.
There are two systematic compact layouts for a two-dimensional array. For example, consider the matrix
2-D Array
In the row-major order layout, the elements in each row are stored in consecutive positions and all of the elements of a row have a lower address than any of the elements of a consecutive row:
123456789