How do I make printf from right to left - c

I've written this code for converting Decimal numbers to binary but it prints the number vice versa how can I make this work?
Can I use getch command to make it happen we are currently learning getch.
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
for(;n>0;n=n/2){
int d = n%2;
printf("%d", d);
}
return 0;
}

You can get tricky with this by using a recursive function:
#include <stdio.h>
void print_binary(int n)
{
if (n != 0) {
print_binary(n/2);
printf("%d ", n%2);
}
}
int main() {
int n;
scanf("%d", &n);
print_binary(n);
return 0;
}
By printing after the recursive call returns, the digits print in the reverse order.
Each time print_binary is called, it calls itself with an argument of n/2, then prints the least significant bit. However, each recursive call does the same thing.
Here's what the call stack looks like with n equal to 11 (binary 1011):
main
scanf
print_binary(11)
print_binary(5)
print_binary(2)
print_binary(1)
print_binary(0)
printf("%d ", 1);
printf("%d ", 0);
printf("%d ", 1);
printf("%d ", 1);
You can see that this results in the most significant bit being printed first.

Here is another way, working from most significant bit, with "zero supression". No reversal is needed.
#include <stdio.h>
int main(void) {
int n = 0; // the value
int hadone = 0; // 0 suppression control
int bits = 8 * sizeof n; // assume 8 bits for example
unsigned mask = 1u << (bits-1); // set msb of mask
scanf("%d", &n);
while(mask) {
if(n & mask) { // is it a 1 bit?
putchar('1');
hadone = 1; // cancel 0 suppression
}
else if(hadone || mask == 1) { // ensure a lone `0` goes out
putchar('0');
}
mask >>= 1; // next bit
}
putchar('\n');
return 0;
}
Program session:
42
101010

You can store digits into an array , and reverse it , to get the correct number .

Here's a non-recursive solution:
#include <stdio.h>
int main() {
int n;
char buf[100];
char *bp;
printf("Enter number: ");
fflush(stdout);
scanf("%d", &n);
bp = buf;
// store into array instead of printing [chars will be reversed]
// NOTE: we use "bp == buf" to force output if entered number is zero
for (; n>0 || bp == buf; n=n/2){
int d = n%2;
bp += sprintf(bp, "%d", d);
}
// print array in reverse order
for (bp -= 1; bp >= buf; --bp)
fputc(*bp,stdout);
printf("\n");
return 0;
}

Related

My input in scanf is not working, process is returned and I don't get any output

The Fibonacci series is not obtained on running this program. The whole process terminates after giving input in scanf.
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int);
int main()
{
int n, i = 0, c;
printf("Print the fibonacci series");
scanf("%d", n);
for (c = 1; c <= n; c++)
{
printf("%d\n", fibonacci(i));
i++;
}
return 0;
}
int fibonacci(int n)
{
if (n = 0)
return 0;
else if (n = 1)
return 1;
else
return (fibonacci(n - 1) + fibonacci(n - 2));
}
With scanf you need the give the address of the variable.
scanf("%d",&n); <= need to give the address of the integer
You can find some examples here:
http://www.cplusplus.com/reference/cstdio/scanf/
As you have already been told in Robert's answer, scanf expects an address for each format specifier. So, if format specifier %d is provided, the address of an integer is expected: scanf will write the value there.
If n is the variable containing the integer, &n is its address. Passing something that is not an address causes trouble: it is undefined behavior and will likely cause a segmentation fault.
There are also some problems in your Fibonacci generator. I suppose you want to print the n-th number in the sequence, but you iterate n times calling fibonacci() function (which only returns the last value) always with parameter i, which value is 0.
In fibonacci function you try to check for the exit conditions, but pay attention:
if (n = 0)
return 0;
doesn't check the value of n; it performs an assignment (the value of n will be 0 and the condition will be false). So it will proceed to the next "test"
if (n = 1)
return 1;
It is an assignment as well, 1 is assigned to n so the condition is true and 1 is returned. That's why you see 1 n times.
In order to make it work
correct the scanf issue
pass c to fibonacci()
correct the function so that the value is tested (== instead of =)
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int);
int main()
{
int n, c;
printf("Print the fibonacci series\n");
scanf("%d", &n);
for (c = 1; c <= n; c++)
{
printf("%d\n", fibonacci(c));
}
return 0;
}
int fibonacci(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return (fibonacci(n - 1) + fibonacci(n - 2));
}
You missed the & sign in the scanf statement, and also , I think you got confused with the assignment operator = and logical equal ==, in the Fibonacci function.
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int);
int main()
{
int n, i = 0, c;
printf("Print the fibonacci series");
scanf("%d", &n);
for (c = 1; c <= n; c++)
{
printf("%d\n", fibonacci(i));
i++;
}
return 0;
}
int fibonacci(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return (fibonacci(n - 1) + fibonacci(n - 2));
}

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;
}

How to show the digits which were repeated in c?

The question is that show the digits which were repeated in C.
So I wrote this:
#include<stdio.h>
#include<stdbool.h>
int main(void){
bool number[10] = { false };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] == true)
{
printf("%d ", digit);
}
number[digit] = true;
n /= 10;
}
return 0;
}
But it will show the repeated digits again and again
(ex. input: 55544 output: 455)
I revised it:
#include<stdio.h>
int main(void){
int number[10] = { 0 };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] == 1)
{
printf("%d ", digit);
number[digit] = 2;
}
else if (number[digit] == 2)
break;
else number[digit] = 1;
n /= 10;
}
return 0;
}
It works!
However, I want to know how to do if I need to use boolean (true false), or some more efficient way?
To make your first version work, you'll need to keep track of two things:
Have you already seen this digit? (To detect duplicates)
Have you already printed it out? (To only output duplicates once)
So something like:
bool seen[10] = { false };
bool output[10] = { false };
// [...]
digit = ...;
if (seen[digit]) {
if (output[digit])) {
// duplicate, but we already printed it
} else {
// need to print it and set output to true
}
} else {
// set seen to true
}
(Once you've got that working, you can simplify the ifs. Only one is needed if you combine the two tests.)
Your second version is nearly there, but too complex. All you need to do is:
Add one to the counter for that digit every time you see it
Print the number only if the counter is exactly two.
digit = ...;
counter[digit]++;
if (counter[digit] == 2) {
// this is the second time we see this digit
// so print it out
}
n = ...;
Side benefit is that you get the count for each digit at the end.
Your second version code is not correct. You should yourself figured it out where are you wrong. You can try the below code to print the repeated elements.
#include<stdio.h>
int main(void){
int number[10] = { 0 };
int digit;
long n;
printf("Enter a number: ");
scanf("%ld", &n);
printf("Repeated digit(s): ");
while (n > 0)
{
digit = n % 10;
if (number[digit] > 0)
{
number[digit]++;;
}
else if (number[digit] ==0 )
number[digit] = 1;
n /= 10;
}
int i=0;
for(;i<10; i++){
if(number[i]>0)
printf("%d ", i);
}
return 0;
}
In case you want to print the repeated element using bool array (first version) then it will print the elements number of times elements occur-1 times and in reverse order because you are detaching the digits from the end of number , as you are seeing in your first version code output. In case you want to print only once then you have to use int array as in above code.
It is probably much easier to handle all the input as strings:
#include <stdio.h>
#include <string.h>
int main (void) {
char str[256] = { 0 }; /* string to read */
char rep[256] = { 0 }; /* string to hold repeated digits */
int ri = 0; /* repeated digit index */
char *p = str; /* pointer to use with str */
printf ("\nEnter a number: ");
scanf ("%[^\n]s", str);
while (*p) /* for every character in string */
{
if (*(p + 1) && strchr (p + 1, *p)) /* test if remaining chars match */
if (!strchr(rep, *p)) /* test if already marked as dup */
rep[ri++] = *p; /* if not add it to string */
p++; /* increment pointer to next char */
}
printf ("\n Repeated digit(s): %s\n\n", rep);
return 0;
}
Note: you can also add a further test to limit to digits only with if (*p >= '0' && *p <= '9')
output:
$./bin/dupdigits
Enter a number: 1112223334566
Repeated digit(s): 1236
Error is here
if (number[digit] == true)
should be
if (number[digit] == false)
Eclipse + CDT plugin + stepping debug - help you next time
As everyone has given the solution: You can achieve this using the counting sort see here. Time complexity of solution will be O(n) and space complexity will be O(n+k) where k is the range in number.
However you can achieve the same by taking the XOR operation of each element with other and in case you got a XOR b as zero then its means the repeated number. But, the time complexity will be: O(n^2).
#include <stdio.h>
#define SIZE 10
main()
{
int num[SIZE] = {2,1,5,4,7,1,4,2,8,0};
int i=0, j=0;
for (i=0; i< SIZE; i++ ){
for (j=i+1; j< SIZE; j++){
if((num[i]^num[j]) == 0){
printf("Repeated element: %d\n", num[i]);
break;
}
}
}
}

Decimal to Binary conversion using recursion with while loop

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));

Resources