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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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)

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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))
    {
    }     
}

chevron_right


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)

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

num = 1 
argv[0] = <file_name>

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up

Improved By : maveriek



Article Tags :
Practice Tags :


17


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.