Write a program to calculate the product of two number inputted integers without using * operator, instead using repeated addition

Python Loop control in Python (Article) Loop control in Python (Program)

103

Here is a Python program to calculate the product of two inputted integers without using the * operator, instead using repeated addition:

Program:

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

product = 0
for i in range(num2):
    product += num1

print("The product of", num1, "and", num2, "is", product)

Output:

Enter the first number: 5
Enter the second number: 3
The product of 5 and 3 is 15

Explanation:

In this program, we first prompt the user to enter two integer numbers using the input() function and convert them to integers using the int() function. We then initialize a variable product to 0, which will store the final product of the two numbers.

Next, we use a for loop to iterate over the range of numbers from 0 to num2 (exclusive). For each iteration of the loop, we add num1 to product, which is equivalent to multiplying num1 by the current iteration number. Since we are iterating num2 times, the final value of product will be the product of num1 and num2.

Finally, we print out the result using the print() function.

This program demonstrates the sequential flow of execution in Python, where the statements are executed in the order in which they appear in the code. The for loop causes the statements inside the loop (i.e., the repeated addition of num1 to product) to be executed num2 times, resulting in the final product.

Here's the same program using a while loop instead of a for loop:


num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

product = 0
i = 0
while i < num2:
    product += num1
    i += 1

print("The product of", num1, "and", num2, "is", product)

In this version of the program, we use a while loop instead of a for loop to iterate over the range of numbers from 0 to num2 (exclusive). We initialize the variable i to 0 before the loop, and increment it by 1 in each iteration until it reaches num2. The statements inside the loop (i.e., the repeated addition of num1 to product) are executed as long as i is less than num2.

The rest of the program is the same as before: we prompt the user to enter two integer numbers, convert them to integers using the int() function, and calculate the product of the two numbers using repeated addition. We then print out the result using the print() function.


This Particular section is dedicated to Programs only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.