C++ Array to one Int variable [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am curently working on one project, it's a converter... i am currently looking at Decimal to Hexadecimal. The code so far looks like this:
int rest;
int arr[50];
int i;
cout << N << " in decimal after conversation ";
while (N>0){
rest=N%16;
if (rest>9){
switch (rest){
case 10:
arr[i]='A';
break;
case 11:
arr[i]='B';
break;
case 12:
arr[i]='C';
break;
case 13:
arr[i]='D';
break;
case 14:
arr[i]='E';
break;
case 15:
arr[i]='F';
break;
}
}
else {
arr[i]=rest;
}
N=N/16;
i+=i;
}
cout<<arr;
return 1;
It's in function so dont be troubeled about the return 1...
my Question is:
is there any way possible to pull the whole array (for example containig [4,2,K,8] into one single variable? In the same exact order!
EDIT
aaaaaaaaaaaaaaaaaaaaaaaaaaand I'm back :D
i made a few changes to the program and now it is working and it goes like this:
int DecToHex(long long N)
{
int rest;
string s="";
while (N>0){
rest=N%16;
if (rest>9){
switch (rest){
case 10:
s="A"+s;
break;
case 11:
s="B"+s;
break;
case 12:
s="C"+s;
break;
case 13:
s="D"+s;
break;
case 14:
s="E"+s;
break;
case 15:
s="F"+s;
break;
}
}
else {
s = char(rest + 48) + s;
}
N=N/16;
}
if (s == "")
cout << "0";
else
cout << s;
return 1;
}
any idea how i could convert hexadecimal number to binary? the hexadecimal can be in string but the binary needs to be in int.
the structure of the program shoud be simmiliar to the this one of mine.
bud thnak's to everyone for the help!

is there any way possible to pull the whole array (for example containig [4,2,K,8] into one single variable?
You could use a std::string and pretend that it is one single variable but it is only an enhanced version of an array of chars.
BTW, couple of points that are unrelated to the above question.
You can simplify the switch statement. This was pointed out in a comment by #Kevin.
Use of arr[i]=rest; is wrong. It needs to be arr[i]=rest+'0';. This was pointed out in a comment by #scohe001.
Here's an updated version of the loop:
while ( N > 0 ) {
rest = N%16;
if (rest > 9){
arr[i] = 'A' + rest - 10;
}
else {
arr[i] = '0' + rest;
}
N = N/16;
i += i;
}
You can make that still simpler by using the suggestion by #Jarod:
char const* hex_letters = "0123456789ABCDEF";
while ( N > 0 ) {
rest = N%16;
arr[i] = hex_letters[rest];
N = N/16;
i += i;
}

Related

how to print multiple numbers to words

in my code, i don't understand why zero doesn't print i did all possible solutions that I know but it doesn't print zero.
#include <iostream>
using namespace std;
int main(){
int digits;
int numberOne = 0;
int integer;
cout<<"Enter the number: ";
cin>>digits;
while (digits != 0) {
numberOne = (numberOne * 10) + (digits % 10);
digits /= 10;
}
for (integer = numberOne; integer > 0; integer = integer / 10){
switch (integer % 10) {
case 0:
cout<<"Zero\n";
break;
case 1:
cout<<"One\n";
break;
case 2:
cout<<"Two\n";
break;
case 3:
cout<<"Three\n";
break;
case 4:
cout<<"Four\n";
break;
case 5:
cout<<"Five\n";
break;
case 6:
cout<<"Six\n";
break;
case 7:
cout<<"Seven\n";
break;
case 8:
cout<<"Eight\n";
break;
case 9:
cout<<"Nine\n";
break;
}
}
return 0;
}
zero doesn't print how do I fix it?
Expected output is 900 (nine zero zero) but zero doesn't print in my case. help thanks.
Because in this line:
for (integer = numberOne; integer > 0; integer = integer / 10){
the loop continues only if integer>0. Therefore you never see "Zero".
Why doesn't it print zero? Look at your loop
for (integer = numberOne; integer > 0; integer = integer / 10){
If integer equals zero then the loop is never entered. You need to be a bit smarter in your loop. How about counting digits?
int num_digits = 0;
while (digits != 0) {
numberOne = (numberOne * 10) + (digits % 10);
digits /= 10;
++num_digits;
}
Now that you have the number of digits, you can use that in your second loop
for (integer = numberOne; num_digits > 0; integer = integer / 10, --num_digits) {
...
}
You still need to treat zero as a special case, because if the user enters 0 then num_digits will equal zero and you again won't print anything. I'll leave you to figure out how to fix that.
#include <iostream>
using namespace std;
int main(){
int digits;
int arrayLength = 10;
cout<<"Enter the number: ";
cin>>digits;
string reverse_number[arrayLength]; //array to store the string of numbers like "Zero"
int array_counter=0;
while (digits != 0) {
switch (digits % 10) {
case 0:
reverse_number[array_counter++] = "Zero";
break;
case 1:
reverse_number[array_counter++] = "One";
break;
case 2:
reverse_number[array_counter++] = "Two";
break;
case 3:
reverse_number[array_counter++] = "Three";
break;
case 4:
reverse_number[array_counter++] = "Four";
break;
case 5:
reverse_number[array_counter++] = "Five";
break;
case 6:
reverse_number[array_counter++] = "Six";
break;
case 7:
reverse_number[array_counter++] = "Seven";
break;
case 8:
reverse_number[array_counter++] = "Eight";
break;
case 9:
reverse_number[array_counter++] = "Nine";
break;
}
digits /=10;
}
int num_digits = array_counter;
for (int i = 0; i < num_digits; i++) {
cout << reverse_number[--array_counter] <<" ";
}
return 0;
}
The reason why your zeros are not showing while doing for 900 is because when you are reversing 900 to 009, there is no condition mentioned to handle the leading zeros in 009 which are just ignored. For this the best approach would be to store them somewhere else like in a string or an array. You can also just store the number words directly to an array while you are converting, that way you wont lose the leading zeros.
The other answers have already addressed the main problem with your code.This answer focus on the post's title: how to print multiple numbers to words?
First, I would consider using an array of strings instead of a switch.
In order to retrieve a string for a given digit, you would just index that array.(see digits[c - '0'] below)
Also, if you are allowed to convert a number to a string, the code would reduce to walking that string and converting each character to a word.You could read the number directly as a string from the standard input, or use std::to_string on an integer.
Notice also that, when reading a character c from the a string of digits, c - '0' gives you an integer betweeen 0 and 9, which you can use as the array index.
Demo
#include <array>
#include <iostream>
#include <string> // to_string
std::array<std::string, 10> digits{
"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"
};
void digits_to_words(int n) {
for (unsigned char c : std::to_string(n)) {
std::cout << digits[c - '0'] << "\n";
}
}
int main() {
for (int n : { 0, 5, 105, 900 }) {
std::cout << "Number: " << n << "\n";
digits_to_words(n);
std::cout << "\n";
}
}

Switch Statement with multi-dimensional array

I have the following switch statement that actually works fine.
for (n = 0; n < 10; n++){
switch(results[r][n]){
case 0:
result[r][n] = "FAIL";
break;
case 1:
result[r][n] = "PASS";
break;
default:
break;
}
}
my question is WHY does this work, is it supposed to work or is there a much better way of doing this?
Is this how you are supposed to implement multi-dimensional arrays within a switch?
(r = 0 or 1)
How does the compiler know whether case 0: refers to r or n?
case 0 refers to results[r][n], not r or n. The values after case are matched to the value of the expression in the switch().
Look at a tutorial on switch-case
Your switch statement
switch(results[r][n]) {
case 0:
result[r][n] = "FAIL";
break;
case 1:
result[r][n] = "PASS";
break;
default:
break;
}
is equivalent to:
if (results[r][n] == 0)
result[r][n] = "FAIL";
else if (results[r][n] == 1)
result[r][n] = "PASS";
else
// do nothing
To anyone who was confused by the assignment of a string to something that should be an integer array, results is the integer[] array, result is a different variable that's a string[] array. As Robert notes below in the comments, a better naming system seems to be in order here.

Can anyone explain this function definition above the switch statement?

Here, I've made a function, that takes a character array and a single element array as input.
The input of expression is like "56+78", and then someone suggested this approach of using ascii code and for loops to store the two "numeric" substrings as two numbers, and used the character and switch statement below. But, I don't understand the part of storing these substrings as numbers and the asciicode concept.
void calculate(char ch[], char op[]){
int i;
int num1 = 0, num2 = 0;
for(i=0; ch[i]!='\0';i++)
{
if((int)ch[i]>=48 && (int)ch[i]<=57){
num1 = num1*10+(((int)ch[i])-48);
}
else{
op[0]=ch[i];
break;
}}
i++;
for(; ch[i]!='\0';i++)
{
if((int)ch[i] >= 48 && (int)ch[i] <= 57){
num2 = num2*10+(((int)ch[i])-48);
}
}
cout<<"OUTPUT: ";
switch(op[0])
{
case '+':
cout<<num1 + num2<<endl;
break;
case '-':
cout<<num1 - num2<<endl;
break;
case '*':
cout<<num1 * num2<<endl;
break;
case '/':
cout<<num1 / num2<<endl;
break;
}
}

Function to convert decimal to hex value (error in my program) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
This is just a pretty simple function to convert decimal to hex. I just wanted to store the numbers (0-9) into a string, and then wrote a simple function to retrieve the letter-values for numbers 10-16. For some reason, the compiler is saying that the retriveHexChar function is not declared in scope (when I use it in my decimalToHex function). There also may be other issues with my program/functions.
#include <iostream>
#include <string>
using namespace std;
char retrieveHexChar(int num);
void decimalToHex(int number, string s);
int
main()
{
string s;
int num = 235;
decimalToHex(num, s);
}
void
decimalToHex(int number, string s)
{
if (number > 0) {
int temp = number % 16;
s += temp;
number = number / 16;
if (temp >= 10)
s += retriveHexChar(temp);
decimalToHex(number, s);
}
for (int i = s.length(); i > 0; i--)
cout << s[i];
}
char
retrieveHexChar(int num)
{
char tempChar;
switch (num) {
case '10':
tempChar = 'A';
break;
case '11':
tempChar = 'B';
break;
case '12':
tempChar = 'C';
break;
case '13':
tempChar = 'D';
break;
case '14':
tempChar = 'E';
break;
case '15':
tempChar = 'F';
break;
}
return tempChar;
}
Your function declaration is:
char retrieveHexChar(int num);
The bogus call is:
retriveHexChar(temp);
You probably meant:
retrieveHexChar(temp);
// ^
Also, case '10': is a mistake. Although it compiles, it checks for a multi-byte character constant. You probably meant case 10: .

Write multiple things in a switch statement in C

So i need to have my switch statement go through and write out five two if the user says 52 but i cannot get it pass my 0-9. if they type 0-9 it works perfect but if i try to do any number past that it makes a blank. help!
#include <stdio.h>
int main (void)
{
int x;
printf("Please enter an integer: ");
scanf("%d", &x);
printf("\nYou have entered:\n\n");
for(x;x<0;x++);
switch (x)
{
case 0:
printf("zero");
break;
case 1:
printf("one");
break;
case 2:
printf("two");
break;
case 3:
printf("three");
break;
case 4:
printf("four");
break;
case 5:
printf("five");
break;
case 6:
printf("six");
break;
case 7:
printf("seven");
break;
case 8:
printf("eight");
break;
case 9:
printf("nine");
break;
}
printf("\n\n");
return 0;
}
do {
switch (x%10) {
...
}
x = x / 10;
} while (x>0) ;
or to get it in the right order use recursion
void f(int x) {
if (x==0) return;
f(x/10);
switch(x%10) { ... }
}
This question has been asked-and-answered before.
The for-loop you wrote is empty, because the body of the loop ends with the semi-colon:
for(x;x<0;x++) /* Empty Body!!*/ ;
The way a typical for loop works is:
for( /*Initialize*/; /*Test*/; /*Change*/)
{
/* Body */
}
In your case, I think you want:
for(int i=0; i < x; ++i)
{
switch(x)
{
[...]
}
}
This will:
Initialize i to 0
Test if i is LESS THAN x (the number you entered)
Keep increasing i by 1, until it gets up to x.
I'm not going to do your homework for you but consider the following pseudo-code:
print_text_digits(x)
{
if (x >= 10) print_text_digits(x / 10);
switch (x) {
print "zero" through "nine" as appropriate
}
}
main()
{
scan number into x;
print_text_digits(x);
}
This relies on a recursive routine so that you get your digits processed one at a time, with the might significant digit printed first.
You could solve this with recursion.
void printDigit(int x) {
int digit = x%10;
if(digit!=x)
printDigit(x/10);
switch(digit) {
...
}
}
This will print the most significant figure first, unlike the while loops most people are mentioning.
I believe you need this:
#include <stdio.h>
int main (void)
{
int count = 0;
int x, count2;
printf("Please enter an integer: ");
scanf("%d", &x);
printf("\nYou have entered:\n\n");
int aux = x;
while(aux>0) {
aux=aux/10;
count++;
}
count2 = count;
while(count) {
aux = x;
for(int i=count-1;i>0;i--)
aux=aux/10;
for(int i=count2-count;i>0;i--)
aux%=10;
switch (aux) {
case 0:
printf("zero");
break;
case 1:
printf("one");
break;
case 2:
printf("two");
break;
case 3:
printf("three");
break;
case 4:
printf("four");
break;
case 5:
printf("five");
break;
case 6:
printf("six");
break;
case 7:
printf("seven");
break;
case 8:
printf("eight");
break;
case 9:
printf("nine");
break;
}
count--;
if(count) printf(" ");
}
printf("\n\n");
return 0;
}
Now, with an input 52 it will propelly return five two.
#include <stdio.h>
static const char * const num[] = {
"zero ", "one ", "two " , "three ", "four ",
"five ", "six ", "seven ", "eight ", "nine "
};
void printNum(int x)
{
if (x < 10) {
printf(num[x]);
return;
}
printNum(x / 10);
printNum(x % 10);
}
int main (void)
{
int x;
printf("Please enter an integer: ");
scanf("%d", &x);
printf("\nYou have entered:\n\n");
printNum(x);
return 0;
}
Here's what you need to do. Similar to what #simonc said, it's a good idea to convert the user input to a string, then loop through the characters. For each character, convert it into an int and then take that into the switch statement.
EDIT---------------------------
Here's a way with strictly using integers.
First find how many digits your integer has. You can do this by a method mentioned here.
Then do integer division starting from the largest power of 10 that divides the integer you have and divide the divisor by 10 until you reach 1. For example:
If user input is 213, it has 3 digits. We divide this by 100 first.
213/100 = 2
We take the 2 and put it into the switch statement, outputting 2. Now we're done with the hundreds digit, so now we take the 13 from 213 and divide it by 10.
13/10 = 1 So now we output one.
Keep doing this process until you get to the ones digit.
Does this make sense?