while


while 条件A:
	処理1
						

条件Aの間、処理1を行え

#!/usr/bin/env python
# coding=utf-8

cntr = 0

while cntr < 10:
    print cntr
    cntr += 1

↓ 実行結果 ↓

0
1
2
3
4
5
6
7
8
9
						

練習問題

下記のような表を、whileを用いて、作ってみよう

0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
						

答え↓

i = 0

while i < 10:
	x = 0
	while x < 10:
		print x,
		x += 1
	print
	i += 1
						

練習問題2

下記のような表を、今度もwhileを用いて、作ってみよう

0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 9
						

答え↓

i = 0

while i < 10:
    x = 0
    y = i + 1
    while x < y:
        print x,
        x += 1
    print
    i += 1
						

ちなみにJavaScriptだとこんな感じ↓

<!DOCTYPE html>
	<html lang="ja">
		<head>
			<meta charset="utf-8"/>
			<title>TEST01-01</title>
		</head>
		<body>
			<script type="text/javascript">
				var i = 0;
				while(i < 10){
					var x = 0;
					y = i + 1;
					while(x < y){
						document.write(x + ' ');
						x += 1;
					}
					document.write('<br/>');
					i += 1;
				}
			</script>
		</body>
	</html>
						

ついでにJAVAなら ↓

public class Sankaku {

	public static void main(String[] args) {

		int i = 0;

		while ( i < 10 ) {
			int x = 0;
			int y = i + 1;
			while (x < y ) {
				System.out.print(x);
				x += 1;
			}
			System.out.println();
			i += 1;
		}

	}

}