Home > Blockchain >  Why does my main function in C only prints the first for loop?
Why does my main function in C only prints the first for loop?

Time:11-02

I am trying to print for each type of number its own line, but when I run the code it doesn't work, I have checked each function on its own and each function works perfectly.

I am getting two numbers from the user, and my aim is to print out each number between the two numbers including them.

void main(void){
    int a, b;
    printf("\n Hello, how are you? Please enter the two numbers: \n");
    scanf("%d %d", &a,&b);
    
    printf("\n isPrime numbers: \n");
    for(a; a<=b; a  ){
        if(isPrime(a) == 1){
            printf("%d, ", a);         
        } 
    } 
    
    printf("\n isStrong numbers: \n");
    for(a; a<=b; a  ){
        if(isStrong(a) == 1){
            printf("%d, ", a);          
        } 
    } 
    
    printf("\n isPalindrome numbers: \n");
    for(a; a<=b; a  ){
        if(isPalindrome(a) == 1){
            printf("%d, ", a);          
        } 
    } 
    
    printf("\n isArmostrong numbers: \n");
    for(a; a<=b; a  ){
        if(isArmstrong(a) == 1){
            printf("%d, ", a);          
        } 
    } 
    
}

This code only prints out the first for loop for the prime numbers.

 Hello, how are you? Please enter the two numbers: 
1 100

 isPrime numbers: 
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 
 isStrong numbers: 

 isPalindrome numbers: 

 isArmostrong numbers: 

CodePudding user response:

After the first for loop

for(a; a<=b; a  ){

the variable a becomes greater than the variable b due to incrementing the variable a in the loop. So the condition in the following for loops evaluates to false.

You could introduce a local variable in the for loops as for example

for( int i = a; i <= b; i  ){
    if(isPrime(i) == 1){
        printf("%d, ", i);         
    } 
} 

Pay attention to that according to the C Standard the function main without parameters shall be declared like

int main( void )

CodePudding user response:

You never reset a. So in the first for loop, a will be equal to 1, and climb to b. But in the next loop, a is still equal to 100. Try storing the user input in a separate variable, and resetting a each time.

CodePudding user response:

you can store a into some temporary variable and then initialize every for loop with that.

int a, b, tmp;

scanf("%d %d", &a,&b);

tmp=a;

Then you can initialize every for loop like this

for(a=tmp; a<=b; a  ){
  • Related