1

How can I return back to the start of the programme if the user picks the option no? please help me.

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int choice;
  printf("Are you done? 1 for Yes, 2 for No: ");
  scanf("%d",&choice);
  
  if (choice==1)
  {
      
  }

return 0;
}
Uwu Zie
  • 19
  • 1
  • 1
    You can do it in a multiple ways, on of is to use `goto – user14063792468 Dec 29 '20 at 14:02
  • Does this answer your question? [C programming - Loop until user inputs number scanf](https://stackoverflow.com/questions/25765040/c-programming-loop-until-user-inputs-number-scanf) – costaparas Dec 29 '20 at 14:04
  • 1
    using goto makes code harder to read and is by convention not recommended, just put the code in a `while(1)` loop and break out of it when the user selects 1 – Expolarity Dec 29 '20 at 14:04
  • 2
    @yvw please do not suggest using a `goto` for this. This is best solved using a loop, as in the linked duplicate. – costaparas Dec 29 '20 at 14:05
  • There is absolutely nothing wrong with a proper use of goto. It is often horribly misused, and misuse ought to be avoided. But `goto start` would be better than convoluted logic in a loop. – William Pursell Dec 29 '20 at 15:32

1 Answers1

0

Using while loop:

int main()
{
    while (1)
    {
        int choice;
        printf("Are you done? 1 for Yes, 2 for No: ");
        scanf("%d", &choice);

        if (choice == 1) {
            break;
        }
    }

    return 0;
}

goto is not recommended because it reduces code readability, but I still write it here because it can also solve your question.

int main()
{
$START:

    int choice;
    printf("Are you done? 1 for Yes, 2 for No: ");
    scanf("%d", &choice);

    if (choice == 0) {
        goto $START;
    }

    return 0;
}

Learn more about goto:

Sprite
  • 3,222
  • 1
  • 12
  • 29
  • Note that if the input begins with a non-integer value (eg `a`), this will invoke undefined behavior since scanf will not write a value into `choice` and the condition is checking the value of an uninitialized variable. You must *always* check the value returned by `scanf`. – William Pursell Dec 29 '20 at 16:48