Rebekah Lynn Wildes
Rebekah Lynn Wildes

Reputation: 43

Python for loops for repeated addition

I am trying to create a program that creates a multiplication table of n x n. It's required for the assignment to use repeated addition instead of the multiplication function.

This is the code I have so far:

def main():
import math
print('Hello!')
n = (abs(eval(input("Enter n for the multiplication table n x n: "))))
n = int(n)
a = 0
for i in range(1,n+1):
    for x in range(1,n+1):
        a = i+a
        print(i,' * ',x,' = ',a)
main()

It gives me an output like this:

Hello!
Enter n for the multiplication table n x n: 4
1  *  1  =  1
1  *  2  =  2
1  *  3  =  3
1  *  4  =  4
2  *  1  =  6
2  *  2  =  8
2  *  3  =  10
2  *  4  =  12
3  *  1  =  15
3  *  2  =  18
3  *  3  =  21
3  *  4  =  24
4  *  1  =  28
4  *  2  =  32
4  *  3  =  36
4  *  4  =  40

The output is obviously incorrect, so what can I change/add to fix the calculations?

Upvotes: 3

Views: 4949

Answers (3)

user5710871
user5710871

Reputation:

In your for loop, you're always incrementing the variable 'a' by itself added to 'i' each time, instead you should multiply i*x

print("Hello!")

n = input("Enter n for the multiplication table n x n: ")
n = int(n)

result = 0

for i in range(1,n+1):
    for j in range(1, n+1):
        result = i*j
        print(i," * ", j, " = ", result)

Upvotes: 0

Lavaman65
Lavaman65

Reputation: 863

You have a variable a inside of your nested for loops that you continuously add values to for different values of the multiplication table. Instead of adding i to a each iteration, let a = i*x. This will give you the correct value of multiplication each time. However, if you really want to do it with repeated addition, set a = 0 outside of the second for loop, but inside the first, like so:

for i in range(1,n+1):
    for x in range(1,n+1):
        a = i+a
        print(i,' * ',x,' = ',a)
    a = 0

Upvotes: 5

mmghu
mmghu

Reputation: 619

For the print statement try using instead:

print(i,' * ',x,' = ',i*x)

I'm not certain what you are using the 'a' variable for, but if you'd like to output the multiplication of i and x still using a, instead keep your code the same and just change what you have for a in your nest for loop:

a = i*x

Hope this helps!

Upvotes: 0

Related Questions