I have to write 2 programs that convert dec to bin. I've finish the 1st one however when I try to run this one it prints out an array of random number not sure why, here is what I have:
#include <stdio.h>
int getNumber();
int dectoBin(int, int binarray[], int);
void printBin(int binary[], int dec);
int main()
{
int M = 8;
int binarray[M];
int dec = getNumber();
printf("The decimal number you entered was: %d", dec);
decToBin(dec, binarray, M);
printBin(binarray, dec);
return 0;
}
int getNumber()
{
int dec;
printf("Enter any a number between 0 and 255: ");
scanf("%d",&dec);
return dec;
}
int decToBin(int dec, int binarray[], int M)
{
int i, j;
for(i=8; i>=0;i--)
{
while(dec != 0)
{
binarray[i]= dec % 2;
dec = dec / 2; binarray[i] = dec;
}
}
return *binarray;
}
void printBin(int binary[], int dec)
{
int i;
if(dec > 255)
{
printf("please use another number");
main();
}
else
{
for(i =8; i >= 0;i--)
{
printf("%d", binary[i]);
printf("\n");
}
}
}
You're setting binarray[i] twice - once correctly (after the modulus statement) and once incorrectly (after dividing dec). So if your decimal number is 65, your second-to-last number would be 32.
You can also make binarray an array of bits rather than numbers. This would have given you a error on compilation and would have perhaps clued you into the logical error.
EDIT: There are a lot of control flow issues with this program. You should check to see if dec > 255 BEFORE calling decToBin otherwise the program will run incorrectly. decToBinary shouldn't return an int - it should return an array of ints (or bits as I suggested) and that is what you should send to printBin. Right now you're returning the pointer to binArray (do you know what pointers are?) decToBin should also return void since it does not perform any calculations.
EDIT 2: As someone else pointed out your array indexes are incorrect, I don't know how you haven't gotten an array out of bounds error. Also, while printing you're going the wrong way: You need to use a for loop that starts at 0 and ends at 7.
Here are some suggestions.
You have dectoBin in the declaration but decToBin in the function call and function definition. Make sure they are all dectoBin or they are all decToBin.
M is not used in decToBin. Feel free to remove it.
I would change getNumber() such that it checks for the range and makes sure that you get a number between 0 to 255 from its return statement. That would eliminate the need to do that check in printBin.
Implementation of decToBin is quite a bit simpler than what you were thinking. The for-loop can be simplified to:
for(i=7; i>=0;i--, dec /= 2)
{
binarray[i]= dec % 2;
}
And finally, implementation of printBin can be a little bit different to make the output more readable. Instead of printing one number at a time, they can all be printed in one line.
Here's what I came up with:
#include <stdio.h>
int getNumber();
int decToBin(int, int binarray[]);
void printBin(int binary[], int dec);
int main()
{
int M = 8;
int binarray[M];
int dec = getNumber();
printf("The decimal number you entered was: %d\n", dec);
decToBin(dec, binarray);
printBin(binarray, dec);
return 0;
}
int getNumber()
{
int dec;
printf("Enter a number between 0 and 255: ");
scanf("%d",&dec);
if( dec < 0 || dec > 255)
{
printf("Please use another number\n");
return getNumber();
}
return dec;
}
int decToBin(int dec, int binarray[])
{
int i;
for(i=7; i>=0;i--, dec /= 2)
{
binarray[i]= dec % 2;
}
return *binarray;
}
void printBin(int binary[], int dec)
{
int i;
printf("The decimal number in binary: ");
for(i=0; i!=8; ++i)
{
printf("%d", binary[i]);
}
printf("\n");
}
A sample execution and output:
~>>./test-07
Enter a number between 0 and 255: 149
The decimal number you entered was: 149
The decimal number in binary: 10010101
Related
Write a program that prints the sum of digits for the entered interval limits. To calculate the sum of
digits form the corresponding function.
#include <stdio.h>
void suma(int a ,int b ){
int s= 0,i;
for(i=a;i<=b;i++){
while(i != 0 ){
int br = i % 10;
s+=br ;
i = i/10;
}
printf("%d\n",s);
}
}
int main(void){
int a,b;
printf("enter the lower limit of the interval: "); scanf("%d",&a);
printf("enter the upper limit of the interval: "); scanf("%d",&b);
suma(a,b);
return 0;
}
when i set a to be 11 and b to be 13 program does first 3 sums but after that it doesent stop.why doesn't it stop. But if i set a to 3 digit number program gives me first sum but then gives me random sums
The reason why your code is not working is because in your while-loop, you are changing the value of i, but i is also used in the for-loop. This results in undefined behaviour. In order to fix this, I would suggest breaking the problem up in two functions. One for calculating the sum of a the digits of a number, and one function that adds these sums in a particular range.
int sumNumber(int number) {
int sum = 0;
while(number != 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
int suma(int a ,int b){
int totalSum = 0;
for(int i=a;i<=b;i++){
int sum = sumNumber(i);
totalSum += sum;
}
return totalSum;
}
This way, you are not modifying i in the while-loop.
You are mixing up the two loop variables. As arguments are passed by value just a instead of introducing an unnecessary variable. Minimize scope of variables. Check the return value from scanf() otherwise you may be operating on uninitialized variables.
#include <stdio.h>
void suma(int a, int b) {
for(; a <= b; a++) {
int s = 0;
for(int i = a; i; i /= 10) {
s += i % 10;
}
printf("%d\n", s);
}
}
int main(void){
printf("enter the lower limit of the interval: ");
int a;
if(scanf("%d",&a) != 1) {
printf("scanf failed\n");
return 1;
}
printf("enter the upper limit of the interval: ");
int b;
if(scanf("%d",&b) != 1) {
printf("scanf failed\n");
return 1;
}
suma(a,b);
}
and example run:
enter the lower limit of the interval: 10
enter the upper limit of the interval: 13
1
2
3
4
I was unreasonably annoyed by how the code was formatted. Extra white space for no reason including at end of line, missing white space between some operations, variables lumped together on one line.
It's a really good idea to separate i/o from logic as in #mennoschipper's answer. My answer is as close to original code as possible.
i did function like this and it works now
void suma(int a ,int b ){
int s= 0,i;
int x ;
for(i=a;i<=b;i++){
x = i;
while(x != 0 ){
int br = x % 10;
s+=br ;
x = x/10;
}
printf("%d\n",s);
s = 0;
} }
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define BUFFER 512
void getCount(int *numCount, int *count);
int sumNumbers(int *numSum, int *sumNumOutput);
int main(void) {
printf("Enter a number greater than 0: ");
char string[BUFFER];
int numMain = 0;
int countMain = 0;
int sumNumMain = 0;
fgets(string, BUFFER, stdin); // gets user input and stores it in string
numMain = atoi(string); // converts the string to numerical and sets sum to the value. If there is a letter in the string, it will be zero.
int numCountMain = numMain;
int numSumNum = numMain;
getCount(&numCountMain, &countMain); // gets how many integers there are
sumNumbers(&numSumNum, &sumNumMain);
printf("Count: %d\n", countMain);
// printf("Sum: %d\n", sumNumMain);
return 0;
}
//shows how many integers were entered
void getCount(int *numCount, int *count){
while(*numCount > 0){
*numCount /= 10;
++*count;
}
return;
}
int sumNumbers(int *numSum, int *sumNumOutput){ // make it so that it isolates a number, then adds it to a universal sum variable
int increment = 1;
int count = 0;
while(*numSum > 0){ // gets the count of the number
while(*numSum > 0){
*numSum /= increment;
++count;
printf("numSum: %d\n",*numSum);
increment *= 10;
}
}
}
Let's say I put in 12345 as the number. It counts the number of digits in there just fine, but when it gets to isolating the individual digits using division, it skips over the third number. In the case of 12345, it would be:
12345
1234
12
0
I'm thinking this is a case of the increment running amok, but I can't find a fix for this. Also I know when I fix this, it will not solve the problem that I have to isolate the individual numbers. That's where the increment comes in and I know I have to use the modulus, but if someone can help me out with that after I take care of this, that would be great too.
Also, in case it isn't obvious, the code that has the problem I'm assuming is the bottom lines.
You are dividing by 1, 10, 100, 1000. So you are getting 12345, 1234, 12.
Try
while (*numSum > 0) {
++count;
printf("numSum: %d\n",*numSum);
*numSum /= 10;
}
I have a problem with C program. The idea of it is similar to Armstrong number checking. Say if the input number is 123. Program needs to check if condition, for example 123=1^1+2^2+3^3 is true. I know how to add digits,but have a problem with powers. It is obvious that I need a loop for powers from 1 to the number of digits. In Armstrong number algorithm you have similar power on every digit. For example 153=1^3+5^3+3^3. Here is what I have so far:
#include<stdio.h>
int main()
{
int n,d,s=0,o,i,k;
printf("n=");scanf("%d",&n);
d=n;
while(d!=0)
{
o=d%10;
s=s+o;
d=d/10;
k++
}
printf("sum:%d",s);
printf("number of digits:%d",k);
return 0;
}
Thanks for the answers.
You need first get the lenth of number, which is used to determine how many times you need to get into loop to calculate each bit.
For example, number 123, you first need to know the number is 3 bits len, then you can mutilply number 3 three times, number 2 twice, and number 1 once.
I use a temporary string to achieve this
here is code, a little bit alteration on yours
#include <stdio.h>
#include <string.h>
#define MAX_NUM_LEN 16
int main()
{
char tmp_num[MAX_NUM_LEN] = {0};
int len,n,d,s=0,o,i,tmp_len, tmp_o;
printf("n=");scanf("%d",&n);
sprintf(tmp_num, "%d", n);
len = strlen(tmp_num);
tmp_len = len;
d=n;
while(d!=0)
{
o=d%10;
for (tmp_o = 1, i = tmp_len; i > 0; i--)
tmp_o *= o;
s=s+tmp_o;
d=d/10;
tmp_len--;
}
printf("sum:%d\n",s);
printf("number of digits:%d\n",len);
return 0;
}
results:
According of what I've understood I think this is what the OP is looking for:
int power(int base, int exp)
{
if (base == 0) return 0;
int result=1;
while (exp-- > 0) result*=base;
return result;
}
void calculate(int number)
{
int d=number;
int tmpnumber=number;
int n=0;
while (d > 0)
{
n++;
d /=10;
}
printf("Number of digits: %d\n", n);
int k=0;
int sum=0;
while (n--)
{
// get digits from left to right
d=number / power(10, n);
k++;
sum+=power(d, k);
number %= power(10, n);
printf("%d^%d=%d\n", d, k, power(d, k));
}
printf("\n%5d %5d", tmpnumber, sum);
}
int main(int argc,char *argv[])
{
int value;
while (TRUE)
{
printf("Enter value (0 = Quit): ");
scanf("%d", &value);
if (value <= 0) return 0;
calculate(value);
printf("\n");
}
}
it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr §6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}
This is the C Program I have written to convert a Decimal number to it's equivalent Binary number. I have used Stack (implemented using array) and the following algorithm:
Number is divided and remainders are pushed in stack.
Remainders are popped one at a time and converted into Binary
The Problem is that the program works fine for numbers up to 3, after that from 4 on wards, each Binary Number comes one less than the actual number.
// Decimal to Binary conversion using Stack
#include<stdio.h>
#include<math.h>
#define max 20
int top=-1, stk[max];
void push(int);
int pop(void);
int main()
{
int i,num,x,flag=0,s, bin=0, factor;
printf("Enter any decimal number: ");
scanf("%d",&num);
while(num>0)
{
if(num==1)
push(num);
else
{
x = num%2;
push(x);
}
num/=2;
flag++;
}
for(i=0;i<flag;i++)
{
s = pop();
bin = bin + s*pow(10,(flag-1-i));
}
printf("\nEquivalent Binary number is --> %d",bin);
return 0;
}
void push(int n)
{
if(top == max-1)
{
printf("Error! Overflow");
return;
}
stk[++top] = n;
}
int pop(void)
{
int y;
if(top == -1)
{
printf("Error! Underflow");
return;
}
y = stk[top];
top = top-1;
return y;
}
Will anybody help me by finding the logical flaw?
Thank You
My answer is your program is unnecessarily complicated.
#include<stdio.h>
int main()
{
unsigned num, i, zeros = 0;
printf("Enter a decimal number: ");
scanf("%u", &num);
printf ("Decimal %u in binary is ", num);
for (i=sizeof(unsigned)*8; i>0; i--)
{
if ((int)num < 0) // get MSB
zeros = printf ("1"); // cancel 0-suppresion
else if (zeros)
printf ("0");
num <<= 1;
}
printf ("\n");
return 0;
}
The function pow return a double that can have a 9999999... after the decimal point, which is rounded to the floor when it is casted to int, you can fix your problem using ceil() function, that returns the smallest integer value greater than or equal the argument, like this.
bin = bin + ceil(s*pow(10,(flag-1-i)));
//C Program to convert Decimal to binary using Stack
#include<stdio.h>
#define max 100
int stack[max],top=-1,i,x;
/*------ Function Prototype------------*/
void push (int x)
{
++top;
stack [top] = x;
}
int pop ()
{
return stack[top];
}
/*-------------------------------------*/
void main()
{
int num, total = 0,item;
printf( "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 ();
printf("%d",item);
}
}
Here is a simpler version of your above program
int main(){
int n,remainder;
printf("Enter a decimal number:");
scanf("%d",&n);
while(n!=0){
remainder = n%2;
n = n/2;
push(remainder); // inserting in stack
}
display(); // displaying the stack elements
}
reference of above code
C program to Convert Decimal number into Binary using Stack
So I've done the math on several numbers, and this appears to be correct. I would agree with others that this is needlessly complicated, but that is not causing your issues on it's own, it's just making them harder to find.
So the output of this program appears correct, from a logical standpoint. Lets look into other potential issues:
You're indexing an array with an int that you initialize to -1
This is bad practice, and unnecessary. Array indexes in C can never be negative, so the compiler will assume this is an unsigned number, so if you have a 32 bit processor, it will assume you're trying to get array[2^32 - 1], which is not what you want. Always use a unsigned value for array indexes
What MIGHT be happening, and I'm not certain, is that your compiler is doing something with this behind the scenes which is screwing up your program, it's really hard to say. But it's probably attempting to convert your negative number into an unsigned int before you do your addition. Fix this by changing your declaration of top to:
unsigned int top = 0;
and changing where you access top from:
stk[++top] = n;
to
stk[top++] = n;
You will also have to change
y = stk[top];
top = top-1;
to
top = top-1;
y = stk[top];
I'd say start there. I'd also suggest removing the pow line, and just individually printing each piece of the array, because it will output in the same way, and you already have all the info there ie.
PRINTF("%d%d%d",stk[2],stk[1],stk[0]);