Question

In: Computer Science

Description CSCI 1151, Fall 2019 Programming Assignment 5 – Structure Construct an array of a structure...

Description

CSCI 1151, Fall 2019 Programming Assignment 5 – Structure

Construct an array of a structure to store the information of vehicles. This structure should consist of: an integer for the vehicle identification number (ID); an integer for the mile driven; an integer for the number of gallons used by the vehicle; and a string for the vehicle’s manufacture. Write a C program that get (input) the information of the vehicles from a file, cardb.txt, one structure per vehicle.

Your program should sort the vehicles by their identification numbers (ID) in ascending order. Prompt the user to enter the vehicle ID number and apply binary search for the vehicle. Output the information of the vehicle on the console, if the vehicle is not found then output “Vehicle not found”. Assume the maximum number of vehicles is 100 which means you need to allocate an array of size 100 of the structure you declared. You may use dynamic memory allocation to get exact memory size. There will be an extra 20 points if you use dynamic memory allocation.

Input

File name: cardb.txt

Output

  1. 1) You need to have at least two functions, sort() and search(), in your program. You may implement any sorting algorithm for your sort() function to sort the vehicles, you have to implement the binary search algorithm for your search() function for searching vehicles, the search key is the vehicle ID number.

  2. 2) To test your sorting, you should output the vehicle information on the console (refer to the sample output example).

  3. 3) A while loop continue prompt user for the vehicle ID number and output the information of the searched vehicle on the console. If not find, then output “Vehicle not found”. After receive a negative vehicle ID number from the user, the while loop will be terminated.

Format of the Input File

Up to 100 records, one per vehicle, a new line between two adjacent records
Four fields (columns) per records (line): vehicle ID number, Miles Driven, Gallons of Gas used, Vehicle Manufactural. A blank (space) between adjacent fields. Refer to the attached file cardb.txt

Specifications:

  •  The name of the source code file must be exactly Lab05.c.

  •  Comments at the top with your name, e-mail, date and the course you are taking.

  •  Submit your program to Blackboard.

  •  Read the syllabus for the late policy.

I will test your program as following example: the submitted program name is Lab05.c

  gcc –o Lab05 Lab05.c
  Lab05 cardb.txt

Sample output example:

Following are the information of all vehicles:
Vehicle ID #   Miles Driven   Gallons Used  Manufacture
============   ============   ============  ===========

25 1450 62 Ford   

36 3240 136 Chrysler

..........

4753 850 0 Tesla

Please enter the vehicle ID number: 25 <Enter>
1,450 Miles Driven 62 Gallons Used Manufactured by Ford

Please enter the vehicle ID number: 80 <Enter> Vehicle not found

Please enter the vehicle ID number: -1 <Enter> Good Bye!

25 1450 62 Ford
36 3240 136 Chrysler
44 1792 76 Audi
52 2360 105 Chevrolet
68 2144 67 BMW
2365 20 2 Ford
2103 105 3 Volkswagon
4753 850 0 Tesla
1499 425 14 Chevrolet
3278 378 21 Ford

Solutions

Expert Solution

I have implemented the complete c program which has following:

  • struct vehicle : store the info about vehicles
  • sort function: i have used selection sort, you may use any other
  • search function : search the vehicle using binary search method
  • main function: copy the contents from the file into struct array, sort the array, while loop for user input etc

Also, i have used dynamic memory allocation for structure array as mentioned in the question.

Note: You may check the screenshot of the code to have better understanding of the indentation.

Here is the my text file, you may add more entries.

C code:

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

//declare struct
struct vehicle{
int id;
int miles;
int gallons;
char manufacturer[20];
};

//sort function
void selectionSort(struct vehicle arr[], int n)
{
int i, j, min_idx;
struct vehicle temp;
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j].id < arr[min_idx].id)
min_idx = j;

// Swap the found minimum element with the first element
temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}

//search function
struct vehicle searchVehicle(struct vehicle arr[], int l, int r, int x)
{
while (l <= r) {
int m = l + (r - l) / 2;

// Check if x is present at mid
if (arr[m].id == x)
return arr[m];

// If x greater, ignore left half
if (arr[m].id < x)
l = m + 1;

// If x is smaller, ignore right half
else
r = m - 1;
}

// if we reach here, then element was
// not present
struct vehicle v = {-1,-1,-1,""};
return v;
}

//main function
int main()
{
int maxSize = 100,i;
int n=0; //number of records
struct vehicle *details;
//create file object to open the input file
FILE* infile = fopen("cardb.txt","rb"); //read mode

//check if file exists
if(!infile)
{
printf("File does not exists.\n");
return 0;
}

//create array using dynamic memory allocation of size 100
details = (struct vehicle*) malloc (maxSize * sizeof(struct vehicle));

if(details == NULL)
{
printf("Memory not allocated.\n");
exit(0);
}

char line[100]; //read individual lines from the file

//take entries from file and fill in details array
while(fgets(line,100,infile) != NULL)
{
//temporary variables to copy from the string of file
char idTemp[9];
char milesTemp[9];
char gallonsTemp[9];
char manTemp[20];
int j;

int i=0;
while(isspace(line[i])){ //skip empty spaces
i++;
}
j=0;
while(!isspace(line[i])) //copy id
{
idTemp[j++] = line[i++];
}
idTemp[j] = '\0';
while(isspace(line[i])){ //skip empty spaces
i++;
}
j=0;
while(!isspace(line[i])) //copy miles
{
milesTemp[j++] = line[i++];
}
milesTemp[j] = '\0';
while(isspace(line[i])){ //skip empty spaces
i++;
}
j=0;
while(!isspace(line[i])) //copy gallons
{
gallonsTemp[j++] = line[i++];
}
gallonsTemp[j] = '\0';
while(isspace(line[i])){ //skip empty spaces
i++;
}
j=0;
while(line[i] != '\n') //copy manufacturer name
{
manTemp[j++] = line[i++];
}
manTemp[j] = '\0';

//enter these details in structure details
//first convert string to int then put in structure
sscanf(idTemp, "%d",&details[n].id);
sscanf(milesTemp,"%d",&details[n].miles);
sscanf(gallonsTemp,"%d",&details[n].gallons);
strcpy(details[n].manufacturer,manTemp); //copy string
n++; //increment number of entries
}

//sort the entries
selectionSort(details, n);

//print sorted vehicle details
printf("Sorted vehicles: \n");
i=0;
while(i<n)
{
printf("%d %d %d %s\n",details[i].id,details[i].miles,
details[i].gallons,details[i].manufacturer);
i++;
}

//while loop for user to search vehicles
int x; //id from user
while(1)
{
printf("Please enter the vehicle ID number: ");
scanf("%d",&x); //read input

if(x < 0){ //negative input- break
printf("Good Bye!\n");
break;
}
struct vehicle found = searchVehicle(details,0,n-1,x);
if(found.id == -1) //not found
{
printf("Vehicle not found\n");
}
else //found
{
printf("%d Miles Driven %d Gallons Used Manufactured by %s\n",
found.miles,found.gallons,found.manufacturer);
}
}

//close the file
fclose(infile);

return 0;
}
Output:

Screenshot of code:

I hope you find the answer helpful :)


Related Solutions

CS 238 – Assembly Language Programming Fall 2019 Assignment 1 (Due: September 10, 2019) Submission Instructions:...
CS 238 – Assembly Language Programming Fall 2019 Assignment 1 (Due: September 10, 2019) Submission Instructions: Online submissions on Blackboard are preferred. Feel free to edit this Word document to insert your answers. Multiple online submissions on Blackboard are allowed, but only the last online submission made by the midnight of September 10 will be graded. Alternatively, a paper submission is possible, but it needs to be done in class on September 10. 1. Data can be interpreted as required...
The purpose of this C++ programming assignment is to practice using an array. This problem is...
The purpose of this C++ programming assignment is to practice using an array. This problem is selected from the online contest problem archive, which is used mostly by college students worldwide to challenge their programming ability and to prepare themselves for attending programming contests such as the prestige ACM International Collegiate Programming Contest. For your convenience, I copied the description of the problem below with my note on the I/O and a sample executable. Background The world-known gangster Vito Deadstone...
Programming Language: JAVA In this assignment you will be sorting an array of numbers using the...
Programming Language: JAVA In this assignment you will be sorting an array of numbers using the bubble sort algorithm. You must be able to sort both integers and doubles, and to do this you must overload a method. Bubble sort work by repeatedly going over the array, and when 2 numbers are found to be out of order, you swap those two numbers. This can be done by looping until there are no more swaps being made, or using a...
Explain the difference between array and structure based on their usage in C++ programming. Declare a...
Explain the difference between array and structure based on their usage in C++ programming. Declare a structure called studentScore which contains name of student, registration number of students, course code and marks. Declare structure variable named studentCS680 based on the structure in (b) to store fifty (50) students’ data. Write a program that prompts a user to enter data for 50 students in a structure variable declared in (b) and calculate the average mark.
Assignment Description This assignment focuses on programming basics; expressions, variables, constants, methods, selection and loops. Danny...
Assignment Description This assignment focuses on programming basics; expressions, variables, constants, methods, selection and loops. Danny runs an ice cream shop in the inner suburbs of Melbourne. Due to the growing number of customers, Danny has decided to take on extra casual employees. In order to manage payroll for his employees, Danny has decided to develop an employee payroll management system. Details of each employee to be maintained in the system will include; employee id, name, gender (M or F),...
Programming Project – Deques, Stacks & Queues General Description: Design and develop array based and linked...
Programming Project – Deques, Stacks & Queues General Description: Design and develop array based and linked list-based implementations for the Dequeue ADT. Your implementation must support generic data types using C++ templates. Develop Adapter Files to provide Stack and Queue functionality for the Deques. Definitions: You should implement the ADTs precisely as described in the following partial header files. Deque.h template class Deque { public:         Deque();                    //constructor         ~Deque();                 //destructor         void insertFront(const E& e);...
C++ Programming Enum - Structure - Array You are asked to develop software for HR department...
C++ Programming Enum - Structure - Array You are asked to develop software for HR department to calculate employee’s weekly salary. The program should contain the following information about a student by declaring a struct: Name (string of characters)        Employee ID (string of characters)        Level (ENGINEER, MANGER, DIRECTOR)        Hourly Rate (floating-point number)        Working Hours (floating-point number)        Weekly Salary (floating-point number) Your program will read an employee data and print the information of employee’s Name, Employee...
CSE/EEE 230 Assignment 4 Fall 2019 Due Sept 30 (11:59PM) In this assignment, you are to...
CSE/EEE 230 Assignment 4 Fall 2019 Due Sept 30 (11:59PM) In this assignment, you are to complete a MIPS program so it will perform the required tasks. The main function of the code is provided. Do not change the code in the main function. There is a loop in the main function. You are to complete the program by writing two functions. Pay particular attention to the purpose of each function and how the parameters and return value are to...
Description: In this assignment, you will implement a deterministic finite automata (DFA) using C++ programming language...
Description: In this assignment, you will implement a deterministic finite automata (DFA) using C++ programming language to extract all matching patterns (substrings) from a given input DNA sequence string. The alphabet for generating DNA sequences is {A, T, G, C}. Write a regular expression that represents all DNA strings that begin with ‘A’ and end with ‘T’. Note: assume empty string is not a valid string. Design a deterministic finite automaton to recognize the regular expression. Write a program which...
COMP1805AB (Fall 2019)  "Discrete Structures I" Specification for Assignment 1 of 4 Please ensure that...
COMP1805AB (Fall 2019)  "Discrete Structures I" Specification for Assignment 1 of 4 Please ensure that you include your name and student number on your submission. Your submission must be created using Microsoft Word, Google Docs, or LaTeX. Translate the following English expressions into logical statements. You must explicitly state what the atomic propositions are (e.g., "Let p be proposition ...") and then show their logical relation. If it is red then it is not blue and it is not...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT