Problem: Write a C program to convert a binary number into corresponding decimal representation using command line argument.

Command line arguments are passed into the main function as two parameters.

• argc – Gives the number of command line arguments passed.
• argv – Stores the argument values as string in string array.

argv stores the “Program name” as first value(i.e argv) as default and rest are used for the command argument passed. Therefore the default value of argc is 1.

## Method 1: As Binary String

Passing Binary value

Output

Explanation:

• Line 6Reading the passed binary value and store in the char array.
• Line 9Counting number of digits in the binary.
• Line 11 – Loop through each digit of binary.
• Line 11 – Adding each digit multiplied by the 2n-1. We are type casting each character to integer, which will give back its ASCII value. Therefore we need to subtract 48(ASCCI value of 0).

## Method 2: As Binary Number

atoi(char *str) is a C standard library function which converts string into integer.

Passing Binary value

Output

Explanation:

• Line 6Reading the passed binary value and converting into integer form.
• Line 11-14Counting number of digits in the binary.
• Line 18 – Loop through each digit of binary.
• Line 19 – Adding last digit multiplied by the 2n-1.
• Line 20 – Removing used last digit.

Note: For the above program to work right, you need to correctly pass a binary value as command-line argument. Different editor or compiler has different ways to pass command line arguments.

This question has been asked in the TCS interview. If you have any doubts then comment below.