Wednesday, July 25, 2012

Print 1 to n with out conditional statement !!

Here we will see how to print 1 to n numbers with out using any loop(for or while) and with out using any if statement in C. I already posted on post on with out using loop but used conditional statement like if statement. In this post I will explaing with out using conditionla statement as well.

How it works: Printing N times can be achieved by repeated calling function by using recursion or by calling main() function as specified here. But stoping that calling function is important here. To stop calling main() function we need some termination condition. So to terminate it, we will use logical AND (&&) operation. The basic concept of AND operation is , if the first value(here it is 10-count) is false, it wont go for the second value. So main() function will be called until first value becomes zero.
  1. Get the global variable or static variable with one
  2. print the value
  3. increment the global varaible
  4. do AND operation (on N+1-count) and main() function.
C Program:


int count=1;
    printf("Number %d\n",count);
    (11-count)&& main();

Explaination: We used the global variable count (you can also use static variable instead of global), and it is initialised to one. Because here we want to display from 1 to 10 numbers. And then main() starts , there we are printing the value of count and incrementing the count. And here comes the trick, for repeated printing we are calling main() function and for stoping this, we used logical AND operation. In AND operation we used 11-count , this statement becomes zero when the count value is 11 and eventually logical AND operation becomes false and it wont call the main() function. And stop calling the main() function.

1 comment:

Anonymous said...

Thank you for writing this information on the internet.
my web page - Digital Printing Melbourne

Popular Posts