Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
C Program to print numbers from 1 to N without using semicolon
Printing numbers from 1 to N is an easy task that can be achieved using loops, but to print numbers from one to N without using a semicolon is a tricky question. We will discuss two different methods to solve this question using iteration and recursion approaches.
In this article, our task is to print numbers from 1 to 'n' and we don't have to use a semicolon. The approaches are listed below:
Using Iteration
This approach uses the iterative approach, where we have used the while loop to print the numbers from 1 to N. The num <=N checks if the number is within the range, we print the numbers using a printf statement and increase the counter of num. We use the logical AND (&&) operator to verify all three conditions are true inside the while loop.
Example
Here is an example of printing numbers from 1 to 20 using an iterative approach. You can change the value of N:
#include<stdio.h>
#define N 20
int main(int num, char *argv[]) {
while (num <=N && printf("%d ", num) && num++) {
//The while body is empty.
}
}
The output of the above code is given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Using Recursion
You can use the recursion for printing the numbers from 1 to N without using a semicolon. The if statement along with the logical AND operator checks if the value of N is valid and prints the N. We have recursively called the main() function to print the next number.
Example
In this example, we have printed numbers from 1 to 25 using a recursive approach:
#include<stdio.h>
#define N 25
int main(int val) {
if (val <=N && printf("%d ", val) && main(val + 1)) {
//Body is empty
}
}
The output of the above code is given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
