In this program, we will convert a number in characters. We will ask the user to enter a number and then convert it to characters.The input must be an integer which is small in size.
Sample examples
Before we discuss the approach and write the code, let's consider some examples to convert a number in characters.
The path to this program is straightforward. Note: Input must be an integer.
First, we will reverse the number using c++ operators.
Then we will get the last digit of the number using c++ loops and operators.
After getting each digit, we use a switch case to print numbers in characters.
After that, we will divide the number by 10 to get the next digit.
The loop continues till the number is greater than 0.
Implementation in C++
#include<iostream>
using namespace std;
void NumtoChar(int x)
{
int r = 0, a = 0;
while (x > 0) {
a = x % 10;
r = r * 10 + a;
x = x / 10;
}
while (r > 0) {
a = r % 10;
switch (a) {
case 1:
cout << "ONE ";
break;
case 2:
cout << "TWO ";
break;
case 3:
cout << "THREE ";
break;
case 4:
cout << "FOUR ";
break;
case 5:
cout << "FIVE ";
break;
case 6:
cout << "SIX ";
break;
case 7:
cout << "SEVEN ";
break;
case 8:
cout << "EIGHT ";
break;
case 9:
cout << "NINE ";
break;
case 0:
cout << "ZERO ";
break;
default:
cout << "inValid Input ";
break;
}
r = r / 10;
}
}
int main()
{
int x;
cout<<"enter a number that is greater than 0 :"<<endl;
cin>>x;
NumtoChar(x);
return 0;
}
You can also try this code with Online C++ Compiler
What is the difference between switch cases and loops in c++?
Switch case
loops
It is a condition checker.
It is an iterator.
It executes the one selected case, and it's done.
It runs the given code n times.
What are arithmetic operators in c++?
Arithmetic Operators are symbols that perform mathematical operations on variables.
Some of the commonly used operators are
Addition operator: +
Subtraction operator: -
Multiplication operator : *
Division operator: /
Modulo operator: %
What is use of cout in c++ code?
Cout is an object used to print output to standard output devices. It is declared in the header file known as iostream.h
Conclusion
In this article, we have discussed the problem of converting a number in characters. We have discussed the solution to this problem coded in C++ language. We have also discussed the time complexity of the approach.
We hope that this blog has helped you enhance your knowledge regarding program to find first non-repeating character in a given string and if you would like to learn more, check out our articles on c++. Do upvote our blog to help other ninjas grow. Happy Coding!”