2. Write a program in Java to display a diamond pattern of asterisks.
Expected Output :
*
***
*****
*******
*********
***********
*************
***********
*********
*******
*****
***
*
3. Write a Java program that reads a positive integer and counts the number of digits the number has.
e.g. Input is 14367, Output is 5.
import java.util.Scanner;
public class App {
/**
* The start point of the program
*
* @param args
*/
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
int n, c, k, space = 1;
System.out.print("Enter number of rows: ");
n = keyBoard.nextInt();
space = n - 1;
for (k = 1; k <= n; k++) {
for (c = 1; c <= space; c++) {
System.out.printf(" ");
}
space--;
for (c = 1; c <= 2 * k - 1; c++) {
System.out.printf("*");
}
System.out.printf("\n");
}
space = 1;
for (k = 1; k <= n - 1; k++) {
for (c = 1; c <= space; c++) {
System.out.printf(" ");
}
space++;
for (c = 1; c <= 2 * (n - k) - 1; c++) {
System.out.printf("*");
}
System.out.printf("\n");
}
keyBoard.close();
}
}
import java.util.Scanner;
public class App {
static int countDigits(int number) {
int counter = 0;
while (number != 0) {
number = number / 10;
counter++;
}
return counter;
}
/**
* The start point of the program
*
* @param args
*/
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
System.out.print("Enter any positve integer number: ");
int number = keyBoard.nextInt();
System.out.print("The number of digits in a decimal number is: " + countDigits(number));
keyBoard.close();
}
}
Comments
Leave a comment