Programming Assignment Samples

Page 1

For any Assignment related queries, Call us at : - +1 (315) 557 6473 You can mail us at :support@programminghomeworkhelp.com or Reach us at : - https://www.programminghomeworkhelp.com/ https://www.programminghomeworkhelp.com/ Programming Homework Help: Function Pointers and Hash Tables - Sample Solutions

Welcome to this presentation showcasing our sample solutions for assignments involving function pointers and hash tables.At ProgrammingHomeworkHelp.com, we provide detailed, step-by-step solutions to help you excel in your programming coursework.

Problem 1 Overview

Question: Problem 1:

In this problem, we will use and create function that utilize function pointers.The file ’callback.c’ contains an array of records consisting of a fictitious class of celebrities. Each record consists of the firstname, lastname and age of the student.Write code to do the following:

https://www.programminghomeworkhelp.com/

Sort the records based on first name.To achieve this, you will be using the qsort() function provided by the standard library: void qsort(void∗ arr,int num,int size,int (∗fp)(void∗ pa,void∗pb)).The function takes a pointer to the start of the array ’arr’, the number of elements ’num’ and size of each element. In addition it takes a function pointer ’fp’ that takes two arguments.The function fp is used to compare two elements within the array. Similar to strcmp(), it is required to return a negative quantity,zero or a positive quantity dependeing on whether element pointed to by ’pa’ is ”less” than, equal to or ”greater” the element pointed to by ’pb’.You are required to write the appropriate callback function. Now sort the records based on last name.Write the appropriate callback function.

The function void apply (...) iterates through the elements of the array calling a function for each element of the array.Write a function isolder() that prints the record if the age of the student is greater 20 and does nothing otherwise.

https:// www.programminghomeworkhelp.com/

Solution Code

https://www.programminghomeworkhelp.com/

/* * prob1.c */

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

/* maximum length of input string (including newline character) */

#define INPUT_MAX 2048

/* enable (1) or disable (0) parentheses checking in parsing strings */

/* leave disabled for part (a); enable for part (b) */

#define PARSE_PARENS 0

/* type of token */

enum token_type {

OPERAND, /* number */

OPERATOR, /* operator: +, -, *, / */

#if PARSE_PARENS

LPARENS, /* left parentheses ( */

RPARENS /* right parentheses ) */

#endif

};
https://www.programminghomeworkhelp.com/

/* operator identifiers (opcodes) */

enum op {

ADD, /* a+b */

SUBTRACT, /* a-b (binary) */

MULTIPLY, /* a*b */

DIVIDE, /* a/b */ NEGATE /* -a (unary) */

enum assoc

LEFT, /* left-to-right (+, binary -, *, /) */

RIGHT /* right-to-left (unary -) */

const unsigned int op_operands[] = {2, 2, 2, 2, 1};

/* order-of-operations (precedence) (0 = evaluated last) */

const unsigned int op_precedences[] = {0, 0, 1, 1, 2};

/* evaluation direction (associativity) for each precedence level */

const enum assoc op_associativity[] = {LEFT, LEFT, RIGHT};

https://www.programminghomeworkhelp.com/

};
{
};

/* contains value of token */

union token_value { double operand; /* numeric value for operand */ enum op op_code; /* opcode for operators */

/* data structure for token */

typedef struct s_expr_token {

union token_value value; /* numeric value or opcode */ enum token_type type; /* type of token */

struct s_expr_token * linked_token; /* linked token in stack/queue */

} * p_expr_token; /* p_expr_token is shorthand for "struct s_expr_token *" */

struct token_queue {

p_expr_token front; /* front of queue, where tokens are dequeued */ p_expr_token back; /* back of queue, where tokens are added */

/* queue functions - enqueue and dequeue */

void enqueue(struct token_queue * pqueue, const p_expr_token ptoken);

p_expr_token dequeue(struct token_queue * pqueue);

https://www.programminghomeworkhelp.com/

};
};

/* stack functions - push and pop */

void push(p_expr_token * ptop, const p_expr_token ptoken);

p_expr_token pop(p_expr_token * ptop);

/* creates a new token in dynamic memory (using malloc()) */

p_expr_token new_token(const enum token_type type, const union token_value value);

/* constructs a queue of tokens in infix order from a space-delimited string */

struct token_queue expr_to_infix(char * str);

/* creates a queue of tokens in postfix order from a queue of tokens in infix order */

/* postcondition: returned queue contains all the tokens, and pqueue_infix should be empty */

struct token_queue infix_to_postfix(struct token_queue * pqueue_infix);

/* evalutes the postfix expression stored in the queue */

/* postcondition: returned value is final answer, and pqueue_postfix should be empty */

double evaluate_postfix(struct token_queue * pqueue_postfix);

/* handles evaluation process (calls above functions) for expression string str */ double evaluate(const char * str);

https://www.programminghomeworkhelp.com/

int main(void) { char input[INPUT_MAX]; double ans; unsigned int len; do { printf("Enter an expression to evaluate: "); fflush(stdout); if (!fgets(input, INPUT_MAX, stdin)) abort(); /* failed to read stdin */ len = strlen(input); /* remove trailing newline character */ if (len > 0 && input[len-1] == '\n') { input[len-1] = '\0'; --len; } if (len == 0) /* empty expression signals exit */ break; /* call evaluation functions */ ans = evaluate(input); https://www.programminghomeworkhelp.com/

/* write result to stdout */

printf("%s => %g\n", input, ans); } while (1); return 0;

} /* enqueue (add) token to end of queue input: pqueue - pointer to queue ptoken - token pointer to add postcondition: token added to end of queue */

void enqueue(struct token_queue * pqueue, const p_expr_token ptoken) { ptoken->linked_token = NULL; if (pqueue->back) pqueue->back->linked_token = ptoken; else /* empty */ pqueue->front = ptoken; pqueue->back = ptoken;

} input: pointer to queue

output: front token pointer (or NULL, if queue was empty)

postcondition: token removed from queue */

https://www.programminghomeworkhelp.com/

p_expr_token dequeue(struct token_queue * pqueue) { p_expr_token ptoken = pqueue->front; if (pqueue->front) { pqueue->front = ptoken->linked_token; if (ptoken == pqueue->back) /* at end */ pqueue->back = NULL; ptoken->linked_token = NULL; } return ptoken;

} /* push (add) token to top of stack

input: ptop - pointer to top token pointer of stack ptoken - token pointer to add postcondition: ptop points to the added token */ void push(p_expr_token * ptop, const p_expr_token ptoken) { ptoken->linked_token = *ptop; *ptop = ptoken;

} /* pop (remove) token from top of stack

input: pointer to top token pointer of stack

https://www.programminghomeworkhelp.com/

output: top token pointer (or NULL, if stack was empty)

postcondition: ptop points to next token in stack */

p_expr_token pop(p_expr_token * ptop) {

p_expr_token ptoken; if ( (ptoken = *ptop) ) {

/* evalutes the postfix expression stored in the queue */

/* postcondition: returned value is final answer, and pqueue_postfix should be empty */

double evaluate_postfix(struct token_queue * pqueue_postfix) {

/*TODO: process postfix-ordered queue and return final answer; all tokens from postfix-ordered queue is freed */

} *ptop = ptoken->linked_token; ptoken->linked_token = NULL; } return ptoken;

}

https://www.programminghomeworkhelp.com/

/* allocate new token on heap, with specified type and value; the token is initially un-linked (field "linked_token" == NULL)

note: token must be freed using free() after use */

p_expr_token new_token(const enum token_type type, const union token_value value) { p_expr_token ptoken = (p_expr_token)malloc(sizeof(struct s_expr_token)); ptoken->type = type; ptoken->value = value; ptoken->linked_token = NULL; return ptoken;

}

/* handles evaluation process (calls above functions) for expression string str */ /* returns the final answer */

double evaluate(const char * str) { char * strbuffer; /* mutable buffer for string (modified in calls to strtok()) */ double ans; /* answer to return */ struct token_queue queue_infix, queue_postfix;

https://www.programminghomeworkhelp.com/

/* copy str into mutable buffer */ strbuffer = strcpy((char *)malloc(strlen(str)+1),str);

}

/* get queue of tokens in infix order from string buffer */ queue_infix = expr_to_infix(strbuffer); /* get queue of tokens in postfix order from infix-ordered queue */ queue_postfix = infix_to_postfix(&queue_infix);

/* get answer from postfix-ordered queue */

ans = evaluate_postfix(&queue_postfix); free(strbuffer); /* free memory from heap */ return ans;

/* constructs a queue of tokens in infix order from a space-delimited string */ default: /* not an operator */ type = OPERAND; value.operand = strtod(str, NULL); } https://www.programminghomeworkhelp.com/

} else { type = OPERAND; value.operand = strtod(str, NULL); } /* add token with parsed type and value to end of queue */ enqueue(&queue_infix, new_token(type, value)); } return queue_infix;

/* creates a queue of tokens in postfix order from a queue of tokens in infix order */

/* postcondition: returned queue contains all the tokens, and pqueue_infix should be empty */

struct token_queue infix_to_postfix(struct token_queue * pqueue_infix) {

/*TODO: construct postfix-ordered queue from infix-ordered queue; all tokens from infix queue should be added to postfix queue or freed */

struct token_queue expr_to_infix(char * str) { struct token_queue queue_infix; /* queue with infix ordering */ enum token_type type = OPERATOR; union token_value value;

https://www.programminghomeworkhelp.com/

}
}

/* initialize the queue to empty */

queue_infix.front = NULL; queue_infix.back = NULL; /* delimiter string for strtok() -- contains whitespace characters */

#define DELIMS_STR " \n\r\t" for (str = strtok(str, DELIMS_STR); str; str = strtok(NULL, DELIMS_STR)) { /* parse token */ if (strlen(str) == 1) { /* operators are all 1 character */ switch (str[0]) { case '+': type = OPERATOR;

value.op_code = ADD; break; case '-': /* check previous token to distinguish between negate (unary) and subtract (binary) */ if (type == OPERATOR)

value.op_code = NEGATE; /* unary */

#if PARSE_PARENS else if (type == LPARENS)

https://www.programminghomeworkhelp.com/

value.op_code = SUBTRACT; /* binary */ type = OPERATOR; break; case '*': type = OPERATOR;

value.op_code = MULTIPLY; break; case '/': type = OPERATOR;

value.op_code = DIVIDE; break;

#if PARSE_PARENS case '(': type = LPARENS; break; case ')': type = RPARENS; break;

https://www.programminghomeworkhelp.com/

#endif else
#endif

Question: Problem 2:

A useful data structure for doing lookups is a hash table. In this problem, you will be implementing a hash table with chaining to store the frequency of words in a file.The hash table is implemented as an array of linked lists.The hash function specifies the index of the linked list to follow for a given word. The word can be found by following this linked list. Optionally, the word can be appended to this linked list.You will require the code file ’hash.c’ and data file ’book.txt’ for this problem.You are required to do the following The function lookup() returns a pointer to the record having the required string. If not found it returns NULL or optionally creates a new record at the correct location. Please complete the rest of the code. Complete the function cleartable() to reclaim memory. Make sure each call to malloc() is matched with a free()

https://www.programminghomeworkhelp.com/

Problem 2 Overview

/* header files */

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <limits.h>

/* the trie node data structure */

struct s_trie_node

char * translation; /* NULL if node not a word */

/* pointer array to child nodes */

struct s_trie_node * children[UCHAR_MAX+1];

/* pointer to the root node of the trie structure */

static struct s_trie_node * proot = NULL;

/* helper functions for trie structure */

/* allocate new node on the heap

output: pointer to new node (must be freed) */

https://www.programminghomeworkhelp.com/

* prob2.c
{
};

struct s_trie_node * new_node(void);

/* delete node and all its children

input: pointer to node to delete postcondition: node and children are freed */

void delete_node(struct s_trie_node * pnode);

/* add word to trie, with translation input: word and translation output: non-zero if new node added, zero otherwise

postcondition: word exists in trie */

int add_word(const char * word, char * translation);

/* read dictionary file into trie structure */

unsigned int load_dictionary(const char * filename);

/* search trie structure for word and return translations input: word to search output: translation, or NULL if not found */

char * lookup_word(const char * word);

/* maximum number of characters for word to search */

https://www.programminghomeworkhelp.com/

#defineWORD_MAX 256

/* maximum number of characters in line */

#ifndef LINE_MAX

#define LINE_MAX 2048

#endif

/* main function */

int main(int argc, char * argv[]) { char word[WORD_MAX], * translation; int len; if (argc <= 1)

return 0; /* no dictionary specified */

/* load dictionary */ proot = new_node();

load_dictionary(argv[1]);

do { printf("Enter word to translate: "); fflush(stdout); if (!fgets(word,WORD_MAX, stdin)) abort();

https://www.programminghomeworkhelp.com/

/* strip trailing newline */ len = strlen(word); if (len > 0 && word[len-1] == '\n') { word[len-1] = '\0'; --len; } if (len == 0) break; /* lookup word */ translation = lookup_word(word); if (translation) printf("%s -> %s\n", word, translation); else printf("\"%s\" not found\n", word); } while (1); delete_node(proot); return 0;

https://www.programminghomeworkhelp.com/

}

struct s_trie_node * new_node(void) {

/*TODO: allocate a new node on the heap, and initialize all fields to default values */

/* delete node and all its children input: pointer to node to delete postcondition: node and children are freed */ void delete_node(struct s_trie_node * pnode) {

/*TODO: delete node and all its children

Be sure to free non-null translations! Hint: use recursion */

}

/* add word to trie, with translation input: word and translation output: non-zero if new node added, zero otherwise postcondition: word exists in trie */ int add_word(const char * word, char * translation) {

/*TODO: add word to trie structure If word exists, append translation to existing string

https://www.programminghomeworkhelp.com/

}

Be sure to store a copy of translation, since the string is reused by load_dictionary() */ } /* delimiter for dictionary */ #define DELIMS "\t"

/* read dictionary file into trie structure */ unsigned int load_dictionary(const char * filename) { FILE * pfile; char line[LINE_MAX], * word, * translation; unsigned int icount = 0; /* ensure file can be opened */ if ( !(pfile = fopen(filename,"r")) ) return icount; /* read lines */ while ( (fgets(line, LINE_MAX, pfile)) ) { /* strip trailing newline */ int len = strlen(line); ;

https://www.programminghomeworkhelp.com/

if (len > 0 && line[len-1] == '\n') { line[len-1] = '\0'; --len

if (len == 0 || line[0] == '#')

continue; /* ignore comment/empty lines */

/* separate word and translation */ word = line + strspn(line, DELIMS);

if ( !word[0] )

continue; /* no word in line */ translation = word + strcspn(word, DELIMS); *translation++ = '\0'; translation += strspn(translation, DELIMS);

/* add word to trie */

if (add_word(word, translation)) icount++;

/* finish */

https://www.programminghomeworkhelp.com/

}
}

Fclose(pfile); return icount;

/* search trie structure for word and return translations input: word to search output: translation, or NULL if not found */ char * lookup_word(const char * word) {

/*TODO: search trie structure for word return NULL if word is not found *

Conclusion

These sample solutions demonstrate our ability to tackle complex programming assignments effectively.At Programming Homework Help, we are committed to providing high-quality assistance tailored to your specific needs.Visit us at https://www.programminghomeworkhelp.com/ to learn more and get the help you need to succeed.

https://www.programminghomeworkhelp.com/

}
}

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.
Programming Assignment Samples by leo smith - Issuu