简体   繁体   中英

C Infinite Loop On While Loop

 #include <stdio.h>
    
 void add(int num){
     while(num < 6){
         add(num+1);
     }
    printf("\n%d",num);
 }

void main(){
    int a = 1;
    add(a);
}

Can any one explain me why its going Infinite

6 6 6 6....

And not only

6

single time.

You don't change the num variable within the loop, try the following:

   #include <stdio.h>
        
     void add(int num){
         while(num < 6){
             num++;
             add(num);
         }
        printf("\n%d",num);
     }
    
    void main(){
        int a = 1;
        add(a);
    }

And not only

6 single time.

Well as it is it will never be only one time even with the infinite loop because of the recursive calls.

To get only a single time you either do:

 void add(int num){
     while(num < 6){
         num++;
     }
    printf("\n%d",num);
 }

or

 void add(int num){
     if(num < 6){
        add(num+1);
     }
    if(num == 6)
      printf("\n%d",num);
 }

But not both combined.

In your loop:

 while(num < 6){
     add(num+1);
 }

You never modify num . So the loop never exits. You eventually end up via recursion with a call to add(5) . That calls add(6) which prints the value 6 and returns. Then the prior recursive call calls add(6) again because of the loop, and so forth.

Given that you have a recursive function, you don't want a loop here. This should only be an if statement:

 void add(int num){
     if(num < 6){
         add(num+1);
     }
    printf("\n%d",num);
 }

This will print values from 6 counting down to (in this case) 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM