Decimal to Binary conversion using recursion with while loop - c

my binary conversion doesn't work after it recurs a second time, it seems to work only during the first time through. The purpose of the is have a user input a number to convert to Hex, Octal, and brinary from a integer and keep on asking and converting until the user inputs 0. Please help!
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
long toBinary(int);
int main(void) {
int number = 0;
long bnum;
int zero = 0;
while(number != zero) {
puts("\nPlease enter a number you would like to convert to");
puts("\nHexadecimal, octal, and binary: ");
scanf("%d", &number);
if(number != zero) {
printf("\nThe Hexadecimal format is: %x", number);
printf("\nThe Octal format is: %o", number);
bnum = toBinary(number);
printf("\nThe binary format is: %ld\n", bnum);
}
else {
puts("\nI'm sorry you have to enter a number greater than 0.\n");
puts("\nOr have enter an invalid entry.");
}
}
return 0;
}
long toBinary(int number) {
static long bnum, remainder, factor = 1;
int long two = 2;
int ten = 10;
if(number != 0) {
remainder = number % two;
bnum = bnum + remainder * factor;
factor = factor * ten;
toBinary(number / 2);
}
return bnum;
}

You just need a function to convert an integer to its binary representation.
Assuming the int is 32 bits then this should work:
#include <stdio.h>
int main()
{
char str[33];
str[32] = 0;
int x = 13, loop;
for (loop = 31; loop >= 0; --loop) {
str[loop] = (x & 1) ? '1' : '0';
x = x >> 1;
}
printf("As %s\n", str);
return 0;
}
You can make this into a function, read x etc...
EDIT
For octal/hex - printf will do this for you
EDIT
Here goes recursively
#include <stdio.h>
void PrintBinary(int n, int x) {
if (n > 0) {
PrintBinary(n - 1, x >> 1);
}
printf("%c",(x & 1) ? '1' : '0');
}
int main()
{
PrintBinary(32,12);
return 0;
}

First of all I am surprised it even works once. Firstly, your while condition is while number does not equal zero. But right off the bat, number equals 0 and zero equals 0. Therefore the while should never run. If you want to keep this condition for the main loop, change it to a do-while loop: do { //code } while (number != zero);. This will run the code at least once, then check if the inputted number doesn't equal zero. That brings me to the next issue; your scanf for number is scanning for a double and placing it in a regular integer memory spot. Quick fix: scanf("%i",&number);. Also I am finding some functions called puts.. I find it best to keep with one printing function, printf. Now, I am finding afew errors in your toBinary function, but if it works than I guess it works. These are all the errors i could find, I hope this helped. But for future reference there is no need to declare a variable for a const number like 2 or 10 at this level.

#include <stdint.h>
char* toBinary(int32_t number, int index){
static char bin[32+1] = {0}, *ret;
if(index == 32){
memset(bin, '0', 32);
return toBinary(number, 31);
} else if(number & (1<<index))
bin[31-index] = '1';
if(index)
(void)toBinary(number, index-1);
else
for(ret = bin; *ret == '0';++ret);
return ret;
}
...
int number = -1;
...
printf("\nThe binary format is: %s\n", toBinary(number, 32));

Related

How to make a binary to decimal program in C?

For some reason the program is not working when I try to run it and I can't figure it out. I'd appricate any help. Homework stuff, so I have to stick to the very basics.
#include <stdio.h>
long long int decimal(long long int);
int power_2 (int);
long int power_10 (int);
int main(void){
long long int n;
while(1){
printf("Write down a binary number. \n");
scanf("%lld", &n);
long long int a = decimal(n);
printf("The binary number %lld converted into decimal is: %lld \n", n, a);
}
}
//Here what I realized is if let's say I have the number 1001, then I subtract 1 and divide by 10, the remainder is going to be 0, meaning it will "jump" on the second if statement. I don't really know how to solve it.
long long int decimal(long long int e){
long long int result;
long long int k = 0;
int i;
for(i=0; i>=0; i++){
if(e % 10 == 1){
k += power_2(i);
e--;
if(e != 0){
e /= 10;
}
}
if(e % 10 == 0){
e /= 10;
if(e==0){
break;
}
}
return(k);
}
//This function should work, so it's not a problem
int power_2(int n){
int base = 2, i, result = 1;
if(n>0){
for(i=1; i<=n; i++){
result *= base;
}
}
if(n=0){
result = 1;
}
return(result);
}
//This is just something I thought I would need but no
long int power_10(int n){
int base = 10, i, result = 1;
if(n>0){
for(i=1; i<=n; i++){
result *= base;
}
}
if(n=0){
result = 1;
}
return(result);
}
You can't use scanf with %lld to input a binary number string (e.g. 10101010101010101010101010101010101). It will interpret the number incorrectly.
You have to accept it as a char string (e.g).
char str[100];
scanf("%s",str);
But, scanf is problematic because it can overflow str. And, IMO, the "usual" remedy of:
scanf("%99s",str);
Is a hack [because if we ever change to (e.g.) char str[80]; then we have to manually change the scanf as well].
Better to use fgets:
char str[100];
fgets(str,sizeof(str),stdin);
str[strcspn(str,"\n")] = 0;
Then, loop on the string. No need for power* functions. You want:
long long int decimal(const char *e){
Loop on e and do: k <<= 1;
Here is the refactored code:
#include <stdio.h>
#include <string.h>
long long int
decimal(const char *e)
{
long long int result = 0;
for (int chr = *e++; chr != 0; chr = *e++) {
result <<= 1;
switch (chr) {
case '0':
case '1':
result += (chr - '0');
break;
default:
fprintf(stderr,"decimal: not a binary digit -- chr='%c'\n",chr);
break;
}
}
return result;
}
int
main(void)
{
char str[100];
while (1) {
printf("Write down a binary number.\n");
if (fgets(str,sizeof(str),stdin) == NULL)
break;
// strip newline
str[strcspn(str,"\n")] = 0;
long long int a = decimal(str);
printf("The binary number '%s' converted into decimal is: %lld (hex: %llX)\n",
str, a, a);
}
return 0;
}
Here is some sample output:
Write down a binary number.
110010111001
The binary number '110010111001' converted into decimal is: 3257 (hex: CB9)
Write down a binary number.
UPDATE:
Apart from the possibility of "overfilling" the register with bits (accepting a string that is more than 32 or 64 'bits'), someone here on SO recently pointed out that left shifting (possibly into the sign bit) a "signed" value can invoke UB... –
Fe2O3
I'm not sure it's UB (depending on the context). But, to keep the peace, here's a version that sets errno:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#ifndef UNSIGNED
#define UNSIGNED 0
#endif
#if UNSIGNED
typedef unsigned long long num_t;
#define FMT "%llu"
#else
typedef long long num_t;
#define FMT "%lld"
#endif
num_t
decimal(const char *e)
{
int count = 0;
long long int result = 0;
errno = 0;
// NOTE: use of error codes is arbitrary
for (int chr = *e++; chr != 0; chr = *e++) {
result <<= 1;
if (++count > (63 + UNSIGNED)) {
fprintf(stderr,"decimal: too many digits\n");
errno = E2BIG;
break;
}
switch (chr) {
case '0':
case '1':
result += (chr - '0');
break;
default:
fprintf(stderr,"decimal: not a binary digit -- chr='%c'\n",chr);
errno = EINVAL;
break;
}
if (errno)
break;
}
return result;
}
int
main(void)
{
char str[100];
while (1) {
printf("Write down a binary number.\n");
if (fgets(str,sizeof(str),stdin) == NULL)
break;
// strip newline
str[strcspn(str,"\n")] = 0;
num_t a = decimal(str);
printf("The binary number '%s' converted into decimal is: " FMT " (hex: %llX)\n",
str, a, a);
}
return 0;
}
Caveat: The following is off topic for this question, but, in response to the comments below ...
Neither of those, although... No, the DV for braces (not an anonymous drive-by shooting!) was for stackoverflow.com/a/74010599/17592432, the most trivial game on the planet... :-) /sigh/ –
Fe2O3
I agree that leaving off the curly braces is not ambiguous. But, I would add them for human clarity. Note that GNU indent complains about premature EOF when trying to indent the code.
But, I eschew if/else ladder logic. In your block, using an if and then switch/case would be clearer, IMO.
And, I've never liked else if because to me, to properly indent it, we'd have:
if (user == robot)
printf("It's a tie!");
else
if (user == 1)
if (robot == 2)
printf("Robot wins by choosing Paper!");
else
printf("User wins by choosing Rock!");
else
if (user == 2)
if (robot == 1)
printf("User wins by choosing Paper!");
else
printf("Robot wins by choosing Scissors! ");
else
if (user == 3)
if (robot == 2)
printf("User wins by choosing Scissors!");
else
printf("Robot wins by choosing Rock!");
So, [to further muddy the waters] I prefer using do { ... } while (0):
do {
if (user == robot) {
printf("It's a tie!");
break;
}
if (user == 1) {
if (robot == 2)
printf("Robot wins by choosing Paper!");
else
printf("User wins by choosing Rock!");
break;
}
if (user == 2) {
if (robot == 1)
printf("User wins by choosing Paper!");
else
printf("Robot wins by choosing Scissors! ");
break;
}
if (user == 3) {
if (robot == 2)
printf("User wins by choosing Scissors!");
else
printf("Robot wins by choosing Rock!");
break;
}
} while (0);
UPDATE #2:
May at least want to mention POSIX and _t types (I'm guilty as charged on the use as well) –
David C. Rankin
Sigh, I was hoping to have a quiet day ;-)
First, I like [love] POSIX (vs. ISO/C). But, claiming all *_t and all _* as POSIX only is hubris.
The _* [for private functions] is quite common in other languages (e.g. python).
As to *_t types, I've been doing that for decades and never once hit a conflict. And, if I did, it's my responsibility as the programmer to fix that [by changing my code or the #include statements]. That is, assess the risks beforehand.
Worse, I also do (e.g.) typedef struct foo foo_t, *foo_p;. Note the *_p for a pointer type that seems to burn people here on SO.
But, it's arguably no worse that MS/Win's pType for pointers. And, it's my convention. And, it's passed code reviews plenty of times.
So, as Nixon once said (re. "Checkers"): Regardless of what they say about it, we're gonna keep it.
#ifndef MUST_REINVENT_THE_WHEEL
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
char str[100];
printf("Write down a binary number. \n");
fgets(str,100,stdin);
printf("Decimal: %ld\n", strtol(str,0,2));
}
#endif
You want to accept an integer value that is the sum of 10^x
Eg 10^6 + 10^4 + 10^2 + 10^1 = 1010110 (base 10)
Then interpret that as a series binary bits
2^6 + 2^4 + 2^2 + 2^1 = 1010110 (base 2)
You're on the right path with dividing by ten, but I get lost in the confusing code that you've written. Here's a simple sample that seems to work (using long with my 32 bit compiler.) It combines bit-shifting and divide-by-ten, and testing whether-or-not to set the current bit in the output accumulator.
int main() {
long in = 10110101, wrk = in;
unsigned long out = 0;
for( unsigned long bit = 1; wrk; wrk /= 10, bit <<= 1 )
if( wrk & 1 )
out |= bit;
printf( "in %ld out %ld (hex %X )\n", in, out, out );
return 0;
}
in 10110101 out 181 (hex B5 )
Testing for negative values seems silly in this "toy" application. There's no way the range of 2^32 can accommodate 10^32.
Turned out my program was pretty much correct. Only thing I missed is the second if in the decimal function should be an else if.
Here's the correct program:
#include <stdio.h>
long long int decimal(long long int);
int power_2 (int);
int main(void){
long long int n;
while(1){
printf("Write down a binary number. \n");
scanf("%lld", &n);
long long int a = decimal(n);
printf("The binary number %lld converted into decimal is: %lld \n", n, a);
}
}
long long int decimal(long long int e){
long long int k = 0;
int i;
for(i=0; i>=0; i++){
if(e % 10 == 1){
k += power_2(i);
e--;
if(e != 0){
e /= 10;
}
}
else if(e % 10 == 0){
e /= 10;
}
if(e==0){
break;
}
}
return(k);
}
int power_2(int n){
int base = 2, i, result = 1;
if(n>0){
for(i=1; i<=n; i++){
result *= base;
}
}
if(n=0){
result = 1;
}
return(result);
}
Example:
Write down a binary number.
100010101011
The binary number 100010101011 converted into decimal is: 2219

How do I make the numbers in this C program print in the correct order and not in reverse?

I am new to C so I am having a little difficulty!
I want to take an integer input from the user and add 7 to each of the digit in the input. All of that works, but the digits are printing in the reverse order.
How do i make the digits print in the correct order? I checked other similar questions on Stack overflow but it does not seem to work. Thanks in advance!
int main(void)
{
int numToEncrypt;
printf("Please input a 4-digit number you wish to encrypt: ");
scanf("%d", &numToEncrypt);
while (numToEncrypt > 0)
{
int digit = numToEncrypt % 10;
// do something with digit
digit = (digit + 7)%10;
numToEncrypt /= 10;
printf("number is: %d \n",digit);
}
}
)
Converting the string input to an integer and back is pointless. Just work with the data as a string. eg:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
int c;
if( getenv("V") ) {
printf("Please input the number you wish to encrypt: ");
fflush(stdout);
}
while( (c = getchar()) != EOF ) {
if( isspace(c) ) {
fflush(stdout);
} else if( isdigit(c) ) {
c = '0' + (c - '0' + 7) % 10;
} else {
fprintf(stderr, "Invalid input: %c", c);
return EXIT_FAILURE;
}
putchar(c);
}
}
Note that a huge advantage of doing this is that it is easy to work with ten million digit integers. You will not be able to do that using scanf to convert the string into an integer.
One way is using a variable to specify which digit to process.
#include <stdio.h>
int main(void)
{
int numToEncrypt;
int delta = 1000; // for 4-digit number
printf("Please input a 4-digit number you wish to encrypt: ");
scanf("%d", &numToEncrypt);
while (delta > 0)
{
int digit = (numToEncrypt / delta) % 10;
// do something with digit
digit = (digit + 7)%10;
delta /= 10;
printf("number is: %d \n",digit);
}
}
As this is homework, you could use recursion:
#include <stdio.h>
void print_recursive(int num)
{
// print leading digits
if (num>9)
{
print_recursive(num/10);
}
// print last digits
printf("number is: %d\n", (num+7)%10);
}
int main(void)
{
int number;
printf("Please input a 4-digit number you wish to encrypt: ");
scanf(" %d", &number); // note: You should check the return value!
print_recursive(number);
}
It is not limited to 4 digits.
For a simple program like this, one usually does not bother with a lot of design. However, it is also beneficial to practice software design on simple problems like this, since the knowledge extends to more complicated programs. This is an application of divide and conquer (as a problem solving strategy, not the computer algorithm). The idea being that smaller problems are simpler than larger ones.
In this case, you consider encapsulating the work of "encrypting" to a function, and have the function return the encrypted value. We'll just implement a stub for now, and fill it in later.
int encryptBy7(int input) {
int output = 0;
return output;
}
In addition, we can encapsulate the work of "printing" to a function. And, this is your actual question, if we think about it critically.
void printDigitByDigit(int num, const char *msg) {
printf("stub\n");
}
So your main program would look like:
int main(void) {
int numToEncrypt;
int numEncrypted;
printf("Please input a 4-digit number you wish to encrypt: ");
scanf("%d", &numToEncrypt);
numEncrypted = encryptBy7(numToEncrypt);
printDigitByDigit(numEncrypted, "number is");
return 0;
}
So, your algorithm to encrypt seems to work, so let's just code that up in a way that it stores it as a number.
int encryptBy7(int input) {
int output = 0;
int pow10 = 1;
/* Original program didn't deal with 0 */
if (input == 0) return 0;
while (input > 0) {
int digit = input % 10;
// do something with digit
digit = (digit + 7)%10;
input /= 10;
// build output
output += digit * pow10;
pow10 *= 10;
}
return output;
}
So, now we get to the meat of your question, which is about how to print out the digits starting with the most significant digit. If we see how we built up the output in the previous function, we can reverse the same process of looking at the powers of 10 to find the most significant digit, and then work backwards from there.
void printDigitByDigit(int input, const char *msg) {
int pow10 = 1;
int x = input;
// Find the position of the most significant digit
while (x > 10) {
pow10 *= 10;
x /= 10;
}
// Divide by the input appropriate power of 10 to
// find and print the corresponding digit
while (pow10 > 0) {
int digit = (input / pow10) % 10;
printf("%s: %d\n", msg, digit);
pow10 /= 10;
}
}
Of course, you are free to choose to try to do this as a single program inside of main as you had originally attempted, and the result would probably be a shorter program. I'll leave that as an exercise. However, I would argue that breaking up the program into tasks will provide you more benefit in the long run, and itself is a problem solving tool. Each function becomes easier to think about, and thus an easier problem to solve.

Comparing digits of two inputs to see if they are the same

I am currently trying to finish a code where a user inputs two 5 digit long numbers. The code then checks to see if there are any identical numbers in the same spot for the two numbers and displays how many identical numbers there are in the same spot of the two inputs. (ex. comparing 56789 and 94712 there would be one similar digit, the 7 in the 3rd digit place.) As of now I have been able to break down the inputs into the digits in each spot, I just need help comparing them. Originally I thought I could just create an int that would serve as a counter and use modulus or division to output a 1 whenever the digits were the same, but I have been unable to put together a formula that outputs a 1 or 0 depending on if the digits are alike or not.
suppose you know the length of strings n (as a condition you would need them to be equal, if they differ in length other validation is needed)
//n is the length of string
for(int i=0;i<n;i++)
{
if(string1[i]==string2[i])
{
//do something, make a counter that increments here...
//also save index i, so you can tell the position when a match occured
}else
{
//do something else if you need to do something when chars didnt match
}
}
Here you when i=0, you are comparing string1[0] with string2[0], when i=1, you compare string1[1] with string2[1] and so on.....
I'd recommend reading the two in as strings or converting to strings if you have the ability to. From there it's a simple string compare with a counter. Something like this:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int is_numeric(char *str)
{
while (*str)
if (!isdigit(*str++))
return (0);
return (1);
}
int main(void)
{
char num1[32];
char num2[32];
int count = 0;
printf("Digit 1\n>> ");
if (scanf("%5s", num1) != 1 || !is_numeric(num1))
return (0);
printf("Digit 2\n>> ");
if (scanf("%5s", num2) != 1 || !is_numeric(num2))
return (0);
if (strlen(num1) != 5 || strlen(num2) != 5)
return (0);
for (int i=0; i<5; ++i)
if (num1[i] == num2[i])
++count;
printf("%d\n", count);
return (0);
}
You can do it very easy using modulo (%) and divide (/). First you do % 10 to get the least significant digit and do the compare. Then you do / 10 to remove the least significant digit. Like:
#include <stdio.h>
#include <string.h>
int main(void) {
unsigned int i1, i2;
int i;
int cnt = 0;
printf("Input first 5 digit number:\n");
if (scanf(" %u", &i1) != 1 || i1 < 10000 || i1 > 99999) // Get integer input and check the range
{
printf("input error\n");
return 0;
}
printf("Input second 5 digit number:\n");
if (scanf(" %u", &i2) != 1 || i2 < 10000 || i2 > 99999) // Get integer input and check the range
{
printf("input error\n");
return 0;
}
for (i=0; i<5; ++i)
{
if ((i1 % 10) == (i2 % 10)) ++cnt; // Compare the digits
i1 = i1 / 10;
i2 = i2 / 10;
}
printf("Matching digits %d\n", cnt); // Print the result
return 0;
}
It can also be done using strings. Read the input as unsigned int and then convert the value to a string using snprintf and finally compare the two strings character by character.
Something like:
#include <stdio.h>
#include <string.h>
int main(void) {
char str1[32];
char str2[32];
unsigned int i1, i2;
int i;
int cnt = 0;
printf("Input first 5 digit number:\n");
if (scanf(" %u", &i1) != 1) // Get integer input
{
printf("input error\n");
return 0;
}
snprintf(str1, 32, "%u", i1);
if (strlen(str1) != 5) // Convert to string
{
printf("input error - not 5 digits\n");
return 0;
}
printf("Input second 5 digit number:\n");
if (scanf(" %u", &i2) != 1) // Get integer input
{
printf("input error\n");
return 0;
}
snprintf(str2, 32, "%u", i2); // Convert to string
if (strlen(str2) != 5)
{
printf("input error - not 5 digits\n");
return 0;
}
for (i=0; i<5; ++i)
{
if (str1[i] == str2[i]) ++cnt; // Compare the characters
}
printf("Matching digits %d\n", cnt); // Print the result
return 0;
}
The reason for taking the input into a unsigned int instead of directly to a string is that by doing that I don't have to check that the string are actually valid numbers (e.g. the user type 12W34). scanf did that for me.

Decimal to Binary Program

I am working on an assignment for a C Programming course in regards to converting a decimal to binary using a function that takes in an unsigned char as its input and has a void output. The function will print the binary code of the unsigned char. A hint for the assignment is to create an array of exponents starting with 128 and going down to 1.
I started working on the assignment and ran the debugger, but my program is not working and I am getting a run time error message: Run-Time Check Failure #2 - Stack around the variable userInput was corrupted.
I would appreciate some suggestions on how I can fix my code and if there is a much simple way to write it in order to make the code easier to understand.
#include <stdio.h>
#include <stdlib.h>
unsigned char DecimalToBinary(unsigned char decimalInput);
void main() {
unsigned char userInput = ' ';
unsigned char resultOfUserInput = DecimalToBinary(userInput);
printf("Enter a number less than 256: ");
scanf_s("%u", &userInput);
printf("%u in binary: %u", userInput, resultOfUserInput);
system("pause");
}
unsigned char DecimalToBinary(unsigned char decimalNumber) {
int arrayOfExponents[128] = {}, i = 1, j;
while (decimalNumber > 0) {
arrayOfExponents[i] = decimalNumber % 2;
i++;
decimalNumber = decimalNumber / 2;
}
for (j = i - 1; j > 0; j--) {
printf("%i", arrayOfExponents[j]);
}
return 0;
}
%u reads an unsigned int (say 4 bytes) and you are trying to read it into variable userInput (1 byte)
Few things
1) scanf_s("%u", &userInput); please change it to scanf_s("%c", &userInput);
2) You are calling DecimalToBinary before reading user input
#include <stdio.h>
#include <stdlib.h>
unsigned DecimalToBinary(unsigned char decimalInput);
int main(void) {//void is invalid as a return value.
unsigned userInput = 256;
unsigned resultOfUserInput;//DecimalToBinary(userInput);userInput did not input at this point.
printf("Enter a number less than 256: ");
if(1 != scanf_s("%u", &userInput)){
printf("invaid input!\n");
return EXIT_FAILURE;
}
if(userInput >= 256){
printf("More than 256 of the value has been entered.\n");
return EXIT_FAILURE;
}
resultOfUserInput = DecimalToBinary((unsigned char)userInput);
printf("%u in binary: %u\n", userInput, resultOfUserInput);
system("pause");
return 0;
}
unsigned DecimalToBinary(unsigned char decimalNumber) {
unsigned bin = 0, exp = 1;//assert(sizeof(unsigned) >= 4);
while (decimalNumber > 0) {
bin += (decimalNumber & 1) * exp;
decimalNumber >>= 1;
exp *= 10;
}
return bin;
}
This is an easy way to convert numbers from base 10 to any other base using recursion. I have shared one example with you. You can have any other number as your base.
#include <stdio.h>
void baseconvert(int number,int base)
{
if(number > 0)
{
int digit = (number % base);
baseconvert(number / base, base);
printf("%d",digit);
}
else
{
printf("\n");
}
}
int main()
{
baseconvert(1023,2);
return 0;
}

In C How to use leftmost digit from an integer

I was wondering how to reverse my output to match entered number.
Example if user entered 543210, I want the output to be: Five Four Three Two One Zero. But instead it's reversed and I can't figure out how to reverse it.
I can't use loops or anything else.
Code:
int main(void){
int value;
int digit;
printf("enter:");
scanf("%i", &value);
while(value)
{
digit = value % 10;
value = value / 10;
if(digit != 0)
{
switch(digit)
{
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;
}
}
}
return 0;
}
Exmaple: If user entered 1234
Output would be: four three two one.
How would I fix it to be: One Two Three Four.
Since you've said that you aren't allowed to use loops, then recursion really is the thing that you are probably being expected to use. I personally am not sure if it would be right to not consider a recursion as a loop, but whatever.
You are using a while there, which also is a loop. If you are allowed to use loops, then you could just do the following, easy-to-understand modification in your code, and get the output you desire:
...
int input; // <-- added this
int value;
int digit;
printf( "enter:" );
scanf( "%i", &input ); // <-- notice the change in variable usage
value = 0;
while ( input ) {
value = 10 * value + input % 10; // adds the last digit of input to value from right
input /= 10;
}
while ( value ) { ... }
...
If you aren't allowed to use loops, then you probably are expected to use a special function, a function which outputs a specific value for a single case, and returns back to itself in any other case. You need a recursive function. Examine this simple example:
// This is in maths, not C
f(x) = 2x + 1 for all integer x >= 0
Out of many ways, this one way to describe the function which maps 0 to 1, then 1 to 3, then n to 2n + 1. If we wanted to define the exact same function recursively:
// In maths
f(x = 0) = 1 for x = 0
f(x > 0) = f(x-1) + 2 for integer x > 0
You see what's going on in there? It's saying that each subsequent f(x) is 2 greater than the previous one f(x-1). But more importantly, the function is calling itself! If you look closer, the called function f(x-1) will also call itself:
f(x) = f(x-1) + 2
f(x) = f(x-2) + 2 + 2
f(x) = f(x-3) + 2 + 2 + 2
...
// all these are the same
All this calling deeper and deeper has to end somewhere, and that somewhere is when f(x-...) is f(0), which has been explicitly defined to be 1.
This is what recursion is all about. Let me write out the examples I gave above in C:
// non-recursive version
int fnonrec( int x ){
return 2 * x + 1;
}
// recursive version
int frec( int x ){
if ( x == 0 )
return 1; // explicit return value for f(0)
else // redundant else, hehe
return frec( x - 1 ) + 2;
}
Definitions of the functions really look similar to how they were defined in maths, don't they? Yeah, well, I don't think giving you the answer for your question would be nice of me. All I can say is that you can print things in reverse really nicely with recursive functions.
//store user input to int variable "value"
char str[15];
sprintf(str, "%d", value);
You can then use the strrev function to reverse the string array. Manipulate it from there.
#include <stdio.h>
void print(int v){
static char *numbers[] = {
"zero","one","two","three","four",
"five","six","seven","eight","nine"
};
int digit = v % 10;
int value = v / 10;
if(value){
print(value);
printf(" %s", numbers[digit]);
} else
printf("%s", numbers[digit]);
}
int main(void){
int value;
printf("enter:");
scanf("%i", &value);
print(value);
return 0;
}
Example using recursive function and numbers from the parameters :
#include <stdio.h>
void display(char c)
{
char *numbers[] = {
"zero","one","two","three","four",
"five","six","seven","eight","nine "
};
printf("%s ", numbers[c]);
}
int aff_num(char *c)
{
if (*c == '\0')
return (0);
display(*c-48);
aff_num(++c);
return (1);
}
int main(int argc, char **argv)
{
if (argc < 2)
{
printf("Need numbers\n");
return (-1);
}
aff_num(argv[1]);
return (0);
}
I'm a python hacker and I almost never program in C. that being said:
#include <stdlib.h>
#include <stdio.h>
int highest_power_of_ten(int value){
int exponent = 0;
int tens = 1;
while(value > tens){
tens *= 10;
exponent += 1;
}
return exponent-1;
}
int pow(int base, int exponent){
if (exponent == 0)
return 1;
int temp = base;
while(exponent > 1){
base *= temp;
exponent -= 1;
}
return base;
}
int main(int argc, char** argv){
char* digits[] =
{"zero","one","two","three","four","five","six","seven","eight","nine"};
int value, n, exp, x;
scanf("%i", &value);
while(highest_power_of_ten(value)>0){
exp = highest_power_of_ten(value);
x = pow(10, exp);
n = value/x;
printf("%s ",digits[n]);
value -= n*x;
}
printf("%s\n", digits[value]);
//system("PAUSE"); for windows i guess
return 0;
}
Another method to get the digits in the right order:
E.g. To get the digit at 1st position in 123 divide 123 by 100, to get 2nd - 123 / 10, to get 3rd 123 / 1. That equals: value / 10^(index of desired digit)
So what we have to do is
Get the length of the (remaining) number by calculating log10(value).
Then get the (remaining) first (most significant) digit by dividing value by 10^length (length of 1.)
calculate value := value - 10^length and start from 1, unless the result is 0 (mind handeling numbers that end on 0).
while (value)
{
len = log10(value);
digit = (int) value / pow(10, len);
value -= pow(10, len);
}
And your code does never enter case 0. To fix that just leave the if(digit != 0) - that's what I meant when I wrote "mind the 0").
if(digit != 0) // enters if digit is not 0
{
switch(digit)
{
case 0: // enters if digit is 0
...
}
}

Resources