如何使用 For 循环和 while 循环编写 C 语言程序,通过实际示例查找字符串中所有字符的 ASCII 值。
此程序使用 For 循环遍历字符串中的每个字符。在其中,我们使用了 printf 语句来打印字符及其 ASCII 值。
#include <stdio.h>
int main()
{
char str[100];
printf("\n Please Enter any String : ");
scanf("%s", str);
for( int i = 0; str[i] != ‘\0’; i++)
{
printf(" The ASCII Value of Character %c = %d \n", str[i], str[i]);
}
return 0;
}

str[] = python
For 循环第一次迭代: for( int i = 0; str[i] != ‘\0’; i++)
条件为 True,因为 str[0] = p。因此,编译器将执行 printf 语句。
对于其余的 For 循环 迭代,请执行相同操作。请参考 ASCII 表 以了解 C 语言编程 中的 ASCII 值。
C 语言使用 While 循环查找字符串中所有字符的 ASCII 值程序
在此 ASCII 值程序 中,我们将 For 循环替换为 While 循环。
#include <stdio.h>
int main()
{
char str[100];
int i = 0;
printf("\n Please Enter any String : ");
scanf("%s", str);
while( str[i] != '\0')
{
printf(" The ASCII Value of Character %c = %d \n", str[i], str[i]);
i++;
}
return 0;
}
Please Enter any String : TutorialGateway
The ASCII Value of Character T = 84
The ASCII Value of Character u = 117
The ASCII Value of Character t = 116
The ASCII Value of Character o = 111
The ASCII Value of Character r = 114
The ASCII Value of Character i = 105
The ASCII Value of Character a = 97
The ASCII Value of Character l = 108
The ASCII Value of Character G = 71
The ASCII Value of Character a = 97
The ASCII Value of Character t = 116
The ASCII Value of Character e = 101
The ASCII Value of Character w = 119
The ASCII Value of Character a = 97
The ASCII Value of Character y = 121