数据结构---对于打印1-N整数的三种方法

方法一(for循环语句):
代码:

#include 
#include 
#include 
void PrintN(int N)     								     //定义函数PrintN
{
     
int  i;
for (i=0;i<=N;i++)
{
     
    printf("%d\n",i);
}
return;
}
int main()
{
     
    int N;
    clock_t start, finish;
    double duration;
    printf("please input N;\n");
    scanf("%d",&N);
    start = clock();
    PrintN(N);            								//调用函数PrintN
    finish = clock();
    duration = (double)(finish-start) / CLOCKS_PER_SEC;
    printf("%f seconds\n", duration);            		//打印循环执行的时间
    return 0;
}

方法二(递归、if循环语句):
代码:

#include 
#include 
#include 
void PrintN(int N)										//定义PrintN函数
{
     
	//递归循环体
    if (N)
    {
     
    PrintN(N-1);
    printf("%d\n",N);
}
return;
}
int main()
{
     
    int N;
    clock_t start, finish;
    double duration;
    printf("please input N:\n");
    scanf("%d",&N);
    start = clock();
    PrintN(N);											//调用PrintN函数
    finish = clock();
    duration = (double)(finish-start) / CLOCKS_PER_SEC;
    printf("%f seconds\n", duration);					//打印循环执行时间
    return 0;
}

方法三(while循环语句):
代码:

#include 
#include 
#include 
void PrintN(int N)										//定义PrintN函数
{
     
int j;
while(N>=j)
{
     
    printf("%d\n",j);
    j = j + 1;
}
return;
}
int main()
{
     
    int N;
    clock_t start, finish;
    double duration;
    printf("please input N:\n");
    scanf("%d",&N);
    start = clock();
    PrintN(N);											//调用PrintN函数
    finish = clock();
    duration = (double)(finish-start) / CLOCKS_PER_SEC;
    printf("%f seconds\n", duration);					//打印循环执行时间
    return 0;
}

你可能感兴趣的:(笔记,数据结构,c语言,算法)