How to Print 1 to 100 without using Loop in C programming?

Probably we all know how to write C program to print 1 to 100 using loop. We can have a quick look of the code snippet.

If we want to use while loop:

It is bit tricky if you are not allowed to use any loop. Here we’ll see what are other possibles solutions to print 1 to 100 without a loop.

Using 100 printf Statements!!!

Yes this is also a solution, you can use 100 printf statements one after another. Obviously this is not a good solution because you have to write the printf statements so many times. Even worse thing is: if you want to print 1000 numbers, you have to write the printf statement 1000 times. It is not scalable at all. Program will look like this.

Print 1 to 100 Using Recursion

Another option to do similar job multiple times other than loop is recursion. Yes recursion is an option to do repetitive work. here is the C program to print 1 to 100 using recursion.

In this example, we have a function, printnum(), to print a number of the number is less than or equal to 100. Additionally it calls itself with the next number. The function, printnum(), is called from main with 1. The function, printnum(), will print 1 first and then will call itself by 2. This process will continue until the parameter becomes more than 100, I.e. 101. In the case the function will neither print the number nor call the function itself. The function will eventually terminates. So the function will print all numbers from 1 to 100.
This program has a time complexity O(n). It has higher space requirement also as recursion uses stack internally to remember the context which is required to comeback to the previous function call context.

We can do the recursion without using any other function. We can call the main() recursively. In that case we have to use global or static variable. The code below uses global variable.

Print 1 to 100Using goto Statement

Another way to do repetitive work in C programming is to use goto statement. Here is the program using goto statement.

This solution is simple. We have a variable i which is initialized as 1. We have a label next to return the execution here using goto statement. After printing the value of i we are checking whether its value is less than or equal to 100. If it is, then we are sending the execution to label next. That way we’ll print i 100 times from 1 to 100. Its time complexity is also O(n) but it does not require any extra space like the previous solution.

Using seq Command on Linux

We can have Linux specific solution. There is a command called seq that can print a range of numbers. We can set the range, starting number and end number, as argument of the command. We can use system() function to execute a Linux command from C program. Here is the program.

Leave a Reply

Your email address will not be published. Required fields are marked *