Week 5 Code Examples

// Combine 2 strings together with strcat

#include <stdio.h>
#include <string.h>

#define MAX_LEN 200

void remove_trailing_nl(char s[]);

int main(void) {
    char first_name[MAX_LEN]; //Tina
    char last_name[MAX_LEN];  //Arena
    //Make sure I have enough room if both names have 
    // MAX_LEN-1 characters
    //(or were longer and cut off by fgets)
    char full_name[MAX_LEN * 2 + 1]; //Arena, Tina

    // Read first name and last name
    printf("Enter first name: ");
    fgets(first_name, MAX_LEN, stdin);
    remove_trailing_nl(first_name);

    printf("Enter last name: ");
    fgets(last_name, MAX_LEN, stdin);
    remove_trailing_nl(last_name);

    // Output the full name as follows
    // Lastname, Firstname
    strcpy(full_name, last_name);
    strcat(full_name, ", ");
    strcat(full_name, first_name);

    printf("Full name: %s\n", full_name);

    
    return 0;
}

void remove_trailing_nl(char s[]) {
    int len = strlen(s);
    if (s[len - 1] == '\n') {
        s[len - 1] = '\0';
    }
}
// Example of using string functions from string.h library
// strings can get a bit tricky and messy in C
// It is easy to overflow buffers or lose our '\0' characters!

#include <stdio.h>
#include <string.h>

#define MAX_LENGTH 100

void remove_trailing_new_line(char s[]);

int main(void) {
    // Declare an array to store a string
    char puppy[MAX_LENGTH] = "Boots";

    printf("%s\n", puppy);
 
    // Copy the string "Finn" into the word array
    // Make sure your array is big enough!!!
    
    //puppy = "Finn";
    strcpy(puppy, "Finn");
    printf("%s\n", puppy);

    // Find string length. It does NOT include '\0' in the length
    int len = strlen(puppy);
    printf("%s has length %d\n", puppy, len);


    // Declare an array to store a string
    char name[] = "Oscar";

    if (strcmp(name, "Oscar") == 0) {
        printf("Hi Oscar\n");
    } else {
        printf("You are not Oscar!\n");
    }

    if (strcmp(name, "Edgar") == 0) {
        printf("Hi Edgar\n");
    } else {
        printf("You are not Edgar!\n");
    }

    if (strcmp(name, "Edgar") < 0) {
        printf("%s Edgar\n", name);
    } else {
        printf("Edgar %s\n", name);
    }

    // Declare an array to store a string
    char name2[MAX_LENGTH];
    printf("\nType in a name: ");

    // Read in a string
    fgets(name2, MAX_LENGTH, stdin);

    // Use strcmp to compare 2 strings
    if (strcmp("Oscar", name2) == 0) {
        printf("Yay Oscar!\n");
    }

    remove_trailing_new_line(name2);

    // Use strcmp to compare 2 strings
    if (strcmp("Oscar", name2) == 0) {
        printf("Yay Oscar!\n");
    }

    return 0;
}

void remove_trailing_new_line(char s[]) {
    int len = strlen(s);
    if (s[len-1] == '\n'){
        s[len-1] = '\0';
    }
}
// Example of using string functions from string.h library
// strings can get a bit tricky and messy in C
// It is easy to overflow buffers or lose our '\0' characters!

#include <stdio.h>
#include <string.h>

#define MAX_LENGTH 100

int main(void) {
    // Declare an array to store a string
    char favourite_food[] = "kfc";

    // Actually pizza is now my favourite food
    strcpy(favourite_food, "pizza");
    printf("%s\n", favourite_food);
    return 0;
}
// An example of an array of strings
// This assumes we have at most 20 9 letter words

#include <stdio.h>
#include <string.h>

#define MAX_STRINGS 20
#define MAX_LEN 10

//  0  1  2  3  4  5  6  7  8  9
//0 h  a  t \0 
//1 c  a  k  e  \0 
//2 t  e  a \0
//3 s  u  n \0
//4 \0
//5 \0
//etc


void print_text(char text[MAX_STRINGS][MAX_LEN], int max_lines);

int main(void){
    char text[MAX_STRINGS][MAX_LEN] = {"hat", "cake", "tea"};
    int num_strings = 3;
    
    // Print one string
    printf("%s\n", text[2]);    
    
    // Print one character
    printf("%c\n", text[1][2]);

    printf("Printing out text\n");
    print_text(text, num_strings);

    strcpy(text[3],"sun");
    num_strings++;
    
    printf("Printing out text\n");
    print_text(text, num_strings);

    return 0;
}

void print_text(char data[MAX_STRINGS][MAX_LEN], int size){
    for (int i = 0; i < size; i++) {
        printf("%s\n", data[i]);
    }
}
// Week 5 lecture
// showing the use of atoi
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    int sum = 0;
    for (int i = 1; i < argc; i++) {
        // atoi converts a string to an int
        // For example atoi("123") would return the int 123.
        sum = sum + atoi(argv[i]);
    }
    printf("%d is the sum of all command line args\n", sum);
    return 0;
}
// Week 5 lecture
// This does not work
// Even if we run
// ./bad_sum 99 -127 918
// 99 etc is the string "99" which is an array of char
// We can't do maths on it

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    int sum = 0;
    for (int i = 1; i < argc; i++) {
        sum = sum + argv[i];
    }
    printf("%d is the sum of all command line args\n", sum);
    return 0;
}
// Week 5 Lecture
// showing the use of command line arguments
// For example you can run this program like
// ./command_line_args "hello world" 5 BLAH
// 

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("There are %d command line arguments\n", argc);
   
    // argv[0] is always the program name
    printf("This program name is %s\n", argv[0]);

    // print out all arguments in the argv array
    for (int i = 0; i < argc; i++) {
        printf("Argument at index %d is %s\n", i, argv[i]);
    }
    return 0;
}
// COMP1511 Week 5 Lecture 
// Time to get our hands (or paws) dirty and write a larger lecture program
// Angela Finlayson 

#include <stdio.h>

// Provided Constants
#define INVALID_INDEX -1
#define MAP_ROWS 8
#define MAP_COLUMNS 8

// User define constants go here
#define MOVE_UP 'w'
#define MOVE_LEFT 'a'
#define MOVE_DOWN 's'
#define MOVE_RIGHT 'd'

 

// Provided enums and structs
enum ground_type {
    GRASS,
    MUD
};

enum item_type {
    EMPTY,
    BONE
};

struct location {
    enum item_type item;
    enum ground_type ground;
};

// User defined enums and structs
struct dog_data{
    int row;
    int col;
    int bone_count;
    int mud_count;
};
 
// Provided function prototypes
void initialise_map(struct location map[MAP_ROWS][MAP_COLUMNS]);

void print_map(
    struct location map[MAP_ROWS][MAP_COLUMNS], 
    int dog_row, 
    int dog_col,
    int bone_count,
    int mud_count
);

void print_location(struct location location, int ground_layer, int print_dog);
void print_ground_type(enum ground_type ground);
void print_item_type(enum item_type item);

// User defined function prototypes
int is_valid_position(int row, int col);
struct dog_data map_update (
    struct location map[MAP_ROWS][MAP_COLUMNS], 
    struct dog_data dog
);

void find_bones(struct location map[MAP_ROWS][MAP_COLUMNS], 
    struct dog_data dog
);

int main(void) {
    struct location map[MAP_ROWS][MAP_COLUMNS];
    initialise_map(map);
    print_map(map, INVALID_INDEX, INVALID_INDEX, 0, 0);
    
    printf("Enter dog's location: "); 
    struct dog_data dog;
    dog.bone_count = 0;
    dog.mud_count = 0;

    if (scanf("%d %d", &dog.row, &dog.col) != 2 || 
        is_valid_position(dog.row, dog.col) == 0){
        dog.row = 0;
        dog.col = 0;
    }

    dog = map_update(map, dog);

    print_map(map, dog.row, dog.col, dog.bone_count, dog.mud_count);

    printf("\nLet's find some bones, but watch the mud!!!!\n");
    find_bones(map, dog);

    printf("Woof Woof\n");
    return 0;
}

// returns 1 if row col are within bounds of array
// returns 0 otherwise
int is_valid_position(int row, int col) {
    int valid = 1;
    if (row < 0 || col < 0 || row >= MAP_ROWS || col >= MAP_COLUMNS) {
       valid = 0; 
    }
    return valid;
}

struct dog_data map_update (
    struct location map[MAP_ROWS][MAP_COLUMNS], 
    struct dog_data dog
) {
    //if dog is in position where there is a bone
    if (map[dog.row][dog.col].item == BONE) {
        dog.bone_count++;
        map[dog.row][dog.col].item = EMPTY;
    }

    if (map[dog.row][dog.col].ground == MUD) {
        dog.mud_count++;
    }
    return dog;
}

void find_bones(struct location map[MAP_ROWS][MAP_COLUMNS], 
    struct dog_data dog
){
    char move;
    while (scanf(" %c", &move) == 1) {
        if (move == MOVE_UP) {
            dog.row--;
        } else if (move == MOVE_DOWN) {
            dog.row++;
        } else if (move == MOVE_LEFT) {
            dog.col--;
        } else if (move == MOVE_RIGHT) {
            dog.col++;
        }
        dog = map_update(map, dog);
        print_map(map, dog.row, dog.col, dog.bone_count, dog.mud_count);
    }

}

// STARTER FUNCTIONS BELOW THIS POINT //////////////////////////

// initialises the map with empty items and grass ground types
// Hard codes some bones and mud
void initialise_map(struct location map[MAP_ROWS][MAP_COLUMNS]) {
    int row = 0;
    while (row < MAP_ROWS) {
        int col = 0;
        while (col < MAP_COLUMNS) {
            map[row][col].ground = GRASS;
            map[row][col].item = EMPTY;
            col++;
        }
        row++;
    } 
    // Hard coding these instead of getting user input
    // so I don't give away too much for the assignment
    // and to save time
    map[0][1].item = BONE;
    map[1][1].item = BONE;
    map[7][7].item = BONE;
    map[5][1].item = BONE;
    map[0][1].ground = MUD;
    map[7][6].ground = MUD;
    map[0][2].ground = MUD;
    map[0][3].ground = MUD;
}

// Print out the map and then the game stats
// Each row has 2 lines of output,
// the first line represents the dog or item
// the second line represents the ground
void print_map(
    struct location map[MAP_ROWS][MAP_COLUMNS], 
    int dog_row, 
    int dog_col,
    int bone_count,
    int mud_count
) {
    printf("==== Mud and Bones ====\n");
    printf("=======================\n");
    for (int row = 0; row < MAP_ROWS * 2; row++) {     
        for (int col = 0; col < MAP_COLUMNS; col++) {
            int print_dog = 0;
            if (dog_row == row/2 && dog_col == col) {
                print_dog = 1;
            }
            print_location(map[row / 2][col], row % 2, print_dog);
        }
        printf("\n");    
    }
    printf("=======================\n");
    printf("Bones: %2d      Mud: % d\n", bone_count, mud_count);
    printf("=======================\n\n");
}

// prints specific location on map (used by print_map)
void print_location(
    struct location location,  int ground_print, int print_dog) {
    if (ground_print) {
        print_ground_type(location.ground);
    } else {
        if (print_dog) {
            printf("(D)");
        } else {
            print_item_type(location.item);
        }
    }
}

// Takes a ground type enum as input and prints 
// a corresponding character to visually represent it
void print_ground_type(enum ground_type ground) {
    if (ground == GRASS) {
        printf(" . ");
    } else if (ground == MUD) {
        printf(" M ");
    } else {
        printf(" ? ");
    }
}

// Takes an item type enum as input and prints 
// a corresponding character to visually represent it
void print_item_type(enum item_type item) {
    if (item == EMPTY) {
        printf("   ");
    } else if (item == BONE) {
        printf(" B ");
    } else {
        printf(" ? ");
    }
}
// COMP1511 Week 5 Lecture 
// Time to get our hands (or paws) dirty and write a larger lecture program
// Angela Finlayson 

#include <stdio.h>

// Provided Constants
#define INVALID_INDEX -1
#define MAP_ROWS 8
#define MAP_COLUMNS 8

// User define constants go here
 

// Provided enums and structs
enum ground_type {
    GRASS,
    MUD
};

enum item_type {
    EMPTY,
    BONE
};

struct location {
    enum item_type item;
    enum ground_type ground;
};

// User defined enums and structs
 
// Provided function prototypes
void initialise_map(struct location map[MAP_ROWS][MAP_COLUMNS]);

void print_map(
    struct location map[MAP_ROWS][MAP_COLUMNS], 
    int dog_row, 
    int dog_col,
    int bone_count,
    int mud_count
);

void print_location(struct location location, int ground_layer, int print_dog);
void print_ground_type(enum ground_type ground);
void print_item_type(enum item_type item);

// User defined function prototypes
 

int main(void) {
    struct location map[MAP_ROWS][MAP_COLUMNS];
    initialise_map(map);
    print_map(map, INVALID_INDEX, INVALID_INDEX, 0, 0);
    
    printf("Enter dog's location: "); 
    //TODO

    printf("\nLet's find some bones, but watch the mud!!!!\n");
    //TODO

    printf("Woof Woof\n");
    return 0;
}


// STARTER FUNCTIONS BELOW THIS POINT //////////////////////////

// initialises the map with empty items and grass ground types
// Hard codes some bones and mud
void initialise_map(struct location map[MAP_ROWS][MAP_COLUMNS]) {
    int row = 0;
    while (row < MAP_ROWS) {
        int col = 0;
        while (col < MAP_COLUMNS) {
            map[row][col].ground = GRASS;
            map[row][col].item = EMPTY;
            col++;
        }
        row++;
    } 
    // Hard coding these instead of getting user input
    // so I don't give away too much for the assignment
    // and to save time
    map[0][1].item = BONE;
    map[1][1].item = BONE;
    map[7][7].item = BONE;
    map[5][1].item = BONE;
    map[0][1].ground = MUD;
    map[7][6].ground = MUD;
    map[0][2].ground = MUD;
    map[0][3].ground = MUD;
}

// Print out the map and then the game stats
// Each row has 2 lines of output,
// the first line represents the dog or item
// the second line represents the ground
void print_map(
    struct location map[MAP_ROWS][MAP_COLUMNS], 
    int dog_row, 
    int dog_col,
    int bone_count,
    int mud_count
) {
    printf("==== Mud and Bones ====\n");
    printf("=======================\n");
    for (int row = 0; row < MAP_ROWS * 2; row++) {     
        for (int col = 0; col < MAP_COLUMNS; col++) {
            int print_dog = 0;
            if (dog_row == row/2 && dog_col == col) {
                print_dog = 1;
            }
            print_location(map[row / 2][col], row % 2, print_dog);
        }
        printf("\n");    
    }
    printf("=======================\n");
    printf("Bones: %2d      Mud: % d\n", bone_count, mud_count);
    printf("=======================\n\n");
}

// prints specific location on map (used by print_map)
void print_location(
    struct location location,  int ground_print, int print_dog) {
    if (ground_print) {
        print_ground_type(location.ground);
    } else {
        if (print_dog) {
            printf("(D)");
        } else {
            print_item_type(location.item);
        }
    }
}

// Takes a ground type enum as input and prints 
// a corresponding character to visually represent it
void print_ground_type(enum ground_type ground) {
    if (ground == GRASS) {
        printf(" . ");
    } else if (ground == MUD) {
        printf(" M ");
    } else {
        printf(" ? ");
    }
}

// Takes an item type enum as input and prints 
// a corresponding character to visually represent it
void print_item_type(enum item_type item) {
    if (item == EMPTY) {
        printf("   ");
    } else if (item == BONE) {
        printf(" B ");
    } else {
        printf(" ? ");
    }
}
// COMP1511 Week 5
// Making pointers point to different things

#include <stdio.h>

int main(void) {
    int x = 3;  
    int y = 7;
    int *x_ptr = &x;
    int *num_ptr = x_ptr; 

    // What will this print?
    printf("%d %d %d %d\n", x, y, *x_ptr, *num_ptr);

    *num_ptr = 10; 
    // What will this print now?
    printf("%d %d %d %d\n", x, y, *x_ptr, *num_ptr);

    // num_ptr is pointing somewhere else now
    num_ptr = &y;

    // What will this print now?
    printf("%d %d %d %d\n", x, y, *x_ptr, *num_ptr);

    y = 99;
    // What will this print now?
    printf("%d %d %d %d\n", x, y, *x_ptr, *num_ptr);

    
    //double d = 1.5;
    //num_ptr = &d; //INVALID C CODE

    
    return 0;     
}
// COMP1511 Week 5
// Exercise. 
// Try to read and work out what it will print
// before running the code.

#include <stdio.h>

int main(void) {
    int x = -7;
    int y = 5;
    
    int *ptr1 = &y;
    int *ptr2 = &x;
    
    int z = *ptr1 + y;
    
    *ptr2 = z - 1;
    printf("%d %d %d\n", x, y, z);
    
    ptr2 = ptr1;
    printf("%d %d\n", *ptr1, *ptr2);

    return 0;
}
// COMP1511 Week 5
// Introduction to basic pointer concepts
// Address of operator &
// Declaring and initialised pointer variables
// Dereferencing pointer variables

#include <stdio.h>

int main(void) {
    // Decare and initialise a normal int variable called 'x'
    int x = 2;   

    // Print the address and value of x
    printf("The int that x stores (x): %d\n", x);
    printf("The address of x (&x): %p\n", &x);
    
    // Declare a pointer variable 'x_ptr' and 
    // assign the address of 'x' to it
    int *x_ptr = &x;

    // Print the addresses and value of x_ptr
    printf("The address that x_ptr stores (x_ptr): %p\n", x_ptr);
    printf("The address of x_ptr (&x_ptr): %p\n", &x_ptr);
    
    // Dereference 'x_ptr'
    printf("x_ptr (*x_ptr): %d\n", *x_ptr);
    
    // Modify x indirectly via our pointer
    *x_ptr = 99;
    printf("x:%d   *x_ptr:%d \n", x, *x_ptr);

    return 0;     
}
// COMP1511 Week 5 Lecture 2
// variables/data are passed into functions by value
// a copy of the value gets passed into the function
// so changes made in the function are on the local copy

#include <stdio.h>

void update(int x, int y);
void swap(int x, int y);

int main(void) {
    int x = 2;
    int y = 5;

    printf("%d %d\n", x, y);
    
    update(x,y);
    printf("%d %d\n", x, y);
    
    swap(x, y);
    printf("%d %d\n", x, y);
    return 0;
}

// This function will only modify the local copy of x and y
void update(int x, int y) {
    x = x + 1;
    y = y - 1;
}

// This function will only modify the local copy of x and y
void swap(int x, int y) {
    int tmp = x;
    x = y;
    y = tmp;
}
// COMP1511 Week 5 Lecture 2
// variables/data are passed into functions by value
// a copy of the value gets passed into the function
// Here we pass in the addresses of the variables
// so we can go directly to their address and modify
// them from within the function

#include <stdio.h>

void update(int *x, int *y);
// TO DO FIX SWAP
void swap(int *x, int *y);

int main(void) {
    int x = 2;
    int y = 5;

    printf("%d %d\n", x, y);
    
    // Pass in the addresses of x and y
    // So update can use the addresses to
    // go modify x and y 
    update(&x, &y);
    printf("%d %d\n", x, y);
    
    //TODO FIX THIS
    swap(&x, &y);
    printf("%d %d\n", x, y);
    return 0;
}

// This function uses pointers.
// We can dereference x and y and modify the data
// at the given addresses
void update(int *x, int *y) {
    *x = *x + 1;
    *y = *y - 1;
}

// This function will only modify the local copy of x and y
// TODO FIX
void swap(int *x, int *y) {
    int tmp = *x;
    *x = *y;
    *y = tmp;
}
// COMP1511 Week 5 Lecture 2
// variables/data are passed into functions by value
// a copy of the value gets passed into the function

#include <stdio.h>

struct point {
    int x;
    int y;
};

void update(struct point p);

int main(void) {
    struct point p;    
    p.x = 10;
    p.y = 9;
    update(p);
	printf("(%d,%d)\n", p.x, p.y);
    return 0;
}

// This function will only modify the local copy of p
void update(struct point p) {
    p.x = p.x + 1;
    p.y = p.y + 1;
}
// COMP1511 Week 5 Lecture 2
// variables/data are passed into functions by value
// a copy of the value gets passed into the function
// TO DO MODIFY THIS TO USE POINTERS

#include <stdio.h>

struct point {
    int x;
    int y;
};

void update(struct point *my_point);
struct point update2(struct point p);

int main(void) {
    struct point p;    
    p.x = 10;
    p.y = 9;

    update(&p);
    printf("(%d,%d)\n", p.x, p.y);
    p = update2(p);
    printf("(%d,%d)\n", p.x, p.y);
    return 0;
}

// This function will only modify the local copy of p
// Modify this version to use pointers.
void update(struct point *my_point) {
    my_point->x = my_point->x + 1;  
    my_point->y = my_point->y + 1;  
}

struct point update2(struct point p) {
    p.x++;
    p.y++;
    return p;
}