You are here:

C/C related to programming

Advertisement


Question
main()
{
unsigned char a,b,c,d;
a=100;
b=40;
c=10;
d=a*b+c;
printf("%d",d);
}
the ouput of this programm is 170. But i don't want this answer. I want d=410. also you don't declear 'd' as int. then it will be very easy. So please can you suggest answer for the same.  

Answer
Looks like this is a question asked in some quiz or interview.

First of all, you must understand what a type is.
When you say a variable of type char, that means it is of size on byte.
1 byte can store maximum value of 255.

Since, d is declared as char, you must not expect it to store more than 255.
The hex value of 4010 is FAA.
Now the size of d is 1 byte and only AA can be stored.
That value is 170.

There is one way which you can give a try.
That is to catch the cary bits that are getting lost and use it when you are trying to print the value.

Here is the modified code:
main()
{
unsigned char a,b,c,d,e;
a=100;
b=40;
c=10;
d=(a*b)+c;
e=((a*b)+c) >> 8;
printf("%d\n",(e << 8 ) + d);
}

Hope this solves your problem.

-Narendra

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.