How can print string num? - c

Problem:
How can print string num? It seems that final statement cannot execute?
Question desciptions:
Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it again!
Now you are suppose to check if there are more numbers with this property. That is, double a given number with k digits, you are to tell if the resulting number consists of only a permutation of the digits in the original number.
/* Have Fun with Numbers */
#include <stdio.h>
#include <string.h>
int book[10] = { 0 };
int main(int argc, char* argv[])
{
char num[22];
int temp = 0;
scanf_s("%s", num, 1);
// Length of numbers
int len = strlen(num);
int flag = 0;
for (int i = len - 1; i >= 0; --i) {
// Convert an ASCII value of a digit into an integer
temp = num[i] - '0';
// Add 1 each time read a digit
++book[temp];
temp = temp * 2 + flag;
flag = 0;
if (temp >= 10) {
temp -= 10;
flag = 1;
}
// Convert an integer into an ASCII value of a digit
num[i] = (temp + '0');
// Subtract 1 each time generate a digit
--book[temp];
}
int flag1 = 0;
for (int i = 0; i < 10; ++i) {
if (book[i] != 0) {
flag1 = 1;
}
}
printf("%s", (flag == 1 || flag1 == 1) ? "No\n" : "Yes\n");
if (flag == 1) {
printf("1");
}
printf("%s", num);
return 0;
}

In this like
scanf_s("%s", num, 1);
You are reporting the buffer size as 1 to scanf_s() while the actual size is 22.
Use correct buffer size.
scanf_s("%s", num, 22);
or
scanf_s("%s", num, (unsigned)(sizeof(num) / sizeof(*num)));

Related

Calculating sum of certain previously inputted numbers

This program should calculate the sum of all numbers whose digits are in descending order. It stops you from inputting if the number isn't a whole number. I think that the problem might be because of the sum variable, but I don't know how to fix it.
Edit: Per #user3386109 request, here is the output I get:
4321
75
56
4,79
0
The sum should be 4396, as sum of 4321 and 75. Not 0.
Sorry for the unclear question I am quite new to this.
int n, last, secondlast, sum, c = 0;
int temp;
while (scanf("%d", &n) == 1) {
sum = 0;
while (temp > 0) {
last = temp % 10;
secondlast = (temp / 10) % 10;
if (secondlast > last) {
c++;
sum = sum + temp;
}
temp = temp / 10;
}
}
if (c == 0) {
printf("There are no numbers that meet the requirements\n");
}
else {
printf("%d\n", sum);
}
As #Support Ukraine commented, this code gets the job done.
#include <stdio.h>
int descendingDigits(int n)
{
int current = n % 10;
n = n / 10;
while(n)
{
int this = n % 10;
if (this <= current) return 0;
current = this;
n = n / 10;
}
return 1;
}
int main(void) {
int sum = 0;
int c = 0;
int n = 0;
while (scanf("%d", &n) == 1) {
if (descendingDigits(n))
{
sum = sum + n;
c = 1;
}
}
if (c == 0) {
printf("There are no numbers that meet the requirements\n");
}
else
{
printf("%d\n", sum);
}
return 0;
}
%10 operations are really not the best way to determine if the digits are descending. It works, but it seems like overkill to use scanf to convert the input to an integer at all, since it's much easier to know if the digits are in order if you leave them as a string. It's tempting to check if the digits of the string are descending and only convert to an integer value if they are, but it seems like a bad idea to parse the string twice. In other words; read the input as a string and do not convert, then compute the integer value while you are looking at the digits to see if they are descending. This is aesthetically appealing, since you minimize computations. (eg, if the input string is "47901", you shouldn't waste cpu cycles converting that to the integer 47901; after you see that 7 is not less than 4, you can abort).
eg:
#include <ctype.h>
#include <stdio.h>
/* If the string s represents an integer
* with (strictly) descending digits, return
* its integer representation (base 10). Else
* return 0.
*/
unsigned
is_descending(const char *s)
{
unsigned rv = 0;
int last = '9' + 1;
while( *s ){
if( isdigit(*s) && *s < last ){
rv = 10 * rv + *s - '0';
} else {
return 0;
}
last = *s++;
}
return rv;
}
int
main(int argc, char **argv)
{
char buf[64];
unsigned sum = 0;
while( scanf("%63s", buf) == 1 ){
sum += is_descending(buf);
}
printf("sum: %u\n", sum);
return 0;
}
Note that this does not handle negative numbers well, but it's not clear how you want to deal with that. Left as an exercise for the reader.

How can I multiply two strings containing 'huge numbers' (over 30 digits)?

I'm doing school project which I'm needed to first receive 2 huge numbers (unlimited size, for the sake of example, lets say over 30 digits), second step is to take the 2 input numbers the create new number of the multiplication of the two, which I'm really breaking a sweat trying to do so.
My code so far:
Type definition to making sure I'm handling the right variables:
typedef char* verylong;
#define MAX_SIZE 100
Input method:
verylong input_long() {
int i, len; //i for loop, len for strlen - using integer for it to avoid invoking the method more than 1 time
verylong number;
char temp_str[MAX_SIZE]; //the input from user - limited to 100
gets(temp_str); //user input
len = strlen(temp_str); //saving the length of the input
number = (char*)calloc(len + 1, sizeof(char)); //allocating memory for the verylong and saving space for \0
for (i = 0; i < len; i++) {
if (temp_str[i] - '0' < 0 || temp_str[i] - '0' > 9) { //the input is not a digit
printf("\nBad input!\n");
return NULL;
}
number[i] = temp_str[i]; //all is good -> add to the verylong number
}
number[i] = '\0'; //setting last spot
return number;
}
My sad attempt of completing my task:
verylong multiply_verylong(verylong vl1, verylong vl2) {
verylong mult;
int cur, i, j, k, lrg, sml, temp_size;
char *temp;
j = 1;
temp = (char*)calloc(lrg + sml + 1, sizeof(char)); //maximum amount of digits
if (strlen(vl1) > strlen(vl2)) {
lrg = strlen(vl1);
sml = strlen(vl2);
}
else {
lrg = strlen(vl2);
sml = strlen(vl1);
}
cur = 0;
for (i = sml-1; i >= 0; i--) {
k = 0;
temp_size = 0;
cur = (vl1[i] - '0')*(vl2[i] - '0');
printf("\ncur=%d", cur);
if (cur > 9)
temp_size = 2;
else
temp_size = 1;
while (k < temp_size) {
if (cur > 9)
temp[j++] = (cur % 10) + '0';
else
temp[j++] = cur + '0';
cur /= 10;
k++;
}
}
mult = (char*)calloc(j + 1, sizeof(char));
for (i = 0; i < j; i++) {
mult[i] = temp[i];
}
mult[i] = '\0';
free(temp);
return mult;
}
Long story short, I know I'm doing mistake at my multiplication method since I'm adding the numbers by simply adding the mult of 2 digits at a time, over that I truly am lost.
Thanks.
My advice would be to break the task into a number of simpler task.
How would you do the multiplication on paper?
123 * 456 -> 1 * (456 * 100) + 2 * (456 * 10) + 3 * (456 * 1)
or written differently
3 * ( 1 * 456)
+ 2 * ( 10 * 456)
+ 1 * (100 * 456)
---------------
SUM TO GET RESULT
or
3 * 456
+ 2 * 4560
+ 1 * 45600
---------------
SUM TO GET RESULT
From this you can identify 3 tasks
Multiplying with powers of 10, i.e. 1, 10, 100, etc. (i.e. add zeros to the end)
Multiplying a string-number with a single digit
Adding two string-numbers.
Write simple functions for each of these steps.
char* mulPowerOf10(char* sn, unsigned power)
{
...
}
char* mulDigit(char* sn, char digit)
{
...
}
char* addNumbers(char* snA, char* snB)
{
...
}
Using these 3 simple functions you can put the real multiplication together. In psedo-code:
char* mulNumbers(char* snA, char* snB)
{
char* result = malloc(2);
strcpy(result, "0");
unsigned power = 0;
for_each_digit D in snA
{
char* t1 = mulPowerOf10(snB, power)
char* t2 = mulDigit(t1, D)
result = addNumbers(result, t2)
++power;
}
free(.. what needs to be freed ..);
return result;
}
Here is a code example.
I found it simpler to store the number as a sequence of digits along with the length in a struct. The number may have leading zeros.
#define MAX_SIZE 1024
typedef struct Number {
int len;
char digits[];
} Number;
// Instantiate a number with room for len digits.
Number *newNumber(int len) {
Number *n = malloc(sizeof(Number)+len);
n->len = len;
memset(n->digits, 0, len);
return n;
}
// inputNumber reads a number from stdin. It return NULL if the input
// is invalid, otherwise it returns a Number containing the given digits.
Number *inputNumber() {
char temp[MAX_SIZE];
if (fgets(temp, sizeof temp, stdin) == NULL)
return NULL; // use fgets because gets is deprecated since C11
// remove trailing \n if any
int len = strlen(temp);
if (len > 0 && temp[len-1] == '\n')
temp[--len] = '\0';
// check input validity
if (len == 0)
return NULL;
for (int i = 0; temp[i] != '\0'; i++)
if (temp[i] < '0' || temp[i] > '9')
return NULL;
Number *n = newNumber(len);
for (int i = 0; temp[i] != '\0'; i++)
n->digits[i] = temp[i] - '0';
return n;
}
To multiply two numbers n1 and n2, we multiply n1 with each digit of n2, and accumulate the result shifted on the left by the position of the n2 digit in the final result.
For instance, to multiply 123*456, we compute 123*4 + 123*5*10 + 123*6*100. Note that *10 and *100 are simply left shifts.
We thus need a function that multiplies a number with a digit, and another function that accumulates a number with a left shift in a result number.
// multiply stores the result of n time digit in result.
// Requires the len of result is the len of n + 1.
void multiplyNumber(Number *n, char digit, Number *result) {
char carry = 0;
for (int i = r->len-1, j = n->len-1; i > 0; i--, j--) {
char x = n->digits[j] * d + carry;
r->digits[i] = x%10;
carry = x/10;
}
r->digits[0] = carry;
}
// accumutateNumber adds n with the left shift s to the number r.
// Requires the len of r is at least len of n + s + 1.
void accumulateNumber(Number *n, int s, Number *r) {
char carry = 0;
for (int i = r->len-1-s, j = n->len-1; j >= 0; i--, j--) {
char x = r->digits[i] + n->digits[j] + carry;
r->digits[i] = x%10;
carry = x/10;
}
r->digits[r->len-1-s-n->len] = carry;
}
Finally, we also need a function to print the number
void printNumber(Number *n) {
int i = 0;
// skip 0 at the front
while (i < n->len && n->digits[i] == 0)
i++;
if (i == n->len) {
printf("0\n");
return;
}
while (i < n->len)
putchar(n->digits[i++] + '0');
putchar('\n');
}
And this is it. We can now write the main function with the input of the numbers, the multiplication of number 1 with each digit of number 2 and accumulate the result with a shift to get the final result.
int main() {
printf("number 1: ");
Number *n1 = inputNumber();
if (n1 == NULL) {
printf("number 1 is invalid\n");
return 1;
}
printf("number 2: ");
Number *n2 = inputNumber();
if (n2 == NULL) {
printf("number 2 is invalid\n");
return 1;
}
Number *r = newNumber(n1->len+n2->len);
Number *tmp = newNumber(n1->len+1);
for (int i = 0; i < n2->len; i++) {
multiplyNumber(n1, n2->digits[n2->len-1-i], tmp);
accumulateNumber(tmp, i, r);
}
printf("result: ");
printNumber(r);
return 0;
}
Here you may have a look at a 'string only' version, multiplying like you would do with a pencil.
It works with 2 loops. The outer loop takes the digits of value2 from the right and multiplies in the inner loop with every digit of value1 from right. The right digit of the multiplication is stored in result, the rest goes in carry for the next inner loop.
At the end of the inner loop, carry is added to result.
After the first outer loop, we have to add previous results to our multiplication.
This is done in if(!first && *lresp) r += toI(*lresp)
The final loop moves the result to the start of the char array.
#include <stdio.h>
#include <stdlib.h>
#define toI(x) ((x)-'0')
#define toC(x) ((x)+'0')
#define max(a,b) ((a)>(b)) ? (a):(b)
char *mul(char *buf1, char *buf2) {
int size, v1, v2, r, carry=0, first=1;
char *startp1, *endp1, *lendp1, *startp2, *endp2;
char *startres, *endres, *resp, *lresp, *result;
for(endp1 = startp1 = buf1; *endp1; endp1++); // start and endpointer 1st value
for(endp2 = startp2 = buf2; *endp2; endp2++); // start and end pointer 2nd value
size = endp2-startp2 + endp1-startp1; // result size
startres = endres = resp = result = malloc(size+10); // some reserve
endres += size+10-1; // result end pointer
for(resp = startres; resp <= endres; resp++) *resp = '\0'; // init result
for(endp1--, endp2--, resp-=2; endp2>=startp2; endp2--, resp--, first=0) {
v2 = toI(*endp2); // current digit of value2
for(lresp = resp, lendp1 = endp1; lendp1 >= startp1; lendp1--, lresp--) {
v1 = toI(*lendp1); // current digit of value1
r = v1 * v2 + carry; // multiply + carry
if(!first && *lresp) r += toI(*lresp); // add result of previous loops
*lresp = toC(r%10); // store last digit
carry = r/10;
}
for( ; carry != 0; carry /= 10)
*lresp-- = toC(carry%10);
}
// we began right with reserve, now move to start of result
for(lresp++; lresp < endres; lresp++, startres++)
*startres=*lresp;
*startres = '\0';
return result;
}
int main() {
char *result = mul("123456789", "12345678");
printf("\n%s\n", result);
free(result);
}

Find product of 5 consecutive integer in C

I'm trying to calculate the product of 5 consecutive integer, but the result the completely wrong. I think my logic is correct, but why it shows me an unreal number: 344362200
The sequence number is from 1 to 10, code is below (just for testing only):
void problem8()
{
char *input = "123456789";
char c;
int step = 5, i = 0, prod = 0, temp = 1;
for (; i < step; i++)
{
temp *= *(input + i);
printf("%d\n", temp);
}
}
The output is really weird! At the first loop, the result is 42 ## while it should be 1, and 1 only. I checked individual result from *(input + 0) or 1 2 4 etc., it's correct. But the product is wrong.
You need to distinguish between the codes for the digits (48 for '0', 49 for '1', etc), and the numbers 1, 2, etc. You should be getting 49 on the first iteration; indeed, I get:
49
2450
124950
6497400
344362200
If you want the first 5 factorials, you'll need to use temp *= input[i] - '0'; (where input[i] is neater than *(input + i), IMNSHO).
The codes I gave are valid for code sets such as ISO 8859-1, and also UTF-8, and many other related code sets. They're not valid for EBCDIC, though.
The problem is that you are converting a char to an int, and not taking into account the ASCII offsets in the ASCII table. Integers start at hex 0x30 for ASCII.
#include <stdio.h>
#include <string.h>
int multiplyFiveSingleDigitNumbersInAString (const char* input, size_t inputLength);
int main(void) {
int tmp = 0;
const char* buf = "12345"; /* Create null-terminated string */
tmp = multiplyFiveSingleDigitNumbersInAString(buf, strlen(buf));
printf("Result of calculation for string %s is %d\n", buf, tmp);
return 0;
}
int multiplyFiveSingleDigitNumbersInAString (const char* input, size_t inputLength) {
if (inputLength != 5) {
printf("Wrong string length (%d), should be %d\n", (int)inputLength, 5);
return 0;
}
int i;
int multiSum = 1;
for (i=0; i<inputLength; i++) {
multiSum *= (int)input[i] - 0x30;
}
return multiSum;
}
References
ASCII Table, Accessed 2014-04-08, <http://www.asciitable.com/>
IMO, the other answers approach this backwards. Simply don't use chars when you want ints. Just change
char *input = "123456789";
to
int input = { 1, 2, 3, 4, 5 };
and your code will work.
P.S. Here's a solution to the actual problem:
char digits[] = "731...";
int main(void)
{
int max = 0;
for (int len = sizeof digits - 1, i = 0; i < len - 4; i++)
{
int prod = 1;
for (int j = 0; j < 5; j++)
prod *= digits[i + j] - '0';
if (max < prod) max = prod;
}
printf("%d\n", max);
return 0;
}

scan n numbers without spaces in C

Suppose n numbers are to be input in a single line without any spaces given the condition that these numbers are subject to the condition that they lie between 1 and 10.
Say n is 6 , then let the input be like "239435"
then if I have an array in which I am storing these numbers then I should get
array[0]=2
array[1]=3
array[2]=9
array[3]=4
array[4]=3
I can get the above result by using array[0]=(input/10^n) and then the next digit
but is there a simpler way to do it?
Just subtract the ASCII code of 0 for each digit and you get the value of it.
char *s = "239435"
int l = strlen(s);
int *array = malloc(sizeof(int)*l);
int i;
for(i = 0; i < l; i++)
array[i] = s[i]-'0';
update
Assuming that 0 is not a valid input and only numbers between 1-10 are allowed:
char *s = "239435"
int l = strlen(s);
int *array = malloc(sizeof(int)*l);
int i = 0;
while(*s != 0)
{
if(!isdigit(*s))
{
// error, the user entered something else
}
int v = array[i] = *s -'0';
// If the digit is '0' it should have been '10' and the previous number
// has to be adjusted, as it would be '1'. The '0' characater is skipped.
if(v == 0)
{
if(i == 0)
{
// Error, first digit was '0'
}
// Check if an input was something like '23407'
if(array[i-1] != 1)
{
// Error, invalid number
}
array[i-1] = 10;
}
else
array[i] = v;
s++;
}
E.g.
int a[6];
printf(">");
scanf("%1d%1d%1d%1d%1d%1d", a,a+1,a+2,a+3,a+4,a+5);
printf("%d,%d,%d,%d,%d,%d\n", a[0],a[1],a[2],a[3],a[4],a[5]);
result:
>239435
2,3,9,4,3,5
You can use a string to take the input and then check each position and extact them and store in an array. You need to check for the numeric value in each location explicitly, as you are accepting the input as a string. For integers taken input as string, there's no gurantee that the input is pure numeric and if it is not, things can go wild.
check this code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char ipstring[64];
int arr[64];
int count, len = 0;
printf("Enter the numbersi[not more than 64 numbers]\n");
scanf("%s", ipstring);
len = strlen(ipstring);
for (count = 0; count < len ; count++)
{
if (('0'<= ipstring[count]) && (ipstring[count] <= '9'))
{
arr[count] = ipstring[count] - '0';
}
else
{
printf("Invalid input detectde in position %d of %s\n", count+1, ipstring );
exit(-1);
}
}
//display
for (count = 0; count < len ; count++)
{
printf("arr[%d] = %d\n", count, arr[count]);
}
return 0;
}

Convert decimal to binary in C

I am trying to convert a decimal to binary such as 192 to 11000000. I just need some simple code to do this but the code I have so far doesn't work:
void dectobin(int value, char* output)
{
int i;
output[5] = '\0';
for (i = 4; i >= 0; --i, value >>= 1)
{
output[i] = (value & 1) + '0';
}
}
Any help would be much appreciated!
The value is not decimal. All values in computer's memory are binary.
What you are trying to do is to convert int to a string using specific base.
There's a function for that, it's called itoa.
http://www.cplusplus.com/reference/cstdlib/itoa/
First of all 192cannot be represented in 4 bits
192 = 1100 0000 which required minimum 8 bits.
Here is a simple C program to convert Decimal number system to Binary number system
#include <stdio.h>
#include <string.h>
int main()
{
long decimal, tempDecimal;
char binary[65];
int index = 0;
/*
* Reads decimal number from user
*/
printf("Enter any decimal value : ");
scanf("%ld", &decimal);
/* Copies decimal value to temp variable */
tempDecimal = decimal;
while(tempDecimal!=0)
{
/* Finds decimal%2 and adds to the binary value */
binary[index] = (tempDecimal % 2) + '0';
tempDecimal /= 2;
index++;
}
binary[index] = '\0';
/* Reverse the binary value found */
strrev(binary);
printf("\nDecimal value = %ld\n", decimal);
printf("Binary value of decimal = %s", binary);
return 0;
}
5 digits are not enough for your example (192). Probably you should increase output
A few days ago, I was searching for fast and portable way of doing sprintf("%d", num). Found this implementation at the page itoa with GCC:
/**
* C++ version 0.4 char* style "itoa":
* Written by Lukás Chmela
* Released under GPLv3.
*/
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
It looks like this, but be careful, you have to reverse the resulting string :-)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char output[256]="";
int main()
{
int x= 192;
int n;
n = x;
int r;
do {
r = n % 2;
if (r == 1)
strcat(output,"1");
else strcat(output,"0");
n = n / 2;
}
while (n > 0);
printf("%s\n",output);
}
So... did you check the output of your code to understand why it doesn't work?
So iteration 1 of your loop:
value = 192
i = 4
output[i] = (11000000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 2 of your loop:
value = 96
i = 3
output[i] = (1100000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 3 of your loop:
value = 48
i = 2
output[i] = (110000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 4 of your loop:
value = 24
i = 1
output[i] = (11000 & 1) + '0' = 0 + 48 = 48 (char `0`)
Iteration 5 of your loop:
value = 12
i = 0
output[i] = (1100 & 1) + '0' = 0 + 48 = 48 (char `0`)
Final string: "00000" and you wanted: "11000000"
See anything wrong with your code? Nope. Neither do I you just didn't go far enough. Change your output/loop to:
output[8] = '\0';
for (i = 7; i >= 0; --i, value >>= 1)
And then you'll have the correct result returned.
I would recomend just a more general approach, you're using a fixed length string, which limits you to binary numbers of a certian length. You might want to do something like:
loop while number dividing down is > 0
count number of times we loop
malloc an array the correct length and be returned
#include <stdio.h>
#include <stdlib.h>
void bin(int num) {
int n = num;
char *s = malloc(sizeof(int) * 8);
int i, c = 0;
printf("%d\n", num);
for (i = sizeof(int) * 8 - 1; i >= 0; i--) {
n = num >> i;
*(s + c) = (n & 1) ? '1' : '0';
c++;
}
*(s + c) = NULL;
printf("%s", s); // or you can also return the string s and then free it whenever needed
}
int main(int argc, char *argv[]) {
bin(atoi(argv[1]));
return EXIT_SUCCESS;
}
You can do it using while loop under a function also. I was just searching the solve for mine but the solves i get were not suitable, so I have done it accordingly the practical approach (divide using 2 until getting 0 and store the reminder in an array) and print the reverse of the array and Shared Here
#include <stdio.h>
int main()
{
long long int a,c;
int i=0,count=0;
char bol[10000];
scanf("%lld", &a);
c = a;
while(a!=0)
{
bol[i] = a%2;
a = a / 2;
count++;
i++;
}
if(c==0)
{
printf("0");
}
else
{
for(i=count-1; i>=0; i--)
{
printf("%d", bol[i]);
}
}
printf("\n");
return 0;
}
//C Program to convert Decimal to binary using Stack
#include<stdio.h>
#define max 100
int stack[max],top=-1,i,x;
void push (int x)
{
++top;
stack [top] = x;
}
int pop ()
{
return stack[top];
}
void main()
{
int num, total = 0,item;
print f( "Please enter a decimal: ");
scanf("%d",&num);
while(num > 0)
{
total = num % 2;
push(total);
num /= 2;
}
for(i=top;top>-1;top--)
{
item = pop ();
print f("%d",item);
}
}
Convert Decimal to Binary in C Language
#include<stdio.h>
void main()
{
long int n,n1,m=1,rem,ans=0;
printf("\nEnter Your Decimal No (between 0 to 1023) :: ");
scanf("%ld",&n);
n1=n;
while(n>0)
{
rem=n%2;
ans=(rem*m)+ans;
n=n/2;
m=m*10;
}
printf("\nYour Decimal No is :: %ld",n1);
printf("\nConvert into Binary No is :: %ld",ans);
}
This is the simplest way to do it
#include <stdio.h>
void main()
{
int n,i,j,sum=0;
printf("Enter a Decimal number to convert it to binary : ");
scanf("%d",&n);
for(i=n,j=1;i>=1;j*=10,i/=2)
sum+=(i%2)*j;
printf("\n%d",sum);
}
This is a simple program to convert a number from decimal to binary
#include <stdio.h>
#include <conio.h>
void decToBinary(int);
int main()
{
int number;
printf("Enter number to convert to binary: ");
scanf("%d", &number);
decToBinary(number);
return 0;
}
void decToBinary(int num)
{
if (num == 0)
{
return ;
}
decToBinary(num / 2);
printf("%d", num % 2);
}
Output of the Program:
Perhaps understanding the algorithm would allow you write or modify your own code to suit what you need. I do see that you don't have enough char array length to display your binary value for 192 though (You need 8 digits of binary, but your code only gives 5 binary digits)
Here's a page that clearly explains the algorithm.
I'm not a C/C++ programmer so here's my C# code contribution based on the algorithm example.
int I = 0;
int Q = 95;
string B = "";
while (Q != 0)
{
Debug.Print(I.ToString());
B += (Q%2);
Q = Q/2;
Debug.Print(Q.ToString());
I++;
}
Debug.Print(B);
All the Debug.Print is just to show the output.
//decimal to binary converter
long int dec2bin(unsigned int decimal_number){
if (decimal_number == 0)
return 0;
else
return ((decimal_number%2) + 10 * dec2bin(decimal_number/2));
}
number=215
a=str(int(number//128>=1))+str(int(number%128>=64))+
str(int(((number%128)%64)>=32))+str(int((((number%12
8)%64)%32)>=16))+str(int(((((number%128)%64)%32)%16)>=8))
+str(int(((((((number%128)%64)%32)%16)%8)>=4)))
+str(int(((((((((number%128)%64)%32)%16)%8)%4)>=2))))
+str(int(((((((((((number%128)%64)%32)%16)%8)%4)%2)>=1)))))
print(a)
You can also use the 'if', 'else', statements to write this code.
int main()
{
int n, c, k;
printf("Enter an integer in decimal number system: ");
scanf("%d", &n);
printf("%d in binary number system is: ", n);
for (c = n; c > 0; c = c/2)
{
k = c % 2;//To
k = (k > 0) ? printf("1") : printf("0");
}
getch();
return 0;
}

Resources