Loop Examples - November 4

Thursday, we spent most of the class looking at several example problems which require loops and arrays to solve. Here are the questions and the solutions we came up with in class.


Simulate the rolling of two dice 1000 times.  Keep track of how often each number (the sum of the two dice) appears.
#include <iostream>
#include <string>

using namespace std;

#define ARRAY_SIZE 13

// print_array()
//
// A function to print out an array, including each index

void print_array(int A[]) {
  int i;
  for (i=0;i<ARRAY_SIZE;i++) {
    cout.width(8);
    cout << i << " : " << A[i] << endl;
  } //end for(i)
  cout << endl;
} //end print_array()

void main() {

  int Roll[ARRAY_SIZE] = {0}; // Initialize array to zero

  int dice1, dice2;
  int sum;

  int i;

  for(i=0; i<=999; i++) {
    dice1 = rand()%6+1;   // Roll Dice 1
    dice2 = rand()%6+1;   // Roll Dice 2
    sum = dice1+dice2;
    Roll[sum]++;
  } //end for(i)

  print_array(Roll);

}// end main()


Read in 20 integers.  As you read, print each number only if it is not a duplicate of a previously-entered number.
#include <iostream>
#include <string>

using namespace std;

#define ARRAY_SIZE 20

void print_array(int A[]) {
  int i;
  for (i=0;i<ARRAY_SIZE;i++) {
    cout.width(12);
    cout << i << ":" << A[i] << endl;
  }
  cout << endl;
} //end print_array

void main() {

  int A[ARRAY_SIZE];

  int i,j;
  bool Same;

  cout << "Enter 20 integers : ";

  for (i=0; i<=19; i++) {

    cin >> A[i];
    Same = false;
    // Check to see if this number equals any previous
    for (j=0; j<=i-1 ; j++) {
      if (A[i] == A[j]) {
        Same=true;
      }
    }//end for(j)

    if (Same) {
      cout << "Duplicate!" << endl;
    } else {
      cout << A[i] << endl;
    }

  }//end for(i)
}// end main()


Write a function that prints a string (an array of characters) backwards.
#include <iostream>
#include <string>
using namespace std;

// This function prints a string backwards

void Backwards(char S[]) {

  int i,j;
  i=0;
 
  // Use a while loop to find the end
  while (S[i] != '\0') {
    i++;
  }

  // index i now is at the end of the string

  // Go backwards through string, printing each character
  for(j=i-1; j>=0; j--) {
    cout << S[j];
  }

}//end Backwards()

void main() {

  char X[] = "ytisrevinU aloiB";
  Backwards(X);
  cout << endl << endl;
}// end main()