0% found this document useful (0 votes)
2 views12 pages

PF Assi Stuff PDF

The document contains multiple C programming assignments focusing on different functionalities such as reading student data, managing a menu system, and file operations. Key features include structures for student and menu items, functions for reading input, calculating grades and totals, and handling file I/O. Each assignment demonstrates the use of arrays, loops, and basic error handling in C.

Uploaded by

Timur Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views12 pages

PF Assi Stuff PDF

The document contains multiple C programming assignments focusing on different functionalities such as reading student data, managing a menu system, and file operations. Key features include structures for student and menu items, functions for reading input, calculating grades and totals, and handling file I/O. Each assignment demonstrates the use of arrays, loops, and basic error handling in C.

Uploaded by

Timur Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

PF assignment: 1)

#include <stdio.h> // For input/output


#include <string.h> // For string functions

// Define a smaller number of students for simplicity


#define NUM_STUDENTS 3
#define MAX_NAME_LEN 20 // Shorter name length

// Structure to hold student data


typedef struct {
char studentFName[MAX_NAME_LEN];
char studentLName[MAX_NAME_LEN];
int testScore;
char grade;
} studentType;

/**
* @brief Reads student names and scores into the array.
* @param students Array of studentType structures.
* @param size Number of students.
*/
void readStudentsData(studentType students[], int size) {
printf("--- Enter Student Data ---\n");
for (int i = 0; i < size; i++) {
printf("\nStudent %d:\n", i + 1);
printf("First Name: ");
scanf("%19s", students[i].studentFName); // Read with width limit
printf("Last Name: ");
scanf("%19s", students[i].studentLName);
int score;
do { // Validate score
printf("Score (0-100): ");
scanf("%d", &score);
if (score < 0 || score > 100) printf("Invalid score. Try again.\n");
} while (score < 0 || score > 100);
students[i].testScore = score;
}
}

/**
* @brief Assigns grades based on test scores.
* @param students Array of studentType structures.
* @param size Number of students.
*/
void assignGrades(studentType students[], int size) {
for (int i = 0; i < size; i++) {
if (students[i].testScore >= 90) students[i].grade = 'A';
else if (students[i].testScore >= 80) students[i].grade = 'B';
else if (students[i].testScore >= 70) students[i].grade = 'C';
else if (students[i].testScore >= 60) students[i].grade = 'D';
else students[i].grade = 'F';
}
}

/**
* @brief Finds the highest test score.
* @param students Array of studentType structures.
* @param size Number of students.
* @return The highest score.
*/
int findHighestScore(const studentType students[], int size) {
if (size <= 0) return -1;
int highestScore = students[0].testScore;
for (int i = 1; i < size; i++) {
if (students[i].testScore > highestScore) highestScore =
students[i].testScore;
}
return highestScore;
}

/**
* @brief Prints students with the highest score.
* @param students Array of studentType structures.
* @param size Number of students.
* @param highestScore The highest score to match.
*/
void printHighestScoreStudents(const studentType students[], int size, int
highestScore) {
printf("\n--- Highest Score Students (%d) ---\n", highestScore);
if (size == 0 || highestScore == -1) {
printf("No data.\n");
return;
}
for (int i = 0; i < size; i++) {
if (students[i].testScore == highestScore) {
printf("%-15s, %s\n", students[i].studentLName,
students[i].studentFName);
}
}
}

/**
* @brief Prints all student data (name, score, grade).
* @param students Array of studentType structures.
* @param size Number of students.
*/
void printStudentsData(const studentType students[], int size) {
printf("\n--- All Student Records ---\n");
printf("%-15s %-10s %s\n", "Name", "Score", "Grade");
printf("----------------------------------\n");
for (int i = 0; i < size; i++) {
printf("%-15s, %-4s %-10d %c\n",
students[i].studentLName, students[i].studentFName,
students[i].testScore, students[i].grade);
}
}

/**
* @brief Main function. Orchestrates program flow.
*/
int main() {
studentType classStudents[NUM_STUDENTS];
int highestTestScore;

readStudentsData(classStudents, NUM_STUDENTS);
assignGrades(classStudents, NUM_STUDENTS);
highestTestScore = findHighestScore(classStudents, NUM_STUDENTS);
printStudentsData(classStudents, NUM_STUDENTS);
printHighestScoreStudents(classStudents, NUM_STUDENTS, highestTestScore);

return 0;
}

Q.2)

#include <stdio.h> // For input/output


#include <string.h> // For string functions

#define MAX_MENU_ITEMS 8 // Total menu items


#define MAX_ITEM_NAME_LEN 20 // Shorter name length for output
#define TAX_RATE 0.05 // 5% tax

// Structure for a menu item


typedef struct {
char itemName[MAX_ITEM_NAME_LEN];
double itemPrice;
} menuItemType;

/**
* @brief Loads menu data.
*/
void getData(menuItemType menuList[], int size) {
// Initialize menu items and their prices
strcpy(menuList[0].itemName, "Plain Egg"); menuList[0].itemPrice = 1.45;
strcpy(menuList[1].itemName, "Bacon and Egg"); menuList[1].itemPrice = 2.45;
strcpy(menuList[2].itemName, "Muffin"); menuList[2].itemPrice = 0.99;
strcpy(menuList[3].itemName, "French Toast"); menuList[3].itemPrice = 1.99;
strcpy(menuList[4].itemName, "Fruit Basket"); menuList[4].itemPrice = 2.49;
strcpy(menuList[5].itemName, "Cereal"); menuList[5].itemPrice = 0.69;
strcpy(menuList[6].itemName, "Coffee"); menuList[6].itemPrice = 0.50;
strcpy(menuList[7].itemName, "Tea"); menuList[7].itemPrice = 0.75;
}

/**
* @brief Displays the menu.
*/
void showMenu(const menuItemType menuList[], int size) {
printf("\n--- Johnny's Breakfast Menu ---\n");
printf("%-3s %-20s %s\n", "No.", "Item", "Price");
for (int i = 0; i < size; i++) {
printf("%-3d %-20s $%.2f\n", i + 1, menuList[i].itemName,
menuList[i].itemPrice);
}
printf("Enter item number, 0 to finish.\n");
}

/**
* @brief Calculates and prints the bill.
*/
void printCheck(const menuItemType menuList[], int size) {
int selection;
double totalCost = 0.0;

printf("\nWelcome to Johnny's Restaurant\n");


printf("--- Your Order ---\n");

while (1) {
printf("Select item (1-%d, 0 to finish): ", size);
scanf("%d", &selection);

if (selection == 0) break;
if (selection > 0 && selection <= size) {
totalCost += menuList[selection - 1].itemPrice;
printf("%-20s $%.2f\n", menuList[selection - 1].itemName,
menuList[selection - 1].itemPrice);
} else {
printf("Invalid selection.\n");
}
}

double taxAmount = totalCost * TAX_RATE;


double amountDue = totalCost + taxAmount;

printf("\n--------------------\n");
printf("%-10s $%.2f\n", "Tax", taxAmount);
printf("%-10s $%.2f\n", "Amount Due", amountDue);
printf("--------------------\n");
printf("Thank you!\n");
}

/**
* @brief Main function.
*/
int main() {
menuItemType menuList[MAX_MENU_ITEMS];

getData(menuList, MAX_MENU_ITEMS);
showMenu(menuList, MAX_MENU_ITEMS);
printCheck(menuList, MAX_MENU_ITEMS);

return 0;
}

Q.3)

#include <stdio.h> // For input/output


#include <string.h> // For string functions

#define MAX_MENU_ITEMS 8 // Total menu items


#define MAX_ITEM_NAME_LEN 20 // Max item name length
#define TAX_RATE 0.05 // 5% tax
// Structure for a menu item
typedef struct {
char itemName[MAX_ITEM_NAME_LEN];
double itemPrice;
} menuItemType;

// Loads menu data.


void getData(menuItemType menuList[]) {
strcpy(menuList[0].itemName, "Plain Egg"); menuList[0].itemPrice = 1.45;
strcpy(menuList[1].itemName, "Bacon and Egg"); menuList[1].itemPrice = 2.45;
strcpy(menuList[2].itemName, "Muffin"); menuList[2].itemPrice = 0.99;
strcpy(menuList[3].itemName, "French Toast"); menuList[3].itemPrice = 1.99;
strcpy(menuList[4].itemName, "Fruit Basket"); menuList[4].itemPrice = 2.49;
strcpy(menuList[5].itemName, "Cereal"); menuList[5].itemPrice = 0.69;
strcpy(menuList[6].itemName, "Coffee"); menuList[6].itemPrice = 0.50;
strcpy(menuList[7].itemName, "Tea"); menuList[7].itemPrice = 0.75;
}

// Displays the menu.


void showMenu(const menuItemType menuList[]) {
printf("\n--- Johnny's Menu ---\n");
printf("%-3s %-15s %s\n", "No.", "Item", "Price");
for (int i = 0; i < MAX_MENU_ITEMS; i++) {
printf("%-3d %-15s $%.2f\n", i + 1, menuList[i].itemName,
menuList[i].itemPrice);
}
printf("Enter item # (0 to end):\n");
}

// Calculates and prints the bill.


void printCheck(const menuItemType menuList[]) {
int selection;
double totalCost = 0.0;

printf("\nWelcome to Johnny's Restaurant\n");


printf("--- Your Order ---\n");

while (1) {
printf("Select item: ");
scanf("%d", &selection);
if (selection == 0) break;
if (selection > 0 && selection <= MAX_MENU_ITEMS) {
totalCost += menuList[selection - 1].itemPrice;
printf("%-15s $%.2f\n", menuList[selection - 1].itemName,
menuList[selection - 1].itemPrice);
} else {
printf("Invalid selection.\n");
}
}

double taxAmount = totalCost * TAX_RATE;


double amountDue = totalCost + taxAmount;

printf("\n-------------------\n");
printf("%-10s $%.2f\n", "Tax", taxAmount);
printf("%-10s $%.2f\n", "Total", amountDue);
printf("-------------------\n");
printf("Thank you!\n");
}

// Main function.
int main() {
menuItemType menuList[MAX_MENU_ITEMS];

getData(menuList);
showMenu(menuList);
printCheck(menuList);

return 0;
}

Q.4)

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

#define MAX_ITEMS 8
#define NAME_LEN 15
#define TAX 0.05

typedef struct {
char name[NAME_LEN];
double price;
} MenuItem;

// Load menu data


void loadMenu(MenuItem menu[]) {
strcpy(menu[0].name, "Plain Egg"); menu[0].price = 1.45;
strcpy(menu[1].name, "Bacon and Egg"); menu[1].price = 2.45;
strcpy(menu[2].name, "Muffin"); menu[2].price = 0.99;
strcpy(menu[3].name, "French Toast"); menu[3].price = 1.99;
strcpy(menu[4].name, "Fruit Basket"); menu[4].price = 2.49;
strcpy(menu[5].name, "Cereal"); menu[5].price = 0.69;
strcpy(menu[6].name, "Coffee"); menu[6].price = 0.50;
strcpy(menu[7].name, "Tea"); menu[7].price = 0.75;
}

// Display menu
void displayMenu(const MenuItem menu[]) {
printf("\n--- Johnny's Menu ---\n");
for (int i = 0; i < MAX_ITEMS; i++) {
printf("%d. %-15s $%.2f\n", i + 1, menu[i].name, menu[i].price);
}
printf("Enter # (0 to end):\n");
}

// Process order and print bill


void printBill(const MenuItem menu[]) {
int sel;
double total = 0.0;

printf("\nWelcome to Johnny's Restaurant\n--- Your Order ---\n");


while (1) {
printf("Select item: ");
scanf("%d", &sel);
if (sel == 0) break;
if (sel > 0 && sel <= MAX_ITEMS) {
total += menu[sel - 1].price;
printf("%-15s $%.2f\n", menu[sel - 1].name, menu[sel - 1].price);
} else {
printf("Invalid selection.\n");
}
}

double tax = total * TAX;


double finalAmount = total + tax;

printf("\n-------------------\n");
printf("%-10s $%.2f\n", "Tax", tax);
printf("%-10s $%.2f\n", "Total", finalAmount);
printf("-------------------\nThank you!\n");
}

int main() {
MenuItem menu[MAX_ITEMS];
loadMenu(menu);
displayMenu(menu);
printBill(menu);
return 0;
}

Q.5)

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

#define MAX_LINES 100


#define MAX_LINE_LENGTH 256

// Reads lines from a file into a 2D char array.


// Returns the number of lines read, or -1 on error.
int readFileToArray(char lines[][MAX_LINE_LENGTH], int max_lines, int
max_line_len) {
char filename[MAX_LINE_LENGTH];
FILE *file_ptr;
int line_count = 0;

printf("Input the file name: ");


scanf("%s", filename);

file_ptr = fopen(filename, "r");


if (file_ptr == NULL) {
printf("Error: Cannot open file %s\n", filename);
return -1;
}

while (fgets(lines[line_count], max_line_len, file_ptr) != NULL && line_count


< max_lines) {
lines[line_count][strcspn(lines[line_count], "\n")] = 0; // Remove
newline
line_count++;
}

if (line_count >= max_lines) {


printf("Warning: Max lines (%d) reached.\n", max_lines);
}

fclose(file_ptr);
return line_count;
}

// Main function to run the program.


int main() {
char file_lines[MAX_LINES][MAX_LINE_LENGTH];
int num_lines_read = readFileToArray(file_lines, MAX_LINES, MAX_LINE_LENGTH);

if (num_lines_read != -1) {
printf("\nThe content of the file are:\n");
for (int i = 0; i < num_lines_read; i++) {
printf("%s\n", file_lines[i]);
}
}

return EXIT_SUCCESS;
}

Q.6)

#include <stdio.h> // For file I/O (fopen, fgetc, fclose, printf)


#include <stdlib.h> // For EXIT_SUCCESS, EXIT_FAILURE
#include <ctype.h> // For isspace function

// Main function to count words and characters in a file.


int main() {
char filename[100]; // Buffer for the filename
FILE *file_ptr; // File pointer
int character_count = 0; // Counter for total characters
int word_count = 0; // Counter for total words
int c; // Variable to hold each character read from file
int in_word = 0; // Flag to track if currently inside a word (1 =
yes, 0 = no)

printf("Count the number of words and characters in a file:\n");


printf("---------------------------------------------------------\n");
printf("Input the filename to be opened: ");
scanf("%99s", filename); // Read filename, limit to 99 chars + null
terminator

// Attempt to open the file in read mode


file_ptr = fopen(filename, "r");

// Check if the file was opened successfully


if (file_ptr == NULL) {
printf("Error: Could not open file '%s'\n", filename);
return EXIT_FAILURE; // Indicate an error
}

printf("The content of the file %s are:\n", filename);

// Read characters one by one until End-Of-File (EOF) is reached


while ((c = fgetc(file_ptr)) != EOF) {
printf("%c", c); // Print the character to display file content

character_count++; // Increment total character count

// Logic to count words:


// If the character is not a whitespace and we were not previously in a
word,
// it means a new word has started.
if (!isspace(c)) {
if (in_word == 0) {
word_count++; // Increment word count
in_word = 1; // Set flag to indicate we are now inside a word
}
} else {
// If the character is a whitespace, reset the 'in_word' flag
in_word = 0;
}
}

fclose(file_ptr); // Close the file

// Print the results


printf("\nThe number of words in the file %s are: %d\n", filename,
word_count);
printf("The number of characters in the file %s are: %d\n", filename,
character_count);

return EXIT_SUCCESS; // Indicate successful execution


}

Q.7)

#include <stdio.h> // For file I/O


#include <string.h> // For string manipulation

#define MAX_LINE_LEN 256 // Max length of a line


// Appends multiple lines to a file.
void appendLinesToFile() {
char filename[100];
FILE *fp;
int num_lines;
char line_buffer[MAX_LINE_LEN];

printf("File name to open: ");


scanf("%99s", filename);
while (getchar() != '\n'); // Consume newline

printf("Number of lines to write: ");


scanf("%d", &num_lines);
while (getchar() != '\n'); // Consume newline

fp = fopen(filename, "a"); // Open in append mode


if (fp == NULL) {
printf("Error: Could not open '%s'.\n", filename);
return;
}

printf("Enter lines:\n");
for (int i = 0; i < num_lines; i++) {
if (fgets(line_buffer, MAX_LINE_LEN, stdin) != NULL) {
line_buffer[strcspn(line_buffer, "\n")] = 0; // Remove trailing
newline
fprintf(fp, "%s\n", line_buffer); // Write line to file
} else {
printf("Error reading line %d.\n", i + 1);
break;
}
}

fclose(fp);
printf("Successfully appended %d lines to '%s'.\n", num_lines, filename);
}

int main() {
appendLinesToFile();
return 0; // Success
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy