0

I have written this program which asks the user about how many rectangles they wants to print out. It also asks for the width and height of each, and prints the triangles. After asking the height and width of each, it moves onto the next rectangle and so on.

This all works fine using the program I've made but at the end I want to print out the total area of all the rectangles that the user has created. How can I update my code and achieve this? How is it possible to store the area of the first rectangle and add the area of the second to this first area and so on? Here is the code:

size = input("How many rectangles?" ) #asks the number of rectangles 
i=1
n = 1
while i <= size:
    w = input("Width "+str(n)+"? ") #asks for width of each rectangle
    h = input("Height "+str(n)+"? ") #asks for height of each rectangle
    n=n+1
    h1=1
    w1=1
    z = ""
    while w1 <= w:
        z=z+"*"
        w1+=1
    while h1<=h:
        print z
        h1+=1
    i+=1
1
  • mistake wrong tag Commented Oct 8, 2016 at 16:55

2 Answers 2

3

How about you just accumulate the total area?

Above your loop, do:

area = 0

Then, somewhere inside your loop, after you've got w and h from the user, just do

area += w * h

When you finish looping, area will contain the total area.

Sign up to request clarification or add additional context in comments.

1 Comment

I feel stupid for not thinking about that. works just fine
2

This code should really use a for loop instead of a while loop to keep track of counters, keep numbers in variables instead of just "*" strings, and use += instead of x=x+1 in a few places, among other things, but here's a minimal step to solve the total area problem you specifically asked about:

size = input("How many rectangles?" ) #asks the number of rectangles 
i=1
n = 1
area = 0
while i <= int(size):
    w = float(input("Width "+str(n)+"? ")) #asks for width of each rectangle
    h = float(input("Height "+str(n)+"? ")) #asks for height of each rectangle
    n+=1
    h1=1
    w1=1
    z = ""
    while w1 <= w:
        z=z+"*"
        w1+=1
    while h1<=h:
        print(z)
        h1+=1
        area += len(z)
    i+=1
print('total area = ',area)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.