자료구조&알고리즘/코딩테스트
기본 알고리즘
밍풀
2022. 10. 7. 11:09
이중루프이용해 구구단 곱셈표 출력하기(feat. N자리로 출력하는 법)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public class Main {
public static void main(String[] args) {
for(int i=1;i<10;i++) {
for(int j=1;j<10;j++) {
System.out.printf("%3d",i*j);//3자리로 출력해줘
}System.out.println();
}
}
}
|
cs |
별 N개 출력하면서 W개 마다 줄바꿈
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//*을 n개 출력하되, w마다 줄바꿈
int n,w;
Scanner sc= new Scanner(System.in);
do {
System.out.print("n : ");
n=sc.nextInt();
}while(n<=0);//n>0이어야 하므로 이의 여집합인
do {
System.out.print("w : ");
w=sc.nextInt();
}while(w<=0 || w>n);//0<w<n 이어야 하므로 이의 여집합인
for(int i=0; i<n/w;i++) { //*을 w번 찍기를 일단 n/w의 몫만큼 반복
System.out.println("*".repeat(w));//"*"를 w번 반복해줘
}//예를들어 n=14, w=5일때 5개 찍는거 몫인 2번 반복함
//n/w몫에 해당하는 값은 다 찍었고 나머지별 찍음
int rest= n%w;
if(rest !=0) {//나머지가 있을때만
System.out.println("*".repeat(rest));
}//n/w의 나머지 4개는 여기서 찍음
}
}
|
cs |
높이가 n인 직각삼각형 출력
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import java.util.Scanner;
public class Main {
//높이가 n인 직각삼각형 출력
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
do {
n=sc.nextInt();
}while(n<=0);
for(int i=1;i<=n;i++) {
for(int j=1;j<=i;j++) {
System.out.print("*");} //System.out.print("*".repeat(i));
System.out.println();
}
}
}
|
cs |
n단 피라미드 출력하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//n단 피라미드 출력
int n;
do {
n=sc.nextInt();
}while(n<=0);
for(int i=1;i<=n;i++) {
System.out.print(" ".repeat(n-i));
System.out.print("*".repeat(2*i-1));
System.out.println();
}
}
}
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//n단 피라미드 출력
int n;
do {
n=sc.nextInt();
}while(n<=0);
for(int i=1;i<=n;i++) {
for(int j=0;j<n-i;j++) {
System.out.print(" ");
}
for(int k=0;k<2*i-1;k++) {
System.out.print("*");
}System.out.println();
}
}
}
|
cs |