Search code examples
cfor-loopif-statementlogicgoto

How do i write C code without using a goto keyword?


I have this code written using a goto keyword:

#include<stdio.h>
    
    int main()
    {
        int i,j,k;
         for(i=1;i<=3;i++)
         {
         for(j=1;j<=3;j++)
         {
         for(k=1;k<=3;k++)
         {
         [***if(i==2&&j==2&&k==2)
         
           goto out;][1]
         else
         printf("%d %d %d\n ",i,j,k);***
        }
        }
       }
       out:
       printf("\nOut of the loop");
        return 0;
    }

And I have tried to write it without using goto with help of if statement and switch case. But I couldn't come with perfect logic. Please, someone, help me with this one.

#include<stdio.h>
    
int main()
{
        int i,j,k;
         for(i=1;i<=3;i++)
         {
         for(j=1;j<=3;j++)
         {
         for(k=1;k<=3;k++)
         {
         if(i>=2&&j>=2&&k>=2)
         break;
         else
         printf("%d %d %d\n ",i,j,k);
    
        }
        **

**switch(i>=2&&j>=3&&k>=1)
        {
        case 1: break;
        default : break;
     }**

**
     }
        switch(i>=3&&j>=2&&k>=2)
        {
        case 1: break;
        default : break;
     }
     }
     return 0;
    }

Solution

  • You can use another variable and use it to "notify" the loops that they should end.

    #include<stdio.h>
    
    int main()
    {
        int i,j,k;
        int run_me = 1;
        for (i = 1; run_me && i <= 3; i++) {
          for (j = 1; run_me && j <= 3; j++) {
            for (k = 1; run_me && k <= 3; k++) {
              if (i == 2 && j == 2 && k == 2) {
                 run_me = 0;
              } else {
                 printf("%d %d %d\n ",i,j,k);***
              }
            }
          }
       }
       printf("\nOut of the loop");
       return 0;
    }
    

    You can create a function from the loops.

    #include<stdio.h>
    
    void function(void) 
    {
        int i,j,k;
        for (i = 1; i <= 3; i++) {
          for (j = 1; j <= 3; j++) {
            for (k = 1; k <= 3; k++) {
              if (i == 2 && j == 2 && k == 2) {
                 return;
              } else {
                 printf("%d %d %d\n ",i,j,k);***
              }
            }
          }
       }
    }
    
    int main()
    {
       function();
       printf("\nOut of the loop");
       return 0;
    }