Displaying individual number with spacing on printf - c

im writing a code which will show the result is to display the individual digits and the decimal equivalent.
For e.g., if n is 6 and the number entered is 110011, the printout will be
1 1 0 0 1 1
The decimal equivalent is 51
I have already sourced and edited a code, however it shows
"110011 110011 110011 110011 110011 110011" instead of
"1 1 0 0 1 1".
#include <math.h>
void main()
{
int num, binary, decimal = 0, base = 1, remainder, n, digits;
printf("Please enter the number of digits:\n");
scanf("%d", &n);
printf("Please enter the %d digits:\n",n);
scanf("%d", &num);
binary = num;
while (n > 0)
{
remainder = num % 10;
decimal = decimal + remainder * base;
num = num / 10 ;
base = base * 2;
printf("%d ", binary);
n--;
}
printf("\nIts decimal equivalent is = %d \n", decimal);
}

The value in the variable binary becomes a copy of the value in the variable num in the following line.
binary = num;
Since it is never changed afterwards, it will always remain the same value, a copy of the value in num at the time when it was copied (see the code line above).
Your loop is executed n times (in your example six times).
Each time through the loop, the same copied value is printed in the following code line.
So the original value will be printed six times in your example.
printf("%d ", binary);
You did not actually ask a question (which is really recommended here at StackOverflow).
So I answered the question "Why is the same value printed six times?"
You probably want to now ask the next question, "How do get the desired result?"
That question is much harder to answer, because your code is quite far away from achieving that.
You would have to determine the binary digits one by one and in the right order.
You do determine the digits one by one, around the following line in your code.
remainder = num % 10;
But that is the wrong order, it gives you the digits from least signifying to most signifying. Try with an input of "100011" to see what I mean.
To be more precise I have to say that I guess that you want the digits from most to least, but maybe not, in that case it is easier: print remainder instead of binary.
If I am right and you do want most to least, then you have to make some way of reversing the digits. You could use a stack, an array, recursion or different (more complicated ) math involving to determine the number of digits first.

The reason you're getting this output is because each call for printf("%d ", binary); prints the entirety of the 'binary' variable onto the screen, and that variable contains the number as opposed to individual digits of that number.
The easiest way of accessing specific digits of a number is by first dividing it by some power of 10, then getting mod10 of that number, e.g.:
int number = 6543;
int lastDigit = number % 10;
int secondLastDigit = (number / 10) % 10;
int thirdLastDigit = (number / 100) % 10;
This works because dividing integers in C causes any fraction parts to be ommitted, thus if you divide 6543/10 (as in the example), you will not get 654.3, but 654.
You could create a function which will return a number's digit from any position like so:
int digitAt(int num, int pos)
{
// Divide num by 10^(pos - 1) to "shift" the number to the right
num /= pow(10, pos - 1);
// Return the last digit after the divisions
return num % 10;
}
The above function returns digits starting from the right (pos 1 = last digit, pos 2 = second last digit)!
To make this function more intuitive you could for example flip the number horizontally before dividing (123 becomes 321).
I went on a little tangent, back to the original topic. To achieve the functionality you want, you could write your code like this (just the while loop):
while (n > 0)
{
remainder = num % 10;
decimal = decimal + remainder * base;
num = num / 10 ;
base = base * 2;
int binaryDigit = (binary / pow(10, n - 1)) % 10;
printf("%d ", binaryDigit);
n--;
}
Now, the reason you don't have to worry about your digits being read backwards (like in the previous function example) is because conveniently, your iterator, n, is already going in reverse direction ('from n to 0' as opposed to 'from 0 to n'), so you're reading the leftmost digits before the rightmost ones.
Hope that helped.
[EDIT] As pointed out in the replies, using pow() in integer operations may lead to undesired results. My bad. There are plenty of ways to achieve an integer power of 10 though, a function like
int powerOf10(int exp)
{
int num = 1;
while (exp > 0) {
num *= 10;
exp--;
}
return num;
}
should do the job.

The problem is that you do:
printf("%d ", binary);
but binary is the same value all the time, i.e. it's never changing so you get the original value printed again and again.
If you changed it to:
printf("%d ", remainder);
things would be "a bit better" as the binary pattern would be printed but in reversed order. So that's not the solution.
So instead you can collect the values in the loop and store them in a string to be printed after the loop. Like:
int main()
{
int num, decimal = 0, base = 1, remainder, n;
printf("Please enter the number of digits:\n");
scanf("%d", &n);
int idx = 2*n-1;
char *str = malloc(2*n); // Allocate memory for the string
str[idx--] = 0; // and zero-terminate it
printf("Please enter the %d digits:\n",n);
scanf("%d", &num);
while (n > 0)
{
remainder = num % 10;
decimal = decimal + remainder * base;
num = num / 10 ;
base = base * 2;
str[idx--] = '0' + remainder; // Put the "binary" (i.e. '0' or '1') char in the string
if (idx>0) str[idx--] = ' '; // Put a space in the string
n--;
}
printf("%s", str); // Print the string
printf("\nIts decimal equivalent is = %d \n", decimal);
free(str); // Free the string
return 0;
}

Related

Breaking down a number into digits - C

I'm trying to create a program that breaks down a number into its component digits.
The code I've written so far is as follows:
#include <stdio.h>
int main() {
int num;
int digits;
int count = 1;
printf("Insert a positive number: ");
do {
scanf("%d", &num);
} while (num <= 0);
printf("In digits... \n");
// Number in digits
while (num != 0) {
digits = num % 10;
printf("Digit %d --> %d \n", count, digits);
num /= 10;
count++;
}
}
The digits of the number are printed correctly, but in reverse order!
Insert a positive number: 345
In digits...
Digit 1 --> 5
Digit 2 --> 4
Digit 3 --> 3
I can't figure out how to fix this, can anyone help me?
You're printing the number mod 10, which is the last digit, then dividing the number by 10 and repeating until the number is zero. So it prints the digits from right to left.
If you want to print from left to right, you need to print the digit that has the highest power of ten first. Here's a naive way to do that, by first finding the highest power of ten the number has a digit for and then using a for loop to go from that power to one to print the digits from left to right:
void print_digits(int n) {
int mask = 1;
for(int n2 = n; n2; n2 /= 10) mask *= 10; // find the left-most power of ten
for(int i = 1; mask > 1; mask /= 10) // loop over the mask to 1
printf("Digit %d --> %d\n", i++, (n % mask) * 10 / mask);
// print the digit number and increment the digit counter
// extract and print the digit:
// `n % mask` gets rid of everything to the left
// `* 10 / mask` gets rid of everything to the right
}
You could also make a simpler solution using the standard library function sprintf (string print formatted) to put the int into a string and then print from that, like so:
void print_digits(int n) {
char num[11]; // 32-bit int up to 9 digits, possible '-', and \0 -> 11
sprintf(num, "%d", n);
for (int i = 0; num[i]; i++)
printf("Digit %d --> %c\n", i + 1, num[i]);
}
The second might also be a tiny bit more performant due to not involving division, but I'm not certain of that and such minor differences don't matter for a problem like this anyway
Your code prints them in reverse because you are starting with the right-most digit (by taking the modulo by 10) each time, then dividing by 10.
To print from left to right, you could have:
#include <stdint.h>
void print_uint32_digits(uint32_t val)
{
int started = 0; // Flag to say we have started printing digits
// Special case for when val is zero
if (val == 0u)
{
printf("0\n");
return;
}
for (uint32_t divider = 1000000000u; divider != 0u; divider /= 10u)
{
uint32_t num = val / divider;
if (num > 0u || started)
{
printf("%c", num + '0');
started = 1;
val -= (num * divider);
}
}
printf("\n");
}
Some notes - I've used uint32_t because it is unsigned and a nice length. To make it work with plain "ints" would involve handling the case of negative numbers, which is more complex. I don't know if you need to handle negative numbers. (Also, ints on your platform could be 64-bit, so the initial divider would have to be adjusted accordingly.)
The 'started' flag is used to signal when we have output at least one digit, to ensure zeros get printed correctly. Until that flag is set, leading zeros are not printed.
A very simple recursive solution looks like this:
void print_num(int num)
{
if (num < 10)
fputc('0' + num, stdout);
else {
print_num(num/10);
print_num(num%10);
}
}

Write a program, which reads an Integer. Output another integer where the even digits are retained and odd digits are decremented by 1,

Here is my code:
#include <stdio.h>
#include <math.h>
int main() {
int num, i = 0, new_num = 0, u;
printf("Enter a number: ");
scanf("%d", &num);
while (num > 0) {
u = num % 10;
if (u % 2 == 0)
u = u;
if (u % 2 == 1)
u = u - 1;
new_num = new_num + u * pow(10, i);
num = num / 10;
i++;
}
printf("The new number is: %d", new_num);
return 0;
}
Now, when I am doing this in gcc(VS Code), for 2-digit number everything is ok. But for digits more than three I am getting a error. Like Input=23145 Output=22043. But I was expecting output=22044.
Also, if I run the same code in DevC/C++, there is no error.
Can anyone help me out in this?
Your program produces the expected output on my system: 22044 for 23145, but this might depend on the implementation of the pow function.
The reason you get a different output is probably a side effect of a precision issue with the pow() function in your C library: if pow(x, y) is implemented as exp(y * log(x)), the result for integral values of x and y could be very close but inferior to the actual integral value, causing the conversion to int to produce the previous integer. Some C library authors make a special case of integral arguments to avoid this problem, but it is highly recommended to avoid floating point functions for integer arithmetics to prevent such tricky issues.
I would advise some more changes in your code:
test the return value of scanf().
remove the if (u % 2 == 0) u = u; part, it has no effect.
in any case, there should be an else clause to not use the result of the previous case when testing for odd digits.
do not use the floating point function pow(): just keep a multiplier variable and update it in the loop.
the program does not handle negative numbers.
Here is a modified version:
#include <stdio.h>
int main() {
int num, new_num = 0, pow10 = 1;
printf("Enter a number: ");
if (scanf("%d", &num) != 1)
return 1;
while (num != 0) {
int digit = num % 10;
/* decrement odd digits absolute value */
digit -= digit % 2;
new_num = new_num + digit * pow10;
pow10 = pow10 * 10;
num = num / 10;
}
printf("The new number is: %d\n", new_num);
return 0;
}
Note that digit -= digit % 2; will decrement positive odd digits and actually increment negative odd digits, which effectively always decrements the absolute value of odd digits. This way both positive values and negative values are handled correctly.
In my instance of Visual Studio Code, for an input 23145, I indeed find 22044 as an output.
I guess the divergence comes with the cast of pow(10,i). Pow function in C returns a double which is not what you really want here. I strongly advice to not use the pow function for integer arithmetic.
A solution could be :
uint16_t i = 0u;
uint16_t current_digit = 0u, decimal_digit = 1u;
uint16_t new_number = 0u;
uint16_t number = 23145u;
while(number > 0u) {
current_digit = number % 10;
if (current_digit % 2) {
current_digit = current_digit - 1;
}
new_number = new_number + current_digit * decimal_digit;
decimal_digit *= 10u;
number /= 10;
i++;
}
printf("The new number is: %d", new_number);
It seems that the problem is using the function pow that returns a double value.
If you are dealing with integers then it is better to avoid using functions that return doubles due to a possible truncation then a double is converted to an integer.
Also pay attention to that the user can enter a negative number. Your program allows to do that. In this case your program also will produce an incorrect result.
I would write the program the following way
#include <stdio.h>
int main( void )
{
while (1)
{
const int Base = 10;
int num;
printf( "Enter a number (0 - exit): " );
if (scanf( "%d", &num ) != 1 || num == 0) break;
int new_num = 0;
for (int tmp = num, multiplier = 1; tmp != 0; tmp /= Base)
{
int digit = tmp % Base;
if (digit % 2 != 0)
{
digit += ( digit < 0 ? 1 : -1 );
}
new_num = new_num + multiplier * digit;
multiplier *= Base;
}
printf( "The original number is %d and the new number is: %d\n",
num, new_num );
putchar( '\n' );
}
}
The program output is
Enter a number (0 - exit): -123456789
The original number is -123456789 and the new number is: -22446688
Enter a number (0 - exit): 123456789
The original number is 123456789 and the new number is: 22446688
Enter a number (0 - exit): 0
If even for negative digits to add -1 then you should substitute this if statement
if (digit % 2 != 0)
{
digit += ( digit < 0 ? 1 : -1 );
}
for this one
if (digit % 2 != 0)
{
digit = ( digit -1 ) % Base;
}
In this case the program output might look like
Enter a number (0 - exit): -123456789
The original number is -123456789 and the new number is: -224466880
Enter a number (0 - exit): 123456789
The original number is 123456789 and the new number is: 22446688
Enter a number (0 - exit): 0
That is in this case the new value for the negative value -123456789 will be -224466880.

How can I separate an integer into muliple digits?

I have a remainder function that finds that modulo of a number then a divider function to divide that number. My program isn't working the way I need it to. For example if I put in 2502 as my number, I should get the output of : 2 5 0 2.
I need to be able to store the value through each iteration, so for example:
number: 123
123 % 10 = 3 //last digit
Number: 123 / 10 = 12
12 % 10 = 2 //second digit
Number: 12 / 10 = 1
1 % 10 = 1 //first digit
int Rem(int num);
int Div(int num);
int main() {
int num;
printf("Enter an integer between 1 and 32767: ");
scanf("%d", &num);
Rem(num);
Div(num);
printf("%d","The digits in the number are: ");
}
int Rem(int num) {
while(num != 0){
int rem = num % 10;
return rem;
}
}
int Div(int num){
while(num != 0){
int div = num / 10;
return div;
}
}
The idea here is pretty simple, but there are some subtleties. Here's some pseudo code. You'll need to convert to C.
num = 9934; // or get it from input
do {
rem = num % 10; // this gives you the lowest digit
num = num / 10; // divide by 10 to get rid of that lowest digit
print rem;
} while (num != 0);
I use a do ... while loop so the output will be correct if the user enters 0.
If you code this up and run it, you'll notice that it prints the digits in reverse order: 4 3 9 9. So you'll need some way to reverse the digits before you output them. Three possible ways are:
Store the digits in an array, and then reverse the array before outputting.
Push each digit onto a stack. When you're done, pop each digit off the stack and output it.
Write a recursive function. That would eliminate the need for an explicit stack or array.
Also you could convert it to a string and then convert back the elements of that string, but keep '\0' in mind
You can simply use this function , it return the number of digits passing by argument
size_t ft_cnbr(int n)
{
size_t count;
count = 1;
if (n < 0)
{
count++;
n = -n;
}
while (n > 9)
{
n = n / 10;
count++;
}
return (count);
}

C: Decimal Value

Can any one help me sort out one problem, i have to reverse a number without using array(int/char) for storing them.
input1 = 123
output1 = 321
input2 = 2300
output2 = 0032
I am trying to find the solution but 0 got erased while printing so i thought of octal conversion but still no solution, so i went with the decimal places and i made the 23 to 0.0032. Now my problem is how can i extract the 0032 from that part.
Is there any possible way to achieve this without using array(int/char), with that it will be easy.
#include<stdio.h>
#include<math.h>
int main()
{
int number =3200;
int temp;
while (number >0)
{
temp= number%10;
printf("%d",temp);
number = number/10;
}
return 0;
}
you could use recursion to solve this problem, without using any array in fact u could also reverse a string without using any array using recursion. This code works for both numbers and strings and it has no arrays:
char reverse(int a)
{
char c,d;
if(a=='\n')
return 0;
c=getchar();
d=reverse(c);
putchar(a);
return (c);
}
int main()
{
char c;
scanf("%c",&c);
reverse(c);
}
for a start try this.
int n, l;
char nBuf[126];
n = 1230010;
l = sprintf(nBuf, "%d", n );
while( l >= 0 )
printf("%c", nBuf[l--] );
Though if you are taking input from stdin take it as string rathar than as int or long.
Edit - for not using array
int n = 123;
while(n) {
printf("%d", n%10);
n/=10;
}
I am assuming to get a value of this sort "output2 = 0032" it is better of being a string, else formatting complications turns up with input value length and format left space with zeros etc etc.
This becomes fairly easy if you know that you can represent numbers like so:
x = a_0 + a_1 * b^1 + a_2 * b^2 + ...
a_i are the digits
b is the base
To extract the lowest digit, you can use the remainder: x % b
Dividing by the base "removes" the last digit. That way you can get the digits in order lowest to highest.
If you reverse the digits then the lowest becomes the highest. Looking at below transformation it's easy to see how to incrementally build up a number when the digits come in order highest to lowest:
x = a_0 + b * (a_1 + b * (a_2 + ...
You start of with 0, and for each digit you multiply with the base and then add the digit.
In pseudo code:
output = 0
while input != 0
digit = input % base
input = input / base ;; integer division
output = output * base + digit
end
If you want to store leading zeros, then you need to either store the digits in an array, or remember for how many steps of above loop the output remained zero:
output = 0
zeros = 0
while input != 0
digit = input % base
input = input / base ;; integer division
output = output * base + digit
if output == 0
zeros = zeros + 1
end
end
To print that you obviously need to print zeros zeros and then the number.
Live example here, relevant code:
unsigned reverse(
unsigned input,
unsigned const base,
unsigned * const zeros) {
unsigned output = 0;
unsigned still_zero = 0;
for (; input != 0; input/=base) {
output *= base;
output += input % base;
if (output == 0) {
++still_zero;
}
}
if (zeros != NULL) {
*zeros = still_zero;
}
return output;
}
void print_zeros(unsigned zeros) {
for (; zeros != 0; --zeros) {
printf("0");
}
}
Recursion allows for a simple solution. A small variation on #vishu rathore
void rev_dec(void) {
int ch = getchar();
if (isdigit(ch)) {
rev_dec();
}
if (ch >= 0) putchar(ch);
}
int main(void) {
rev_dec();
return 0;
}
input
0123456789012345678901234567890123456789
output
9876543210987654321098765432109876543210

Sum of Digits using recursion in C

For our activity today, we were tasked to make using recursion with the sum of digits. I already made this program:
int main()
{
int num = 0, sum;
printf("Enter an integer: ");
scanf("%d",&num);
//counter=1;
for ( sum=0; num>0;)
{
sum = sum + num % 10;
num = num /10;
}
printf("Sum = %d", sum);
getch();
return 0;
}
Our teacher added "Input and output must be done in the main() function." Am doing the right thing? Or am I missing something in my code?
To do recursion, create a function that recurses rather than using a for loop.
int SumDigits(int i) {
if (i < 10) {
return i;
}
else {
return i%10 + SumDigits(i/10);
}
}
scanf("%d", &i);
printf("%d\n", SumDigits(i));
What you have there is an iterative solution, not a recursive one.
Recursion involves defining the problems in terms of a simpler version of the problem, all the time working towards a fixed end point.
The fixed end point in this case is any number less than 10, for which the value is that digit.
The transition to a simpler case (for numbers greater than 9) is simply to add the least significant digit to the result of the number divided by ten (integer division).
Since it's classwork, pseudo-code only I'm afraid.
def digitSum (n):
if n < 10:
return n
return (n % 10) + digitSum (n / 10)
If you follow that for the number 314, you'll see what happens.
At recursion level one, n == 314 so it calculates 314 % 10 to get 4 and calls digitSum(31).
At recursion level two, n == 31 so it calculates 31 % 10 to get 1 and calls digitSum(3).
At recursion level three, n == 3 so it just returns 3
Back up to level two, that's added to the remembered 1 and returned as 4.
Back up to level one, that's added to the remembered 4 and returned as 8.
Hence you end up with the digit sum of 8 for the number 314.

Resources