Saturday 13 July 2013

[C Programming #1] Print 1 to 100 without using loops

How to print 1 to 100 numbers without using loops concepts (for/while/do-while) ?
This is a tricky question. Think Think Think.
..
..
..
..
Hint: We can use the concept of static variables to do this task.
Think
..
..
..
Here is the program, which solves the problem.

  1. #include<stdio.h>

  2. int main()
  3. {
  4.   static int i = 0;

  5. printf("%d\n", i++);
  6. if (i<=100)
  7.   main();


  8. return 0;
  9. }
Output: 1 to 100 numbers printed line by line.

Now, we can made a small change in the program to display numbers from x to y;
Here is the program to do this task.

  1. #include<stdio.h>

  2. int main()
  3. {
  4.   static int i = 0, x ,y;

  5. if (i == 0) {
  6.     printf("Please enter two numbers, x should be <= y\n");
  7.   printf("x = ");
  8.   scanf("%d", &x);
  9.   printf("y = ");
  10.     scanf("%d", &y);
  11.     if (x > y) {
  12.     printf("x should be less than or equal to y.\n");
  13.   return 0;
  14.     }
  15. }

  16. printf("%d\n", x+(i++));
  17. if ((x+i)<=y)
  18.   main();

  19. return 0;
  20. }
Output: Numbers are displayed from X to Y line bye line:
Example output:
Please enter two numbers, x should be <= y
x = 12
y = 17
12
13
14
15
16
17

Example output_2:
Please enter two numbers, x should be <= y
x = 12
y = 6
x should be less than or equal to y.

No comments:

Post a Comment

You might also like

Related Posts Plugin for WordPress, Blogger...