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

3.3

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 semicoolon
#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 semicoolon
#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>

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

GATE CS Corner    Company Wise Coding Practice

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

Recommended Posts:



3.3 Average Difficulty : 3.3/5.0
Based on 22 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.