0

Writing a program to print the ASCII values of all 256 characters.

    int digit[] = new int[256];
    char array[] = new char[256];

    for(int i=0;i<array.length;i++)
    {
        array[i] = (char) digit[i];
    }
    for(int i=0;i<array.length;i++)
    {
        System.out.println(array[i]);
    }

I get a blank output when I run this code.

3
  • 3
    Replace array[i] = (char) digit[i] with array[i] = (char) i Commented Jun 24, 2020 at 23:06
  • Considering you're not initialising digit[] with any values before you read them into array[], why do you expect the output not to be blank? Commented Jun 24, 2020 at 23:06
  • 1
    Mr. Nitpicker writes: ASCII is a 7 bit code; codepoints > 127 are not ASCII. Also, this is Java, so a char is a 16-bit Unicode (specifically UTF-16) value. Codepoints 0-127 are identical to ASCII; beyond that, see Unicode. Commented Jun 24, 2020 at 23:23

2 Answers 2

3

You do not need int digit[]. You only need to loop from 0 to 255 and cast each int to a char.

for (int i = 0; i < 256; i++) {
    array[i] = (char) i;
}

Alternatively, you can write a for loop using char.

for (char i = 0; i < 256; i++) {
    System.out.println(i);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Since you didn't initialize them, all the elements in digit are 0, and ASCII 0 is the null character.

TO be honest, you don't need an array there - just iterate over them numbers 0 to 255 and print their cast to chars:

for (int i = 0; i < 256; ++i) {
    System.out.println(i + " -- " + ((char)i)));
}

2 Comments

Thanks for the answer. Could you please tell how should I have initialized the array to get the desired output?
@VaishakhYKumar you could loop over digits and initialized it - for (int i = 0; i < 256; ++i) {digits[i] = i;}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.