CS1101C Lab 2 (Odd Week)

Base-N to Decimal Conversion

The deadline for this lab question is Friday 07 March 2008, 23:59:59 hours.

The name of your C program file must be called todec1.c, files with any other name will not be marked.

Preliminary

Read this website and understand binary to decimal conversion and octal to decimal conversion. You may of course refer to other web sites if you wish.

After this, write a program to convert a base-n number to its equivalent base-10 (decimal) number, where 2 <= n <= 9.

Text File

Your program must read the base-n numbers from a text file called todec1.txt. The sample text file contains the following lines:
2 0
2 1
2 11
2 01010101
2 111101000
2 111111111
8 0
8 1
8 11
8 0123
8 70523164
5 0440321
9 888888888
We will of course test your programs with different test data.

Look at the sample run below and use your inference and deductive skills to figure out the format of the text file as well as the data it contains.

Sample Runs

Assuming that the executable is todec1, sample runs of the program are shown below. User input is denoted in bold.

$ gcc -Wall todec1.c -o todec1

$ ./todec1

0 in base 2 has decimal value of 0.
1 in base 2 has decimal value of 1.
11 in base 2 has decimal value of 3.
1010101 in base 2 has decimal value of 85.
111101000 in base 2 has decimal value of 488.
111111111 in base 2 has decimal value of 511.
0 in base 8 has decimal value of 0.
1 in base 8 has decimal value of 1.
11 in base 8 has decimal value of 9.
123 in base 8 has decimal value of 83.
70523164 in base 8 has decimal value of 14853748.
440321 in base 5 has decimal value of 15086.
888888888 in base 9 has decimal value of 387420488.

$

Note and Ponder

  1. Assume that all user input is valid, and that the base-n number has at most nine digits. (Why?)

  2. Use %d instead of %i in your scanf format specifier. (Why?)

  3. Loops and the modulus operator may prove to be very useful.

  4. To edit the text file, you may use the vim editor by typing "vim todec1.txt".

  5. If your program does not work as you expect (logical errors), use extra printf statements to print out all the values of your variables to aid in your debugging.

  6. How do you know if your program is working perfectly? Did you test your programs with your own test data? What constitutes as good test data?

  7. Most importantly, have lots of fun programming!


This document, index.html, has been accessed 15 times since 25-Jun-24 11:57:13 +08. This is the 1st time it has been accessed today.

A total of 8 different hosts have accessed this document in the last 445 days; your host, nsrp-source.comp.nus.edu.sg, has accessed it 7 times.

If you're interested, complete statistics for this document are also available, including breakdowns by top-level domain, host name, and date.