Click here to Skip to main content
14,332,142 members
Rate this:
Please Sign up or sign in to vote.
See more:
How to assign a value to a variable by using expression? in C language
Find average of the two nos without division or ternary operator

int a=10,b=20;
int avg=<expression>;
printf("%d",avg);

What I have tried:

I have no Idea

How to assign a value to a variable by using expression? in C language
Find average of the two nos without division or ternary operator

int a=10,b=20;
int avg=<expression>;
printf("%d",avg);
Posted
Updated 2-Apr-17 14:09pm
Comments
Ravi Bhavnani 2-Apr-17 13:30pm
   
(1) How to assign a value to a variable by using expression? in C language
If you truly have no idea how to do this, you need to re-read your programming textbook.

(2) Find average of the two nos without division or ternary operator
One way to do this would be to successively increment(decrement) the smaller(larger) of the two numbers until you converge at a common value, which is the average.

/ravi
PIEBALDconsult 2-Apr-17 15:20pm
   
http://mathforum.org/library/drmath/view/57574.html
Rate this:
Please Sign up or sign in to vote.

Solution 2

Hi Member 13100982,

Are you allowed to use bit operations? Then following is the simplest solution:

int a = 10, b = 20;
int avg = (a + b) >> 1;
printf("%d", avg);

algorithm - Fast average without division - Stack Overflow[^]
   
v2
Comments
Member 13100982 3-Apr-17 3:02am
   
Thanks Mehedi Shams
Rate this:
Please Sign up or sign in to vote.

Solution 1

Think about your problem:
you need to know what is the half of something, one way is to divide by 2, there is another way, it is mathematics.

We do not do your HomeWork.
   
Comments
Member 13100982 2-Apr-17 13:45pm
   
Sorry.. We should not use DIVISION Operator

I am having a concept
int x=a+b;
y=0;
while(x>0)
{
x=x-2;
y++;
}

Now Y is the answer.. I dont know ,,how to assign the value of Y to AVG in a single experssion
Patrice T 2-Apr-17 13:50pm
   
Ask a math teacher "How to divide by 2 without using a division?"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100