By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,649 Members | 696 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,649 IT Pros & Developers. It's quick & easy.

Help me switch to no if-else coding?

P: 1
Hi all,

I'm working on an assignment and I've been asked to change my code so that I am not using any if or if else coding...

So as of now, my full code works perfecting but uses If Else and I've been trying everything but I can't seem to find a good alternative. Here's a small sample of what I have, I don't want to post the whole thing since I don't want my prof to flag me for plagiarism lol

....

case 2:
cout << endl;
cout << "\t\tCalculate the area of a Rectangle\n\n";
cout << "\tEnter length: ";
cin >> length;

cout << "\tEnter width: ";
cin >> width;
if (length <= 0 || width <= 0)
{
cout << endl;
cout << "\tEnter a positive value.\n\n";

}
else
{
RectArea = length * width;
cout << "\tArea= " << RectArea << " square units.";
}
break;
...

I've used this if else coding for the other sections (case 1 is the circle, case 2 is the rectangle, case 3 is the triangle). Just a basic geometry calculator...

I don't want anyone to do the work for me, I just really need help knowing what alternative I should use. I'm on thin ice with my prof, so I'd rather not ask him... thank you so so so much!
Sep 28 '15 #1
Share this Question
Share on Google+
3 Replies


P: 22
The option I can think of is a ternary operator.
Sep 28 '15 #2

weaknessforcats
Expert Mod 5K+
P: 9,197
Try writing functions.

Expand|Select|Wrap|Line Numbers
  1. struct Rect
  2. {
  3.    int length;
  4.    int width;
  5.  
  6. };
  7.  
  8. Rect r;
  9.  
  10. GetData(&r);   //enter the data
  11. int area = CalcArea(&r);  
  12. DisplayArea(&area);
  13.  
Then you can introduce object based code:

Expand|Select|Wrap|Line Numbers
  1. Rect r;  //the object;
  2.      r.GetData();
  3.      r.CalacArea();
  4.      r.DisplayArea();
  5.  
The thing with if/else coding is that the logic threads don't stay separated. They intertwine to form spaghetti which s nearly impossible to understand.

This is enough hints for now.
Sep 28 '15 #3

Expert 100+
P: 2,398
Another option is to use a loop:
Expand|Select|Wrap|Line Numbers
  1. do {
  2.  length = width = 0;
  3.  cout << "\tEnter length: ";
  4.  cin >> length;
  5.  cout << "\tEnter width: ";
  6.  cin >> width;
  7.  } while ((length <= 0) || (width <= 0));
Sep 28 '15 #4

Post your reply

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