Tell the syntax to execute code if number in range otherwise exit

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • HolyDoom Witch
    New Member
    • Oct 2012
    • 34

    Tell the syntax to execute code if number in range otherwise exit

    H! Everyone

    Here is one small question.

    What do you people write if you have to execute a code if say, a number is from 6 to 10? Anything else does not execute that action, and may be used to do something else, like exit. I also hope the syntax you would show would be common knowledge, meaning all programmers big and small would know.

    Code:
    int a;
    cin >>a;
    [if the number is from 6 to 10, then:] cout <<"6 to 10";
    [otherwise exit]
    I happen to ask this because nowhere on the net is there an example of this. Not even on the site I am studying the C++ tutorial from (CPlusPlus.com) .

    After I receive a few replies, I would have something more to add.

    Thanks
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    There are several ways to code this. Here is one:

    Code:
    switch (thenumber)
    {
       case 6:
       case 7:
       case 8:
       case 9:
       case 10:
       {
    
        //the action
    
       }
       break;
    }
    If that's not comfortable you can use compound expressions:

    Code:
    if ( number > 5 && number < 11)
    {
        //the action
    }
    If that is hard to see then use an if/else syntax:

    Code:
    if (number > 5)
    {
      if (number < 11)
      {
        //the action
      }
    }
    etc...

    Comment

    • divideby0
      New Member
      • May 2012
      • 131

      #3
      for me, if it's a range such as 6-10

      Code:
      if(num >= 6 && num <= 10)
          // do something with num
      else
          exit(1);
      if there's a couple of valid ranges

      Code:
      if((num >= 6 && num <= 10) || (num >= 20 && num <= 24))
         // do something with num
      else
         exit(1);
      or maybe num cannot be a num in the valid range

      Code:
      if((num >= 6 && num <= 10) && num != 8)
         // do something with num
      else
         exit(1);

      Comment

      • HolyDoom Witch
        New Member
        • Oct 2012
        • 34

        #4
        H! again WeaknessForCats
        and thanks DivideBy0.

        Well nothing, just a minor thing I discovered which I thought was no one may know because of lack of examples, but I think WeaknessForCats has already given an example of, which happens to be the same-- all one has to do is remove the braces from the last example given by WeaknessForCats .

        Thank you for showing me other examples of this, too. I needed to know these too, since the whole of net does not show any of these; I don't know why they have forgotten this situation.

        I am a newbie, just half way through C++, studying Data Structures (or rather Operators, doing it again creating section-by-section documents for each of the chapters) on the site mentioned above.

        Thanks

        HDW

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          This code:
          Code:
          if (a>5)
          if (a<11)
           cout <<"6 to 10";
          and this code:
          Code:
          if (number > 5)
          {
            if (number < 11)
            {
              //the action
            }
          }
          is the same code. These a two ways of writing a nested-if statement. Just remove the braces.

          Comment

          • HolyDoom Witch
            New Member
            • Oct 2012
            • 34

            #6
            So it occurs to me that the braces are there, so that if you write a statement after say, the second condition which is in the second brace-set, then THIS statement would execute after just two conditions, and a final one can be given in the inner-most brace. Right?

            Thanks

            Comment

            • weaknessforcats
              Recognized Expert Expert
              • Mar 2007
              • 9214

              #7
              That is correct.

              Personally, I always use the braces so I can clearly see what is going on. Nested if/else to several levels can become very hard to understand.

              The area between braces is called a code block.

              Comment

              • HolyDoom Witch
                New Member
                • Oct 2012
                • 34

                #8
                You are saying that:
                1. You always use braces to make if/else statements nested to several levels SO that you can CLEARLY see what's going on.
                2. And then you are saying that nested if/else statements to several levels can become very hard to understand.
                Meaning?

                Comment

                • weaknessforcats
                  Recognized Expert Expert
                  • Mar 2007
                  • 9214

                  #9
                  This is an experience thing. It's about going into code to change it or fix a bug and you can't figure out how the code works all the while your boss is saying, "Hey wfc, you got that working yet...?"

                  Nested if/else are hard to read. Like this:
                  Code:
                  if ((data == 'A' || data == 'B') && data != 'C')
                  {
                  if (data != 'B')
                  {
                   cout  << "Goodbye" << endl;
                  }
                  else if (data != 'X')
                  {
                  if (data != 'Y')
                  {
                  if (data != 'Z')
                  cout << "Hello" << endl;
                  }
                  }
                  }
                  }
                  What values of data cause "Hello" and "Goodbye" to be displayed?

                  Code like this would not pass a code review and depending upon your company, might cost you your job.

                  It's very important that another person can pick up your code and understand it quickly. The world moves too fast for a logic analysis with truth tables to be written to understand current code.

                  Comment

                  • HolyDoom Witch
                    New Member
                    • Oct 2012
                    • 34

                    #10
                    Well what I wanted to ask was that why would you want to nest the if-else statements if they become hard to understand. And how can you see them clearly THEN when they become hard to understand. The things you wrote previously to above are kind of contradictory. Or may be a "Though" can be added to the second sentence of the middle para, like:
                    "Personally , I always use the braces so I can clearly see what is going on. *Though* nested if/else to several levels can become very hard to understand."
                    and it was to be understood this way. Meaning the two sentences were never connected to eachother. Is this right?

                    On the other hand you may want to look at these two variations of code:
                    Code:
                    int a, b, c;
                    cout <<"Give a: "; cin >>a;
                    cout <<"Give b: "; cin >>b;
                    cout <<"Give c: "; cin >>c;
                    
                    // VARIATION ONE: NESTED
                    if (a>05) if (a<11)
                    {cout <<NL <<"6 to 10";
                     if (b>55) if (b<61) cout <<NL <<"56 to 60";
                      {if (c>95) if (c<101) cout <<NL <<"96 to 100";
                      }
                    }
                    
                    cout <<NL <<NL;
                    
                    // VARIATION TWO: ONE BRACE SET ONLY
                    if (a>05) if (a<11)
                    {cout <<NL <<"6 to 10";
                      if (b>55) if (b<61) cout <<NL <<"56 to 60";
                      if (c>95) if (c<101) cout <<NL <<"96 to 100";
                    }
                    In variation one, if the innermost statement gets executed only if both the previous conditions are fulfilled, THEN it is any use of this nested piece of code.

                    Because what I see here is, variation one is behaving just like variation two. The first condition (or set of conditions) has become compulsory, and the rest of the actions will be executed if their respective conditions get fulfilled on individual basis. (I thought repeating the last condition in variation one, in one more brace-set would change that but it is not any good.) So why not use this one since there does not seem to be any difference between them? This one is much easier.

                    Comment

                    • weaknessforcats
                      Recognized Expert Expert
                      • Mar 2007
                      • 9214

                      #11
                      Well, there you have it. The original code (mine) is analyzed and replaced with easier to understand code (yours) and no work was actually done to modify the program. This is a common occurrance.

                      My two sentences were to he connected. 1) use braces, 3) lots of nested if/else are hard to read.

                      Conclusion: Shift thinking from procedural to object-oriented.

                      Comment

                      • divideby0
                        New Member
                        • May 2012
                        • 131

                        #12
                        From the looks of things, both snippits are coded so that b and c are evaluated independently of each other so long as both a conditions are met.

                        Code:
                        if(condition) if(condition) execute statement
                        if(condition) if(condition) execute statement
                        if you were wanting c dependent on b and b dependent on a, then

                        Code:
                        if(a > 5)  if(a < 11)
                        {
                            cout << "6 to 10"; 
                          
                            if(b > 55) if(b < 61)
                            {
                                cout << "56 to 60";
                        
                                if(c > 95) if(c < 101)
                                    cout << "96 to 100";
                            }
                        }
                        or maybe

                        Code:
                        if(a > 5 && a < 11)
                        {
                           cout << "6 to 10";
                        
                           if(b > 55 && b < 61)
                           {
                              cout << "56 to 60";
                        
                              if(c > 95 && c < 101)
                                 cout << "96 to 100";
                           }
                        }
                        I find the latter a bit easier to read and follow, but the compiler doesn't care so long as the code is syntactically correct.

                        Comment

                        • HolyDoom Witch
                          New Member
                          • Oct 2012
                          • 34

                          #13
                          Hey DivideBy0,

                          After saying that c becomes dependent on a and b, you have given the same nested code that I had given, AND which was NOT working in this manner. You gave it by mistake I guess.

                          Because your second example is working perfect. I think && operators are the way if one has to go the nested way. Because then conditions can be met from up to down order, if that is what is required. This can't happen in the simple nested ifs, that is to be understood.

                          Comment

                          • divideby0
                            New Member
                            • May 2012
                            • 131

                            #14
                            Sorry about that; I didn't check it.

                            I threw together the following just to see what happens and it "seems" to follow c needing b and b needing a. The else paths were just to see what conditions led to what outcomes.

                            Code:
                            int a, b, c;
                            
                            for(;;)
                               {
                            	   cout << "Enter values for a, b, and c"
                            		    << "\na(6-10); b(56-60); c(96-100)"
                            			<< "\nranges listed to test (-1 to quit): ";
                            
                            	   cin >> a;
                            
                            	   if(a == -1)
                            		   break;
                            
                            	   cin >> b >> c;
                            
                                   if(a > 5)
                            	   {
                            		   if(a < 11)
                            		   {
                                           cout << "\na) 6 to 10"; 
                                 
                                           if(b > 55)
                            			   {
                            				   if(b < 61)
                            				   {
                                                   cout << "\nb) 56 to 60";
                                 
                                                   if(c > 95)
                            					   {
                            						   if(c < 101)
                                                           cout << "\nc) 96 to 100\n";
                            						   else
                            							   cout << "\nc) max outside range\n";
                            					   } else
                            						   cout << "\nc) min outside range; c) max branch excluded\n";
                                               } else
                            					   cout << "\nb) max outside range; c branch excluded\n";
                            			   } else
                            				   cout << "\nb) min outside range; b) max and c branches excluded\n";
                            
                                       } else
                            			   cout << "\na) max outside range; b and c branches excluded\n";
                            	   } else
                            		   cout << "\na) min outside range; a) max, b and c branches excluded\n";
                            
                            	   cout << "\n";
                               }

                            Comment

                            • HolyDoom Witch
                              New Member
                              • Oct 2012
                              • 34

                              #15
                              Well, your code confused me a little. So I modified mine the same way you did (you may have given a few extra braces in fact), and now the nesting works fine. So I think the mistake was, giving more than one condition before a brace. Giving more than one condition before a brace somehow breaks the continuity of the program. This had occurred to me yesterday, but I did not try. But I would have tried it later anyway.
                              Code:
                              int a, b, c;
                              cout <<"Give a: "; cin >>a;
                              cout <<"Give b: "; cin >>b;
                              cout <<"Give c: "; cin >>c;
                              
                              if (a>05)
                               {if (a<11) cout <<NL <<"6 to 10";
                                 if (b>55)
                                 {if (b<61) cout <<NL <<"56 to 60";
                                  if (c>95)
                              	{if (c<101) cout <<NL <<"96 to 100";
                              	}
                                 }
                               }
                              So I think this thread can rest now. This is how it went for me:
                              1. I discovered the difference between many ifs at the same time nested, and un-nested (single brace-set).
                              2. I discovered that the dependency is broken if there are MORE THAN ONE ifs before a brace.
                              3. And lastly, I learnt some new coding from you people, especially that && thing's usage with if for the same purpose this thread was opened for (and which may have been hard to guess for me).

                              We hereby take leave to go and restart "Operators" chapter and forward. We thank our fellow producers, the directors, and all the Hollywood fraternity associated with this project from the spot boy, to the very lead actors, lead actors' families, and those families' friends, who made this blockbuster possible. :)

                              (Wait a minute... that did not make sense, but I think it was nested! ;)

                              Comment

                              Working...