areas of rectangles

i just finished this problem but i feel the code could be better improved and simplified. can anybody help me out? this program finds which of the two rectangles has a bigger area

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
   int length, width,area;
    int length2, width2,area2;
    
    cout << "what is the length of the rectangle"<<endl;
    cin >> length;
    
    cout << "what is the width of the rectangle"<<endl;
    cin >> width;
    
    area = length * width;
    
    cout << "what is the length of the second rectangle?"<< endl;
    cin >> length2;
    
    cout << "what is the width of the second rectangle? "<<endl;
    cin >> width2;
    
    area2 = length2 * width2;
    
    if ( area > area2)
        cout << "the first rectangle has a bigger area"<<endl;
    else
        cout << "the second rectangle has a biggger area"<<endl;
    
    
    
    
    
i guess i can just use the conditional operator instead of ( if / else statement)
You could combine the entry of the length and width together.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int length, width,area;
    int length2, width2,area2;
    
    //They need to put a space in between the two numbers
    cout << "what is the length and width of the rectangle"<<endl;
    cin >> length;
    cin >> width;
    
    area = length * width;
    
    cout << "what is the length and width of the second rectangle?"<< endl;
    cin >> length2;
    cin >> width2;
    
    area2 = length2 * width2;
    
    if ( area > area2)
        cout << "the first rectangle has a bigger area"<<endl;
    else
        cout << "the second rectangle has a biggger area"<<endl;
i didn't even think of combining them. thanks!
You just need to make sure there is a space between the two numbers.

You can also combine the int declarations if you want. It might be easier to keep them separated though.
Last edited on
If just trying to make code more compact get rid of area and area2. Then change last part to,
cout << "The " << ((length * width) > (length2 * width2) ? "first" : "second ") << "rectangle has a bigger area\n";
Vidus, great suggestions that work well! But then I accidentally entered two rectangles of the same area and realized that there was a third possibility, so had to resort to longer code! Donnie
closed account (NyhkoG1T)
The ability to resist being a smart ass eludes me

1
2
int length,length2,width,width2,area,area2;cout<<"what is the length and width of the rectangle"<<endl;cin>>length;cin>>width;area=length*width;cout<<"what is the length and width of the second rectangle?"<<endl;cin>>length2;cin>>width2;area2=length2*width2;if(area>area2){cout<<"the first rectangle has a bigger area"<<endl;}else{cout<<"the second rectangle has a biggger area"<<endl;}


All white space removed. Its a one-liner! :D
Topic archived. No new replies allowed.