Program: Checking the Validity of a Credit Card Number


Exercise: Write a program that checks the validity of a credit card number using the Luhn algorithm.

First step: Break the problem down into manageable sub-tasks that can each be solved by a relatively small function


One way:

function ccnToList()-
    Takes a credit card number (a string)
    converts it to a list of all digits in the ccn
    returns this list

function checkLengthPrefix()-
    takes the ccn list produced by ccnToList()
    returns "invalid" if list's length and prefix doesn't match any of our card types
    otherwise returns "American Express", "Visa" or "Master Card"

function reverseList()-
    takes ccn list
    returns reverse list

function luhn()-
    takes ccn list
    calls reverseList() to reverse it
    doubles every other entry of reversed list, and returns resulting list

function luhnSum()-
    takes list produced by luhn()
    returns sum of digits of all numbers in list

function main()-
    reads CCN from user (prompt user to enter number w/o dashes)
    if it's all digits:
        convert to a list
        if the length/prefix match one of our card types:
            apply luhn algorithm
            print a message indicating card type