Help me switch to no if-else coding?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • SelNasser
    New Member
    • Sep 2015
    • 1

    Help me switch to no if-else coding?

    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\tCalcul ate 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!
  • Clearner321
    New Member
    • Sep 2015
    • 22

    #2
    The option I can think of is a ternary operator.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Try writing functions.

      Code:
      struct Rect
      {
         int length;
         int width;
      
      };
      
      Rect r;
      
      GetData(&r);   //enter the data
      int area = CalcArea(&r);  
      DisplayArea(&area);
      Then you can introduce object based code:

      Code:
      Rect r;  //the object;
           r.GetData();
           r.CalacArea();
           r.DisplayArea();
      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.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Another option is to use a loop:
        Code:
        do {
         length = width = 0;
         cout << "\tEnter length: ";
         cin >> length;
         cout << "\tEnter width: ";
         cin >> width;
         } while ((length <= 0) || (width <= 0));

        Comment

        Working...