Printing Numbers from 1 to 100
(Without using If, Switch, For, While, Do While and Goto)
Recently I come across the above mentioned problem. You have to write a C program to print numbers from 1 to 100. But you should not use If, Switch, For, While, Do While or Goto. Here are the three solutions I felt O.K.
//Solution 1
C is case sensitive. So is C++. So the restriction does not apply to the C/C++ keywords if, switch, for, while, do or goto. So you could use the keywords and write an ordinary C program to print the numbers.
//Solution 2
You could use printf( ) function to print the numbers. printf("1\n2\n3\n......99\n100");. May not be the best solution. But it is also a solution.
//Solution 3
Use the ternary operator (? : ) in C/C++. The program is given below.
#include<stdio.h>int i=0;
int main()
{
i++;
printf("\n%d",i);
(i>99)?i:main();
}
Download
//Solution 4
Use the Token Pasting operator in C/C++. Token Pasting operator allows you to merge separate tokens. The solution is given below.
#include<stdio.h>
#define LOOP wh##ile
int main()
{
int i=1;
LOOP(i<=100)
{
printf("\n%d",i);
i++;
}
}
#define LOOP wh##ile
int main()
{
int i=1;
LOOP(i<=100)
{
printf("\n%d",i);
i++;
}
}
There might be other solutions also. If you know any please post them.
No comments:
Post a Comment