Open In App

C Program to print numbers from 1 to N without using semicolon?

How to print numbers from 1 to N without using any semicolon in C.
 




#include<stdio.h>
#define N 100
 
// Add your code here to print numbers from 1
// to N without using any semicolon

What code to add in above snippet such that it doesn’t contain semicolon and prints numbers from 1 to N?
We strongly recommend you to minimize your browser and try this yourself first
Method 1 (Recursive)
 






// A recursive C program to print all numbers from 1
// to N without semicolon
#include<stdio.h>
#define N 10
 
int main(int num)
{
    if (num <= N && printf("%d ", num) && main(num + 1))
    {
    }    
}

Output: 

1 2 3 4 5 6 7 8 9 10 

See this for complete run. Thanks to Utkarsh Trivedi for suggesting this solution.
Method 2 (Iterative)
 






// An iterative C program to print all numbers from 1
// to N without semicolon
#include<stdio.h>
#define N 10
 
int main(int num, char *argv[])
{
while (num <= N && printf("%d ", num) && num++)
{
}
}

Output: 

1 2 3 4 5 6 7 8 9 10 

See this for complete run. Thanks to Rahul Huria for suggesting this solution.
How do these solutions work? 
main() function can receive arguments. The first argument is argument count whose value is 1 if no argument is passed to it. The first argument is always program name. 
 




#include<stdio.h>
 
int main(int num, char *argv[])
{
   printf("num = %d\n", num);
   printf("argv[0] = %s ", argv[0]);
}

Output: 

num = 1 
argv[0] = <file_name>

 


Article Tags :