As a begineer I write a program of adding the places of a digit.
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,sum=0,e,z;
printf("Enter the digit");
scanf("%d",&a);
while(a!=0)
{
b=a%10;
sum=sum+b;
a=a/10;
}
printf("the sum is %d",sum);
getch();
}
but if I enter a character e.g. "w" then it gives value -26. I don't understand how this works? I also debug my code and find that it takes value -29359(0x8D51)
Instead of this if I put a=0 then at output if I enter "a" then it shows 0. How it works as I want to understand.
Anyone can help??
ok lets for a sec it takes a garbage value but why the answer is -26 as I write a code for adding the place value of the digit. Instead of this it should shows 8.
Whats the reason behind this??
Just take a look at the format of storing an integer...
Let us consider you are using 32 bit compiler...
An integer takes 4 Bytes and the character you have entered is just of 1 BYTE wide...
For example your I/P data is stored in an unknown address 1000H
So that for your operation it takes 1000H,1001H,1002H and 1003H
But the char you have enterd was stored only in 1000H...
There might be some garbage values in 1001H to 1003H...
For your operation it takes those garbages into account and gave you another garbage result -26...
Do u get my points???