LoginSignup
0
0

二重for文① 山型グラフ(累乗)

Last updated at Posted at 2022-06-15

実行結果

スクリーンショット 2022-06-15 21.19.30.png

コード①:二重for文を2つ使う場合

public class Main {
	public static void main(String[] args) {
		for(int i = 0;i < 10;i++) {
			System.out.print(i + ":");
			for(int j = 0;j < i*i;j++) {
				System.out.print("◯");
			}
			System .out .println("(" + i*i + ")");
		}
		for(int i = 8;i >= 0;i--) {
		    System.out.print(i + ":");
		    for(int j = 0;j < i * i;j++) {
		    	System.out.print("◯");
		    }
			System .out .println("(" + i * i + ")");
		}
	}
}

コード②:Math.abs()メソッドを使う場合

※『Math.abs()』絶対値を取得するメソッド

public class Main { 
	public static void main(String[] args) {
		for(int i = -9;i <= 9;i++) {	
			int k =9-Math.abs(i);
			System.out.print(k + ":");
			for(int j = 0;j < k*k ;j++) {
				System.out.print("◯");
			}
			System .out .println("(" + k * k + ")");
		}
	}
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0