C语言循环语句分为for循环和while循环语句,本文介绍这两种循环语句。
循环语句的基本工作方式:
do, while, for的区别:
while循环我们从do...while
语句和while语句来讲解。
do...while
语句do...while
语句的循环方式如下
示例
do {
//code
} while (condition);
while语句的循环方式为
示例:
while(condition) {
//code
}
for 语句的循环方式
示例
for(i=0;condition;i++) {
//code
}
#include <stdio.h>
int f1(int n)
{
int ret = 0;
if( n > 0 )
{
do
{
ret += n;
n--;
}
while( n > 0 );
}
return ret;
}
int f2(int n)
{
int ret = 0;
while( n > 0 )
{
ret += n;
n--;
}
return ret;
}
int f3(int n)
{
int ret = 0;
int i = 0;
for(i=1; i<=n; i++)
{
ret += i;
}
return ret;
}
int main()
{
printf("%d\n", f1(100));
printf("%d\n", f2(100));
printf("%d\n", f3(100));
return 0;
}
运行结果:
break和continue可以用于中断或终止循环,两者的区别是
#include <stdio.h>
void f1(int n)
{
int i = 0;
for(i=1; i<=n; i++)
{
if( (i % 2) == 0 )
{
break;
}
printf("%d ", i);
}
printf("\n");
}
void f2(int n)
{
int i = 0;
for(i=1; i<=n; i++)
{
if( (i % 2) == 0 )
{
continue;
}
printf("%d ", i);
}
printf("\n");
}
int main()
{
f1(10);
f2(10);
return 0;
}
运行结果:
可以做到goto语句的效果。
#include <stdio.h>
#include <malloc.h>
int func(int n)
{
int i = 0;
int ret = 0;
int* p = (int*)malloc(sizeof(int) * n);
do
{
if( NULL == p ) break;
if( n < 5 ) break;
if( n > 100) break;
for(i=0; i<n; i++)
{
p[i] = i;
printf("%d\n", p[i]);
}
ret = 1;
}while( 0 );
printf("free(p)\n");
free(p);
return ret;
}
int main()
{
if( func(10) )
{
printf("OK\n");
}
else
{
printf("ERROR\n");
}
return 0;
}
运行结果:
本文链接:http://so.lmcjl.com/news/23725/