読み込んだ整数値を0までカウントダウン (while文)

明解C言語 入門編 > 4. プログラムの流れの繰り返し >

読み込んだ整数値を0までカウントダウン (while文)

C


#include <stdio.h>
int main(int argc, char* argv[])
{
int no;

printf("正の整数を入力してください:");
scanf("%d", &no);

while (no >= 0)
{
printf("%d\n", no--);
}

return 0;
}

実行結果


R:\>lesson027\project1.exe
正の整数を入力してください:11
11
10
9
8
7
6
5
4
3
2
1
0

R:\>lesson027\project1.exe
正の整数を入力してください:0
0

R:\>lesson027\project1.exe
正の整数を入力してください:-5

Delphi


program Project1;

{$APPTYPE CONSOLE}

uses
SysUtils;
var
no: Integer;
begin
write('正の整数を入力してください:');
read(no);

while (no >= 0) do
begin
writeln(format('%d', [no]));
dec(no);
end;
end.

実行結果


S:\>lesson027\project1.exe
正の整数を入力してください:11
11
10
9
8
7
6
5
4
3
2
1
0

S:\>lesson027\project1.exe
正の整数を入力してください:0
0

S:\>lesson027\project1.exe
正の整数を入力してください:-5

Perl
print "正の整数を入力してください:";
chomp($no = <>);
while ($no >= 0)
{
    printf("%d\n", $no--);
}

print "正の整数を入力してください:";
chomp($no = <>);
printf("%d\n", $no--) while ($no >= 0);

print "正の整数を入力してください:";
chomp($no = <>);
until ($no < 0)
{
    printf("%d\n", $no--);
}

print "正の整数を入力してください:";
chomp($no = <>);
printf("%d\n", $no--) until ($no < 0);

実行結果

L:\>perl lesson_04_027.pl
正の整数を入力してください:7
7
6
5
4
3
2
1
0
正の整数を入力してください:6
6
5
4
3
2
1
0
正の整数を入力してください:5
5
4
3
2
1
0
正の整数を入力してください:4
4
3
2
1
0

Ruby
print "正の整数を入力してください:"
no = STDIN.gets.chomp.to_i
while (no >= 0)
    printf("%d\n", no)
    no -= 1
end

print "正の整数を入力してください:"
no = STDIN.gets.chomp.to_i
until (no < 0)
    printf("%d\n", no)
    no -= 1
end

実行結果

L:\>ruby l:\lesson_04_027.rb
正の整数を入力してください:11
11
10
9
8
7
6
5
4
3
2
1
0
正の整数を入力してください:0
0

L:\>ruby l:\lesson_04_027.rb
正の整数を入力してください:-5
正の整数を入力してください:0
0