Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

C code unknown value at output

Status
Not open for further replies.

shaswat

Advanced Member level 4
Joined
Jul 2, 2013
Messages
115
Helped
1
Reputation
2
Reaction score
1
Trophy points
18
Activity points
963
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??
 

Since you are using %d in scanf for integer data type it cannot get a char data as input... Instead it takes gorbage value...
 

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???
 
Thnx fr the ans
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top