Lets say your binary number is 1111101000
First step , n has 1111101000
Second , n has 111110100,.. then 111110100 , then 11111010 , 1111101 , 111110 , 11111, 1111 , 111, 11, 1 , and finally Zero..
At the same time , k holds the digits which gets removed from right of the variable 'n' ...
The statements inside the while loop repeats until the condition becomes false.. Here the condition is n!=0 ..
When n reaches zero .. you have calculated the powers of all the digits interms of binary.. then the loop exits..
Lets go back to our example..
K holds the last digit , when last digit in n gets removed...
k = n%10 ... if n is 57 , k holds 7 .. if n is 231 , k holds 1 .. Its like a remainder.. So in your program k always holds last digit of n ..
n = n/10 ... if n is 555 , n becomes 55 .. it just divides it by 10 and leaves out the remainder .. if n is 459 , n becomes 45..
Lets get back to our example.. we started with n 1111101000
the variable decimal holds the value of final decimal value which we calculate from binary..
After first loop.. n has 111110100 and k has 0 .. so decimal = decimal + 0x2 ^ 0 ... p becomes 1..
after second loop.. n has 11111010 and k has 0. so decimal = 0 + 0 x2^ 1.. p becomes 2.
after third loop.. n has 11111101 and k has 0 , so decimal = 0 + 0 x2^ 2.. p becomes 3
after fourth loop.. n has 1111110 and k has 1 , so decimal = 0 + 1 x2^ 3=8.. p becomes 4
and so on .. after 11th loop.. n becomes zero.. and decimal value has 1000..
Well if binary was a string representing a binary number (10010)
then the loop would be to convert the string into the integer value of the number. But that would be wrong because it is using n%10 and n/10 instead of n%2 and n/2. But it does not do a base 10 conversion because it used pow(2,p).
So it seems to break out the base 10 digits, then create a number using those to create a base 2 number.
This looks seriously messed up.
But that is irrelevant, because binary is an int. And it is read in using scanf("%d", &binary), so the conversion from the base 10 number (character sting) the user entered into its integer value has already been done.
Looks like a seriously messed up piece of code.
int binary,decimal,p=0,n,k;
printf("ENTER A BINARY NUMBER\n");
scanf("%d",&binary);
n=binary;
while(n!=0)
{
k=n%10;
n=n/10;
decimal+=k*pow(2,p);
p++;
}
system("cls");
printf("THE EQUIVALENT