473,320 Members | 1,572 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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.

Expand|Select|Wrap|Line Numbers
  1. int a;
  2. cin >>a;
  3. [if the number is from 6 to 10, then:] cout <<"6 to 10";
  4. [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
Feb 11 '13 #1
20 1834
weaknessforcats
9,208 Expert Mod 8TB
There are several ways to code this. Here is one:

Expand|Select|Wrap|Line Numbers
  1. switch (thenumber)
  2. {
  3.    case 6:
  4.    case 7:
  5.    case 8:
  6.    case 9:
  7.    case 10:
  8.    {
  9.  
  10.     //the action
  11.  
  12.    }
  13.    break;
  14. }
  15.  
If that's not comfortable you can use compound expressions:

Expand|Select|Wrap|Line Numbers
  1. if ( number > 5 && number < 11)
  2. {
  3.     //the action
  4. }
If that is hard to see then use an if/else syntax:

Expand|Select|Wrap|Line Numbers
  1. if (number > 5)
  2. {
  3.   if (number < 11)
  4.   {
  5.     //the action
  6.   }
  7. }
  8.  
etc...
Feb 11 '13 #2
divideby0
131 128KB
for me, if it's a range such as 6-10

Expand|Select|Wrap|Line Numbers
  1. if(num >= 6 && num <= 10)
  2.     // do something with num
  3. else
  4.     exit(1);
  5.  
if there's a couple of valid ranges

Expand|Select|Wrap|Line Numbers
  1. if((num >= 6 && num <= 10) || (num >= 20 && num <= 24))
  2.    // do something with num
  3. else
  4.    exit(1);
  5.  
or maybe num cannot be a num in the valid range

Expand|Select|Wrap|Line Numbers
  1. if((num >= 6 && num <= 10) && num != 8)
  2.    // do something with num
  3. else
  4.    exit(1);
  5.  
Feb 11 '13 #3
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
Feb 12 '13 #4
weaknessforcats
9,208 Expert Mod 8TB
This code:
Expand|Select|Wrap|Line Numbers
  1. if (a>5)
  2. if (a<11)
  3.  cout <<"6 to 10";
  4.  
and this code:
Expand|Select|Wrap|Line Numbers
  1. if (number > 5)
  2. {
  3.   if (number < 11)
  4.   {
  5.     //the action
  6.   }
  7. }
  8.  
is the same code. These a two ways of writing a nested-if statement. Just remove the braces.
Feb 12 '13 #5
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
Feb 13 '13 #6
weaknessforcats
9,208 Expert Mod 8TB
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.
Feb 13 '13 #7
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?
Feb 14 '13 #8
weaknessforcats
9,208 Expert Mod 8TB
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:
Expand|Select|Wrap|Line Numbers
  1. if ((data == 'A' || data == 'B') && data != 'C')
  2. {
  3. if (data != 'B')
  4. {
  5.  cout  << "Goodbye" << endl;
  6. }
  7. else if (data != 'X')
  8. {
  9. if (data != 'Y')
  10. {
  11. if (data != 'Z')
  12. cout << "Hello" << endl;
  13. }
  14. }
  15. }
  16. }
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.
Feb 14 '13 #9
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:
Expand|Select|Wrap|Line Numbers
  1. int a, b, c;
  2. cout <<"Give a: "; cin >>a;
  3. cout <<"Give b: "; cin >>b;
  4. cout <<"Give c: "; cin >>c;
  5.  
  6. // VARIATION ONE: NESTED
  7. if (a>05) if (a<11)
  8. {cout <<NL <<"6 to 10";
  9.  if (b>55) if (b<61) cout <<NL <<"56 to 60";
  10.   {if (c>95) if (c<101) cout <<NL <<"96 to 100";
  11.   }
  12. }
  13.  
  14. cout <<NL <<NL;
  15.  
  16. // VARIATION TWO: ONE BRACE SET ONLY
  17. if (a>05) if (a<11)
  18. {cout <<NL <<"6 to 10";
  19.   if (b>55) if (b<61) cout <<NL <<"56 to 60";
  20.   if (c>95) if (c<101) cout <<NL <<"96 to 100";
  21. }
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.
Feb 14 '13 #10
weaknessforcats
9,208 Expert Mod 8TB
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.
Feb 15 '13 #11
divideby0
131 128KB
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.

Expand|Select|Wrap|Line Numbers
  1. if(condition) if(condition) execute statement
  2. if(condition) if(condition) execute statement
  3.  
if you were wanting c dependent on b and b dependent on a, then

Expand|Select|Wrap|Line Numbers
  1. if(a > 5)  if(a < 11)
  2. {
  3.     cout << "6 to 10"; 
  4.  
  5.     if(b > 55) if(b < 61)
  6.     {
  7.         cout << "56 to 60";
  8.  
  9.         if(c > 95) if(c < 101)
  10.             cout << "96 to 100";
  11.     }
  12. }
  13.  
or maybe

Expand|Select|Wrap|Line Numbers
  1. if(a > 5 && a < 11)
  2. {
  3.    cout << "6 to 10";
  4.  
  5.    if(b > 55 && b < 61)
  6.    {
  7.       cout << "56 to 60";
  8.  
  9.       if(c > 95 && c < 101)
  10.          cout << "96 to 100";
  11.    }
  12. }
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.
Feb 15 '13 #12
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.
Feb 15 '13 #13
divideby0
131 128KB
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.

Expand|Select|Wrap|Line Numbers
  1. int a, b, c;
  2.  
  3. for(;;)
  4.    {
  5.        cout << "Enter values for a, b, and c"
  6.             << "\na(6-10); b(56-60); c(96-100)"
  7.             << "\nranges listed to test (-1 to quit): ";
  8.  
  9.        cin >> a;
  10.  
  11.        if(a == -1)
  12.            break;
  13.  
  14.        cin >> b >> c;
  15.  
  16.        if(a > 5)
  17.        {
  18.            if(a < 11)
  19.            {
  20.                cout << "\na) 6 to 10"; 
  21.  
  22.                if(b > 55)
  23.                {
  24.                    if(b < 61)
  25.                    {
  26.                        cout << "\nb) 56 to 60";
  27.  
  28.                        if(c > 95)
  29.                        {
  30.                            if(c < 101)
  31.                                cout << "\nc) 96 to 100\n";
  32.                            else
  33.                                cout << "\nc) max outside range\n";
  34.                        } else
  35.                            cout << "\nc) min outside range; c) max branch excluded\n";
  36.                    } else
  37.                        cout << "\nb) max outside range; c branch excluded\n";
  38.                } else
  39.                    cout << "\nb) min outside range; b) max and c branches excluded\n";
  40.  
  41.            } else
  42.                cout << "\na) max outside range; b and c branches excluded\n";
  43.        } else
  44.            cout << "\na) min outside range; a) max, b and c branches excluded\n";
  45.  
  46.        cout << "\n";
  47.    }
  48.  
Feb 15 '13 #14
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.
Expand|Select|Wrap|Line Numbers
  1. int a, b, c;
  2. cout <<"Give a: "; cin >>a;
  3. cout <<"Give b: "; cin >>b;
  4. cout <<"Give c: "; cin >>c;
  5.  
  6. if (a>05)
  7.  {if (a<11) cout <<NL <<"6 to 10";
  8.    if (b>55)
  9.    {if (b<61) cout <<NL <<"56 to 60";
  10.     if (c>95)
  11.     {if (c<101) cout <<NL <<"96 to 100";
  12.     }
  13.    }
  14.  }
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! ;)
Feb 15 '13 #15
donbock
2,426 Expert 2GB
Regarding the advantages of using braces with if instructions...
A common mistake is to forget that the compiler does not see indentation. These two snippets are different:
Expand|Select|Wrap|Line Numbers
  1. if (a > 10)
  2.    a += 100;
  3.    a *= 10;
  4. printf("%d\n", a);
  5.  
  6. if (a > 10) {
  7.    a += 100;
  8.    a *= 10;
  9.    }
  10. printf("%d\n", a);
Even experienced programmers may fail to notice this error in a 500-line source file.
Feb 16 '13 #16
Just for the info:
That example with "if<condition>&&<condition>" is given in the Operators chapter in its section, only, with emphasis on something else inserted into it (but still easily derivable, if one understands what is being said there).

Now that I will have separate documents even for each section and with all the experimenting in progress, you can say I discovered this number in range-code after KNOWING it. :D

(Hint: Then I would have posted the same to know if everybody knows this "if-&&" code!;)
Mar 4 '13 #17
Ah, forgot to mention one thing though. Well, I discovered it today. Same kind "if" code was not working with "else" that day, but I did not understand this.

Even if you place too many conditions with ifs before an action, an "else" would need one and ONLY one "if" to work, or it won't work. So rest of the ifs would need be in a brace set starting second condition.

And as it seems, in a nested "else if":
Expand|Select|Wrap|Line Numbers
  1. else if (condition1)
  2.  {if (condition 2)
  3.    action;
  4.  }
  5.  
after the first and main "if", the program does not go beyond the first nested "else if", if there are more than one "else ifs". Using if-&& code happens to get you past all the conditions.

I don't know what the hell is the problem. This language is one hell of a nutty problem I've seen. Because this SHOULD work, especially when the first else-if is working.

Thanks
Mar 27 '13 #18
weaknessforcats
9,208 Expert Mod 8TB
You may be making this too hard. There is only an if-else.

Expand|Select|Wrap|Line Numbers
  1. if (condition)
  2. {
  3.     ...true
  4. }
  5. else
  6. {
  7.  ....false
  8. }
You can have a nested if inside either the true or false block . There is no else-if operator. You get this by omitting braces:

Expand|Select|Wrap|Line Numbers
  1. if (condition)
  2. {
  3.     ...true
  4. }
  5. else
  6. {
  7.   if (condition1)
  8.   {
  9.   }
  10. }
which can re-written as:
Expand|Select|Wrap|Line Numbers
  1. if (condition)
  2. {
  3.     ...true
  4. }
  5. else
  6.  
  7.   if (condition1)
  8.   {
  9.   }
  10.  
and then rearranged since whitespace doesn't count:
Expand|Select|Wrap|Line Numbers
  1. if (condition)
  2. {
  3.     ...true
  4. }
  5. else if (condition1)
  6.   {
  7.   }
  8.  
and you sre on your way to a real mess. This style of coding (also known as go-to)beomes increasng hard to follow once several conditions are involved. You lose track of which braces go with which if or which else. The only way to follow it is with a debugger.

The reason for the braces is to enclose multiple statements. When you remove them, the code block stops at the first semi-colon whch limits you to one statement.

Then there's:
Expand|Select|Wrap|Line Numbers
  1. if (10)
  2. {
  3.     ...true
  4. }
  5. else if (condition1)
  6.   {
  7.   }
  8.  
you may find that the compiler ignores the else because 10 is always true. It just drops the code from your program since it can never be reached.
Mar 27 '13 #19
H! WeaknessForCats

Thanks for replying, but I think now this is off the topic in this thread. Since we already resolved the title of this thread, I made a new thread here:
http://bytes.com/topic/c/answers/948...if#post3745814.
Please paste your reply there.

Thanks
Mar 27 '13 #20
And by the way, one may give as many conditions as they want using Logical Operators, AND use as many logical operators too:
Expand|Select|Wrap|Line Numbers
  1. if (condition && condition || condition) action;
  2.  
etc.
***
Apr 2 '13 #21

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: Ken in Melbourne Australia | last post by:
If I use the curly bracket syntax (referred to as the complex syntax) within a string, how do I get to call a function within it? The php manual says that the first (or previous) character for...
699
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro...
14
by: Sandy Norton | last post by:
If we are going to be stuck with @decorators for 2.4, then how about using blocks and indentation to elminate repetition and increase readability: Example 1 --------- class Klass: def...
41
by: John Marshall | last post by:
How about the following, which I am almost positive has not been suggested: ----- class Klass: def __init__(self, name): self.name = name deco meth0: staticmethod def meth0(x):
4
by: Xah Lee | last post by:
while programing in Python, one can lookup syntax or info for keywords or modules within Python. In the command line, type python to get into the python interactive program. then type...
7
by: Joe Weinstein | last post by:
Hi all. Sorry for the basic question... What's the syntax for creating a procedure which simply returns a cursor for "select * from foo"? I am completely illiterate about DB2, and I'm just...
10
by: C# newcomer | last post by:
Hi all Please help me with the C# equivalent syntax for the following C++ code. Thanks a lot in advance. double *firstVal; int secondVal; double thirdVal; int fourthVal; firstVal = new...
0
by: Travis Oliphant | last post by:
This post is to gather feedback from the wider community on PEP 357. It is nearing the acceptance stage and has previously been discussed on python-dev. This is a chance for the wider Python...
7
by: (Jamie Andrews) | last post by:
For a research project, we're looking for a reliable parser for C that will take an ANSI C program and yield a tree representation of the program (as a Java or C++ object). Of course a grammar...
5
by: Budde, Marco | last post by:
We have developed a big library using managed C++. The project started with .NET 1.0 and has been ported to .NET 1.1. Today we ship the library compiled for .NET 1.1 and 2.0. At the moment the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.