Posts

Showing posts from February, 2016

Checking The Validity of a Credit Card in C [Luhn's Algorithm]

Image
Checking the validity of a credit card might seem to be a pretty big task right ? But it is actually simple. The numbers allotted to the cards by the credit card companies always pass the Luhn's test. The following is the Luhn's algorithm.

Luhn's Algorithm

 Reverse the number.Take the odd indexed elements and add them.Take the even indexed elements and multiply each element by 2.Add the sum of digits of the even indexed numbers. (ex : for 15 - 1 + 5 = 6)Add the Odd Sum and the Even Sum.If the result is divisible by 10, it is a valid number else it is invalid.
Example


It looks pretty simple right ? Yeah it is :) And so now let's implement this in our code. This is just simple mathematics but the only problem is the length of the number. You cannot input 16 digit number in a integer or long int or even a unsigned long int. So what we do is we just get the numbers as a character array. And we pass it into a switch case to convert that to a number array. We use that number a…

Merge Sort Using Recursion in C

Image
Merge sort is one of the best algorithms used for sorting after quick sort. It is a divide and conquer algorithm in which the given set of numbers is divided into two halves until it reaches the base level and then it is sorted up. Take a look at the picture below for better understanding.


So in the below program the merge_divide function will be used to divide the array into sub parts as you see in the animation above. The merge_sort function is used to sort the elements in an ascending order. 
WORK FLOW  :
merge_divide takes 3 arguments. The array, starting position of the array and the ending position. We check if the starting position is lesser than ending position and if so we find the middle element and store in the variable r.We recursively call the function passing the value of p and r (denoting the first half) and call it again passing r+1 and q (denoting the second half). It will again call the function so on until the values of p and q are equal or p < q. At the final rec…