Thread: Another beginner 'n when to use while vs if

  1. #1
    Registered User
    Join Date
    May 2007
    Posts
    20

    Another beginner 'n when to use while vs if

    I am really getting confused between using while and if loops

    eg: Here's a solution for swapping current element with it's left node in a binary tree:

    Code:
    TREE swap_left (TREE T){
    	element_type tmp;
    	if(T!=NULL){
    		if(T->left){
    		tmp = T->element;
    		T->element = T->left->element;
    		T->left->element = tmp;		
    		}
    
    	swap_left(T->right);
    	swap_left(T->left);
    }	
    	return T;	
    }
    why can't I replace if (T!=NULL) with while(T!=NULL)?...please give me some suggestion on when to use what....

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    Generally....

    Use if, if you're only needing to test the condition and run the block of code once. Use while when you need to repeatedly run the code while the condition is true until it is false.

  3. #3
    Registered User
    Join Date
    May 2007
    Posts
    20
    Is this the right solution using while?

    Code:
    TREE swap_left (TREE T){
    	element_type tmp;
    	while ((T!=NULL) && (T->left!=NULL)){
    		tmp = T->element;
    		T->element = T->left->element;
    		T->left->element = tmp;	
    		return (swap_left(T->right)&&swap_left(T->left));
    		}
    	
    	return T;	
    }

  4. #4
    Registered User
    Join Date
    May 2007
    Posts
    20
    I printed out the solution and it does look right....thanks for your answer Mac

  5. #5
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    You can't compare if with while...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Same old beginner question...
    By Sharmz in forum C Programming
    Replies: 15
    Last Post: 08-04-2008, 11:48 AM
  2. What are some good beginner programs I shouold make?
    By oobootsy1 in forum C# Programming
    Replies: 6
    Last Post: 08-09-2005, 02:02 PM
  3. Books, Beginner, MustHave
    By Zeusbwr in forum C++ Programming
    Replies: 9
    Last Post: 10-25-2004, 05:14 PM
  4. Windows programming for beginner (Absolute beginner)
    By WDT in forum Windows Programming
    Replies: 4
    Last Post: 01-06-2004, 11:21 AM