C言語の例 - ループでアルファベット26文字を出力
ループでアルファベット26文字を出力します。
以下の例では、変数 letter を使用して現在出力する文字を格納し、for ループを使って26回繰り返して文字を出力し、各文字の後にスペースを1つ追加します。
ループ内では printf 関数を使用して letter 変数の値を出力します。%c は printf の変換指定子であり、1文字を出力するために使用されます。
例 1
#include <stdio.h>
int main() {
char letter = 'A'; // ASCIIコードでは 'A' の値は65
// ループを使用してアルファベット26文字を出力
for (int i = 0; i < 26; i++) {
printf("%c ", letter);
letter++; // letter変数の値をインクリメントし、次の文字のASCIIコードを取得
}
printf("\n");
return 0;
}
別の例:
例 2
#include <stdio.h>
int main()
{
char c;
for(c = 'A'; c <= 'Z'; ++c)
printf("%c ", c);
return 0;
}
実行結果:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
小文字を出力したい場合は、変数 letter の初期値を 'a' に設定するだけです(ASCIIコードでは 'a' の値は97)。その後、ループ内で letter++ を使用します:
例
#include <stdio.h>
int main() {
char letter = 'a'; // ASCIIコードでは 'a' の値は97
// ループを使用してアルファベットの小文字26文字を出力
for (int i = 0; i < 26; i++) {
printf("%c ", letter);
letter++; // letter変数の値をインクリメントし、次の文字のASCIIコードを取得
}
printf("\n");
return 0;
}
実行結果:
a b c d e f g h i j k l m n o p q r s t u v w x y z
以下の例では、大文字と小文字のどちらを入力するかを選択できます:
例 - 大文字または小文字を出力
#include <stdio.h>
int main()
{
char c;
printf("u を入力すると大文字を表示し、l を入力すると小文字を表示します:");
scanf("%c", &c);
if(c== 'U' || c== 'u')
{
for(c = 'A'; c <= 'Z'; ++c)
printf("%c ", c);
}
else if (c == 'L' || c == 'l')
{
for(c = 'a'; c <= 'z'; ++c)
printf("%c ", c);
}
else
printf("Error! 不正な文字が入力されました。");
return 0;
}
実行結果:
输入 u 显示大写字母,输入 l 显示小写字母: l a b c d e f g h i j k l m n o p q r s t u v w x y zその他の拡張
C言語の例