#include <stdio.h>
int sum(int a, int b, int c) {
return a + b + c / 2;
}
void main() {
int (*function_pointer)(int, int, int); // how this will be interpreted
function_pointer = sum;
printf("%d", function_pointer(2, 3, 4));
return ;
}
When i ran on ide it gave output 7, i dont understand how?
The statement
int (*function_pointer)(int, int, int);
declares a pointer to a function that accepts three int arguments and return an int. Latter this is pointed to function sum and used to call the function.
Inside the sum function the statement
return a + b + c / 2;
is parsed as
return a + b + (c / 2); // division operator has higher precedence than + operator
// and therefore the operands `c` and `2` will be bind to `/` operator
this:
int (*function_pointer)(int, int, int);
means you are defining a function pointer with the name function_pointer that can be used as alias for ANY other function that takes 3 integers as parameter an returns an integer
then when you do this:
function_pointer = sum;
you are assigning the address of the function sum to the function_pointer, that means later, you can do both:
function_pointer(2, 3, 4)
or
sum(2, 3, 4)
now to the result, and why is printing out 7
a + b + c / 2
with 2,3,4 is the same as 2 + 3 + 4 / 2 or 2 + 3 + 2 = 7
Related
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a , b ,c ;
printf("Enter values for a and b: ");
scanf("%d%d",&a,&b);
a = a + b-- ;
if (a<b){
c = -1;
printf("\n\t%d %d %d\n\n",a,b,c);
}
else {
c = 0;
printf("\n\t%d %d %d\n\n",a,b,c);
}
}
Lets assume the value of the input for a and b are 2 (for both of them).
I studied the above program, but when it comes to the output it will be 4 1 0, a=4,b=1,c=0.
But, the calculation part above said that a=a+b-1 which will be the value of a is 3, now the new value of a is 3. But for b the value is still 2 because we didn't assign a new value to it.
I am very confused about the output.
There is a difference between a+1, a++ and ++a. Details here.
Therefore, when you say
a = a + b--;
You are actually saying
a = a + b;
b = b - 1;
If you say
a = a + --b;
It becomes
b = b - 1;
a = a + b;
And if you say
a = a + (b-1)
It does what you think: a = a + b - 1. The value of b doesn't change afterwards.
At the beginning, a and b are both 2
Then, you execute a = a + b--;.
The decrement operator is located after the b, so it evaluates to:
a=a+b;
b=b-1;
After this, a will be 4 and b will be 1.
a is not smaller than b, so c will be 0.
Note:
If it would be a = a + --b, it would evaluate to
b=b-1;
a=a+b;
Because the -- is executed at the beginning of the evaluation.
I would like to compare two positive integers and add a comparison sign between them. I may not use any logical, relational or bitwise operators and no if then else or while loop or ternary operator.
I found the max and min of these two numbers.
How can I preserve the order and still insert the comparison sign? Any ideas?
E.g.:
4 6 was entered by user output must be 4 < 6
10 2 was entered by user output must be 10 > 2
2 2 was entered by user output must be 2 = 2
f1 = x / y;
f2 = y / x;
f1 = (f1 + 2) % (f1 + 1);
f2 = (f2 + 2) % (f2 + 1);
max = f1 * x + f2 * y ;
max = max / (f1 + f2);
You can use an array of char:
#include <stdio.h>
int main(void)
{
unsigned a, b;
scanf("%u %u", &a, &b);
size_t cmp = (_Bool)(a / b) - (_Bool)(b / a);
char relation = "<=>"[cmp + 1];
printf("%u %c %u\n", a, relation, b);
return 0;
}
This approach don't require min and max found out.
Explanation:
(_Bool)exp will be 1 if exp is non-zero, and 0 if exp equals to 0.
Since a and b are positive integers, a / b will be 0 when a < b, and 1 when a >= b. See the truth table below for details.
(_Bool)(a / b) (_Bool)(b / a) (_Bool)(a / b) - (_Bool)(b / a)
a > b 1 0 1
a = b 1 1 0
a < b 0 1 -1
As a result, cmp evaluates to -1, 0, 1, like a typical comparison function. And thus, cmp + 1 will conveniently lead to 0, 1, 2 valid array indexes.
Thanks #janos for his help.
Edit:
As #chux carefully points out,
OP stated "I may not use any logical, ... operators". The C spec has
"... the logical negation operator !...". §6.5.3.3 5. Using ! may not
meet OP's goals.
So I changed !!exp to (_Bool)exp to meet OP's demand.
Edit II:
OP commented:
Thanks. This does not work when one of the inputs is 0.
But isn't the input numbers granted to be positive? Well, to handle zeros you can use size_t cmp = (_Bool)((a + (_Bool)(a - UINT_MAX)) / (b + (_Bool)(b - UINT_MAX))) - (_Bool)((b + (_Bool)(b - UINT_MAX)) / (a + (_Bool)(a - UINT_MAX)));. Don't forget to #include <limits.h>.
EDIT III (The last edit, I hope):
#include <stdio.h>
#include <limits.h>
#define ISEQUAL(x, y) (_Bool)((_Bool)((x) - (y)) - 1) // 1 if x == y, 0 if x != y
#define NOTEQUAL(x, y) (_Bool)((x) - (y)) // 0 if x == y, 1 if x != y
int main(void)
{
unsigned a, b;
printf("%u\n", UINT_MAX);
scanf("%u %u", &a, &b);
_Bool hasZero = NOTEQUAL(ISEQUAL(a, 0) + ISEQUAL(b, 0), 0);
_Bool hasMax = NOTEQUAL(ISEQUAL(a, UINT_MAX) + ISEQUAL(b, UINT_MAX), 0);
int hasBoth = ISEQUAL(hasZero + hasMax, 2);
int cmp = (_Bool)((a + hasZero + hasBoth) / (b + hasZero + hasBoth))\
- (_Bool)((b + hasZero + hasBoth) / (a + hasZero + hasBoth));
// "+ hasZero + hasBoth" to avoid div 0: UINT_MAX -> 1, while 0 -> 2.
hasBoth = 1 - hasBoth * 2; // 1 if hasBoth == 0, or -1 if hasBoth == 1
char relation = "<=>"[hasBoth * cmp + 1]; // reverse if has both 0 and UINT_MAX
printf("%u %c %u\n", a, relation, b);
return 0;
}
Fixed a bug when a == UINT_MAX - 1 and b == UINT_MAX at #chux points out.
Used macro to improve readability.
Added some comments.
As OP has x, y and has computed their minimum min and maximum max
void prt(unsigned x, unsigned y, unsigned min, unsigned max) {
// min not used
unsigned cmp = 1 + x/max - y/max;
printf("%u %c %u\n", x, "<=>"[cmp], y);
}
#include <stdio.h>
static unsigned int cmpgt(const unsigned int a, const unsigned int b)
{
return b?(a/b ? (a-b):0):a;
// if B is 0, then return A. non zero A will be treated as true
// if a is zero then is false
// if b is not zero then do a/b, if non zero then return (a-b)
// non zero (a-b) will be treated as true
// if (a-b) is zero then will be treated as false
//
// This is a very ugly way of implementing operator >
// There are other ways to do it
// But the point is, you need operator >, but you can not use it
// ( for whatever reason), then you just make it, which is doable
}
static const char *mark(const unsigned int a, const unsigned int b)
{
return cmpgt(a, b)?">":(cmpgt(b,a)?"<":"=");
// no if-else, but ternary operator is a good alternative
// so those are two nested operator ?:
// basically :
// if a>b then return ">"
// else if a<b return "<"
// else return "="
// with cmpgt/operator > implemented, this is a lot easier
}
int main(void) {
const int input[] = {1,3,4,5,5,2,3,4}; //test input
size_t input_size = sizeof(input)/sizeof(int);
for (size_t i=0;cmpgt(input_size-1, i);i++){
// while loop is banned, but for loop is still usable
// the loop condition is handled by cmpgt
printf("%d %s ",input[i],mark(input[i], input[i+1]));
}
printf("%d\n", input[input_size-1]);
return 0;
}
sample output:
1 < 3 < 4 < 5 = 5 > 2 < 3 < 4
https://ideone.com/dFHWnn
A simple compare is to use <=, >= and then lookup the compare character from a string.
void cmp1(unsigned x, unsigned y) {
int cmp = (x >= y) - (x <= y);
printf("%u %c %u\n", x, "<=>"[cmp + 1], y);
}
Yet since we cannot use various operators, etc., All we need to do is replace >=.
_Bool foo_ge(unsigned x, unsigned y) {
_Bool yeq0 = 1 - (_Bool)y; // y == 0?
_Bool q = (x + yeq0)/(y + yeq0); // Offset both x,y, by yeq0
return q + yeq0;
}
void cmp2(unsigned x, unsigned y) {
int cmp = foo_ge(x,y) - foo_ge(y,x)
printf("%u %c %u\n", x, "<=>"[cmp + 1], y);
}
Heavy use of _Bool credit to #sun qingyao
i have the recurrence relation of
and the initials condition is
a0 = a1 = 0
with these two, i have to find the bit strings of length 7 contain two consecutive 0 which i already solve.
example:
a2 = a2-1 + a2-2 + 22-2
= a1 + a0 + 20
= 0 + 0 + 1
= 1
and so on until a7.
the problem is how to convert these into c?
im not really good at c but i try it like this.
#include<stdio.h>
#include <math.h>
int main()
{
int a[7];
int total = 0;
printf("the initial condition is a0 = a1 = 0\n\n");
// a[0] = 0;
// a[1] = 0;
for (int i=2; i<=7; i++)
{
if(a[0] && a[1])
a[i] = 0;
else
total = (a[i-1]) + (a[i-2]) + (2 * pow((i-2),i));
printf("a%d = a(%d-1) + a(%d-2) + 2(%d-2)\n",i,i,i,i);
printf("a%d = %d\n\n",i,total);
}
}
the output are not the same as i calculate pls help :(
int func (int n)
{
if (n==0 || n==1)
return 0;
if (n==2)
return 1;
return func(n-1) + func(n-2) + pow(2,(n-2));
}
#include<stdio.h>
#include <math.h>
int main()
{
return func(7);
}
First of uncomment the lines which initialized the 2 first elements. Then at the for loop the only 2 lines need are:
a[i]=a[i-1]+a[i-2]+pow(2, i-2);
And then print a i
In the pow() function, pow(x,y) = x^y (which operates on doubles and returns double). The C code in your example is thus doing 2.0*(((double)i-2.0)^(double)i)... A simpler approach to 2^(i-2) (in integer math) is to use the bitwise shift operation:
total = a[i-1] + a[i-2] + (1 << i-2);
(Note: For ANSI C operator precedence consult an internet search engine of your choice.)
If your intention is to make the function capable of supporting floating point, then the pow() function would be appropriate... but the types of the variables would need to change accordingly.
For integer math, you may wish to consider using a long or long long type so that you have less risk of running out of headroom in the type.
Consider the following code:
#define P1(x) x+x
#define P2(x) 2*P1(x)
int main()
{
int a = P1(1) ? 1 : 0;
int b = P2(a)&a;
return 0;
}
Now, I thought that the compiler first replacing the macros with their values and so int b = 2*a+a&a; (and since a=1 then b=3). Why isn't it so?
This is because & has lower precedence than that of addition + operator. The grouping of operands will take place as
int b = ( (2*a + a) & a );
Therefore, (2*a + a) = 3 and 3 & 1 = 1 (011 & 001 = 001).
There's no precedence in your operation (it is just a textual substitution) thus, as you've noted,
#define P1(x) x+x
#define P2(x) 2*P1(x)
int a = P1(1) ? 1 : 0; // 1
and since & has lower precedence than +, it is equivalent to
int b = ((2 * a) + a) & a;
i.e. only the rightmost bit is set on b.
((2 * a) + a) 011 &
a 001 =
--------------------
b 001
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);
}