in Programming in C closed by
661 views
0 votes
0 votes
closed as a duplicate of: C Programming Recursion
#include<stdio.h>
void print(int n){
    printf("Hello ");
    if(n++ == 0) return ;
    print(n);
    n++;
}

int main(){
    void print();
    print(-4);
}
in Programming in C closed by
661 views

1 Answer

1 vote
1 vote

The working of the given code is described below:

  1. The print function is defined, which takes an integer as a parameter.
  2. Inside the function, it first prints "Hello ".
  3. It then checks the condition n++ == 0 This condition evaluates whether the value of incremented by 1 is equal to 0. Note that the postfix ++ operator increments the value of n after the comparison.
  4. If the condition is true, i.e., n++ is equal to 0, the function returns and the recursion stops.
  5. If the condition is false, the function calls itself recursively with the argument n.
  6. After the recursive call, n is incremented by 1 (n++).
  7. The function continues to the next line, which is the end of the function.

In the main function:

  1. There is an declaration of the print function: void print(); (Note:This declaration is unnecessary since the print function is already defined above.)
  2. The print function is then called with the argument -4.

When you run the code, the output will be: Hello Hello Hello Hello Hello

Explanation:

  • The initial call to print(-4) prints "Hello " once.
  • The next recursive call is made with n incremented by 1, which becomes -3.
  • The second call prints "Hello " again.
  • This process continues until n becomes 0.
  • Since the condition n++ == 0 is satisfied when n is 0, the recursion stops and no further calls are made.
  • The total number of "Hello " strings printed is five.