CS1101C Lab 2 (Even Week)

Decimal to Base-N Conversion

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

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

Preliminary

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

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

Text File

Your program must read the base-10 (decimal) numbers from a text file called fromdec1.txt. The sample text file contains the following lines:
2 0
2 1
2 3
2 85
2 488
2 511
8 0
8 1
8 9
8 83
8 14853748
5 015086
9 387420488
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 fromdec1, sample runs of the program are shown below. User input is denoted in bold.

$ gcc -Wall fromdec1.c -o fromdec1

$ ./fromdec1

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

$

Note and Ponder

  1. Assume that all user input is valid, and that the resulting base-n value will have 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 fromdec1.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 17 times since 25-Jun-24 11:57:13 +08. This is the 1st time it has been accessed today.

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

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