I have been working on this code for a while and I can't seem to get to work right. I have been trying to make a credit card validator program in c for a class assignment. Any help would be welcome.

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

void checkCard( long x[16], long *s );

int main ()
{
    //define variables for the data
    long *s;
    long x[16], i;
    
    malloc(sizeof(x[16]));
    //ask user to enter a credit card number as a long int. Number must have between 13-16 digits. It must start with 4 for Visa cards,
    //5 for Master cards, 37 for American Express cards, or 6 for Discover cards
    //store the data that the user entered
    //call to array containing the credit card check function
    //print for the user whether the credit card number is valid or invalid
    printf( "Enter a credit card number as a long integer: \n" );
    scanf( "%ld", x );
    checkCard( x, s );

    return 0;
}

void checkCard( long x[16], long *s )
{
    long S1, S2, Sum;
    //Step 1: Double every second digit from right to left. If doubling of a digit results in a two-digit number, add up the two digits to get a single digit number.
    x[14] = x[14] * 2;
    
    if ( x[14] > 9 ) {
        x[14] = x[14] - 9;
    }
    
    x[12] = x[12] * 2;
    
    if ( x[12] > 9 ) {
        x[12] = x[12] - 9;
    }
    
    x[10] = x[10] * 2;
    
    if ( x[10] > 9 ) {
        x[10] = x[10] - 9;
    }
    
    x[8] = x[8] * 2;
    
    if ( x[8] > 9 ) {
        x[8] = x[8] - 9;
    }
    
    x[6] = x[6] * 2;
    
    if ( x[6] > 9 ) {
        x[6] = x[6] - 9;
    }
    
    x[4] = x[4] * 2;
    
    if ( x[4] > 9 ) {
        x[4] = x[4] - 9;
    }
    
    x[2] = x[2] * 2;
    
    if ( x[2] > 9 ) {
        x[2] = x[2] - 9;
    }
    
    x[0] = x[0] * 2;
    
    if ( x[0] > 9 ) {
        x[0] = x[0] - 9;
    }
    //Step 2: Now add all single-digit numbers from Step 1.
    S1 = x[14] + x[12] + x[10] + x[8] + x[6] + x[4] + x[2] + x[0];
    //Step 3: Add all digits in the odd places from right to left in the card number.
    S2 = x[15] + x[13] + x[11] + x[9] + x[7] + x[5] + x[3] + x[1];
    //Step 4: Sum the results from Step 2 and Step 3.
    Sum = S1 + S2 - 48;
    //Step 5: If the result from Step 4 is divisible by 10, the card number is valid; otherwise, it is invalid.
    if ( Sum % 10 == 0 ) {
        printf( "%ld is valid.\n", *x );
    } else {
         printf( "%ld is invalid.\n", *x );
    }
    exit(main());
}

"Get it to work right", is THE most vague description of the problem!

C'mon! Put some specifics into it. FCOL!

Sorry. Well from what I see running the program, the whole card number is stored in x[0], but I want each character stored in their own array address so that I can run the characters through my function.

This article has been dead for over six months. Start a new discussion instead.