Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

an if statement nested in a for loop : breaking from loop in the second iteration upon reaching condition check in if statement

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading