Answer to Question #161891 in C++ for Rahul

Question #161891

Write a program which multiplies an N digit number M by a 1 digit number d, where N could be large, e.g. 1000. The input will be given as follows. First, the user gives d, then N and then the digits of M, starting from the least significant to the most significant. The program must print out the digits of the product one at a time, from the least significant to the most significant.

Hint: Mimic the process of manual multiplication. Keep track of the current carry in a variable and update it as you go along.


1
Expert's answer
2021-02-07T08:55:12-0500

Here's result, you can see result of multiplication by looking at digits in console from bottom to top (least significant will be printed as "Next result digit:" first)

#include <iostream>

int main() {
	int d, N;
	std::cout << "Enter multiplier d value: ";
	std::cin >> d;
	std::cout << "Enter number of digits N: ";
	std::cin >> N;

	int curDigit, carry = 0;
	std::cout << "Beginning multiplication...\n";
	while (N-- > 0) {
		std::cout << "Enter next digit of M: ";
		std::cin >> curDigit;
		int prod = curDigit * d + carry;
		carry = prod / 10;
		std::cout << "Next result digit: " << prod % 10 << std::endl;
	}
	if (carry > 0) {
		std::cout << "Last result digit: " << carry << std::endl;
	}
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog