Home > Net >  an if statement nested in a for loop : breaking from loop in the second iteration upon reaching cond
an if statement nested in a for loop : breaking from loop in the second iteration upon reaching cond

Time:05-20

declaration ( globale ) :

struct list
{
    int v ;
    struct list *suivant ;
};


int i ;
struct list *T_list = NULL, *courent = NULL ;

the follwing function test if a number is prime or not ; return 1 in case the number is prime and 0 if not :

int est_premier ( int x )
{
    for ( i = x/2 ; i > 1 ; i-- )
    {
        if ( x % i == 0 )
        {
            return 0 ;
        }
    }
    return 1 ;
}

i'm facing problem when calling "est_premier" function in the following code and testing it in the if statement ; the loop is supposed to create a linked list of prime numbers between 0 and x ( x included ), what happens is that the code is breaking from the loop as soon as it reachs the second iteration ignoring the if statement in the proccess.

the code with issues :

void Creer_L ( int x )
{
    for ( i = x ; i > 1 ; i-- )
    {
        if ( est_premier ( i ) == 1 )
        {
            courent = malloc ( sizeof ( struct list ) ) ;
            (*courent).v = i ;
            (*courent).suivant = T_list ;
            T_list = courent ;
        }
    }
}

calling the function in main :

int main()
{
    Creer_L ( 10 ) ;
    while ( T_list != NULL )
        {
            printf("%d ", (*T_list).v );
            T_list = (*T_list).suivant ;
        }
    return 0 ;
}

input : 10 expected output : 2 3 5 7 ( prime numbers between 0 and 10 ) the actual output : ( nothing) but the program is terminated correctly.

CodePudding user response:

I think it's your i that is declared as a global and used in both of your loops that creates this behaviour.

You probably want to declare it inside your loop

int est_premier ( int x )
{
    for (int i = x/2 ; i > 1 ; i-- )
    {
        if ( x % i == 0 )
        {
            return 0 ;
        }
    }
    return 1 ;
}

and

   for ( int i = x ; i > 1 ; i-- )
    {
        if ( est_premier ( i ) == 1 )
        {
            courent = malloc ( sizeof ( struct list ) ) ;
            (*courent).v = i ;
            (*courent).suivant = T_list ;
            T_list = courent ;
        }
    }

And you can remove it from you global declaration since you don't use it anywhere else.

  •  Tags:  
  • c
  • Related