C语言使用while语句实现循环结构

计算sum=\sum_{n=1}^{100}n的值。

#include
int main()
{
    int i,sum;
    i=1;sum=0;
    while(i<=100)
    {
        sum=sum+i;
        i+=1;
}
    printf("sum=%d\n",sum);
    return 0;
}

运行结果:

C语言使用while语句实现循环结构_第1张图片

输入一个正整数 n,计算n!

#include
int main()
{
    int i;long n,fact;
    i=2;fact=1;
    printf("请输入n的值:");
    scanf("%ld",&n);
    while(i<=n)
    {
        fact=fact*i;
        i=i+1;
}
    printf("%ld!=%ld\n",n,fact);
    return 0;
}

运行结果:

C语言使用while语句实现循环结构_第2张图片

由键盘输入一串字符,分别统计输入字符中数字字符,字母字符及其他字符的个数。

#include
int main()
{
    int digit,letter,other;
    char ch;
    digit=letter=other=0;
    printf("请输入一串字符:");
    while((ch=getchar())!='\n')
        if((ch>='0')&&(ch<='9'))
            digit++;
        else if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
            letter++;
        else
            other++;
    printf("数字%d个,字母%d个,其他%d个\n",digit,letter,other);
    return 0;
}

 运行结果:

C语言使用while语句实现循环结构_第3张图片

 

你可能感兴趣的:(c语言,学习)