Cpp Tutorial Contains
Problem Statement
Write a C++ program which asks user to input a binary number then convert it into its equivalent decimal number and show the result.
To improve readability of program make a separate function and function should return the resultant number.
C++ CODE
Compiler used: C++ codeBlocks Compiler
Program Explanation
- Binary to Decimal Conversion Code in C++
- Program Logic Explanation
- Dry run the code with a simple input so the basic working of program can be understand easily
- Know the basic math of converting one number to other number e.g BINARY to DECIMAL
- functions
- while loop
Problem Statement
Write a C++ program which asks user to input a binary number then convert it into its equivalent decimal number and show the result.
To improve readability of program make a separate function and function should return the resultant number.
C++ CODE
Compiler used: C++ codeBlocks Compiler
#include<iostream>
using namespace std;
long ConvertBinary2Decimal(unsigned long num);
int main()
{
unsigned long binary_num, decimal = 0;
cout <<"\n\tEnter a binary number to get
Equivalent Decimal : ";
cin >> binary_num;
decimal=ConvertBinary2Decimal(binary_num);
cout <<"\n\tDecimal Value Of
" <<binary_num << " is = " << decimal << endl;
return 0;
}
long ConvertBinary2Decimal(unsigned long bin_num)
{
unsigned long decimal = 0;
int remainder=0, base = 1;
while (bin_num > 0)
{
remainder = bin_num % 10;
decimal = decimal + remainder * base;
bin_num = bin_num / 10;
base = base * 2;
}
return decimal;
}
Program Explanation
- In main function user enters input number
- Calls the function and pass the number
- Function calculates the required result and return
- In main function program displays the final result
Dry Run of Code
Input = 101
--------------------------------
Iteration = 1
remainder = 1
decimal = 1
bin_num = 10
base = 2
--------------------------------
Iteration = 2
remainder = 0
decimal = 1
bin_num = 1
base = 4
--------------------------------
Iteration = 3
remainder = 1 -> as 1 mod 10 =1
decimal = 5 -> previous value+remainder*base = 5 RESULT
bin_num = 0
base = 8
--------------------------------
Main logic of the program in while loop take another input and dry run it into a notebook. Best of Luck
See another example here
0 comments:
Post a Comment