Tags:
create new tag
view all tags

Functions Sample code 2

#include<iostream>
using namespace std;
void displayBoard(char board[3][3]);
void getMove(char b[3][3], char player, int &r, int &c);
char checkWin(char board[3][3]);
int main() {
    char board[3][3] = {' ',' ',' ',' ',' ',' ',' ',' ',' '};
    bool gameOver = false;
    int row, col;
    char curPlayer = 'X';
    int moves = 0;
    do {
        getMove(board,curPlayer, row, col);
        board[row - 1][col - 1] = curPlayer;
        if (curPlayer == 'X') {
            curPlayer = 'O';
        } else {
            curPlayer = 'X';
        }
        displayBoard(board);
        char winner = checkWin(board);
        moves++;
        if (winner!= ' ') {
            cout << winner << " Wins!!!" << endl;
            gameOver=true;
        } else if (moves>=9) {
            gameOver = true;
            cout << "No Winner!" << endl;
        }
    } while (!gameOver);
    return 0;
}

void displayBoard(char board[3][3]) {
    for (int r = 0; r < 3; r++) {
        for (int c = 0; c < 3; c++) {
            cout << board[r][c] << " ";
        }
        cout << endl;
    }
}
bool inRange(int x) {
    return (x>0 && x<4);
}
void getMove(char b[3][3], char player, int &r, int &c) {
    bool moveBad = true;
    do {
        cout << player << " enter row and column (1-3):";
        cin >> r >> c;
        if (!inRange(r)||!inRange(c)||b[r-1][c-1]!=' ') {
            cout << "Row and Column must be 1-3, and unused!" << endl;
        } else {
            moveBad = false;
        }
    } while (moveBad);
}
char checkWin(char b[3][3]){
    for (int r=0;r<3;r++) {
        if (b[r][0]!= ' '&&
                (b[r][0]==b[r][1])&&(b[r][1]==b[r][2])) {
            return b[r][0];
        }
    }
    for (int c=0;c<3;c++) {
        if (b[0][c]!= ' '&&
                (b[0][c]==b[1][c])&&(b[1][c]==b[2][c])) {
            return b[0][c];
        }
    }
    return ' ';
}
 

Functions Sample code 2

//DISPLAY 7.13 Two-Dimensional Array
//Reads quiz scores for each student into the two-dimensional array grade (but  
//the input code is not shown in this display). Computes the average score  
//for each student and the average score for each quiz. Displays the quiz scores  
//and the averages.
#include <iostream>
#include <iomanip>
const int NUMBER_STUDENTS = 4, NUMBER_QUIZZES = 3;

void compute_st_ave(const int grade[][NUMBER_QUIZZES], double st_ave[]);
//Precondition: Global constants NUMBER_STUDENTS and NUMBER_QUIZZES
//are the dimensions of the array grade. Each of the indexed variables
//grade[st_num-1, quiz_num-1] contains the score for student st_num on quiz 
//quiz_num.
//Postcondition: Each st_ave[st_num-1] contains the average for student 
//number stu_num.


void compute_quiz_ave(const int grade[][NUMBER_QUIZZES], double quiz_ave[]);
//Precondition: Global constants NUMBER_STUDENTS and NUMBER_QUIZZES
//are the dimensions of the array grade. Each of the indexed variables
//grade[st_num-1, quiz_num-1] contains the score for student st_num on quiz 
//quiz_num.
//Postcondition: Each quiz_ave[quiz_num-1] contains the average for quiz number
//quiz_num.


void display(const int grade[][NUMBER_QUIZZES],
                            const double st_ave[], const double quiz_ave[]);
//Precondition: Global constants NUMBER_STUDENTS and NUMBER_QUIZZES are the
//dimensions of the array grade. Each of the indexed variables grade[st_num-1, 
//quiz_num-1] contains the score for student st_num on quiz quiz_num. Each 
//st_ave[st_num-1] contains the average for student stu_num. Each 
//quiz_ave[quiz_num -1] contains the average for quiz number quiz_num.
//Postcondition: All the data in grade, st_ave, and quiz_ave has been output.


int main( )
{
    using namespace std;
    //int grade[NUMBER_STUDENTS][NUMBER_QUIZZES];
    int grade[NUMBER_STUDENTS][NUMBER_QUIZZES]={20,16,17,19,13,14,19,19,20,17,17,15};//This works too
    //int grade[NUMBER_STUDENTS][NUMBER_QUIZZES]={{20,16,17},{19,13,14},{19,19,20},{17,17,15}};
    double st_ave[NUMBER_STUDENTS];
    double quiz_ave[NUMBER_QUIZZES];

//The code for filling the array grade goes here, but is not shown.
    compute_st_ave(grade, st_ave);
    compute_quiz_ave(grade, quiz_ave);
    return 0;
}

void compute_st_ave(const int grade[][NUMBER_QUIZZES], double st_ave[])
{
    for (int st_num = 1; st_num <= NUMBER_STUDENTS; st_num++)
    {//Process one st_num:
        double sum = 0;
        for (int quiz_num = 1; quiz_num <= NUMBER_QUIZZES; quiz_num++)
            sum = sum + grade[st_num -1][quiz_num -1];
        //sum contains the sum of the quiz scores for student number st_num.
        st_ave[st_num -1] = sum/NUMBER_QUIZZES;
        //Average for student st_num is the value of st_ave[st_num-1]
    }
} 


void compute_quiz_ave(const int grade[][NUMBER_QUIZZES], double quiz_ave[])
{
    for (int quiz_num = 1; quiz_num <= NUMBER_QUIZZES; quiz_num++)
    {//Process one quiz (for all students):
        double sum = 0;
        for (int st_num = 1; st_num <= NUMBER_STUDENTS; st_num++)
            sum = sum + grade[st_num -1][quiz_num -1];
        //sum contains the sum of all student scores on quiz number quiz_num.
        quiz_ave[quiz_num -1] = sum/NUMBER_STUDENTS;
        //Average for quiz quiz_num is the value of quiz_ave[quiz_num-1]
    }
}


//Uses iostream and iomanip:
void display(const int grade[][NUMBER_QUIZZES],
                         const double st_ave[], const double quiz_ave[])
{
    using namespace std;
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(1);
    cout << setw(10) << "Student"
         << setw(5) << "Ave"
         << setw(15) << "Quizzes\n";
    for (int st_num = 1; st_num <= NUMBER_STUDENTS; st_num++)
    {//Display for one st_num:
        cout << setw(10) << st_num 
             << setw(5) << st_ave[st_num-1] << " ";
        for (int quiz_num = 1; quiz_num <= NUMBER_QUIZZES; quiz_num++)
            cout << setw(5) << grade[st_num -1][quiz_num -1];
        cout << endl;
    }

    cout << "Quiz averages = ";
    for (int quiz_num = 1; quiz_num <= NUMBER_QUIZZES; quiz_num++)
        cout << setw(5) << quiz_ave[quiz_num -1];
    cout << endl;
}


 

Search Array

//DISPLAY 7.10 Searching an Array 
//Searches a partially filled array of nonnegative integers.
#include <iostream>
using namespace std;
const int DECLARED_SIZE = 20;
 
void fill_array(int a[], int size, int& number_used);
//Precondition: size is the declared size of the array a.
//Postcondition: number_used is the number of values stored in a.
//a[0] through a[number_used-1] have been filled with
//nonnegative integers read from the keyboard.
 
int search(const int a[], int number_used, int target);
//Precondition: number_used is <= the declared size of a.
//Also, a[0] through a[number_used -1] have values.
//Returns the first index such that a[index] == target,
//provided there is such an index; otherwise, returns -1.
 
int main( )
{
 
    int arr[DECLARED_SIZE], list_size, target;
 
    fill_array(arr, DECLARED_SIZE, list_size);
 
    char ans;
    int result;
    do
    {
        cout << "Enter a number to search for: ";
        cin >> target;
 
        result = search(arr, list_size, target);
        if (result == -1)
            cout << target << " is not on the list.\n";
        else
            cout << target << " is stored in array position " 
                 << result << endl
                 << "(Remember: The first position is 0.)\n";
 
        cout << "Search again?(y/n followed by Return): ";
        cin >> ans;
    }while ((ans != 'n') && (ans != 'N'));
 
    cout << "End of program.\n";
    return 0;
}
//Uses iostream:
void fill_array(int a[], int size, int& number_used)
{
 
    cout << "Enter up to " << size << " nonnegative whole numbers.\n"
         << "Mark the end of the list with a negative number.\n";
    int next, index = 0;
    cin >> next;
    while ((next >= 0) && (index < size))
    {
        a[index] = next;
        index++;
        cin >> next;
    }
 
    number_used = index;
}
 
int search(const int a[], int number_used, int target)
{
 
    int index = 0; 
    bool found = false;
    while ((!found) && (index < number_used))
        if (target == a[index])
            found = true;
        else
            index++;
 
    if (found)
        return index;
    else
        return -1;
}
 
 

TickTackToe

#include <iostream>
using namespace std;

void DisplayBoard(char board[][3]) {
    cout << endl;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            cout << " " << board[i][j];
            if (j < 2) {
                cout << " |";
            }
        }
        cout << endl;
        if (i < 2) {
            cout << "-----------" << endl;
        }
    }
    cout << endl;
}

void nextMove(char player, char board[][3]) {
    int row, col;
    bool ok = true;
    do {
        ok = true;
        cout << "Player " << player << " What row (1,2,3) and column (1,2,3)? ";
        cin >> row >> col;
        if (row < 1 || row > 3) {
            cout << "Bad row, must be between 1 and 3." << endl;
            ok = false;
        }
        if (col < 1 || col > 3) {
            cout << "Bad column, must be between 1 and 3." << endl;
            ok = false;
        }
        if (ok && board[row - 1][col - 1] != ' ') {
            cout << "Sorry, there is already an " << board[row - 1][col - 1] << " in that position!" << endl;
            ok = false;
        }
    } while (!ok);
    board[row - 1][col - 1] = player;

}

bool checkDone(char board[][3], char& winner) {
    // Checks rows
    for (int i = 0; i < 3; i++) {
        if (board[i][0] != ' ') {
            if (board[i][0] == board[i][1] && board[i][0] == board[i][2]) {
                winner = board[i][0];
                return true;
            }
        }
    }
    // Checks columns
    for (int i = 0; i < 3; i++) {
        if (board[0][i] != ' ') {
            if (board[0][i] == board[1][i] && board[0][i] == board[2][i]) {
                winner = board[0][i];
                return true;
            }
        }
    }

    // Check diagonals
    if (board[0][0] != ' ') {
        if (board[0][0] == board[1][1] && board[0][0] == board[2][2]) {
            winner = board[0][0];
            return true;
        }
    }
    if (board[2][0] != ' ') {
        if (board[2][0] == board[1][1] && board[2][0] == board[0][2]) {
            winner = board[2][0];
            return true;
        }
    }
    return false;
}

/*
 * 
 */
int main() {
    char myBoard[3][3] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};
    char winner;
    do {
        DisplayBoard(myBoard);
        nextMove('X', myBoard);
        if (checkDone(myBoard, winner)) {
            break;
        }
        DisplayBoard(myBoard);
        nextMove('O', myBoard);
        if (checkDone(myBoard, winner)) {
            break;
        }
    } while (1);
    DisplayBoard(myBoard);
    cout << "You win " << winner << "!!!!" << endl;
    
    return 0;
}


 

Sort Array

#include <iostream>
using namespace std;
void displayValues(int scores[], int scoreCount) {
    for (int i = 0 ; i < scoreCount ; i++) {
        cout << scores[i] << " ";
    }
    cout << endl;
}

void inputValues(int scores[], int aSize, int& scoreCount) {
    int i=0;
    do {
        cin >> scores[i++];  
    } while (scores[i-1] > 0 && i < aSize);
    if (scores[i-1] < 0) {
        i--;
    }
    scoreCount = i;
}
void swap_values(int& v1, int& v2)
{
    int temp;
    temp = v1;
    v1 = v2;
    v2 = temp;
}
 
 
int index_of_smallest(const int a[], int start_index, int number_used)
{
    int min = a[start_index];
    int   index_of_min = start_index;
    for (int index = start_index + 1; index < number_used; index++)
        if (a[index] < min)
        {
            min = a[index];
            index_of_min = index;
            //min is the smallest of a[start_index] through a[index]
        }
 
    return index_of_min;
}

void sort(int a[], int number_used)
{
    int   index_of_next_smallest;
    for (int index = 0; index < number_used - 1; index++)
    {//Place the correct value in a[index]:
 
        index_of_next_smallest = index_of_smallest(a, index, number_used);
 
        swap_values(a[index], a[index_of_next_smallest]);
        //a[0] <= a[1] <=...<= a[index] are the smallest of the original array 
        //elements. The rest of the elements are in the remaining positions.
    }
}

const int MAX = 100;
int main() {
    int theNums[MAX];
    int ncount;
    cout << "Input up to " << MAX << " Values to sort, -1 to end: ";
    inputValues(theNums, MAX, ncount);
    displayValues(theNums, ncount);
    sort(theNums, ncount);
    displayValues(theNums, ncount);    
    
    return 0;
}

 



Edit | Attach | Watch | Print version | History: r4 < r3 < r2 < r1 | Backlinks | Raw View | Raw edit | More topic actions
Topic revision: r4 - 2018-03-27 - JimSkon
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2018 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback