How to create a parameterized variable?

Asked

Viewed 42 times

0

In one exercise I must create a valid number for credit cards "Luhn’s Algorithm".

need to create a parameterized variable to avoid using if, but the code gets too big and I want to reduce it

I can’t use string.

Follow what would be my idea for the parameterized variable, if it exists.

# include <stdio.h>

int main (void)
{
    int sobra_number_cartao = 0;
    int contador = 0;
    int d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d14, d15, d16;
    long number_cartao = get_long("Digite o número do seu cartão de crédito: \n");

    printf ("%li\n", number_cartao);

// Realiza a contagem da quantidade de números tem o cartão
while (number_cartao != 0)
{
    number_cartao = number_cartao / 10;
    contador ++;

/* Aqui eu quero criar uma variável parametrizada, exemplo: Vamos dizer que o valor da variável
"contador", seja 1, então quero escrever na d(1) = number_cartao.*/
    d(contador) = number_cartao;
}

printf ("Seu cartão tem %i números.\n", contador);

}

1 answer

1


What you want to use is array. But you should be careful because it’s easy to mess with it in C. You have to make sure you store the right amount of data. If you try to carve something out of it, it will be accepted and corrupt the memory.

I took the opportunity to resolve some other issues, but did not make any validations, this code is ready to explode in any situation out of the normal. Nor have I said that you do not store credit card number as a number, this is a descriptive field and should be a text, but I decided to ignore this conceptual error and focus on the issue, which would be easier, just know that this is wrong. Something like that (it would be better to use one for in place of while):

#include <stdio.h>

int main(void) {
    int contador = 0;
    int d[16];
    printf("Digite o número do seu cartão de crédito:\n");
    long number_cartao;
    scanf("%ld", &number_cartao);
    printf("%ld\n", number_cartao);
    while (number_cartao != 0) {
        number_cartao /= 10;
        d[++contador] = number_cartao;
    }
    printf("Seu cartão tem %d números.\n", contador);
    printf("Item 0: %d", d[0]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thanks Maniero. That’s just what I needed. Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.