top of page

10) Decimal to Binary

We can convert any decimal number (base-10 (0 to 9)) into binary number(base-2 (0 or 1)) by c++ program.

Decimal Number

Decimal number is a base 10 number because it ranges from 0 to 9, there are total 10 digits between 0 to 9. Any combination of digits is decimal number such as 23, 445, 132, 0, 2 etc.

Binary Number

Binary number is a base 2 number because it is either 0 or 1. Any combination of 0 and 1 is binary number such as 1001, 101, 11111, 101010 etc.

Let's see the some binary numbers for the decimal number.

Decimal to Binary Conversion Algorithm

  • Step 1: Divide the number by 2 through % (modulus operator) and store the remainder in array

  • Step 2: Divide the number by 2 through / (division operator)

  • Step 3: Repeat the step 2 until number is greater than 0

Let's see the c++ example to convert decimal to binary.

Write a c++ program to convert decimal number to binary.

Input: 5

Output: 101

Input: 20

Output: 10100

Let's see the c++ example to convert decimal to binary.

back.png

#include <iostream>  

using namespace std;  

int main()  

{  

int a[10], n, i;    

cout<<"Enter the number to convert: ";    

cin>>n;    

for(i=0; n>0; i++)    

{    

a[i]=n%2;    

n= n/2;  

}    

cout<<"Binary of the given number= ";    

for(i=i-1 ;i>=0 ;i--)    

{    

cout<<a[i];    

}    

}  

decc.png

11) Alphabet Triangle

There are different triangles that can be printed. Triangles can be generated by alphabets or numbers. In this c++ program, we are going to print alphabet triangles.

Let's see the c++ example to print alphabet triangle.

Write a c++ program to print alphabet triangle.

Output:

A ABA ABCBA ABCDCBA ABCDEDCBA

back.png

#include <iostream>  

using namespace std;  

int main()  

{  

 char ch='A';    

    int i, j, k, m;    

    for(i=1;i<=5;i++)    

    {    

        for(j=5;j>=i;j--)    

            cout<<" ";    

        for(k=1;k<=i;k++)    

            cout<<ch++;    

            ch--;    

        for(m=1;m<i;m++)    

            cout<<--ch;    

        cout<<"\n";    

        ch='A';    

    }    

return 0;  

}  

12) Number Triangle

Like alphabet triangle, we can write the c++ program to print the number triangle. The number triangle can be printed in different ways.

Let's see the c++ example to print number triangle.

Write a c++ program to print number triangle.

Input: 7

Output:

enter the range= 6 1 121 12321 1234321 123454321 12345654321

back.png

#include <iostream>  

using namespace std;  

int main()  

{  

int i,j,k,l,n;    

cout<<"Enter the Range=";    

cin>>n;    

for(i=1;i<=n;i++)    

{    

for(j=1;j<=n-i;j++)    

{    

cout<<" ";    

}    

for(k=1;k<=i;k++)    

{    

cout<<k;    

}    

for(l=i-1;l>=1;l--)    

{    

cout<<l;    

}    

cout<<"\n";    

}    

return 0;  

bottom of page