adspace


write a program that will accept a number and print.its
equivalent in words the maximum input number is 9999

Answer Posted / Gautam Kishor

Here's an example STL (Standard Template Library) C++ code for converting numbers to words with a maximum input of 9999:

#include <iostream>
#include <string>
#include <vector>

std::vector<std::string> ones = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
std::vector<std::string> tens = {"", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
std::vector<std::string> hundreds = {"", "hundred", "thousand", "lakh", "crore"};

void printWords(int num) {
if (num == 0) {
std::cout << "zero";
return;
}

bool last_one = false;
for (int i = 3; i >= 1; --i) {
int hundreds_part = num / (int)(pow(10, i));
num -= (hundreds_part * pow(10, i));

if (hundreds_part > 0) {
std::cout << hundreds[i];
if (!last_one && hundreds_part != 1) {
std::cout << " and ";
}
last_one = true;

if (hundreds_part > 9 && hundreds_part < 20) {
std::cout << tens[num];
num = 0;
} else if (hundreds_part > 19) {
std::cout << ones[num % 10];
num -= (num % 10);
num /= 10;
std::cout << " hundred and ";
} else if (hundreds_part > 0) {
std::cout << ones[hundreds_part];
std::cout << " hundred";
}
}

if (num > 0 && i != 1) {
if (num < 20) {
std::cout << ones[num];
} else if (num < 100) {
std::cout << tens[num / 10];
int last_digit = num % 10;
if (last_digit > 0) {
std::cout << "-";
}
std::cout << ones[last_digit];
} else if (num < 1000) {
int tens_part = num / 100;
std::cout << tens[tens_part];
int last_two_digits = num % 100;
if (last_two_digits > 0) {
std::cout << "-";
}
if (last_two_digits >= 20 && last_two_digits < 100) {
std::cout << ones[last_two_digits];
} else if (last_two_digits > 9 && last_two_digits < 20) {
std::cout << tens[last_two_digits / 10];
std::cout << "-";
std::cout << ones[last_two_digits % 10];
} else if (last_two_digits > 0) {
std::cout << ones[last_two_digits / 100] << " hundred ";
int last_three_digits = last_two_digits % 100;
if (last_three_digits > 0) {
std::cout << ones[last_three_digits];
}
}
}
}
}
}

int main() {
int num;
std::cout << "Enter a number (max 9999): ";
std::cin >> num;

if (num > 9999 || num < 0) {
std::cout << "Invalid input. Please enter a number between 0 and 9999.";
return 1;
}

printWords(num);
return 0;
}

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

draw a flowchart that accepts two numbers and checks if the first is divisible by the second.

3475


sir please send me bpcl previous question papers

2479