Commit 557906b3 by emonyi

Upload New File

parent 03aa1e6d
Showing with 103 additions and 0 deletions
/*
* File: homework2.c
* Author:
*
* Created on November 24, 2018, 9:06 PM
* Description: To pass
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
// Function that gets data from user and write to destinations array
void getData(int w, int h, int destinations[][w]);
// Print the destinations matrix to stdout
void printMatrix(int w, int h, int destinations[][w]);
// Get the total flights and return an array of total
int* getTotal(int w, int h, int destinations[][w]);
// Find the busiest flight based on total array
void findBusiest(int, int*);
int main() {
int w, h;
// Check if the user's input is acceptable
do {
printf("Please input array dimension HxW (eg. 3x4): ");
scanf("%dx%d", &h, &w);
if (w > 15 || w <= 0 || h > 15 || h <= 0)
puts("width and height can only be in between 1 and 15");
} while (w > 15 || w <= 0 || h > 15 || h <= 0);
int destinations[h][w];
// Get user input data
getData(w, h, destinations);
printMatrix(w, h, destinations);
int* total = getTotal(w, h, destinations);
printf(" TOTAL");
for (int i = 0; i < w; i++) {
printf("%4d", total[i]);
}
findBusiest(w, total);
free(total);
return 0;
}
void getData(int w, int h, int destinations[][w]) {
printf("Please input destinations: (eg. 2 3 4 5)\n");
for (int j = 0; j < h; j++) {
printf("Please input DESTINATION%.2d: ", j + 1);
char buffer[50];
// Scanf for the whole string that ends with \n
scanf(" %[^\n]", buffer);
// Get data from the string based on " "
destinations[j][0] = atoi(strtok(buffer, " "));
for (int i = 1; i < w; i++) {
destinations[j][i] = atoi(strtok(NULL, " "));
}
}
}
void printMatrix(int w, int h, int destinations[][w]) {
puts("Flights");
printf(" ");
for (int i = 0; i < w; i++) {
printf("C%.2d ", i + 1);
}
printf("\n");
for (int j = 0; j < h; j++) {
printf("DESTINATION%.2d", j + 1);
for (int i = 0; i < w; i++) {
printf("%4d", destinations[j][i]);
}
printf("\n");
}
}
int* getTotal(int w, int h, int destinations[][w]) {
int* total = calloc(w, sizeof(int));
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
// Add all the column together
total[i] += destinations[j][i];
}
}
return total;
}
void findBusiest(int w, int* total) {
int highest = -1;
int id;
for (int i = 0; i < w; i++) {
if (total[i] > highest) {
highest = total[i];
id = i + 1;
}
}
printf("\nMost frequent flight: C%.2d\n", id);
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment