How to use a linked list in C Programming

/* 
* Program to use linked lists
* From the book: C Programming Quickstart Visual Guide
*
* By adding pointers to the definations of a structure,
* we can create a linked list of unlimited length. (well,
* limited only by the amount of available memory).
*/

#include <stdio.h>
#include <string.h> // For string functions.
#include <stdlib.h> // For memory functions.

#define STR_LEN 20

int main (void) {

/*
* Define the structure.
*/

struct student_grade {
char first_name[STR_LEN];
char last_name[STR_LEN];
float grade;
struct student_grade *next;
};

/*
* Rename the structure syntax.
*/

typedef struct student_grade sg;

/*
* Create two structure pointers.
*/

sg *first = NULL;
sg *new = NULL;
sg *temp = NULL;

int num; // For counting the input.

/*
* Need a temporary float.
*/

float g; //grade

/*
* Need some strings to handle the input.
*/

char classname[12], fn[STR_LEN], ln[STR_LEN];

/*
* Prompt the user.
*/

printf("Enter the classname (without spaces): ");
scanf("%11s", classname);

/*
* Prompt the user again.
*/

printf("Enter the student's name and their grade. Enter 0 0 0 to quite.\n(First Last ##.#): ");

/*
* Read the input.
*/

num = scanf("%11s %11s %f", fn, ln, &g);

/*
* Check if the user is done
*/

while (fn[0] != '0') {

/*
* Handle input.
*/

if (num == 3) {

new = (sg *) malloc(sizeof(sg));

/*
* Check that new is not NULL.
*/

strncpy(new->first_name, fn, STR_LEN-1);

new ->first_name[STR_LEN-1] = '\0';

strncpy(new->last_name, ln, STR_LEN-1);

new->last_name[STR_LEN-1] = '0';

new->grade = g;
new->next = first;
first = new;

} else {

printf("The data was not in the proper format.\n");
}

/*
* Prompt the user.
*/

printf("Enter the studen's name and their grade. Enter 0 0 0 to quit.\n(First Last ##.#): ");

/*
* Read the input.
*/

num = scanf("%11s %11s %f", fn, ln, &g);

} // End of while loop

/*
* Print the data and free the memory.
*/

printf("Student and grades for the class '%s':\n", classname);

new = first; //Start at the beginning.

while (new != NULL) { //Stop when list is done.

printf("%s %s %01.f\n", new->first_name, new->last_name, new->grade);

temp = new->next;
free(new);
new = temp;

}

getchar(); //Pause
getchar();//Pause
return 0;

}

How to use an array of structures in C Programming

/*
* Program to use arrays of structures
* From the book: C Programming Visual Quickstart Guide
*
* Structures, just like integers, floats,
* and characters, can be used in arrays.
* This program creates a list of student
* names and gradesby taking input from 
* the user and storing it in an array
* of structures.
*/

#include <stdio.h>
/* 
* In order to use the strncpy() function,
* the string.h file must be included.
*/
#include <string.h>

/*
* Define two macro constants. The first 
* represents the maximum string length
* (for a person's first and last names.)
* The second will be the number of 
* elements in the array.
*/

#define STR_LEN 20

#define NUM_STUDENTS 10

int main (void) {

/*
* Define the structure. The structure
* has two character arrays and one float.
*/

struct student_grade {
char first_name[STR_LEN];
char last_name[STR_LEN];
float grade;
};

/*
* Use typedef to rename the structure 
* syntax, then create an array of 
* structures. The typedef simplififes
* the process of referring to a structure.
* Then an array of structures called class
* is created.
*/

typedef struct student_grade sg;

/*
* Create an array of structures.
*/

sg class[NUM_STUDENTS];

/* 
* Need some counters.
*/

int i, num;
int count =0;

/*
* Need some strings to handle the input.
*/

char classname[12], fn[STR_LEN], ln[STR_LEN];

/*
* Need a temporary float.
*/

/*
* grade
*/

float g;

/* 
* Prompt the user.
*/

printf("Enter the classname (without spaces): ");
scanf("%11s", classname);

/* 
* Loop to read in all the student data.
*/

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

/*
* Prompt the user.
*/

printf("Enter the student's name and their grade. Enter 0 0 0 to quit.\n(First Last ##.#): ");

/*
* Read in the input.
*/

num = scanf("%11s %11s %f", fn,ln, &g);

/*
* Check if the user is done.
*/

if(fn[0] == '0') {
break;
}

/*
* Handle the input.
*/

if(num == 3) {

strncpy(class[i].first_name, fn, STR_LEN-1);

class[i].first_name[STR_LEN-1] = '\0';

strncpy(class[i].last_name, ln, STR_LEN-1);

class[i].last_name[STR_LEN-1] = '\0';

class[i].grade = g;
++count;

/*
* Improper input format.
*/
} else {

printf("The data was not in the proper format.\n");
break;
}
}

/*
* Print the data.
*/

printf("Students and grades for the class '%s':\n", classname);

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

printf("%s %s %0.1f\n", class[i].first_name, class[i].last_name, class[i].grade);
}

/*
* Pause.
*/

getchar();
getchar();
return 0;

}

How to use typedef in C Programming

/* 
* Program to use typedef
* From the book: C Programming Visual Quickstart Guide
*
* The typedef operator can help shorten how you
* refer to structures. This application uses 
* those structures to read data from a binary 
* file.
*/

#include <stdio.h>

/*
* Set the file path and name.
*/

#define THEFILE "weather.dat"

int main(void) {

/* 
* Define the structure.
*/

struct weather_record {
char date[11];
int high;
int low;
};

/* 
* Use typedef to create an alias.
* The first line  makes an alias so that 
wr (short for weather_record) stands for 
struct weather_record. Then wr is used to
* create a day variable of type struct
weather_record.
*/

typedef struct weather_record wr;

/*
* Create a structure variable.
*/

wr day;

/*
* Need a pointer of type FILE.
*/

FILE *fp;

/* 
* Attempt to open the file for binary reading.
*/

fp = fopen(THEFILE, "rb");

/*
* The file is open.
*/

if (fp != NULL) {

/*
* Loop through the entire file, assigning each structure to day.
*/

while(fread(&day, sizeof(wr), 1, fp)) {

/* 
* Print the information using the structure's field.
*/

printf("Date: %s\nHigh: %d\nLow: %d\n\n", day.date, day.high, day.low);

}

} else {

printf("The file could not be opened.\n");

/*
* Exit the function/application.
*/

return 1;
}

/*
* Close the file
*/

if (fclose(fp) !=0) {
printf("The file cound not be closed.\n");
}

/*
* Pause
*/

getchar();
return 0;

}

Python Game: Reversi

# Reversi
# https://inventwithpython.com/reversi.py

import random
import sys

def drawBoard(board):
    # This function prints out the board that it was passed. Returns None.
    HLINE = '  +---+---+---+---+---+---+---+---+'
    VLINE = '  |   |   |   |   |   |   |   |   |'

    print('    1   2   3   4   5   6   7   8')
    print(HLINE)
    for y in range(8):
        print(VLINE)
        print(y+1, end=' ')
        for x in range(8):
            print('| %s' % (board[x][y]), end=' ')
        print('|')
        print(VLINE)
        print(HLINE)


def resetBoard(board):
    # Blanks out the board it is passed, except for the original starting position.
    for x in range(8):
        for y in range(8):
            board[x][y] = ' '

    # Starting pieces:
    board[3][3] = 'X'
    board[3][4] = 'O'
    board[4][3] = 'O'
    board[4][4] = 'X'


def getNewBoard():
    # Creates a brand new, blank board data structure.
    board = []
    for i in range(8):
        board.append([' '] * 8)

    return board


def isValidMove(board, tile, xstart, ystart):
    # Returns False if the player's move on space xstart, ystart is invalid.
    # If it is a valid move, returns a list of spaces that would become the player's if they made a move here.
    if board[xstart][ystart] != ' ' or not isOnBoard(xstart, ystart):
        return False

    board[xstart][ystart] = tile # temporarily set the tile on the board.

    if tile == 'X':
        otherTile = 'O'
    else:
        otherTile = 'X'

    tilesToFlip = []
    for xdirection, ydirection in [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]:
        x, y = xstart, ystart
        x += xdirection # first step in the direction
        y += ydirection # first step in the direction
        if isOnBoard(x, y) and board[x][y] == otherTile:
            # There is a piece belonging to the other player next to our piece.
            x += xdirection
            y += ydirection
            if not isOnBoard(x, y):
                continue
            while board[x][y] == otherTile:
                x += xdirection
                y += ydirection
                if not isOnBoard(x, y): # break out of while loop, then continue in for loop
                    break
            if not isOnBoard(x, y):
                continue
            if board[x][y] == tile:
                # There are pieces to flip over. Go in the reverse direction until we reach the original space, noting all the tiles along the way.
                while True:
                    x -= xdirection
                    y -= ydirection
                    if x == xstart and y == ystart:
                        break
                    tilesToFlip.append([x, y])

    board[xstart][ystart] = ' ' # restore the empty space
    if len(tilesToFlip) == 0: # If no tiles were flipped, this is not a valid move.
        return False
    return tilesToFlip


def isOnBoard(x, y):
    # Returns True if the coordinates are located on the board.
    return x >= 0 and x <= 7 and y >= 0 and y <=7


def getBoardWithValidMoves(board, tile):
    # Returns a new board with . marking the valid moves the given player can make.
    dupeBoard = getBoardCopy(board)

    for x, y in getValidMoves(dupeBoard, tile):
        dupeBoard[x][y] = '.'
    return dupeBoard


def getValidMoves(board, tile):
    # Returns a list of [x,y] lists of valid moves for the given player on the given board.
    validMoves = []

    for x in range(8):
        for y in range(8):
            if isValidMove(board, tile, x, y) != False:
                validMoves.append([x, y])
    return validMoves


def getScoreOfBoard(board):
    # Determine the score by counting the tiles. Returns a dictionary with keys 'X' and 'O'.
    xscore = 0
    oscore = 0
    for x in range(8):
        for y in range(8):
            if board[x][y] == 'X':
                xscore += 1
            if board[x][y] == 'O':
                oscore += 1
    return {'X':xscore, 'O':oscore}


def enterPlayerTile():
    # Lets the player type which tile they want to be.
    # Returns a list with the player's tile as the first item, and the computer's tile as the second.
    tile = ''
    while not (tile == 'X' or tile == 'O'):
        print('Do you want to be X or O?')
        tile = input().upper()

    # the first element in the tuple is the player's tile, the second is the computer's tile.
    if tile == 'X':
        return ['X', 'O']
    else:
        return ['O', 'X']


def whoGoesFirst():
    # Randomly choose the player who goes first.
    if random.randint(0, 1) == 0:
        return 'computer'
    else:
        return 'player'


def playAgain():
    # This function returns True if the player wants to play again, otherwise it returns False.
    print('Do you want to play again? (yes or no)')
    return input().lower().startswith('y')


def makeMove(board, tile, xstart, ystart):
    # Place the tile on the board at xstart, ystart, and flip any of the opponent's pieces.
    # Returns False if this is an invalid move, True if it is valid.
    tilesToFlip = isValidMove(board, tile, xstart, ystart)

    if tilesToFlip == False:
        return False

    board[xstart][ystart] = tile
    for x, y in tilesToFlip:
        board[x][y] = tile
    return True


def getBoardCopy(board):
    # Make a duplicate of the board list and return the duplicate.
    dupeBoard = getNewBoard()

    for x in range(8):
        for y in range(8):
            dupeBoard[x][y] = board[x][y]

    return dupeBoard


def isOnCorner(x, y):
    # Returns True if the position is in one of the four corners.
    return (x == 0 and y == 0) or (x == 7 and y == 0) or (x == 0 and y == 7) or (x == 7 and y == 7)


def getPlayerMove(board, playerTile):
    # Let the player type in their move.
    # Returns the move as [x, y] (or returns the strings 'hints' or 'quit')
    DIGITS1TO8 = '1 2 3 4 5 6 7 8'.split()
    while True:
        print('Enter your move, or type quit to end the game, or hints to turn off/on hints.')
        move = input().lower()
        if move == 'quit':
            return 'quit'
        if move == 'hints':
            return 'hints'

        if len(move) == 2 and move[0] in DIGITS1TO8 and move[1] in DIGITS1TO8:
            x = int(move[0]) - 1
            y = int(move[1]) - 1
            if isValidMove(board, playerTile, x, y) == False:
                continue
            else:
                break
        else:
            print('That is not a valid move. Type the x digit (1-8), then the y digit (1-8).')
            print('For example, 81 will be the top-right corner.')

    return [x, y]


def getComputerMove(board, computerTile):
    # Given a board and the computer's tile, determine where to
    # move and return that move as a [x, y] list.
    possibleMoves = getValidMoves(board, computerTile)

    # randomize the order of the possible moves
    random.shuffle(possibleMoves)

    # always go for a corner if available.
    for x, y in possibleMoves:
        if isOnCorner(x, y):
            return [x, y]

    # Go through all the possible moves and remember the best scoring move
    bestScore = -1
    for x, y in possibleMoves:
        dupeBoard = getBoardCopy(board)
        makeMove(dupeBoard, computerTile, x, y)
        score = getScoreOfBoard(dupeBoard)[computerTile]
        if score > bestScore:
            bestMove = [x, y]
            bestScore = score
    return bestMove


def showPoints(playerTile, computerTile):
    # Prints out the current score.
    scores = getScoreOfBoard(mainBoard)
    print('You have %s points. The computer has %s points.' % (scores[playerTile], scores[computerTile]))



print('Welcome to Reversi!')

while True:
    # Reset the board and game.
    mainBoard = getNewBoard()
    resetBoard(mainBoard)
    playerTile, computerTile = enterPlayerTile()
    showHints = False
    turn = whoGoesFirst()
    print('The ' + turn + ' will go first.')

    while True:
        if turn == 'player':
            # Player's turn.
            if showHints:
                validMovesBoard = getBoardWithValidMoves(mainBoard, playerTile)
                drawBoard(validMovesBoard)
            else:
                drawBoard(mainBoard)
            showPoints(playerTile, computerTile)
            move = getPlayerMove(mainBoard, playerTile)
            if move == 'quit':
                print('Thanks for playing!')
                sys.exit() # terminate the program
            elif move == 'hints':
                showHints = not showHints
                continue
            else:
                makeMove(mainBoard, playerTile, move[0], move[1])

            if getValidMoves(mainBoard, computerTile) == []:
                break
            else:
                turn = 'computer'

        else:
            # Computer's turn.
            drawBoard(mainBoard)
            showPoints(playerTile, computerTile)
            input('Press Enter to see the computer\'s move.')
            x, y = getComputerMove(mainBoard, computerTile)
            makeMove(mainBoard, computerTile, x, y)

            if getValidMoves(mainBoard, playerTile) == []:
                break
            else:
                turn = 'player'

    # Display the final score.
    drawBoard(mainBoard)
    scores = getScoreOfBoard(mainBoard)
    print('X scored %s points. O scored %s points.' % (scores['X'], scores['O']))
    if scores[playerTile] > scores[computerTile]:
        print('You beat the computer by %s points! Congratulations!' % (scores[playerTile] - scores[computerTile]))
    elif scores[playerTile] < scores[computerTile]:
        print('You lost. The computer beat you by %s points.' % (scores[computerTile] - scores[playerTile]))
    else:
        print('The game was a tie!')

    if not playAgain():
        break

How do I use structures in C Programming

/*
* Program to use structures
* From the book: C Programming Visual Quickstart Guide
*
* One structure at a time is written to a binary file
*/

#include <stdio.h>

/*
* Set the file path and name as a C preprocessor macro.
*/

#define THEFILE "weather.dat"

int main (void) {

/*
* Define a structure and create a variable of that type.
* The structure will be called weather_record. It contains
* three members: a character array called date, an integer
* called high, and another integer called low. Each of 
* these correspond to the variables that were used in the
* previous versions of this application. 
* One variable of the weather_record type is created, 
* called today. Note that you have to use both the 
* keyword struct as well as the structure name in
* defining this variable.
*/

struct weather_record {
/*
* YYYY-MM-DD
*/
char date[11];

int high;
int low;

};

/* 
* One structure variable of type weather_record.
*/

struct weather_record today;

/* 
* Need a pointer of type FILE.
*/

FILE *fp;

/* 
* Attempt to open the file for appended binary writing.
*/

fp = fopen(THEFILE, "ab");

/*
* The file is open.
*/
if (fp != NULL) {

/*
* Prompt the user.
*/

printf("Enter a date, the high tempature, and the low tempature.\n(YYYY-MM-DD ## ##): ");

/* 
* Handle the input, assigning it to the structure fields.
*/

if(scanf ("%10s %d %d", today.date, &today.high, &today.low) ==3) {

/*
* Write the data.
*/

fwrite(&today, sizeof(struct weather_record), 1, fp);
printf("The data has been written.\n");

} else {

printf("The data was not in proper format.\n");
}

} else{

printf("The file could not be opened.\n");

/*
* Exit the function/application.
*/

return 1;

}

/* 
* Close the file.
*/

if (fclose(fp) != 0) {
printf("The file could not be closed.\n");
}

/*
* Pause
*/
getchar();
getchar();
return 0;

} 

How to navigate a binary file in C Programming

/*
* Program to navigate a binary file
* From the book: C Programming Visual Quickstart Guide
*
* A random point in the data file is used to
* return a "lucky number."
*/

#include <stdio.h>
/*
* For rand() and srand().
*/
#include <stdlib.h>
/*
* For time(), used with srand().
*/
#include <time.h>

/*
* Set the file path and name.
*/

#define THEFILE "numbers.dat"

/* 
* Numbers of items being written.
* Creat a constant macro representing
* the number of items in the array.
*/

#define ITEMS 50

int main(void) {

/* 
* Need a pointer of type FILE
*/

FILE *fp;

/*
* Two integers are required.
* The first integer will be used as the
* off-set: the location within the number
* file to move to. The second will store 
* the read-in number value.
*/

int offset, number;

/*
* Attempt to open the file for binary reading.
*/

fp = fopen(THEFILE, "rb");

/*
* Start a conditional based on the file pointer.
* The file is open.
*/

if (fp != NULL) {

/*
* Find a random offset in bytes.
* The first line seeds the rand() funcion.
* The second line picks an arbitrary offset,
* as a random number up to the number of items
* stored. After this second line of code, offset
* will be qual to a number between 0 and 49, 
* corresponding to the 50 items originally stored
* in the file (like an array though, we begin
* counting at 0.)
* The third line multiplies the value of offset
* by the size of an integer. This is neccessary
* because we need to specify the offset in bytes.
* For example, if the randomly generated value is 
10, then the offset needs to be 40 bytes: 10 times
* sizeof(int), normally 4 bytes.
*/

srand((unsigned)time(NULL));
offset = rand() % ITEMS;
offset *= sizeof(int);

/* 
* Move to the random location and read in a number.
* The first line moves the virtual marker offset
* bytes into the file, starting from the beginning
* of the file. The second line reads one bk of data
* of sizeof(number) bytes and stores this in the 
* number variable. Remember that the fread() 
* function takes an address of a variable as its 
* first argument, so &number is used (the memory
* addres of the number variable.)
*/

fseek(fp, offset, SEEK_SET);
fread(&number, sizeof(number), 1, fp);

/*
* Print the number.
*/

printf("Your lucky number is: %d.\n", number);

} else {

printf("The file could not be opened.\n");

/*
* Exit the function/application.
*/

return 1;
}

/*
* Close the file.
*/

if (fclose(fp) != 0){
printf("The file could not be closed.\n");

}

/* 
* Pause.
*/

getchar();

return 0;

}