Decimal to Binary convert in C - c

My simple program fails to convert 7 to 111 (the current code gives 101). I know myArray[] and the last printf() can be improved, but we can talk about that next time.
int main() {
int myDecimal, quo, rem;
int i = 0; //counter
int myArray[3];
printf("Enter valid decimal number: ");
scanf("%d", &myDecimal);
while(quo != 1){
quo = myDecimal / 2;
rem = myDecimal % 2;
myArray[i] = rem;
myDecimal = quo;
i++;
} myArray[i] = quo;
printf("\nBinary: %d %d %d", myArray[i + 2], myArray[i + 1], myArray[i] );
return 0;
}

It's work fine for me. have you include header files properly? and which compiler do you using ?
#include <stdio.h>
#include <conio.h>
int main() {
int myDecimal, quo, rem;
int i = 0; //counter
int myArray[3];
printf("Enter valid decimal number: ");
scanf("%d", &myDecimal);
while(quo != 1){
quo = myDecimal / 2;
rem = myDecimal % 2;
myArray[i] = rem;
myDecimal = quo;
i++;
} myArray[i] = quo;
printf("\nBinary: %d %d %d", myArray[i + 2], myArray[i + 1], myArray[i] );
return 0;
}
Output
I also try this. you also can try this if you want :)
#include <stdio.h>
#include <conio.h>
int main() {
long myDecimal;
long binary = 0, i = 1;
int rem;
printf("Enter valid decimal number: ");
scanf("%d", &myDecimal);
while(myDecimal != 0) {
rem = myDecimal%2;
myDecimal = myDecimal/2;
binary= binary + (rem*i);
i = i*10;
}
printf("Binary number is %ld",binary);
}

There's some errors that should be taken care of..
Initialize the array because for conversion of 1, it maybe garbage 0 1
Don't force the myArray[i] = quo;
You should take care of printing as i maybe of different length and may cause unstable behavior.
Also initialize quo before use as it may lead to garbage comparison.
Also follow the tips in comments, they are useful.
int main() {
int myDecimal, quo, rem;
int i = 0; //counter
int myArray[3] = {0};
printf("Enter valid decimal number: \n");
scanf("%d", &myDecimal);
quo = myDecimal;
while(quo > 0){
quo = myDecimal / 2;
rem = myDecimal % 2;
myArray[i] = rem;
myDecimal = quo;
i++;
}
printf("Binary: %d %d %d", myArray[2], myArray[1], myArray[0]);
return 0;
}

By your logic you have used you need to make smaller changes to get this to work.
check.c
#include<stdio.h>
int main() {
int myDecimal, quo, rem;
int i = 0; //counter
int myArray[3];
printf("Enter valid decimal number: ");
scanf("%d", &myDecimal);
//check myDecimal whether it's above 0 after each iteration
while(myDecimal > 0){
quo = myDecimal / 2;
rem = myDecimal % 2;
myArray[i] = rem;
myDecimal = quo;
i++;
} myArray[i] = quo;
//print the array in the reverse order
for(i=2;i>=0;i--){
printf("%d",myArray[i]);
}
printf("\n");
return 0;
}
Ouput:

Related

*** stack smashing detected ***: terminated

#include <stdio.h>
#include <stdlib.h>
void get_nbits(int num, int n);
void replace_nbits(int num, int n, int val);
void get_nbits_from_pos(int num, int n, int pos);
void replace_nbits_from_pos(int num, int n, int pos, int val);
void toggle_bits_from_pos(int num, int n, int pos);
void print_bits(unsigned int num, int n);
int main()
{
printf("\tThis program is to show the below mentioned bitwise functions\n\n");
printf("Select bit operation from below list:\n1. get_nbits\n2. set_nbits\n3. get_nbits_from_pos\n");
printf("4. set_nbits_from_pos\n5. toggle_bits_from_pos\n6. print_bits\n");
printf("Enter your choice: ");
int choice,num,n,pos,val;
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter number: ");
scanf("%d",&num);
printf("Enter n: ");
scanf("%d",&n);
get_nbits(num,n);
printf("\n");
break;
case 2:
printf("Enter number: ");
scanf("%d",&num);
printf("Enter n: ");
scanf("%d",&n);
printf("Enter val: ");
scanf("%d",&val);
replace_nbits(num,n,val);
printf("\n");
break;
case 3:
printf("Enter number: ");
scanf("%d",&num);
printf("Enter n: ");
scanf("%d",&n);
printf("Enter pos: ");
scanf("%d",&pos);
get_nbits_from_pos(num,n,pos);
printf("\n");
break;
case 4:
printf("Enter number: ");
scanf("%d",&num);
printf("Enter n: ");
scanf("%d",&n);
printf("Enter val: ");
scanf("%d",&val);
printf("Enter pos: ");
scanf("%d",&pos);
replace_nbits_from_pos(num,n,pos,val);
printf("\n");
break;
case 5:
printf("Enter number: ");
scanf("%d",&num);
printf("Enter n: ");
scanf("%d",&n);
printf("Enter pos: ");
scanf("%d",&pos);
toggle_bits_from_pos(num,n,pos);
printf("\n");
break;
case 6:
printf("Enter number: ");
scanf("%d",&num);
printf("Enter n: ");
scanf("%d",&n);
print_bits(num,n);
printf("\n");
break;
}
}
void get_nbits(int num, int n)
{
int bin_num[9];
int cnt = 0;
int bin_dig = 0;
int multiple = 1;
int decimal_num = 0, base = 1, rem;
while (num > 0) {
bin_num[cnt] = num % 2;
num = num / 2;
cnt++;
}
for(int i=0;i<8;i++)
{
bin_num[i+cnt] = 0;
}
printf("The binary form of given number: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num[i]);
}
for(int i=0;i<n;i++)
{
bin_dig = bin_dig + multiple*bin_num[i];
multiple*=10;
}
while ( bin_dig > 0)
{
rem = bin_dig % 10;
decimal_num = decimal_num + rem * base;
bin_dig = bin_dig / 10;
base = base * 2;
}
printf("\nThe decimal number is: %d\n",decimal_num);
}
void replace_nbits(int num, int n, int val)
{
int bin_num1[9],bin_num2[9];
int cnt1 = 0,cnt2 = 0;
int bin_dig = 0,bin_dig2 = 0;
int multiple = 1;
int decimal_num = 0, base = 1, rem;
while (num > 0) {
bin_num1[cnt1] = num % 2;
num = num / 2;
cnt1++;
}
for(int i=0;i<8;i++)
{
bin_num1[i+cnt1] = 0;
}
printf("\nThe binary form of given number: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num1[i]);
}
while (val > 0) {
bin_num2[cnt2] = val % 2;
val = val / 2;
cnt2++;
}
for(int i=0;i<8;i++)
{
bin_num2[i+cnt2] = 0;
}
printf("\nThe binary form of given value: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num2[i]);
}
for(int i=0;i<n;i++)
{
bin_dig = bin_dig + multiple*bin_num2[i];
multiple*=10;
}
multiple = 1;
int temp = bin_dig;
for(int i=0;i<n;i++)
{
bin_num1[i] = temp%10;
temp/=10;
}
printf("\nThe binary form of given number after replacing is: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num1[i]);
}
for(int i=0;i<cnt1;i++)
{
bin_dig2 = bin_dig2 + multiple*bin_num1[i];
multiple*=10;
}
while ( bin_dig2 > 0)
{
rem = bin_dig2 % 10;
decimal_num = decimal_num + rem * base;
bin_dig2 = bin_dig2 / 10;
base = base * 2;
}
printf("\nThe decimal from given number after replacing is: %d\n",decimal_num);
}
void get_nbits_from_pos(int num, int n, int pos)
{
int bin_num[9];
int cnt = 0;
int bin_dig = 0;
int multiple = 1;
int decimal_num = 0, base = 1, rem;
while (num > 0) {
bin_num[cnt] = num % 2;
num = num / 2;
cnt++;
}
for(int i=0;i<8;i++)
{
bin_num[i+cnt] = 0;
}
printf("\nThe binary form of given number: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num[i]);
}
int from_num = 0;
for(int i = pos;from_num<n;i--,from_num++)
{
bin_dig = bin_dig + multiple*bin_num[i];
if(bin_dig==1) multiple*=10;
}
while ( bin_dig > 0)
{
rem = bin_dig % 10;
decimal_num = decimal_num + rem * base;
bin_dig = bin_dig / 10;
base = base * 2;
}
printf("\nThe decimal number is: %d\n",decimal_num);
}
void replace_nbits_from_pos(int num, int n, int pos, int val)
{
int bin_num1[9],bin_num2[9];
int cnt1 = 0,cnt2 = 0;
int bin_dig = 0,bin_dig2 = 0;
int multiple = 1;
int decimal_num = 0, base = 1, rem;
while (num > 0) {
bin_num1[cnt1] = num % 2;
num = num / 2;
cnt1++;
}
for(int i=0;i<8;i++)
{
bin_num1[i+cnt1] = 0;
}
printf("\nThe binary form of given number: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num1[i]);
}
while (val > 0) {
bin_num2[cnt2] = val % 2;
val = val / 2;
cnt2++;
}
for(int i=0;i<8;i++)
{
bin_num2[i+cnt2] = 0;
}
printf("\nThe binary form of given value: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num2[i]);
}
for(int i=n;i>0;i--)
{
bin_dig = bin_dig + multiple*bin_num2[i];
if(bin_dig==1) multiple*=10;
}
multiple = 1;
int temp = bin_dig;
printf("\n%d",bin_dig);
for(int i=pos;i>(pos-n);i--)
{
bin_num1[i] = temp%10;
temp/=10;
}
printf("\nThe binary form of given number after replacing is: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num1[i]);
}
for(int i=0;i<8;i++)
{
bin_dig2 = bin_dig2 + multiple*bin_num1[i];
multiple*=10;
}
while ( bin_dig2 > 0)
{
rem = bin_dig2 % 10;
decimal_num = decimal_num + rem * base;
bin_dig2 = bin_dig2 / 10;
base = base * 2;
}
printf("\nThe decimal from given number after replacing is: %d\n",decimal_num);
}
void toggle_bits_from_pos(int num, int n, int pos)
{
int bin_num[9];
int cnt = 0;
int bin_dig = 0;
int multiple = 1;
int decimal_num = 0, base = 1, rem;
while (num > 0) {
bin_num[cnt] = num % 2;
num = num / 2;
cnt++;
}
for(int i=0;i<8;i++)
{
bin_num[i+cnt] = 0;
}
printf("The binary form of given number: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num[i]);
}
int from_num = 0;
for(int i = pos;from_num<n;i--,from_num++)
{
bin_num[i] = bin_num[i]^1;
}
printf("\nThe binary form of given number after toggling: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num[i]);
}
for(int i=0;i<8;i++)
{
bin_dig = bin_dig + multiple*bin_num[i];
multiple*=10;
}
while ( bin_dig > 0)
{
rem = bin_dig % 10;
decimal_num = decimal_num + rem * base;
bin_dig = bin_dig / 10;
base = base * 2;
}
printf("\nThe decimal number is: %d\n",decimal_num);
}
void print_bits(unsigned int num, int n)
{
int* bin_num = malloc(n*sizeof(int));
int cnt = 0;
int bin_dig = 0;
int multiple = 1;
int decimal_num = 0, base = 1, rem;
while (num > 0) {
bin_num[cnt] = num % 2;
num = num / 2;
cnt++;
}
if(n>num)
{
for(int i=0;i<n;i++)
{
bin_num[i+cnt] = 0;
}
}
if(cnt>n)
{
printf("The n value is lower than the orignal number of digits\n");
n = cnt;
}
printf("The binary form of given number: ");
for(int i=n-1;i>=0;i--)
{
printf("%d ",bin_num[i]);
}
free(bin_num);
}
I'm a beginner and working with Arrays switch cases and loops of arrays concept coding to do some operations on binary numbers using arrays Here I am able to get the output as expected, but I can't figure out the problem of *** stack smashing detected ***: terminated. This comes at the end of the output I don't know why; anyone can help me with it please? And please tell me what the error means.
This answer is not related for the error, however, using this bit position arithmetic technique you would get rid of the main causes of that error. In this technique you don't have to use neither arrays nor number base conversions but bit arithmetics only.
Consider the number 105 which would be expressed as 01101001 in 8-bit binary right? If it is assigned to an int there will be 24 more digits toward MSb (Most Significant bit). Using bit position arithmetic we can read and print the bit values and we can slice between any 2 positions within the type's bit count range.
Here I show how it could be done using your 2 functions called get_nbits and get_nbits_from_msb_pos (I changed the 2nd one's name to specify the direction operation). I modified their content for this purpose and also added a utility function called printBinary to print binary values of a given int variable, within the desired range.
#include <stdio.h>
#define mBitCount(var) (sizeof(var) * 8)
void printBinary(int val, int from, int to);
void get_nbits(int num, int n);
void replace_nbits(int num, int n, int val);
void get_nbits_from_msb_pos(int num, int n, int pos);
void replace_nbits_from_msb_pos(int num, int n, int pos, int val);
void toggle_nbits_from_msb_pos(int num, int n, int pos);
int main(void) {
/* 105 in decimal, 01101001 in 8-bit binary */
#define NUM 105
get_nbits(NUM, 4);
get_nbits_from_msb_pos(NUM, 4, 6);
replace_nbits(NUM, 4, 7);
replace_nbits_from_msb_pos(NUM, 4, 6, 15);
toggle_nbits_from_msb_pos(NUM, 4, 6);
return 0;
}
void printBinary(int val, int from, int to) {
int bit_count = mBitCount(val);
if(from < to) {
puts("Argument error: from cannot be lesser than or equal to 'to'");
return;
}
else if(from >= bit_count || to < 0) {
puts("Argument error: Position values out of range");
return;
}
for(int i = from; i >= to; i--)
{
if((val & (1 << i))) {
// The ith digit is one
printf("%d",1);
}
else {
// The ith digit is zero
printf("%d",0);
}
}
putchar('\n');
}
void get_nbits(int num, int n)
{
puts("\nget_nbits:");
printf("Parameters: num %d, n %d\n", num, n);
if(n >= mBitCount(num)) {
printf("Argument error: The n must not exceed the bit count of num type which is: %lu\n", (sizeof(num) * 8));
return;
}
puts("The binary form of given number: ");
printBinary(num, mBitCount(num) - 1, 0);
// No need to align since bits ranges to 0th bit
int decimal_num = num & ((1 << n) - 1);
printf("The decimal number is: %d\n",decimal_num);
}
void replace_nbits(int num, int n, int val)
{
puts("\nreplace_nbits:");
printf("Parameters: num %d, n %d, val %d\n", num, n, val);
if(n >= mBitCount(num)) {
printf("Argument error: The n must not exceed the bit count of num type which is: %lu\n", (sizeof(num) * 8));
return;
}
puts("The binary form of given number: ");
printBinary(num, mBitCount(num) - 1, 0);
puts("The binary form of given value: ");
printBinary(val, n - 1, 0);
// No need to align since bits ranges to 0th bit
int mask = (1 << n) - 1; // Set n bits from zero to 1
int decimal_num = num & ~mask; // Clear out the bits that will be replaced
decimal_num |= val & mask;
puts("The binary form of given number after replacing is: ");
printBinary(decimal_num, mBitCount(num) - 1, 0);
printf("The decimal number is: %d\n",decimal_num);
}
// Get n bits from Most Significant Bit (from left to right)
void get_nbits_from_msb_pos(int num, int n, int pos)
{
puts("\nget_nbits_from_msb_pos:");
printf("Parameters: num %d, n %d, pos %d\n", num, n, pos);
if((pos - n) < 0) {
puts("Argument error: n from position should not underflow the bit position");
return;
}
int decimal_num = 0;
puts("The binary form of given number: ");
printBinary(num, mBitCount(num) - 1, 0);
int mask = ((1 << (pos + 1)) - 1); // Mask beyond the pos toward MSb
mask &= ~((1 << ((pos + 1) - n)) - 1); // Mask below pos - n toward LSb
// Slice the num between the pos and n, and then align it to the right
// in order to get the correct value
decimal_num = ((num & mask) >> (pos - (n - 1)));
printf("The decimal number is: %d\n",decimal_num);
}
// Replace n bits from Most Significant Bit (from left to right)
void replace_nbits_from_msb_pos(int num, int n, int pos, int val)
{
puts("\nreplace_nbits_from_msb_pos:");
printf("Parameters: num %d, n %d, pos %d, val %d\n", num, n, pos, val);
if((pos - n) < 0) {
puts("Argument error: n from position should not underflow the bit position");
return;
}
int decimal_num = 0;
puts("The binary form of given number: ");
printBinary(num, mBitCount(num) - 1, 0);
puts("The binary form of given value: ");
printBinary(val, n - 1, 0);
int mask = ((1 << (pos + 1)) - 1); // Mask beyond the pos toward MSb
mask &= ~((1 << ((pos + 1) - n)) - 1); // Mask below pos - n toward LSb
decimal_num = num & ~mask; // Clear the corresponding bits first
decimal_num |= val << (pos - (n - 1)); // Replace the corresponding bits
puts("The binary form of given number after replacing is: ");
printBinary(decimal_num, mBitCount(num) - 1, 0);
printf("The decimal number is: %d\n",decimal_num);
}
void toggle_nbits_from_msb_pos(int num, int n, int pos)
{
puts("\ntoggle_nbits_from_msb_pos:");
printf("Parameters: num %d, n %d, pos %d\n", num, n, pos);
if((pos - n) < 0) {
puts("Argument error: n from position should not underflow the bit position");
return;
}
puts("The binary form of given number: ");
printBinary(num, mBitCount(num) - 1, 0);
int decimal_num = num, i = pos - n; // Get the start index
// Start toggling from start index to the pos
do {
decimal_num ^= 1 << i;
i++;
}
while(i <= pos);
puts("The binary form of given number after toggling: ");
printBinary(decimal_num, mBitCount(decimal_num) - 1, 0);
printf("The decimal number is: %d\n",decimal_num);
}
The output
get_nbits:
Parameters: num 105, n 4
The binary form of given number:
00000000000000000000000001101001
The decimal number is: 9
get_nbits_from_msb_pos:
Parameters: num 105, n 4, pos 6
The binary form of given number:
00000000000000000000000001101001
The decimal number is: 13
replace_nbits:
Parameters: num 105, n 4, val 7
The binary form of given number:
00000000000000000000000001101001
The binary form of given value:
0111
The binary form of given number after replacing is:
00000000000000000000000001100111
The decimal number is: 103
replace_nbits_from_msb_pos:
Parameters: num 105, n 4, pos 6, val 15
The binary form of given number:
00000000000000000000000001101001
The binary form of given value:
1111
The binary form of given number after replacing is:
00000000000000000000000001111001
The decimal number is: 121
toggle_nbits_from_msb_pos:
Parameters: num 105, n 4, pos 6
The binary form of given number:
00000000000000000000000001101001
The binary form of given number after toggling:
00000000000000000000000000010101
The decimal number is: 21
stack smashing occur when one exceeds the size of a specific array(buffer overflow). It a defense mechanism to prevent overwriting of data. Please check your for loop in your functions the value of cnt goes beyond 9 which the size of the array. You can also you refer to What is the "stack smashing detected" error?

I want to print a series of Armstrong numbers which lie between m and n. Here m and n are the two inputs given by the user

I am trying to print the series but whenever I set the range (input given by me) above 407. I only get the output till 407. However, when I set the range below 407 it gives me the result according to the input I have given. Can anybody tell me what I'm doing wrong?
I used an online compiler (www.onlinegdb.com) to write my code.
Here is the code.
#include<stdio.h>
#include<stdlib.h>
int
main ()
{
int m, n;
printf
("Enter two numbers to find the Armstrong numbers that lie between them.\n");
scanf ("%d%d", &m, &n);
system("clear");
if(m>n)
{
m = m + n;
n = m - n;
m = m - n;
}
for (; m < n; m++)
{
int i = m + 1, r, s = 0, t;
t = i;
while (i > 0)
{
r = i % 10;
s = s + (r * r * r);
i = i / 10;
}
if (t == s)
printf ("%d ", t);
}
return 0;
}
enter image description here
enter image description here
Try this code!!!
#include <math.h>
#include <stdio.h>
int main() {
int low, high, number, originalNumber, rem, count = 0;
double result = 0.0;
printf("Enter two numbers(intervals): ");
scanf("%d %d", &low, &high);
printf("Armstrong numbers between %d and %d are: ", low, high);
// swap numbers if high < low
if (high < low) {
high += low;
low = high - low;
high -= low;
}
// iterate number from (low + 1) to (high - 1)
// In each iteration, check if number is Armstrong
for (number = low + 1; number < high; ++number) {
originalNumber = number;
// number of digits calculation
while (originalNumber != 0) {
originalNumber /= 10;
++count;
}
originalNumber = number;
// result contains sum of nth power of individual digits
while (originalNumber != 0) {
rem = originalNumber % 10;
result += pow(rem, count);
originalNumber /= 10;
}
// check if number is equal to the sum of nth power of individual digits
if ((int)result == number) {
printf("%d ", number);
}
// resetting the values
count = 0;
result = 0;
}
return 0;
}
Try this code :
#include <stdio.h>
#include <math.h>
int main()
{
int start, end, i, temp1, temp2, remainder, n = 0, result = 0;
printf(“Enter start value and end value : “);
scanf(“%d %d”, &start, &end);
printf(“\nArmstrong numbers between %d an %d are: “, start, end);
for(i = start + 1; i < end; ++i)
{
temp2 = i;
temp1 = i;
while (temp1 != 0)
{
temp1 /= 10;
++n;
}
while (temp2 != 0)
{
remainder = temp2 % 10;
result += pow(remainder, n);
temp2 /= 10;
}
if (result == i) {
printf(“%d “, i);
}
n = 0;
result = 0;
}
printf(“\n”);
return 0;
}

multiplying number from 1 to N while adding 2 every time

I have to write a C program that multiplies numbers from 1 to N.
N is scanned. Before multiplication, I have to increase each number by 2.
For example: N = 3 => (1+2)(2+2)(3+2) = 60
I have to only use while loop and print and scan function.
Example program:
Enter the value of N: 4
The result of multiplication: 360
This is my code and I am not sure what is wrong with this. Please help.
#include <stdio.h>
int N;
int count=1, ii, result;
printf("Enter the value of N:");
scanf("%d", &N);
while (count<=N)
{
count ii = count + 2;
ii = ii * ii ; //three
count++;
}
result = ii;
printf("The result of multiplication: %d", result);
return 0;
}
If you're looking for that series as a sum:
const int N = 3;
int c = 1;
for (int i = 1; i <= N; ++i) {
c *= (i + 2);
}
Or in a more C-esque form:
const int N = 3;
int c = 1;
for (int i = 0; i < N; ++i) {
c *= (i + 1 + 2);
}
int main()
{
int N;
int count=1, ii = 1, result;
printf("Enter the value of N:");
scanf("%d", &N);
while (count<=N)
{
ii = ii * ( count + 2 };
count++;
}
result = ii;
printf("The result of multiplication: %d", result);
return 0;
}

Binary addition in c, why does run time error occur?

i'm trying to write a code which can convert 2 decimal numbers 0 to 1 into binary, then adding them and printing the binary values for the 2 initial numbers AND the final sum. It compiles with no problems however when I run it crashes right after it converts and prints num1 and num2 (the initial numbers), I can't seem to find the problem.
the general formula for binary addition is:
*ith bit of sum = ith bit of binary1 + ith bit of binary2 + carry factor (0 or 1)
if sum > 1, subtract 2 and add 1 to the next operation (which is the carry factor i mentions earlier)
Below is the code
#include <stdio.h>
// Converting decimal number to a binary number
void convertDecToBin(double num, int len, int binary[]) {
// this function STORES conversion result in binary[]
double tmp = num;
binary[0] = 0;
for (int i = 0; i < len; i++) {
tmp *= 2;
binary[i + 1] = tmp >= 1;
if (tmp >= 1) {
tmp -= 1;
}
}
}
// Binary number addition
void addTwoBinary(int binary1[], int binary2[], int sum[]) {
int tmp;
int carry;
for (unsigned int i = 20; i >= 0; i--) {
if (i == 20 || tmp <= 1) {
carry = 0;
}
else if (tmp > 1) {
carry = 1;
}
sum[i] = binary1[i] + binary2[i] + carry;
tmp = sum[i];
if (sum[i] > 1) {
sum[i]-=2;
}
}
}
//Printing the numbers
void PrintBinary(int binary[], int len) {
for (unsigned int i = 0; i < len; i++) {
printf("%d", binary[i]);
}
}
int main(void) {
double num1, num2;
int binary1[30], binary2[30], sum[30];
scanf("%lf", &num1);
scanf("%lf", &num2);
convertDecToBin(num1, 30, binary1);
convertDecToBin(num2, 30, binary2);
printf("num1 is ");
PrintBinary(binary1, 21);
printf("\nnum2 is ");
PrintBinary(binary2, 21);
addTwoBinary(binary1, binary2, sum);
printf("\nsum is ");
PrintBinary(sum, 21);
return 0;
}

Sum of Digits Program not giving correct answer for negative number in c

printf("Sum Digit Program\n");
int n,re, sum = 0;
printf("Enter an integer n="); scanf("%d", &n);
while(n){
re = n % 10;
sum = sum + re;
n = n / 10;
}
printf("Sum digit = %d", sum);
return 0;
}
I try this and it works well with positive integer but when I enter a negative integer like: -323 => -8
It's supposed to be -3+2+3 =2 not -3-2-3=-8
I try using abs function but it still doesn't work right
OP almost had it. Simply treat MSDigit as signed. All other digits, use abs(rem). Works for INT_MIN
printf("Sum Digit Program\n");
int sum = 0;
printf("Enter an integer n=");
scanf("%d", &n);
while (n) {
int re = n % 10;
n = n / 10;
sum += n ? abs(re) : re; // At MSDigit when n==0
}
printf("Sum digit = %d", sum);
Well, you may use conditional operator to store the sign value like int sign = (n >= 0 ? 1 : -1); as shown below -
#include <stdio.h>
#include <stdlib.h>
/*
* #brief Logic for returning sum of digits
*/
int digi_sum(int n)
{
int sign = (n >= 0 ? 1 : -1);
int sum = 0;
n *= sign;
while (n)
{
if (n < 10)
sum += (sign * (n % 10));
else
sum += n % 10;
n /= 10;
printf("Sum: %d, n: %d\n", sum, n);
}
printf("sum: %d, n: %d\n", sum, n);
return sum;
}
/*
* #brief Driver function
*/
int main(int argc, char *argv[])
{
int num = -323;
printf("Sum: %d\n", digi_sum(num));
return 0;
}
The idea is to store the sign of the number into a separate variable and use it when n < 10.
Use n=abs(n/10) instead of n=n/10
#include <stdio.h>
#include <math.h>
main()
{
printf("Sum Digit Program\n");
int n,re, sum = 0;
printf("Enter an integer n="); scanf("%d", &n);
while(n)
{
re = n % 10;
sum = sum + re;
n =abs(n/10);
}
printf("Sum digit = %d", sum);
return 0;
}
You can add a condition to the first line of your loop to make sure that the sum so far is positive when n < 10, after that it will make the subtraction for the least digit if it has too. Then your loop should look like this:
while(n){
if (abs(n) < 10) {
sum = abs(sum);
}
re = n % 10;
sum = sum + re;
n = n / 10;
}
I think that you need a precondition for the first number.
with an if then else.
Solved
I changed the output to see the values
include<stdio.h>
int main(void)
{
int re,n;
int sum =0 ;
printf("Sum Digit Program \n");
printf("Enter an integer n= ");
scanf("%d", &n);
while(n)
{
if (abs(n) < 10) {
sum = abs(sum);
}
re= (n % 10);
sum = sum + re;
n= n / 10;
printf ("\n re = %d , n= %d \n", re, n);
}
printf ("\n sum= %d \n",sum);
return 0;
}

Resources