Saturday, April 4, 2015

Java Programs Algorithms for Selenium Interview -Class3

Java program to print alphabets

This program print alphabets on screen i.e a, b, c, ..., z. Here we print alphabets in lower case.

Java source code

class Alphabets
{
   public static void main(String args[])
   {
      char ch;
 
      for( ch = 'a' ; ch <= 'z' ; ch++ )
         System.out.println(ch);
   }
}
You can easily modify the above java program to print alphabets in upper case.
Download Alphabets program class file.
Output of program:
alphabets
Printing alphabets using while loop (only body of main method is shown):
char c = 'a';
 
while (c <= 'z') {
  System.out.println(c);
  c++;
}
Using do while loop:
char c = 'A';
 
do {
  System.out.println(c);
  c++;
} while (c <= 'Z');
 

Java program to print multiplication table

This java program prints multiplication table of a number entered by the user using a for loop. You can modify it for while or do while loop for practice.

Java programming source code

import java.util.Scanner;
 
class MultiplicationTable
{
   public static void main(String args[])
   {
      int n, c;
      System.out.println("Enter an integer to print it's multiplication table");
      Scanner in = new Scanner(System.in);
      n = in.nextInt();
      System.out.println("Multiplication table of "+n+" is :-");
 
      for ( c = 1 ; c <= 10 ; c++ )
         System.out.println(n+"*"+c+" = "+(n*c));
   }
}
Download Multiplication table program class file.
Output of program:

multiplication table

Using nested loops we can print tables of number between a given range say a to b, For example if the input numbers are 3 and 6 then tables of 3, 4, 5 and 6 will be printed. Code:
import java.util.Scanner;
 
class Tables
{
  public static void main(String args[])
  {
    int a, b, c, d;
 
    System.out.println("Enter range of numbers to print their multiplication table");
    Scanner in = new Scanner(System.in);
 
    a = in.nextInt();
    b = in.nextInt();
 
    for (c = a; c <= b; c++) {
      System.out.println("Multiplication table of "+c);
 
      for (d = 1; d <= 10; d++) {
         System.out.println(c+"*"+d+" = "+(c*d));
      }
    }
  }
}
 

No comments:

Post a Comment

TestNG - Can i use the 2 different data providers to same @test methods in TestNG?

public Object [][] dp1 () { return new Object [][] { new Object [] { "a" , "b" }, new Obje...