GCSE Program: Round-table - cycling around a 1D array using MOD (modulo)


This question was posed in a GCSE Computing exam by the OCR exam-board in the UK.







Six people are sat around a table. Their names are stored in a 1D array of string values.

You choose a number of seats that you want each person to move by, clockwise around the table. The program must then update the array.

The original example used an array whose index started at 1, ending at item number 6. This solution in C++ uses an array that is zero-indexed: the first item has index 0, the last item has index 5.

To try out the program, select and copy the C++ source-code at the bottom of this post.

Paste into a text editor, such as Nano or Geany.

Then save the new file, ending in .cpp

I used  round.cpp


To compile from the command-line:


    g++ -o round round.cpp


To run from the command-line:


    ./round



Here's the source-code below:




#include <iostream>


using namespace std;


int main()
{
    string PlayerName[] = {"Helen", "Adam", "Lidia", "Kwaku", "Priya", "Chan"};



    // Display contents of the original array    cout << "Original array:" << endl;
    for ( int index = 0; index < 6; index++ )
        cout << index << " " << PlayerName[index] << endl;



    // Find out how many places to move each person by
    cout << endl << "How many places to move?" << endl;
    int moves;
    cin >> moves;



    // Copy the name of each person to a new position, via a temporary holding array
    // This ensures any names aren't lost/overwritten after each move
    string TempArray[6];
    int newindex;

    for ( int oldindex = 0; oldindex < 6; oldindex++ )
    {
        newindex = ( oldindex + moves ) % 6;
        TempArray[newindex] = PlayerName[oldindex];
    }
  // end of loop that moves each item to new place in temp array



    // Display the results after all moves have been made
    cout << endl << "Updated array:" << endl;


    for ( int index = 0; index < 6; index++ )
    {
        PlayerName[index] = TempArray[index];
        cout << index << " " << PlayerName[index] << endl;
    }
  // end of copy and display loop



}  // end of main function


More programs and details in the book - available now on Amazon in the UK for £14.95 ($16.50 in the USA)