Transpose function, decimal to binary - c

i am trying to develop a transpose function which can transpose from decimal to binary an up to 9digits number. I'm pretty new on coding and this is my first try. But it does not seem to be working, sorry if i am asking something obvious, but i need some help. Thanks in advance.
void transpose(int n)
{
int c, k;
for (c = 31; c >= 0; c--)
{
k = (n % c);
if (k == 0) printf("1");
else printf("0");
}
}

Instead of using arithmetic operations, you could use bitwise operations and get the digit directly:
for (c = 31; c >= 0; --c)
{
printf("%d", (n >> c) & 1);
}
This shifts the value in n right by c steps, i.e. putting bit number c in the rightmost (least-signigficant) bit. Then the mask with 1 will result in either a one or a zero, which is then printed.

#include <stdio.h>
#include <limits.h>
void transpose(int n){
unsigned x;
char bits[CHAR_BIT * sizeof(n)+1];
char *p = bits + CHAR_BIT * sizeof(n);
*p = '\0';
for(x=n; p!=bits ;x>>=1)
*--p = "01"[x & 1];
puts(bits);
}

Debugging your program for n = 5:
When c becomes 5, 1 get printed after 26 0's
000000000000000000000000001
now for rest of c (till 0), the output is
00000000000000000000000000100000
and unfortunately this is not 5 in decimal. Hope you understand what you are doing wrong.

You are checking whether a number n is divisible by all numbers 31 to 0. This is not what you need to do to convert the base.
Where a decimal representation shows you a number, for instance, 6174 (kapreka constant)
as able to be built up out of these blocks:
4 * 10^0
7 * 10^1
1 * 10^3
6 * 10^4
0*..
0*..
you would want your transpose function to result in a representation of powers of 2. I hope this helps directing you to an answer.

Related

Octal to decimal and binary with wrong outputs

We were assigned a task to convert octal numbers to binary and decimal. Smaller numbers works just fine but it then gives a different output at a higher input. Here is the code:
#include <stdio.h>
void main() {
unsigned long n, g, ans = 1, r = 0, dec = 0, place = 1, bin = 0;
printf("Conversion: Octal to decimal and binary.\n");
printf("Enter number: ");
scanf("%lu", &n);
printf("%lu is ", n);
for (g = n; g != 0; ans = ans * 8) {
r = g % 10;
dec = dec + r * ans;
g = g / 10;
}
printf("%lu in Decimal Form. \n", dec);
printf("%lu is ", n);
for (; dec != 0; place = place * 10) {
r = dec % 2;
bin = bin + (r * place);
dec = dec / 2;
}
printf("%lu in Binary Form.\n", bin);
}
We were only required to use limited data types and control structures. No arrays, strings, functions or such.
The input in our teacher's test case is 575360400 which must print an output of 101111101011110000100000000 in binary and 100000000 in decimal. But the output in binary is 14184298036271661312. I used unsigned long already and it just won't work.
I don't know how this is possible with the given restrictions and your comments and answers will be really much of a help.
Smaller numbers works just fine but it then gives a different output at a higher input.
Overflow
Input "575360400" (base 8) converts to a 27-bit value. For place = place * 10 ... bin = bin + (r * place); to work, bin needs to be a 90-bit unsigned long. unsigned long is certainly 64-bit or less.
OP needs a new approach.
I'd start with reading the octal input with scanf("%lo", &n); and printing the decimal with printf("%lu\n", n);.
To print in binary, without arrays, functions, etc., consider a mask, first with the most significant bit, that is shifted right each iteration.
bool significant_digit = false;
// Form 0b1000...0000
// 0b1111... - 0b01111..
unsigned long mask = ULONG_MAX - ULONG_MAX/2;
while (mask) {
bool bit = mask & n;
if (bit || significant_digit || mask == 1) {
significant_digit = true;
printf("%d", bit);
}
mask >>= 1;
}
printf("\n", bit);
}
Better approaches exist. Yet with OP's artificial limitations: "No arrays, strings, functions or such.", I opted for something illustrative and simple.
Or wait until 2023
C2x expected to support printf("%lb\n", n);. Just ask the professor for an extension 😉.

How to print values in reverse without the use of arrays nor pointers in C

I've been working on a code that converts a given number (decimal base) to any other base from 2 to 16.
Clearly, I've come across the issue that the function base_conversion_it (it stands for iterative) prints the values in reverse.
I cannot use arrays nor pointers, and everyone on the internet seems to solve this issue like that. My assignment requires making both an iterative and a recursive function (which I did and works).
void base_conversion_it(unsigned int n, unsigned int b) {
if (n > 0) {
//bases between 2 and 16
if (b >= 2 && b <= 16) {
int r; //r = remainder
int q = 1; //quotient
int num; //saves the remainder
while (q != 0) {
r = n % b;
printf("%X", r);
q = n / b;
n = q;
}
}
}
}
You start converting from the units digit.
Maybe start with the most significant digit instead?
// It's Undefined Behaviour if `b` is outside the range [2...16]
void base_conversion_it(unsigned int n, unsigned int b) {
unsigned highestbase = 1;
while (highestbase * b <= n) highestbase *= b; //possible wrap around and infinite loop
while (highestbase) {
printf("%X", n / highestbase);
n %= highestbase;
highestbase /= b;
}
printf("\n");
}
Sorry missed iterative.
char digits[] = "0123456789ABCDEFGHIJKLMNOP";
void print(unsigned long long val, unsigned base)
{
unsigned long long mask = base;
while(val / mask >= base) mask *= base;
do
{
printf("%c", digits[val / mask]);
val %= mask;
mask /= base;
}while(val);
}
int main(void)
{
print(45654756453, 10); printf("\n");
print(45654756453, 16); printf("\n");
print(45654756453, 24); printf("\n");
print(45654756453, 2); printf("\n");
}
https://godbolt.org/z/W3fGnnhYs
Recursion:
char digits[] = "0123456789ABCDEF";
void print(unsigned long long val, unsigned base)
{
if(base <= 16 && base > 1)
{
if(val >= base) print(val / base, base);
printf("%c", digits[val % base]);
}
}
https://godbolt.org/z/84hYocnjv
If you cannot use either arrays (including strings) or recursion, then I think you need to compute the output digits in most-significant-first order. This is a bit less natural than computing them in the opposite order and reversing the result, but it can be done:
use a loop to find the place value of the most significant non-zero base-b digit of n. For example, check the result of dividing n by successive powers of b until the result is 0, then back off one step.
In a separate loop, read off the base-b digits of n one by one, starting with the one at the discovered most-significant position. For each digit,
Divide the current value of n by the place value pv of the current digit to get a digit value.
Replace n with n % pv.
Be careful to continue all the way down to place value 1, as opposed, say, to stopping when n becomes zero.

increment digits of natural number recursively

I wanna make a funcion that will take a natural number and make a new number so every digit in the old number will be incremented and if the digit is 9 it will become zero, but not to check specificly if the digit is 9.
example:
930 will return 41
9999 will return 0
879021 will return 980132.
This is what i got so far:
int newNumber(int n)
{
int dig;
if (n < 9)
return n + 1;
dig = n % 10;
dig++;
n = n / 10;
n = n * 10 + dig;
return newNumber(n/10);
}
There are a couple of issues with your code:
It doesn't handle a single digit of 9 (which cause a stack overflow).
Adding 1 to 9 makes 10 not 0.
I've run it through the sample data you supplied and it seems to work (in C#) and it has a hard core recursive line at the end.
int newNumber(int n)
{
if (n == 9)
return 0;
if (n < 9)
return n + 1;
return (newNumber(n / 10) * 10) + newNumber(n % 10);
}
Here's to avoid the check for n == 9:
int newNumber(int n)
{
static int table[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
return (n <= 9) ? table[n] : (newNumber(n / 10) * 10) + newNumber(n % 10);
}
A lookup table seems the most appropriate and does exactly what the requirements describe. Trying to use the non-compatible arithmetic operators results in side effects (as we see in Bathsheba's answer for example), that then need to be corrected.
unsigned newNumber(unsigned n, unsigned c = 0)
{
return n ? (n + 1) % 10 + 10 * newNumber(n / 10, 1 + c) : !c;
}
is one way, and it will treat 0 as 1, via the !c branch where c counts the number of recursions. Note the tail recursion in the ternary conditional branch - some compilers will optimise a tail recursion out to a simple loop, see What is tail recursion?
Bathsheba's solution posted above is very elegant by using the ternary operator, but it will give you a wrong result if the input is zero. To avoid that you may use a stub function:
#include <stdio.h>
int incDigits(int n)
{
return n ? (n + 1) % 10 + incDigits(n / 10) * 10 : 0;
}
int newNumber(int n)
{
return n ? incDigits(n) : 1;
}
int main()
{
for(int i = 0; i <= 100; ++i)
{
int n = newNumber(i);
printf("%d -> %d\n", i, n);
}
}
EDIT: user meaning-matters also posted a way to fix the input value problem using a lookup table, but he still has to check if n equals 9, which is something you don't want. So I believe using a stub function still is the best way.
Two ternary operator has been used to take care of the two cases:
i) number equal to 9
ii) number not equal to 9 => Another ternary operator is used to take care of further two possible cases:
a) number greater than 9( return sum of num(n/10)*10 and num(n%10) ); this can be further elaborated based on the argument fed to the num function.
b)number smaller than 9(return number plus one(n+1))
Once this function is called from the main function with argument equal to the number to be transformed in the manner asked in the question, each call in line4 will undergo recursion until they pass the argument to the subsequent iteration less than or equal to 9(which leads to termination of the recursion). With basic understanding of recursion, the above para can easily be understood in context to the subroutine below.
Blockquote
int num(int n)//line1
{//line2
int t;//line3
t=(n==9?0:(n>9?num(n/10)*10+num(n%10):n+1));//line4
return t;/line5
}//line6
Blockquote

Decimal to octal in C

I have just begun teaching myself C out of K.N King's C Programming: A Modern Approach (2ndEdn).
I'm enjoying it, but am hoping to post the odd question here for advice if appropriate because unfortunately I don't have a tutor and some bits raise more questions then they answer!
I'm doing a question on taking an integer entered and displaying it in octal. It says there is an easy way to do it, but that comes later in the book. I have come up with the following:
// Convert a number to octal
int n, n2, n3, n4, n5, n6;
printf("Enter a number between 0 and 32767: ");
scanf("%d", &n);
n6 = n % 8;
n5 = (n / 8) % 8;
n4 = ((n / 8) / 8) % 8;
n3 = (((n / 8) / 8) / 8) % 8;
n2 = ((((n / 8) / 8) / 8) / 8) % 8;
printf("%d%d%d%d%d", n2, n3, n4, n5, n6);
It works OK, but I'm not good at math and was wondering if there is a more efficient way of doing this or have I done it the only way possible...
If anyone else has the book it's Q4 p.71.
Thanks for your time.
Andrew
P.S I did look in the search engine but couldn't find anything that was doing it this 'slower' way!
Everyone is right in saying that there's a built-in way to do that with printf. But what about doing it yourself?
The first thing that came to mind is that one octal digit is exactly three bits. Therefore you can do the conversion this way:
Loop while n != 0
Isolate the leftmost 3 bits of n into d and print d
Shift n 3 bits to the left
The code is trivial, but I 'm not providing it so you can do it yourself (you will need to be familiar with the bitwise and shift operators in order to do it).
The easy way is probably to use printf()'s %o format specifier:
scanf("%d", &n);
printf("%o", n);
Others have posted the real, production code answer, and now I see from your comments that you haven't done loops yet. Perhaps your book is trying to teach you about recursion:
void print_oct(int n)
{
if (n != 0) {
print_oct(n / 8);
printf("%d", n % 8);
}
}
This works for n > 0.
With loops you can roll up your five very similar lines like this:
for (int d = 8 * 8 * 8 * 8; d > 0; d /= 8)
printf("%d", n / d % 8);
printf("\n");
d will start at 8 * 8 * 8 * 8, which is the divisor you use for n2 and then step through 8 * 8 * 8, 8 * 8, 8 and finally 1, which is the divisor for n6, printing each digit along the way.
A good compiler will actually optimize this by unrolling it back into five lines, so you'll get almost the same thing you started with. The advantage of writing it as a loop is that you can't make a mistake in just one of the lines.
The compiler will also take care of replacing divisions by 8 with shifts by 3 bits. Both give the same result in binary, but the latter is faster.
/* Converts a positive base_10 into base_b */
int DecimalToBase(int n, int b)
{
int rslt=0, digitPos=1;
while (n)
{
rslt += (n%b)*digitPos;
n /= b;
digitPos *= 10;
}
return rslt;
}
Use %o format specifier inside printf
printf("Enter a number between 0 and 32767: ");
scanf("%d", &n);
printf("%o", n);
Since only basics are introduced you don't want (at least at this point) to use functions, loops, bitwise operators, %o format specifier and all that stuff. Here is my basic solution:
int n, d1, d2, d3, d4, d5, o;
printf("Enter a number between 0 and 32767: ");
scanf("%d", &n);
d5 = n % 8;
n /= 8;
d4 = n % 8;
n /= 8;
d3 = n % 8;
n /= 8;
d2 = n % 8;
n /= 8;
d1 = n % 8;
o = 10000 * d1 + 1000 * d2 + 100 * d3 + 10 * d4 + d5;
printf("In octal, your number is: %.5d\n", o);
Note that since n is not needed in output, you can modify (divide) it for every step (thus saving divides, which are computationally and relatively expensive). You are safe up to 32767 (in octal: 77777), as 32768 (8*8*8*8*8 = 8^5 = (2^3)^5 = 2^15) is the first number, that requires six digits in octal: 100000.
This o variable is not really needed, morever it will not work when int is signed 16-bit (on some ancient system), so from this point it's better to just print separate digits.
Existing answers aren't clean enough for my liking. Here's mine:
#include <stdio.h>
#define OCTALBASE 8
#define OCTALSIZE 8
int main(int argc, char **argv) {
int indecimal = 1337;
char output[OCTALSIZE + 1];
output[OCTALSIZE] = '\0';
int outindex = OCTALSIZE;
int outdigit = 0;
int outvalue = indecimal;
while (--outindex >= 0) {
outdigit = outvalue % OCTALBASE;
if (outvalue > 0 || outdigit > 0)
{ output[outindex] = '0' + outdigit; }
else { output[outindex] = ' '; }
outvalue /= OCTALBASE;
}
fprintf(stdout, "{ DEC: %8d, OCT: %s }\n", indecimal, output);
fflush(stdout);
return 0;
}
Result:
{ DEC: 1337, OCT: 2471 }
Convert Decimal to Octal in C Language
#include<stdio.h>
#include<conio.h>
void main()
{
A:
long int n,n1,m=1,rem,ans=0;
clrscr();
printf("\nEnter Your Decimal No :: ");
scanf("%ld",&n);
n1=n;
while(n>0)
{
rem=n%8;
ans=(rem*m)+ans;
n=n/8;
m=m*10;
}
printf("\nYour Decimal No is :: %ld",n1);
printf("\nConvert into Octal No is :: %ld",ans);
printf("\n\nPress 0 to Continue...");
if(getch()=='0')
goto A;
printf("\n\n\n\tThank You");
getch();
}

Subtraction without minus sign in C

How can I subtract two integers in C without the - operator?
int a = 34;
int b = 50;
You can convert b to negative value using negation and adding 1:
int c = a + (~b + 1);
printf("%d\n", c);
-16
This is two's complement sign negation. Processor is doing it when you use '-' operator when you want to negate value or subtrackt it.
Converting float is simpler. Just negate first bit (shoosh gave you example how to do this).
EDIT:
Ok, guys. I give up. Here is my compiler independent version:
#include <stdio.h>
unsigned int adder(unsigned int a, unsigned int b) {
unsigned int loop = 1;
unsigned int sum = 0;
unsigned int ai, bi, ci;
while (loop) {
ai = a & loop;
bi = b & loop;
ci = sum & loop;
sum = sum ^ ai ^ bi; // add i-th bit of a and b, and add carry bit stored in sum i-th bit
loop = loop << 1;
if ((ai&bi)|(ci&ai)|(ci&bi)) sum = sum^loop; // add carry bit
}
return sum;
}
unsigned int sub(unsigned int a, unsigned int b) {
return adder(a, adder(~b, 1)); // add negation + 1 (two's complement here)
}
int main() {
unsigned int a = 35;
unsigned int b = 40;
printf("%u - %u = %d\n", a, b, sub(a, b)); // printf function isn't compiler independent here
return 0;
}
I'm using unsigned int so that any compiler will treat it the same.
If you want to subtract negative values, then do it that way:
unsgined int negative15 = adder(~15, 1);
Now we are completly independent of signed values conventions. In my approach result all ints will be stored as two's complement - so you have to be careful with bigger ints (they have to start with 0 bit).
Pontus is right, 2's complement is not mandated by the C standard (even if it is the de facto hardware standard). +1 for Phil's creative answers; here's another approach to getting -1 without using the standard library or the -- operator.
C mandates three possible representations, so you can sniff which is in operation and get a different -1 for each:
negation= ~1;
if (negation+1==0) /* one's complement arithmetic */
minusone= ~1;
else if (negation+2==0) /* two's complement arithmetic */
minusone= ~0;
else /* sign-and-magnitude arithmetic */
minusone= ~0x7FFFFFFE;
r= a+b*minusone;
The value 0x7FFFFFFFE would depend on the width (number of ‘value bits’) of the type of integer you were interested in; if unspecified, you have more work to find that out!
+ No bit setting
+ Language independent
+ Can be adjusted for different number types (int, float, etc)
- Almost certainly not your C homework answer (which is likely to be about bits)
Expand a-b:
a-b = a + (-b)
= a + (-1).b
Manufacture -1:
float: pi = asin(1.0);
(with minusone_flt = sin(3.0/2.0*pi);
math.h) or = cos(pi)
or = log10(0.1)
complex: minusone_cpx = (0,1)**2; // i squared
integer: minusone_int = 0; minusone_int--; // or convert one of the floats above
+ No bit setting
+ Language independent
+ Independent of number type (int, float, etc)
- Requires a>b (ie positive result)
- Almost certainly not your C homework answer (which is likely to be about bits)
a - b = c
restricting ourselves to the number space 0 <= c < (a+b):
(a - b) mod(a+b) = c mod(a+b)
a mod(a+b) - b mod(a+b) = c mod(a+b)
simplifying the second term:
(-b).mod(a+b) = (a+b-b).mod(a+b)
= a.mod(a+b)
substituting:
a.mod(a+b) + a.mod(a+b) = c.mod(a+b)
2a.mod(a+b) = c.mod(a+b)
if b>a, then b-a>0, so:
c.mod(a+b) = c
c = 2a.mod(a+b)
So, if a is always greater than b, then this would work.
Given that encoding integers to support two's complement is not mandated in C, iterate until done. If they want you to jump through flaming hoops, no need to be efficient about it!
int subtract(int a, int b)
{
if ( b < 0 )
return a+abs(b);
while (b-- > 0)
--a;
return a;
}
Silly question... probably silly interview!
For subtracting in C two integers you only need:
int subtract(int a, int b)
{
return a + (~b) + 1;
}
I don't believe that there is a simple an elegant solution for float or double numbers like for integers. So you can transform your float numbers in arrays and apply an algorithm similar with one simulated here
If you want to do it for floats, start from a positive number and change its sign bit like so:
float f = 3;
*(int*)&f |= 0x80000000;
// now f is -3.
float m = 4 + f;
// m = 1
You can also do this for doubles using the appropriate 64 bit integer. in visual studio this is __int64 for instance.
I suppose this
b - a = ~( a + ~b)
Assembly (accumulator) style:
int result = a;
result -= b;
As the question asked for integers not ints, you could implement a small interpreter than uses Church numerals.
Create a lookup table for every possible case of int-int!
Not tested. Without using 2's complement:
#include <stdlib.h>
#include <stdio.h>
int sillyNegate(int x) {
if (x <= 0)
return abs(x);
else {
// setlocale(LC_ALL, "C"); // if necessary.
char buffer[256];
snprintf(buffer, 255, "%c%d", 0x2d, x);
sscanf(buffer, "%d", &x);
return x;
}
}
Assuming the length of an int is much less than 255, and the snprintf/sscanf round-trip won't produce any unspecified behavior (right? right?).
The subtraction can be computed using a - b == a + (-b).
Alternative:
#include <math.h>
int moreSillyNegate(int x) {
return x * ilogb(0.5); // ilogb(0.5) == -1;
}
This would work using integer overflow:
#include<limits.h>
int subtractWithoutMinusSign(int a, int b){
return a + (b * (INT_MAX + INT_MAX + 1));
}
This also works for floats (assuming you make a float version…)
For the maximum range of any data type , one's complement provide the negative value decreased by 1 to any corresponding value. ex:
~1 --------> -2
~2---------> -3
and so on... I will show you this observation using little code snippet
#include<stdio.h>
int main()
{
int a , b;
a=10;
b=~a; // b-----> -11
printf("%d\n",a+~b+1);// equivalent to a-b
return 0;
}
Output: 0
Note : This is valid only for the range of data type. means for int data type this rule will be applicable only for the value of range[-2,147,483,648 to 2,147,483,647].
Thankyou .....May this help you
Iff:
The Minuend is greater or equal to 0, or
The Subtrahend is greater or equal to 0, or
The Subtrahend and the Minuend are less than 0
multiply the Minuend by -1 and add the result to the Subtrahend:
SUB + (MIN * -1)
Else multiply the Minuend by 1 and add the result to the Subtrahend.
SUB + (MIN * 1)
Example (Try it online):
#include <stdio.h>
int subtract (int a, int b)
{
if ( a >= 0 || b >= 0 || ( a < 0 && b < 0 ) )
{
return a + (b * -1);
}
return a + (b * 1);
}
int main (void)
{
int x = -1;
int y = -5;
printf("%d - %d = %d", x, y, subtract(x, y) );
}
Output:
-1 - -5 = 4
int num1, num2, count = 0;
Console.WriteLine("Enter two numebrs");
num1 = int.Parse(Console.ReadLine());
num2 = int.Parse(Console.ReadLine());
if (num1 < num2)
{
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
}
for (; num2 < num1; num2++)
{
count++;
}
Console.WriteLine("The diferrence is " + count);
void main()
{
int a=5;
int b=7;
while(b--)a--;
printf("sud=%d",a);
}

Resources