'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 following 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 reaches the second iteration ignoring the if statement in the process.
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
