码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-04-07 13:50:55      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:for语句   实例   c   if语句   

通过学习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语言中,最好是提前声明一下变量。

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

标签:for语句   实例   c   if语句   

原文地址:http://blog.csdn.net/hongbochen1223/article/details/44918939

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!