148k views
5 votes
1 procedure base b expansion (n, b: positive integers with b>1)

2
3 q = n
4
5 k:= 0
6
7 while q≠0
8
9 aₖ: qmodb
10
11 q:= gdivb
12
13 k: k+1
14
15 return (base b expansion of n)

Use the pseudocode above to write a C++ program that implements and tests the base conversion algorithm. The program should allow the user to enter a positive integer for n (the decimal value) and a positive integer greater than 1 for b (the base). Finally the program should print on the screen the result of the conversion.
Sample output:
Enter a positive integer: 52
Enter a value for the base: 2
52=110100 base 2

User Darlington
by
8.5k points

1 Answer

2 votes

Final answer:

The provided C++ program asks the user for a positive integer and a base greater than 1 and then outputs the base b representation of that integer.

Step-by-step explanation:

The following C++ program implements a base conversion algorithm based on the procedure outlined in the pseudocode provided by the student. The program allows the user to input a positive integer n and a base b, with b being greater than 1, and outputs the base b representation of the integer n.

#include
#include
#include

int main() {
int n, b;
std::cout << "Enter a positive integer: ";
std::cin >> n;
std::cout << "Enter a value for the base: ";
std::cin >> b;

std::string result = "";
int pos = 0; // Represents the position in the base-b number

// Begin the conversion process
while(n != 0) {
int remainder = n % b;
result += '0' + (remainder > 9 ? remainder - 10 + 'A' : remainder);
n /= b;
pos++;
}

std::reverse(result.begin(), result.end()); // Reverse the string to get the correct order

std::cout << "Base " << b << " expansion of " << n << " is: " << result << std::endl;

return 0;
}

In this code, the algorithm performs division by the base (b) and appends the remainder to the result string, which accumulates the base b digits in reverse order. Afterwards, the string is reversed to get the digits in the correct order, and the base b representation of n is displayed.

User Dweebo
by
9.1k points