How to print alphabet using char values in JAVA

First you have to code a java program by using variables and a flow control.

You may need:
  • a char variable to store current char value
  • flow control structure (for,while,or do while loop)
  • command to print current char value
First we create a class program and a main method using java

class ascii{
           public static void main(String args[]){

           }
}

Now create a char variable to store a char value and initialize it to zero.

class ascii{
          public static void main(String args[]){
                      char c=0; //char variable named c
          }
}

Now we want a flow control structure to automate printing process. Here I used for loop but you can use while or do while loop also.

class ascii{
           public static void main(String args[]){

                     char c=0; //char variable named c

                     for(c=65;c<91;c++){

                     }
          }
}

Here I have initialize c as 65 (c=65) because “A” in ASCII is 65 and terminate value as 91 because here I stop printing process after printing “Z”.

Now we want a command to print this in command prompt screen.

class ascii{
           public static void main(String args[]){

                    char c=0; //char variable named c

                    for(c=65;c<91;c++){

                               System.out.print(c+“ ”);

                    }
          }
}

So here print command print ascii value and space. This will run until variable reaches it's terminating value.

Here is the complete code.

Now save your java program with .java extension
After compiling(javac a1.java) run your java program with java “class name”
Then the final output is shown below.

------------------------
Note
------------------------

If you want simple letters you can start c=97 and terminating value as 123
eg: for(c=97;c<123;c++){}
Thanks.

No comments: