Chapter 10: Applied problem solving

Linear indices to subscripts

face Josiah Wang

Now, try to solve the previous problem, but in the inverse direction.

That is, convert the single-dimensional index s to subscripts (r, c) given the number of rows R and columns C.

A user gives you the number of rows R, number of columns C, and a two-dimensional index (r, c) that refers to a cell position, where r is a row index and c a column index.

Write a program to convert (r, c) to a single-dimensional index s, assuming row-major ordering (i.e. s is ordered from left to right, and then top to bottom). All indices start from 0. See the figure below for an illustration.

Convert linear indices to subscripts

More specifically, write a program that reads in the following integer inputs from the user:

  1. The number of rows in the table
  2. The number of columns in the table
  3. An index

The program should output the subscript (r, c) corresponding to the given index.

Again, assume that the user will always enter valid numbers.

Sample run #1:

Enter the number of rows: 3
Enter the number of columns: 4
Enter index: 6
(1, 2)

Sample run #2:

Enter the number of rows: 6
Enter the number of columns: 2
Enter index: 11
(5, 1)