CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 15

Thread: Nesting If/Else

  1. #1
    Join Date
    Jan 2006
    Location
    Cincinnati
    Posts
    24

    Nesting If/Else

    Seems like a simple thing...I have tried to nest If statements (I have seen examples on the web) but it doesn't seem to like it. If I put and "End IF" between every statement it likes it... Here it is as I have it nested. I can just do it the other day but it bothers me when I can't find out why it's no good.
    Code:
    		If Salesamount > 0 And Salesamount <= 5000 Then
    			Salesamount = Salesamount * 0.01
    			If Salesamount > 5000 And Salesamount <= 10000 Then
    				Salesamount = Salesamount * 0.03
    				If Salesamount > 10000 Then
    					Salesamount = Salesamount * 0.07
    				End If

  2. #2
    Join Date
    Jan 2006
    Posts
    86

    Re: Nesting If/Else

    You must end every IF with a End If, if what you want is nested Ifs...
    A complete diferent story would be if what you want is a ElseIf, where you just need one End If at the end.

    Try this:

    Code:
            If Salesamount > 0 And Salesamount <= 5000 Then
                Salesamount = Salesamount * 0.01
            ElseIf Salesamount > 5000 And Salesamount <= 10000 Then
                Salesamount = Salesamount * 0.03
            ElseIf Salesamount > 10000 Then
                Salesamount = Salesamount * 0.07
            End If
    Or this:

    Code:
            If Salesamount > 0 And Salesamount <= 5000 Then
                Salesamount = Salesamount * 0.01
                If Salesamount > 5000 And Salesamount <= 10000 Then
                    Salesamount = Salesamount * 0.03
                    If Salesamount > 10000 Then
                        Salesamount = Salesamount * 0.07
                    End If
                End If
            End If
    Hope that helps.

  3. #3
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,284

    Re: Nesting If/Else

    You also get a "Single Line" If Statement
    Example:
    Code:
    If Sales > 1000 Then Profit = Profit * 2
    Note that what should be done when Sales > 1000 is placed next to Then, and not underneath it - denoting a single line If statement.

  4. #4
    Join Date
    Jan 2006
    Posts
    293

    Re: Nesting If/Else

    I prefer using Select Case over a lot of If.. Else statements... I think its prettier
    Code:
            Select Case SalesAmount
                Case Is < 5000
                    MessageBox.Show("less than 5000")
                Case 5000 To 10000
                    MessageBox.Show("between 5000 and 10000")
                Case Is > 10000
                    MessageBox.Show("greater than 10000")
                Case Else
                    MessageBox.Show("Invalid Value!!")
            End Select

  5. #5
    Join Date
    Jan 2006
    Location
    Cincinnati
    Posts
    24

    Re: Nesting If/Else

    Quote Originally Posted by juanchoc
    You must end every IF with a End If, if what you want is nested Ifs...
    Thank you. I guess I had the wrong idea about nested IF statements. If you have to put an END IF statement after every line then I'm not seeing where nesting helps other than making the code a little easier (visually) to debug. Then again, maybe that's the point. The book I am using sucks. It's says you can nest them but doesn't give an example or define it.

  6. #6
    Join Date
    Jan 2006
    Posts
    86

    Re: Nesting If/Else

    It always depends on what you want to do.
    Remember that there can be multiple levels of nesting, not just the linear example above.

  7. #7
    Join Date
    Oct 2005
    Location
    Islamabad, Pakistan
    Posts
    1,277

    Re: Nesting If/Else

    u can have multiple levels of nesting like this
    Code:
    If condition Then
    	If condition Then
    		If condition Then
    
    		End If
    	End If
    End If

  8. #8
    Join Date
    Jul 2001
    Location
    Sunny South Africa
    Posts
    11,284

    Re: Nesting If/Else

    You could also have a nested Select Case Statement
    Code:
    Select Case Gender
        Case "Female"
          Select Case Age
             Case 20
            
             Case 30
    
         End Select
        Case "Male"
          Select Case Age
             Case 20
            
             Case 30
    
         End Select
    End Select

  9. #9
    Join Date
    Jan 2006
    Location
    Cincinnati
    Posts
    24

    Re: Nesting If/Else

    So guys, what is the benefit of nesting - just for visual clarity? It looks like it takes the same amount of coding. Sorry if this is a lame question but I'm all about efficiency and it doesn't appear to be more effiicient.

  10. #10
    Join Date
    Jun 2004
    Location
    Kashmir, India
    Posts
    6,808

    Re: Nesting If/Else

    Quote Originally Posted by FZ1
    So guys, what is the benefit of nesting - just for visual clarity? It looks like it takes the same amount of coding. Sorry if this is a lame question but I'm all about efficiency and it doesn't appear to be more effiicient.
    Basically you would avoid nesting Ifs and use a Select Case statement rather.

    And it all depends on what you want to do?

  11. #11
    Join Date
    Dec 2003
    Location
    St. Cugat - Catalunya
    Posts
    441

    Re: Nesting If/Else

    Quote Originally Posted by FZ1
    So guys, what is the benefit of nesting - just for visual clarity? It looks like it takes the same amount of coding. Sorry if this is a lame question but I'm all about efficiency and it doesn't appear to be more effiicient.
    What exactly do you understand by "nesting"?
    Same amount of coding than what?
    More efficient than what?

    End If tells the compiler where the If ends.

    Consider the following

    Code:
    If condition1 Then
        statement1
        If condition2 Then
            statement2
            If condition3 Then
                statement3
                statement4
            End If
            statement5
        End If 
        statement6
    End If
    How will you tell the compiler which statements are to be executed by every If without End If counterparts?

    How will you code it without nested Ifs in a more efficient way?

    Last edited by DeepButi; March 8th, 2006 at 05:10 AM.
    Did it help? rate it.

    The best conversation I had was over forty million years ago ... and that was with a coffee machine.

  12. #12
    Join Date
    Jan 2006
    Location
    Cincinnati
    Posts
    24

    Re: Nesting If/Else

    Quote Originally Posted by DeepButi
    End If tells the compiler where the If ends.

    How will you tell the compiler which statements are to be executed by every If without End If counterparts?
    I understand that now but I guess I never got the answer to: what's the point of nesting?
    Quote Originally Posted by DeepButi
    Same amount of coding than what?
    More efficient than what?
    My original thought process was this - I thought (by assumption - I know this is bad) by nesting you would be able to only use 1 final "END IF" statement at the end of all the IF instructions thereby saving some coding and being more efficient. Also bear in mind that our homework assignment came from a problem in our text book which was nice enough to say: "(hint: You can nest an IF...THEN...ELSE statement, which means you can place one IF...THEN...ELSE statement inside another IF...THEN...ELSE statement.)" That's all the explanation I got and nowhere was it discussed in detail in the book. So, I took this to be telling me that its more efficient to do it this way so I guess I read a little into it but again, I wasn't given much to work with.

  13. #13
    Join Date
    Jan 2006
    Location
    Cincinnati
    Posts
    24

    Re: Nesting If/Else

    OK, so I have been monkeying around with the code because that's the best way to learn, right? So when I code this:
    Code:
    		If Salesamount > 0 And Salesamount <= 5000 Then
    			Bonus = Salesamount * 0.01
    			If Salesamount > 5000 And Salesamount <= 10000 Then
    				Bonus = Salesamount * 0.03
    				If Salesamount > 10000 Then
    					Bonus = Salesamount * 0.07
    				End If
    			End If
    		End If
    The program will only look at the first statement. If I enter an amount >5000 it will not return an answer. However, if I code it this way:
    Code:
    		If Salesamount > 0 And Salesamount <= 5000 Then
    			Bonus = Salesamount * 0.01
    		End If
    		If Salesamount > 5000 And Salesamount <= 10000 Then
    			Bonus = Salesamount * 0.03
    		End If
    		If Salesamount > 10000 Then
    			Bonus = Salesamount * 0.07
    		End If
    The logic for all statements is evaluated and the correct results are displayed. This tells me there is a difference between the 2 ways of formatting the code other than being visually different. The question is, why is it interpreting it different and when would you want to use the nested version vs. the non? Again, the book is no help on the subject and apparently something we aren't going to learn in class
    I drive way too fast to worry about cholesterol

  14. #14
    Join Date
    Oct 2005
    Location
    Islamabad, Pakistan
    Posts
    1,277

    Re: Nesting If/Else

    Using nesting depends on what u want to do , it depends on the logic u adapt to solve a problem.
    very important in sophisticated programming like games, its good until it is in ur control, but turns bad if u loose control(diagrams used to draw the flow of control).
    Although deeply nested structures are confusing, difficult to understand and maintain, so u should minimize the depth of nested control structures, not more then 5 levels.
    following example will show the use of nesting. Counts the words in sentence.
    Code:
       'ch is the sharacter from sentence
            If ch = " " Then ' It is a space 
    
                ' Handle spaces 
                If (inAWord) Then ' reset 
                    inAWord = False
                Else ' Just another space
                      
                End If
    
            Else
    
                If inAWord Then ' It is part of a word 
    
                Else ' Starting a new word 
                    numWords += 1  ' count it
                    inAWord = True
                End If
    
            End If

  15. #15
    Join Date
    Feb 2006
    Posts
    43

    Re: Nesting If/Else

    This is the way my text explains Nested If statements...

    Nested, If/ElseIf/Else, and Case Selection Structures
    Nested Selection Structures
    You use the selection structure when you want a procedure to make a decision and then select one of two paths—either the true path or the false path—based on the result of that decision
    Both paths in a selection structure can include instructions that declare and initialize variables, perform calculations, and so on
    Both also can include other selection structures
    When either a selection structure’s true path or its false path contains another selection structure, the inner selections structure is referred to as a nested selection structure, because I is contained (nested) within the outer selection structure
    You use a nested selection structure when more than one decision must be made before the appropriate action can be taken
    Assume you want to create a procedure that determines whether a person can vote, and then, based on the result of that determination, displays one of three messages
    The person’s voter registration status is important only after his or her age is determined
    You can think of the decision regarding the age as the primary decision, and the decision regarding the registration status as being the secondary decision, because whether the registration decision needs to be made by the outer selection structure, while the secondary decision is always made by the inner (nested) selection structure
    The lines connecting the selection structures in the pseudocode and code are included in the figure to help you see which clauses are related to each other
    The procedure begins by declaring the variables and then getting the age from the user
    The condition in the outer selection structure then checks whether the age is greater than or equal to 18
    If the condition is false, it means that the person is not old enough to vote
    In that case, only one message—the “You are too young to vote.” message—is appropriate
    After the message is displayed, both the outer selection structure and the procedure end
    If the outer selection structure’s condition is true, it means that the person is old enough to vote
    If he or she is registered, the instruction in the nested selection structure’s true path displays the “You can vote” message
    Otherwise, the false path displays the “You need to register before you can vote” message
    After the appropriate message is displayed, both selection structures and the procedure end
    The nested selection structure in this procedure is processed only when the outer selection structure’s condition is true
    The new example first declares the necessary variables and then gets the age from the user
    However, rather than checking whether the age is greater than or equal to 18, the outer selection structure in this version checks whether the age is less than 18
    If the condition is true, the instruction in the outer selection structure’s true path displays a message
    If the condition is false, the instructions first get the registration status from the user, and then use a nested selection structure to determine whether the person is registered
    Then it displays a message
    Otherwise, it displays another message
    The nested selection structure in this version is processed only when the outer selection is false
    Both versions of the voter eligibility procedure produce the same results
    Neither version is better than the other
    Each simply represents a different way of solving he same problem

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured