C学习if条件判断和for循环

通过学习if条件判断和for循环之后,做了一个实例。实现的实例都在代码中有详细的注释。

#include <stdio.h>

/******************************************************
 * 输入一个数字n,求
 * 1+1+2+1+2+3+1+2+3+4...+n
 * 该实例主要为了练习if语句和for语句
 ******************************************************/
int main(void)
{
    printf("%s\n","Please enter the number n:");

    int n;
    int count = 0;

    scanf("%d",&n);

    if(n <= 0){  //如果输入的数字n小于0,则提示错误
        printf("%s\n","The number you entered is too small!!");
        return -1;
    }

    int i;
    for(i = 1;i <= n;i++){
        int j;
        for(j = 1;j <= i;j++){
            count += j;
        }
    }

    printf("The count of the number n = %d.\n",count);

    return 0;
}

在C语言中,不像C++,要求比较高,是不能这样使用的。

for(int i = 0;i < 4;i++)

这样在编译的时候就会报这样的错误

/**
 * error:'for' initial declaration are 
 * only allowed in C99 mod
 */

所以在C语言中,最好是提前声明一下变量。

posted @ 2015-04-07 13:07  陈洪波  阅读(374)  评论(0编辑  收藏  举报