Home > Back-end >  How can I have a output if I put a variable inside the array square brackets?
How can I have a output if I put a variable inside the array square brackets?

Time:12-29

How can I make tipoDeProduto[categoriaPretendida] work? If I put tipoDeProduto[0]it will output C but if categoriaPretendida is 0 it wont output anything, I dont understand how can I make tipoDeProduto[categoriaPretendida] work.

I would be highly appreciated if someone can help please.

#include <stdio.h>

int main()
{
    char tipoDeProduto[] = {'C', 'A', 'S', 'R', 'L'};
    char categoriaPretendida;
    
    printf("\n 0 - Cerveja\n 1 - Agua\n 2 - Sumo Natural\n 3 - Refrigerante\n 4 - Leite\n"
    );

    printf("\n Choose the pretended category: ");
    scanf("%c", &categoriaPretendida);
    
    printf(" You chose the category %c", tipoDeProduto[categoriaPretendida]);
}

CodePudding user response:

The issue here is that categoriaPretendida is a character variable, but the tipoDeProduto array uses integer indices. When you use tipoDeProduto[categoriaPretendida], it is trying to access an element of the array using the ASCII value of categoriaPretendida as the index, rather than the intended integer value.

To fix this issue, you can either change the type of categoriaPretendida to an integer, or you can use the ASCII value of categoriaPretendida to get the corresponding element of the array.

For example, to change the type of categoriaPretendida to an integer, you can do the following:

int main()
{
    char tipoDeProduto[] = {'C', 'A', 'S', 'R', 'L'};
    int categoriaPretendida;  // change char to int

    printf("\n 0 - Cerveja\n 1 - Agua\n 2 - Sumo Natural\n 3 - Refrigerante\n 4 - Leite\n");

    printf("\n Choose the pretended category: ");
    scanf("%d", &categoriaPretendida);  // change %c to %d

    printf(" You chose the category %c", tipoDeProduto[categoriaPretendida]);
}

CodePudding user response:

The variable categoriaPretendida holds the value that represents the character/digit '0' (called ASCII value).

'0' is actually 48 in ASCII, or written in hex 0x30. You can see a full table here

So the trick to get the numeric value of 0, is actually to subtract the value of '0' from the input. Since '1' is next to '0' in ASCII, subtracting them will give exactly 1. Same with the rest of the digits.

Hence, to your solution, update the following line:

printf(" You chose the category %c", tipoDeProduto[categoriaPretendida - '0']);

Or more verbosely:

scanf("%c", &categoriaPretendida);

int categoriaValue = categoriaPretendida - '0';
    
printf(" You chose the category %c", tipoDeProduto[categoriaValue]);
  • Related