Problem: Create a triangle like below in Java:
*
***
*****
Solution: Java Program:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class triangle {
public static void main(String[] args) {
try {
BufferedReader object = new BufferedReader
(new InputStreamReader(System.in));
System.out.println("enter the number");
int a= Integer.parseInt(object.readLine());
for (int i = 1; i <= a; i++) {
for (int j = i; j < a; j++) {
System.out.print(" ");
}
for (int k = ((i*2)-1); k > 0 ; k--) {
System.out.print("*");
}
System.out.println("");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The run-time execution on my Linux machine (core2duo 1.6GHz, 3GB ram) is around 0.60 secs for a triangle of length 100. Can you improvise this algo further?
*
***
*****
Solution: Java Program:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class triangle {
public static void main(String[] args) {
try {
BufferedReader object = new BufferedReader
(new InputStreamReader(System.in));
System.out.println("enter the number");
int a= Integer.parseInt(object.readLine());
for (int i = 1; i <= a; i++) {
for (int j = i; j < a; j++) {
System.out.print(" ");
}
for (int k = ((i*2)-1); k > 0 ; k--) {
System.out.print("*");
}
System.out.println("");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The run-time execution on my Linux machine (core2duo 1.6GHz, 3GB ram) is around 0.60 secs for a triangle of length 100. Can you improvise this algo further?
No comments:
Post a Comment