//------------------------------------------------- // // Examples of combinations of strings and arrays, and // functions that handle both. // // Simon Parsons // November 12th 2008 // //------------------------------------------------- // Include C++ library definitions #include // For input and output #include // To handle strings using namespace std; // Function headers int totalLength(string s1, string s2); // Takes strings as arguments and // returns an integer. string oddOne(int n); // Takes an integer as an arguement // and returns a string. void printArray(int a[], int size); // Takes an array as an argument int doubleArray(int a[], int size); // Takes an array as an argument // and returns an int int main() { int i, j, num, length; // Variable definitions string dna1 = "ggtataccggaatatagg"; // Two strings string dna2 = "ttggaagg"; string str; string genes[3] = {"tatagg", "gagattc", "cgcgttat"}; int grid[2][3] = {{0, 1, 2}, {7, 8, 9}}; int list[5] = {2, 4, 6, 8, 34}; int list2[6] = {12, 43, 66, 32, 11, 44}; // Some of the variables still need to be initialised. num = rand() % 25; length = 0; str = ""; // Call totalLength length = totalLength(dna1, dna2); cout << "The DNA snips dna1 and dna2 are " << length << " bases long"; cout << endl << endl; // Call oddOne str = oddOne(num); cout << num << " is " << str << endl << endl; // Print out the length of each element of genes cout << "The three snips in 'genes' are the following lengths: " << endl; for(i = 0; i < 3; ++i){ cout << genes[i].length() << endl; } cout << endl; // Now print out the values in grid plus 3 cout << "The values in grid are" << endl; for(i = 0; i < 2; ++i){ for(j = 0; j < 3; j++){ cout << grid[i][j] + 3 << " "; } } cout << endl; // Now use a function to print arrays cout << endl << "Now we play with arrays of numbers" << endl; cout << endl; printArray(list, 5); cout << endl; printArray(list, 4); cout << endl; printArray(list2, 6); cout << endl; // doubleArray changes the array num = doubleArray(list, 5); cout << num << endl; printArray(list, 5); cout << endl; return 0; } int totalLength(string s1, string s2) { return s1.length() + s2.size(); // length() and size() do the same thing. } string oddOne(int n) { if((n % 2) == 0){ return "even"; } else{ return "odd"; } } void printArray(int a[], int size) { int i; for(i = 0; i < size; ++i){ cout << a[i] << " "; } } int doubleArray(int a[], int size) { int i; for(i = 0; i < size; ++i){ a[i] = a[i] * 2; } return a[0]; }