Algorithm training 4-1 Prints the following graphics time limit: 1.0s memory Limit: 256.0MB problem description Use the loop structure to print the following graphic, and print the number of rows n is entered by the user. Use the format "%s" When printing spaces, and pass the string "" "with only one or more spaces to the printf function, as below.
Sample input An input example that satisfies the requirements of the topic.
Cases:
The output of the 5 sample output corresponds to the example input above.
Cases:
Data size and convention the range of each number in the input data.
Example: 0<n<20.
Topic Analysis:
This is a total of two ideas, because the range of n is very small (0 < n <20), so the two ideas on the running time, memory and complexity are not the pros and cons of.
(1) Use circular statements to control the lines, the spaces at the beginning of each line, and the * of each line, respectively.
for example, n = 3
Table 1.1
using I (I starting from 1) to control the line, so you can introduce the space number space and the number of rows N and control the relationship between the row variable i: space = n-i, * Number asterisk and control row variable i relationship: asterisk = 2 * I-1.
(2) The graph is stored in an array of type String, and the array is initialized to null. 1.1, find the center column number centers = n-1, each i row is in the center column of the left and right side plus I *, and finally the array output.
Example code 1:
1 ImportJava.util.Scanner;2 3 Public classMain {4 Public Static voidMain (string[] args) {5Scanner sc =NewScanner (system.in);6 intn =sc.nextint ();7 8 for(inti = 1; I <= N; i++) {//Control Line9 for(intSpace = N-i; Space >= 1; space--) {//control the spaces in front of each lineTenSystem.out.print (""); One } A for(intasterisk = 1; Asterisk <= 2 * i-1; asterisk++) {//control each line of * -System.out.print ("*"); - } the System.out.println (); - } - } -}
Example code 2:
1 ImportJava.util.Scanner;2 3 Public classMain {4 5 Public Static voidMain (string[] args) {6Scanner sc =NewScanner (system.in);7 intn =sc.nextint ();8 9string[][] Triangle =NewSTRING[N][2*N-1];//creates an array, initialized to nullTen for(inti = 0; I < n; i++) { One for(intj = 0; J < 2*n-1; J + +) { ATRIANGLE[I][J] = ""; - } - } the - intCenter = n-1;//Center Column number - for(inti = 0; I < n; i++) {//Control Line - for(intj = 0; J <= I; J + +) {//each row adds I on the left and right sides of the center * +TRIANGLE[I][CENTER-J] = "*"; -TRIANGLE[I][CENTER+J] = "*"; + } A } at //Output Graphics - for(inti = 0; I < n; i++) { - for(intj = 0; J < 2*n-1; J + +) { - System.out.print (Triangle[i][j]); - } -System.out.print ("\ n"); in } - } to}
Blue Bridge Cup algorithm training ALGO-145 4-1 print the following graphic