How to print numbers from 1 to 100 without using loop?
With the help of recursion we can achieve the output. Please find below code snippet.
From the above code snippet, one thing need to understand is "Usage of comma operator".#include <stdio.h>
/* Prints numbers from 1 to n */
void printNos(unsigned int n)
{
(n > 0 && (printNos(n-1), printf("%d ", n)));
return;
}
/* program to test printNos */
int main()
{
printNos(100);
getchar();
return 0;
}
(n > 0 && (printNos(n-1), printf("%d ", n)));
As per the precedence & associativity the above statement gets evaluated from left to right. and the order follows as below
1. checks whether n is greater than 0 or not? i.e., n > 0
2. As the input (1st) for logical AND operator is true and checks for the second input. That's why it is acting as a "if" block.
3. When it comes to second input for && operator, its a set of statements enclosed by parenthesis ( '(' and ')' ).
Note: Comma ( ,) has the lest precedence, so all statements will call/run inside the parenthesis and the right most value will be used as a final set value.
To understand this please see the below example.
int a = (3, 5); // a gets value as 5. not 3
why because = has high precedence and evaluates from right to left (as per associativity). Right part is parenthesis and has two values separated by comma (,) and comma evaluates from left to right. and the right most value will gets returned to from the set to the variable a.
No comments:
Post a Comment