C Language Examples - Printing 26 Letters in a Loop
Print 26 letters in a loop.
In the following example we use the variable letter to store the current letter to output, then use a for loop to repeat the output 26 times, adding a space after each letter.
Inside the loop we use the printf function to output the value of the letter variable; %c is the format specifier of printf, used to output a single character.
Example 1
#include
<
stdio.h
int
main
(
)
{
char
letter= '
A
';
// In ASCII, the value of 'A' is 65
// Use a loop to output 26 letters
for
(
int
i
=
0
;
i
<
26
;
i
++
)
{
printf
(
"
%c
"
,
letter
)
;
letter
++;
// Increment the value of the letter variable to get the ASCII code of the next letter
}
printf
(
"
\
n
"
)
;
return
0
;
}
Another example:
Example 2
#include
<
stdio.h
int
main
(
)
{
char
c;
for
(
c
= '
A
';
c
<= '
Z
'; ++
c
)
printf
(
"
%c
"
,
c
)
;
return
0
;
}
Running result:
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
If you want to output lowercase letters, simply set the initial value of the variable letter to 'a' (in ASCII, the value of 'a' is 97), and then use letter++ inside the loop:
Example
#include
<
stdio.h
int
main
(
)
{
char
letter= '
a
';
// In ASCII, the value of 'a' is 97
// Use a loop to output 26 lowercase letters
for
(
int
i
=
0
;
i
<
26
;
i
++
)
{
printf
(
"
%c
"
,
letter
)
;
letter
++;
// Increment the value of the letter variable to get the ASCII code of the next letter
}
printf
(
"
\
n
"
)
;
return
0
;
}
Running result:
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
The following example lets you choose whether to output uppercase or lowercase:
Example - Outputting uppercase or lowercase letters
#include
<
stdio.h
int
main
(
)
{
char
c;
printf
(
"
Enter u to display uppercase letters, enter l to display lowercase letters:
"
)
;
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! Invalid character entered.
"
)
;
return
0
;
}
Running result:
输入 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 Language Examples