掌握一維數組和二維數組的定義、賦值和輸入輸出的方法。ios
掌握字符數組和字符串函數的使用。編程
經過實驗進一步掌握指針的概念,會定義和使用指針變量。數組
能正確使用數組的指針和指向數組的指針變量。dom
能正確使用字符串的指針和指向字符串的指針變量。函數
能正確使用引用型變量。oop
#include <iostream> #include <cstdlib> #include <ctime> #include <cmath> using namespace std; int rand_0toN1(int n); void draw_a_card(); char *suits[4] = {"hearts", "diamonds", "spades", "clubs"}; char *ranks[13] = {"ace", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king" }; int main() { int n, i; srand(time(NULL)); // Set seed for random numbers. while (1) { cout << "Enter no. of cards to draw (0 to exit): "; cin >> n; if (n == 0) break; for (i = 1; i <= n; i++) draw_a_card(); } return 0; } // Draw-a-card function // Performs one card-draw by getting a random 0-4 and a random // 0-12. These are then used to index the string arrays, ranks // and suits. // void draw_a_card() { int r; // Random index (0 thru 12) into ranks array int s; // Random index (0 thru 3) into suits array r = rand_0toN1(13); s = rand_0toN1(4); cout << ranks[r] << " of " << suits[s] << endl; } // Random 0-to-N1 Function. // Generate a random integer from 0 to N-1. // int rand_0toN1(int n) { return rand() % n; }
#include <iostream> using namespace std; void sort(int n); void swap(int *p1, int *p2); int a[10]; int main () { int i; for (i = 0; i < 10; i++) { cout << "Enter array element #" << i << ": "; cin >> a[i]; } sort(10); cout << "Here are all the array elements, sorted:" << endl; for (i = 0; i < 10; i++) cout << a[i] << " "; cout << endl; system("PAUSE"); return 0; } // Sort array function: sort array named a, having n elements. // void sort (int n) { int i, j, low; for(i = 0; i < n - 1; i++) { // This part of the loop finds the lowest // element in the range i to n-1; the index // is set to the variable named low. low = i; for (j = i + 1; j < n; j++) if (a[j] < a[low]) low = j; // This part of the loop performs a swap if // needed. if (i != low) swap(&a[i], &a[low]); } } // Swap function. // Swap the values pointed to by p1 and p2. // void swap(int *p1, int *p2) { int temp = *p1; *p1 = *p2; *p2 = temp; }