In this C Program, we have been asked to take a binary number as input as command line argument and convert it into its equivalent decimal form.

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[0]) 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.

Hope you find this helpful. This question has been asked into the TCS interview. If you have any doubts then comment below.

Leave a Reply

Close Menu