Tuesday, July 17, 2012

Print n times with out using loop C program!!!

Here I will explain how to do this.The basic idea is repeatedly calling print function. So solution lies in the previous statement itself . i.e repeatedly calling the function. And use one global variable to maintain the count. We can do this in two ways.
  • Recursive method
  • Non-recursive method
Recursive method: Most important part in recursive function is termination condition. So to break the recursive  function, just use the global variable (here it is n). If the n value matches required value(here it is 10 ), stop calling and return. other wise increment global value and call the function. That's it. Below is the C Code.
int n=0;
void print()
{
    printf("%d\n",n);
    if(n==10)
        return;
    n++;
    print();
}
int main()
{
    print();
}

In the above C program, we are calling user defined function print(). To terminate that process we are using one global variable n,  and we are checking global variable and if it reaches the required value, we are terminating the process.

Non-recursive method: This is similar to recursive method only, but the difference is instead of calling user defined function, just call main() function itself. And the remaining logic is same like maintaining the global variable and termination condition. C code is given below.
int x=0;
int main()
{
    if(x==10)
        return 0;
    x++;
    printf("%d\n",x);
    main();
}

No comments:

Popular Posts