-5
for(i=0;i<10;i++)
    {printf("\n %d",i);}

Write a c program to print a message "Hello world" when the above for loop reaches to 5 with the help of goto keyword? Output: 1 2 3 4 Hello World 6 7 8 9 10

  • `goto` i always a bad idea and for is not capitalized. – user10191234 Dec 12 '20 at 09:35
  • 2
    While goto has its uses... This is not one of them. Is this an assignment for a class? – Shawn Dec 12 '20 at 10:20
  • This is not an assignment for a class. I am learning C on my own and I got this question after I learn about goto from an online course. It will be great if you can solve the problem. – Manish Khadka Dec 12 '20 at 10:33

1 Answers1

0

First of all, that's a weird way to put goto to use. You don't need a goto at all and can just use a simple loop instead.

    for(int i = 0; i < 10; i++)
    {
        if(i == 5)
        {
            printf("Hello World ");
        }
        printf("%i ", i + 1);
    }

or if you really want to use goto for the sake of it, you can change it to

    int i = 0;
    for(i = 0; i < 10; i++)
    {
        if(i == 4)
        {
            goto point;
        }
        printf("%i ", i + 1);
    }

    point:
    printf("Hello World ");

    for(int i = 5; i < 10; i++)
    {
        printf("%i ", i + 1);
    }

and this is by no means a good code at all because it practically does the same thing as the previous one.