-2
#include<stdio.h>

int main()
{
    int num;
    printf("Enter a EVEN Number: ");
    scanf("%d",&num);

    if (num%2!=0)
    {
        printf("WRONG INPUT\n\n");
        main();
    }

    printf("EVEN NUMBER ENTERED\n");
}

Here Is The Output For Above Code When I DONT USE ELSE

Is it something to do with how A C Program stores information using stack? Or am i missing some concept

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • consider a loop rather than recursively calling `main` – yano Jun 12 '18 at 15:16
  • i know the method using a loop but i wanted to get my basics with recursion clear as i have started programming recently – patrick1024 Jun 12 '18 at 15:19
  • 1
    Please do not show pictures of text, show the text itself. – Yunnosch Jun 12 '18 at 15:19
  • 2
    If that is the result of getting your basics of recursion clear, then you should review them from start. – Yunnosch Jun 12 '18 at 15:20
  • If you make N mistakes before entering an even number, you will get N+1 message that an even number was entered. Don't use recursion on `main()` like that. Yes, it is allowed in C (it isn't in C++ — yet another of the differences between the languages), but it isn't a good idea. Use a loop instead. – Jonathan Leffler Jun 12 '18 at 15:45
  • Where is the `else` you mention in the title. You do not have any `else` part in that code. If you compare things you should show us both. – Gerhardh Jun 12 '18 at 16:11

1 Answers1

0

When you gave 3 as input, the if condition is true and main() will be called a 2nd time.

Then you gave an even number as input in which case, the flow of control won't enter the body of if and just print the "EVEN NUMBER ENTERED" message and the program control exits the 2nd main().

Now the control goes back to the place where the main() was recursively called and executes what is left of the first main() call which happens to be the same "EVEN NUMBER ENTERED" message.

See this about making main() recursive. A recursive main() is not considered good.

Consider making another function and then calling it from main() like

int fn()
{
    int num;
    printf("Enter an EVEN Number: ");
    scanf("%d",&num);

    if (num%2!=0)
    {
        printf("WRONG INPUT\n\n");
        return fn();
    }
    printf("EVEN NUMBER ENTERED\n");
}

Or use else as you did first.

J...S
  • 5,079
  • 1
  • 20
  • 35