diff --git a/LEARNING_RESOURCES.md b/LEARNING_RESOURCES.md new file mode 100644 index 0000000..eace339 --- /dev/null +++ b/LEARNING_RESOURCES.md @@ -0,0 +1,40 @@ +# C Learning Resources on GitHub (as of September 2025) + +This page lists useful GitHub repositories for learning and practicing C programming. +Each resource includes a description and a suggested difficulty level. + +--- + +## Repository Table + +| Repository | Description | Difficulty | +|------------|-------------|------------| +| [CodeWithHarry / The-Ultimate-C-Programming-Course](https://github.com/CodeWithHarry/The-Ultimate-C-Programming-Course) | A structured course with chapters, practice sets, and project code. Good for beginners who want guided progression. | Beginner | +| [nCally / Project-Based-Tutorials-in-C](https://github.com/nCally/Project-Based-Tutorials-in-C) | A collection of tutorials building projects in C (from small programs to advanced topics like emulators and OS concepts). | Intermediate → Advanced | +| [sbccas / c-programming-tutorials](https://github.com/sbccas/c-programming-tutorials) | Tutorials, assignments, and sample programs covering basics and intermediate C programming concepts. | Beginner → Intermediate | +| [h0mbre / Learning-C](https://github.com/h0mbre/Learning-C) | A repository of small programs and exercises created while learning C. Shows practical learning progress. | Beginner | +| [mcinglis / c-style](https://github.com/mcinglis/c-style) | A C style guide with best practices for readability, maintainability, and consistent coding. | All Levels | +| [ShravanDalavi / CProgrammingProjects](https://github.com/ShravanDalavi/CProgrammingProjects) | A set of projects and algorithmic exercises implemented in C. Useful for practice and inspiration. | Intermediate | + +--- + +## Suggested Learning Path + +1. **Start Here (Beginner):** + - [CodeWithHarry / The-Ultimate-C-Programming-Course](https://github.com/CodeWithHarry/The-Ultimate-C-Programming-Course) + - [h0mbre / Learning-C](https://github.com/h0mbre/Learning-C) + +2. **Next Steps (Beginner → Intermediate):** + - [sbccas / c-programming-tutorials](https://github.com/sbccas/c-programming-tutorials) + - Practice writing small programs and algorithms. + +3. **Level Up (Intermediate → Advanced):** + - [nCally / Project-Based-Tutorials-in-C](https://github.com/nCally/Project-Based-Tutorials-in-C) + - [ShravanDalavi / CProgrammingProjects](https://github.com/ShravanDalavi/CProgrammingProjects) + +4. **Always Useful:** + - [mcinglis / c-style](https://github.com/mcinglis/c-style) – Follow this style guide throughout your learning. + +--- + +💡 **Tip:** Don’t just read the code — clone the repositories, compile, run, and try modifying the programs yourself! diff --git a/Makefile b/Makefile index c1afeec..c1b3192 100644 --- a/Makefile +++ b/Makefile @@ -1,15 +1,22 @@ - -# Simple Makefile for Lab 1 +# Simple Makefile for Lab 1, Lab 2, Lab 3, Lab 4 CC = gcc CFLAGS = -std=c11 -Wall -Wextra -Wpedantic -O2 -LDFLAGS = +LDFLAGS = -lm BUILD_DIR = bin SRC_DIR = src -PROGRAMS = $(BUILD_DIR)/hello $(BUILD_DIR)/calculator $(BUILD_DIR)/formats +PROGRAMS = $(BUILD_DIR)/hello $(BUILD_DIR)/calculator $(BUILD_DIR)/formats \ + $(BUILD_DIR)/lab2_1 $(BUILD_DIR)/lab2_2 $(BUILD_DIR)/lab2_3 \ + $(BUILD_DIR)/lab3_task1 $(BUILD_DIR)/lab3_task2 $(BUILD_DIR)/lab3_task3 \ + $(BUILD_DIR)/week4_1_dynamic_array $(BUILD_DIR)/week4_2_struct_student $(BUILD_DIR)/week4_3_struct_database all: $(PROGRAMS) +# ----------------------- +# Lab 1 +# ----------------------- +lab1: $(BUILD_DIR)/hello $(BUILD_DIR)/calculator $(BUILD_DIR)/formats + $(BUILD_DIR)/hello: $(SRC_DIR)/hello.c @mkdir -p $(BUILD_DIR) $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS) @@ -22,18 +29,158 @@ $(BUILD_DIR)/formats: $(SRC_DIR)/format_specifiers.c @mkdir -p $(BUILD_DIR) $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS) -hello: $(BUILD_DIR)/hello -calculator: $(BUILD_DIR)/calculator -formats: $(BUILD_DIR)/formats +# ----------------------- +# Lab 2 +# ----------------------- +lab2: $(BUILD_DIR)/lab2_1 $(BUILD_DIR)/lab2_2 $(BUILD_DIR)/lab2_3 + +$(BUILD_DIR)/lab2_1: $(SRC_DIR)/lab2_1.c + @mkdir -p $(BUILD_DIR) + $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS) + +$(BUILD_DIR)/lab2_2: $(SRC_DIR)/lab2_2.c + @mkdir -p $(BUILD_DIR) + $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS) + +$(BUILD_DIR)/lab2_3: $(SRC_DIR)/lab2_3.c + @mkdir -p $(BUILD_DIR) + $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS) + +# ----------------------- +# Lab 3 +# ----------------------- +lab3: $(BUILD_DIR)/lab3_task1 $(BUILD_DIR)/lab3_task2 $(BUILD_DIR)/lab3_task3 + +$(BUILD_DIR)/lab3_task1: $(SRC_DIR)/lab3_task1.c + @mkdir -p $(BUILD_DIR) + $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS) + +$(BUILD_DIR)/lab3_task2: $(SRC_DIR)/lab3_task2.c + @mkdir -p $(BUILD_DIR) + $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS) + +$(BUILD_DIR)/lab3_task3: $(SRC_DIR)/lab3_task3.c + @mkdir -p $(BUILD_DIR) + $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS) + +# ----------------------- +# Lab 4 +# ----------------------- +lab4: $(BUILD_DIR)/week4_1_dynamic_array $(BUILD_DIR)/week4_2_struct_student $(BUILD_DIR)/week4_3_struct_database + +$(BUILD_DIR)/week4_1_dynamic_array: $(SRC_DIR)/week4_1_dynamic_array.c + @mkdir -p $(BUILD_DIR) + $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS) -run-hello: hello +$(BUILD_DIR)/week4_2_struct_student: $(SRC_DIR)/week4_2_struct_student.c + @mkdir -p $(BUILD_DIR) + $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS) + +$(BUILD_DIR)/week4_3_struct_database: $(SRC_DIR)/week4_3_struct_database.c + @mkdir -p $(BUILD_DIR) + $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS) + +# ----------------------- +# Run targets +# ----------------------- +run-hello: $(BUILD_DIR)/hello ./$(BUILD_DIR)/hello -run-calculator: calculator +run-calculator: $(BUILD_DIR)/calculator ./$(BUILD_DIR)/calculator -run-formats: formats +run-formats: $(BUILD_DIR)/formats + ./$(BUILD_DIR)/formats + +run-lab2_1: $(BUILD_DIR)/lab2_1 + ./$(BUILD_DIR)/lab2_1 + +run-lab2_2: $(BUILD_DIR)/lab2_2 + ./$(BUILD_DIR)/lab2_2 + +run-lab2_3: $(BUILD_DIR)/lab2_3 + ./$(BUILD_DIR)/lab2_3 + +run-lab3_task1: $(BUILD_DIR)/lab3_task1 + ./$(BUILD_DIR)/lab3_task1 + +run-lab3_task2: $(BUILD_DIR)/lab3_task2 + ./$(BUILD_DIR)/lab3_task2 + +run-lab3_task3: $(BUILD_DIR)/lab3_task3 + ./$(BUILD_DIR)/lab3_task3 + +run-week4_1_dynamic_array: $(BUILD_DIR)/week4_1_dynamic_array + ./$(BUILD_DIR)/week4_1_dynamic_array + +run-week4_2_struct_student: $(BUILD_DIR)/week4_2_struct_student + ./$(BUILD_DIR)/week4_2_struct_student + +run-week4_3_struct_database: $(BUILD_DIR)/week4_3_struct_database + ./$(BUILD_DIR)/week4_3_struct_database + +# Run all tasks in Lab 2 +run-lab2: lab2 + ./$(BUILD_DIR)/lab2_1 + ./$(BUILD_DIR)/lab2_2 + ./$(BUILD_DIR)/lab2_3 + +# Run all tasks in Lab 3 +run-lab3: lab3 + ./$(BUILD_DIR)/lab3_task1 + ./$(BUILD_DIR)/lab3_task2 + ./$(BUILD_DIR)/lab3_task3 + +# Run all tasks in Lab 4 +run-lab4: lab4 + ./$(BUILD_DIR)/week4_1_dynamic_array + ./$(BUILD_DIR)/week4_2_struct_student + ./$(BUILD_DIR)/week4_3_struct_database + +# Run all labs (Lab 1 → Lab 4) +run-all: all + ./$(BUILD_DIR)/hello + ./$(BUILD_DIR)/calculator ./$(BUILD_DIR)/formats + ./$(BUILD_DIR)/lab2_1 + ./$(BUILD_DIR)/lab2_2 + ./$(BUILD_DIR)/lab2_3 + ./$(BUILD_DIR)/lab3_task1 + ./$(BUILD_DIR)/lab3_task2 + ./$(BUILD_DIR)/lab3_task3 + ./$(BUILD_DIR)/week4_1_dynamic_array + ./$(BUILD_DIR)/week4_2_struct_student + ./$(BUILD_DIR)/week4_3_struct_database + +# ----------------------- +# Debug build +# ----------------------- +debug: + $(MAKE) clean + $(MAKE) CFLAGS="-std=c11 -Wall -Wextra -Wpedantic -g" all + +# ----------------------- +# Help +# ----------------------- +help: + @echo "Available make targets:" + @echo " make all - Build all labs (1–4)" + @echo " make lab1 - Build Lab 1 programs" + @echo " make lab2 - Build Lab 2 programs" + @echo " make lab3 - Build Lab 3 programs" + @echo " make lab4 - Build Lab 4 programs" + @echo " make run-hello - Run Lab 1 hello program" + @echo " make run-calculator - Run Lab 1 calculator" + @echo " make run-formats - Run Lab 1 format specifiers" + @echo " make run-lab2 - Run all Lab 2 programs" + @echo " make run-lab3 - Run all Lab 3 programs" + @echo " make run-lab4 - Run all Lab 4 programs" + @echo " make run-all - Run all labs (1–4)" + @echo " make debug - Rebuild all with debugging (-g)" + @echo " make clean - Remove build artifacts" +# ----------------------- +# Cleanup +# ----------------------- clean: rm -rf $(BUILD_DIR)/*.o $(PROGRAMS) diff --git a/README.md b/README.md index a97e1fa..1cf43e6 100644 --- a/README.md +++ b/README.md @@ -1,120 +1,107 @@ -# Lab 1 — C Basics (Week 1) - -**Goals** -- Set up a working C toolchain (GitHub Codespaces *or* local Linux with GCC + VS Code). -- Write, compile, and run simple C programs. -- Practice `printf` / `scanf` format specifiers. - -## Repository Layout -``` -Lab01_C_Basics/ -├─ src/ -│ ├─ hello.c -│ ├─ calculator.c -│ └─ format_specifiers.c -├─ include/ -├─ bin/ # compiled binaries land here -├─ .vscode/ # VS Code tasks & debug config -├─ .devcontainer/ # one-click Codespaces -├─ Makefile -├─ .gitignore -├─ LICENSE (MIT) -└─ README.md -``` +# 📘 C Programming – 5-Week Course Syllabus + +This 5-week course introduces core concepts of the C programming language. +It is designed for **second-year Computer Science students** who already know Java and/or C++ and will continue with Python afterward. +Each week consists of one **lecture** (2×45 min) and one **lab** (2×45 min). --- -## Option A — Run in **GitHub Codespaces** (recommended) +## 📅 Weekly Overview -1. Push this repo to GitHub and click **Code → Codespaces → Create codespace on main**. -2. The provided **devcontainer** will provision a C/C++ environment (GCC, GDB, Make). -3. Open the **Terminal** in VS Code (inside Codespaces) and run: +| **Week** | **Topic** | **Focus Keywords** | +|-----------|------------|--------------------| +| **1** | Introduction & C Basics | setup, syntax, compilation, printf/scanf | +| **2** | Control Flow & Functions | branching, loops, functions | +| **3** | Arrays, Strings & Pointers | arrays, strings, pointers | +| **4** | Dynamic Memory & Structures | malloc, struct, typedef, union | +| **5** | Files & Modular Programming | file I/O, preprocessor, headers, modularity | -```bash -make # builds all targets -./bin/hello -./bin/calculator -./bin/formats -``` +--- -Or use the pre-configured **VS Code Tasks**: -- **Build All (Make)** — builds all targets -- **Run: Hello** — builds and runs `hello` -- **Run: Calculator** — builds and runs `calculator` -- **Run: Formats** — builds and runs `formats` +## Week 1 – Introduction & C Basics +**Lecture** +- History and role of C (systems, embedded, portability) +- Program structure (`#include`, `main`, standard library) +- Compilation process (source → preprocessor → compiler → linker → executable) +- Data types (`int`, `char`, `float`, `double`), variables, and constants +- Input/output using `printf` and `scanf` -Debugging: -- Put a breakpoint in `src/hello.c` -- Run **Start Debugging (Hello)** from the Run/Debug panel +**Lab** +- Set up environment (GitHub Codespaces / VS Code + GCC) +- Write, compile, and run “Hello, World” +- Simple arithmetic calculator +- Explore `printf` / `scanf` format specifiers --- -## Option B — Run locally on Linux (or WSL) +## Week 2 – Control Flow & Functions +**Lecture** +- Operators and precedence +- Conditional statements (`if`, `else`, `switch`) +- Loops (`for`, `while`, `do…while`) +- Functions: prototypes, parameters, return types, scope (`auto`, `static`) +- Comparing Java methods vs C functions -1. Install build tools: - ```bash - sudo apt update && sudo apt install -y build-essential gdb - ``` -2. Build with `make`: - ```bash - make - ./bin/hello - ./bin/calculator - ./bin/formats - ``` +**Lab** +- Write branching and looping programs +- Create functions (factorial, prime test, calculator) +- Trace program flow and debug using print statements --- -## Targets (via `make`) -- `make` or `make all` — build all programs -- `make hello` — build Hello, World -- `make calculator` — build calculator -- `make formats` — build format specifier demo -- `make clean` — remove build artifacts - ---- +## Week 3 – Arrays, Strings & Pointers (Introduction) +**Lecture** +- One-dimensional and multidimensional arrays +- Strings as character arrays and null termination +- Introduction to pointers: addresses, dereferencing, pointer–array relationship +- Function arguments by value vs by pointer -## Programs +**Lab** +- Implement manual string functions (`strlen`, `strcpy`) +- Work with numeric arrays (min, max, average) +- Pass pointers to functions (swap two values) -### 1) `hello.c` -- Prints a greeting and shows command-line arguments (if any). +--- -### 2) `calculator.c` -- Simple arithmetic calculator (sum, difference, product, quotient). -- Demonstrates input validation and division-by-zero handling. +## Week 4 – Advanced Pointers, Dynamic Memory & Structures +**Lecture** +- Pointer arithmetic and pointer to pointer +- Dynamic memory allocation (`malloc`, `calloc`, `realloc`, `free`) +- `struct` definitions and field access +- `typedef`, `union`, and `enum` -### 3) `format_specifiers.c` -- Demonstrates key `printf`/`scanf` format specifiers: - - Integers: `%d`, `%u`, `%x`, `%o` - - Characters: `%c` - - Floats: `%f`, `%e`, precision like `%.2f` - - Strings: `%s` (single word), `fgets` for full line input - - Field width & alignment basics +**Lab** +- Create dynamic arrays with `malloc` +- Define and use a `struct` (e.g., Student record) +- Build a small in-memory database (array of structs) --- -## Sample Commands - -```bash -# Build everything -make +## Week 5 – Files, Preprocessor & Modular Programming +**Lecture** +- File I/O (`fopen`, `fprintf`, `fscanf`, `fread`, `fwrite`) +- Preprocessor directives (`#include`, `#define`, conditional compilation) +- Separate compilation and header files +- Debugging and best practices -# Run Hello (with arguments) -./bin/hello Alice 42 +**Lab** +- Read/write data from files +- Save and load structured records +- Split program into multiple source and header files +- Mini-project: Student management system with file persistence -# Run Calculator -./bin/calculator +--- -# Run Format Specifiers demo -./bin/formats -``` +## Course Outcomes +By the end of the course, students will be able to: ---- +- Write, compile, and debug C programs in a Linux/GCC environment +- Apply control flow, functions, arrays, strings, and pointers effectively +- Manage dynamic memory and create composite data types using `struct` +- Work with text and binary files +- Organize programs into multiple source files with headers +- Understand how C differs from Java and how it connects to Python +- Demonstrate foundational skills for later systems and software courses -## Notes on `scanf` -- `scanf("%d", &x)` reads an integer; **always** pass the address-of `&x`. -- After numeric `scanf`, there may be a leftover newline `\n` in the buffer. - Use `getchar()` or prefer `fgets()` + `sscanf()` for robust input. -Happy hacking! 🎯 diff --git a/Week_1_Instructions.md b/Week_1_Instructions.md new file mode 100644 index 0000000..a97e1fa --- /dev/null +++ b/Week_1_Instructions.md @@ -0,0 +1,120 @@ + +# Lab 1 — C Basics (Week 1) + +**Goals** +- Set up a working C toolchain (GitHub Codespaces *or* local Linux with GCC + VS Code). +- Write, compile, and run simple C programs. +- Practice `printf` / `scanf` format specifiers. + +## Repository Layout +``` +Lab01_C_Basics/ +├─ src/ +│ ├─ hello.c +│ ├─ calculator.c +│ └─ format_specifiers.c +├─ include/ +├─ bin/ # compiled binaries land here +├─ .vscode/ # VS Code tasks & debug config +├─ .devcontainer/ # one-click Codespaces +├─ Makefile +├─ .gitignore +├─ LICENSE (MIT) +└─ README.md +``` + +--- + +## Option A — Run in **GitHub Codespaces** (recommended) + +1. Push this repo to GitHub and click **Code → Codespaces → Create codespace on main**. +2. The provided **devcontainer** will provision a C/C++ environment (GCC, GDB, Make). +3. Open the **Terminal** in VS Code (inside Codespaces) and run: + +```bash +make # builds all targets +./bin/hello +./bin/calculator +./bin/formats +``` + +Or use the pre-configured **VS Code Tasks**: +- **Build All (Make)** — builds all targets +- **Run: Hello** — builds and runs `hello` +- **Run: Calculator** — builds and runs `calculator` +- **Run: Formats** — builds and runs `formats` + +Debugging: +- Put a breakpoint in `src/hello.c` +- Run **Start Debugging (Hello)** from the Run/Debug panel + +--- + +## Option B — Run locally on Linux (or WSL) + +1. Install build tools: + ```bash + sudo apt update && sudo apt install -y build-essential gdb + ``` +2. Build with `make`: + ```bash + make + ./bin/hello + ./bin/calculator + ./bin/formats + ``` + +--- + +## Targets (via `make`) +- `make` or `make all` — build all programs +- `make hello` — build Hello, World +- `make calculator` — build calculator +- `make formats` — build format specifier demo +- `make clean` — remove build artifacts + +--- + +## Programs + +### 1) `hello.c` +- Prints a greeting and shows command-line arguments (if any). + +### 2) `calculator.c` +- Simple arithmetic calculator (sum, difference, product, quotient). +- Demonstrates input validation and division-by-zero handling. + +### 3) `format_specifiers.c` +- Demonstrates key `printf`/`scanf` format specifiers: + - Integers: `%d`, `%u`, `%x`, `%o` + - Characters: `%c` + - Floats: `%f`, `%e`, precision like `%.2f` + - Strings: `%s` (single word), `fgets` for full line input + - Field width & alignment basics + +--- + +## Sample Commands + +```bash +# Build everything +make + +# Run Hello (with arguments) +./bin/hello Alice 42 + +# Run Calculator +./bin/calculator + +# Run Format Specifiers demo +./bin/formats +``` + +--- + +## Notes on `scanf` +- `scanf("%d", &x)` reads an integer; **always** pass the address-of `&x`. +- After numeric `scanf`, there may be a leftover newline `\n` in the buffer. + Use `getchar()` or prefer `fgets()` + `sscanf()` for robust input. + +Happy hacking! 🎯 diff --git a/Week_3_instructions.md b/Week_3_instructions.md new file mode 100644 index 0000000..379c86a --- /dev/null +++ b/Week_3_instructions.md @@ -0,0 +1,169 @@ +# Lab 3 – Arrays, Pointers, and Strings + +In this lab you will practice three core topics in C programming: +1. Array processing (min, max, sum, average) +2. Pointers as function parameters (swap, modify) +3. Manual string handling (strlen, strcpy) + +You will work on **three separate C source files**: + +- `lab3_task1.c` +- `lab3_task2.c` +- `lab3_task3.c` + +Each file already contains: +- A comment header with your **Name** and **Student ID** to fill in +- Function prototypes +- A simple `main` with example tests +- Placeholders (`// TODO`) where you need to write code + +--- +## Acquiring Lab 3 Files in Codespaces + +There are two ways to get the new Lab 3 files into your Codespaces. +Choose the method that fits your situation. + +--- + +### Option A – Update Your Existing Codespace (Recommended) + +If you already forked the course repository in Week 1 and created a Codespace, you can simply **pull the new files**. + +1. Open your existing Codespace. +2. Make sure you are on the `main` branch from terminal: + ```bash + git checkout main + ``` +3. Check that you have the teacher’s repository set as upstream: +```git remote -v``` +You should see something like this in the output: +``` +origin https://github.com/student123/RTU_Programming_Languages_C_Lab_Fall_2025.git (fetch) +upstream https://github.com/ValRCS/RTU_Programming_Languages_C_Lab_Fall_2025.git (fetch) +``` +If you do not see upstream, add it manually: +```git remote add upstream https://github.com/ValRCS/RTU_Programming_Languages_C_Lab_Fall_2025.git``` +4. Pull the new files from the teacher repository: +```git pull upstream main``` +5. After this, you should see the new files: +``` +src/lab3_task1.c +src/lab3_task2.c +src/lab3_task3.c +week3_instructions.md +``` + +### Option A2 – Update Your Fork Using GitHub "Sync Fork" Button + +If you don’t want to use terminal commands in Codespaces, you can update your fork directly on the GitHub website. + +#### Steps + +1. Open your fork of the course repository on GitHub (e.g. `https://github.com/student123/RTU_Programming_Languages_C_Lab_Fall_2025`). +2. On the repository page, you should see a **“Sync fork”** button near the top of the page. + - If your fork is behind the teacher’s repository, GitHub will show something like: + *“This branch is 3 commits behind ValRCS:main”*. +3. Click the **“Sync fork”** button, then click **“Update branch”** to bring your fork up to date. +4. After that, go back to your Codespace and run: +```bash + git pull origin main +``` +This will download the updated files from your fork into your Codespace. +⚠️ Note: The “Sync fork” method updates your fork on GitHub, but you still need to run +git pull origin main inside your Codespace to get the new files locall + +### Option B – Create a New Fork and Codespace (Only if Needed) + +Use this option **only if**: +- You accidentally deleted your Codespace, **or** +- Your fork is broken and cannot be updated. + +Steps: + +1. Go to the [teacher repository](https://github.com/ValRCS/RTU_Programming_Languages_C_Lab_Fall_2025). +2. Click **Fork** to create your own copy under your GitHub account. +3. When forking, GitHub may ask for a repository name. + - Example: if your GitHub username is `student123`, the default fork name will be + `student123/RTU_Programming_Languages_C_Lab_Fall_2025`. + - If you already created a fork in Week 1 or Week 2, you will need to **rename this new fork** (e.g. `RTU_Programming_Languages_C_Lab_Fall_2025_v2`) to avoid conflicts. +4. Open the newly forked repository in GitHub and click: +**Code → Codespaces → Create Codespace on main** +5. You will now have a fresh Codespace with all files, including Lab 3. + **NOTE**: Option A is much preferred. At some point in your future jobs you will not be allowed to just fork anytime you need a fresh copy - that is highly unprofessional. + + +## Task 1 – Array Algorithms (`lab3_task1.c`) + +Implement the following functions for integer arrays: +- `int array_min(int arr[], int size)` – return the smallest element +- `int array_max(int arr[], int size)` – return the largest element +- `int array_sum(int arr[], int size)` – return the sum of elements +- `float array_avg(int arr[], int size)` – return the average as a float + +**Rules:** +- Do not use external libraries besides ``. +- Write separate functions for each operation. + +**Example:** +```c +int arr[] = {10, 20, 5, 30, 15}; +printf("Min: %d\n", array_min(arr, 5)); // 5 +printf("Max: %d\n", array_max(arr, 5)); // 30 +printf("Sum: %d\n", array_sum(arr, 5)); // 80 +printf("Avg: %.2f\n", array_avg(arr, 5));// 16.00 +``` + +## Task 2 – Pointers in Function Parameters (`lab3_task2.c`) + +Practice using pointers to modify values inside functions. + +### Implement +- `void swap(int *x, int *y)` – swap the values of two integers +- `void modify_value(int *x)` – multiply the value by 2 + +### Rules +- Functions must modify the caller’s variables via pointers. +- Test your functions in `main`. + +### Example +```c +int a = 3, b = 7; +printf("Before swap: a=%d, b=%d\n", a, b); + +swap(&a, &b); +printf("After swap: a=%d, b=%d\n", a, b); + +modify_value(&a); +printf("After modify_value: a=%d\n", a); +``` + +## Task 3 – String Handling (`lab3_task3.c`) + +Write your own versions of two basic string functions: + +### Implement +- `int my_strlen(const char *str)` – return the number of characters (not counting `'\0'`) +- `void my_strcpy(char *dest, const char *src)` – copy a string into `dest` + +### Rules +- Do **not** use `` functions. +- Use loops or pointer arithmetic. +- Ensure `dest` has enough space to hold the copied string. + +### Example +```c +char text[] = "hello"; +int len = my_strlen(text); // 5 + +char buffer[100]; +my_strcpy(buffer, text); +printf("%s\n", buffer); // hello +``` + +## Submit + +* As usual, for each assignment submit the source code file for the assignment `lab3_task1.c` for first and so on. +* Alternatively, you can also submit the link to your repository which has this MODIFIED BY YOU file. Not just my original stub.. + + + diff --git a/Week_4_Instructions.md b/Week_4_Instructions.md new file mode 100644 index 0000000..e63ee63 --- /dev/null +++ b/Week_4_Instructions.md @@ -0,0 +1,154 @@ +# 🧩 Week 4 – Dynamic Memory & Structures + +This week focuses on using pointers for **dynamic memory allocation**, creating and using **structures**, and combining both ideas to build a small **in-memory database**. +All programs should compile cleanly without warnings using the provided Makefile. + +--- + +## 🧠 Task 1 – Create Dynamic Arrays with `malloc` + +### Implement +Write a C program that: +- Asks the user for the number of elements. +- Dynamically allocates memory for an integer array using `malloc`. +- Reads integers from user input and stores them in the array. +- Calculates and prints the sum and average of the entered numbers. +- Frees all allocated memory before the program exits. + +The file should be named: +`src/week4_1_dynamic_array.c` + +### Rules +- Always **check** if `malloc` returned a valid pointer. +- Use `sizeof(int)` when allocating memory. +- Avoid memory leaks: every successful `malloc` should have a corresponding `free`. +- Use clear, formatted output with `printf`. + +### Example +``` +Enter number of elements: 5 +Enter 5 integers: 10 20 30 40 50 +Sum = 150 +Average = 30.00 +``` + +--- + +## 🎓 Task 2 – Define and Use a `struct` (Student Record) + +### Implement +Write a C program that defines and uses a structure called `Student`. +Each student has: +- `char name[50]` +- `int id` +- `float grade` + +The program should: +- Declare at least **two** `Student` variables. +- Assign values to their fields (either manually or through user input). +- Print the information of each student in a formatted way. + +The file should be named: +`src/week4_2_struct_student.c` + +### Rules +- Use `struct` keyword for the definition. +- Access fields using the dot (`.`) operator. +- You may use `strcpy()` to assign a string to the `name` field. +- Keep output readable and labeled. + +### Example +``` +Student 1: Alice Johnson, ID: 1001, Grade: 9.1 +Student 2: Bob Smith, ID: 1002, Grade: 8.7 +``` + +--- + +## 🗂️ Task 3 – Build an In-Memory Database (Array of Structs) + +### Implement +Create a C program that: +- Defines a `struct Student` (same as in Task 2). +- Dynamically allocates memory for an **array of Student records** using `malloc`. +- Prompts the user for the number of students. +- Reads each student’s name, ID, and grade from the user. +- Prints all student records in a formatted table. +- Frees all allocated memory before exit. + +The file should be named: +`src/week4_3_struct_database.c` + +### Rules +- Reuse your `struct Student` definition from Task 2. +- Use `malloc(n * sizeof(struct Student))` for allocation. +- Remember to use `scanf("%s", student[i].name)` for names (no spaces) or `fgets()` for full names. +- Free the allocated memory before program termination. +- Consider sorting or computing averages as optional bonus. + +### Example +``` +Enter number of students: 3 +Enter data for student 1: Alice 1001 9.1 +Enter data for student 2: Bob 1002 8.7 +Enter data for student 3: Carol 1003 9.5 + +ID Name Grade +1001 Alice 9.1 +1002 Bob 8.7 +1003 Carol 9.5 +``` + +--- + +## 💾 Submission Instructions + +Students can submit their work in **either of two ways or BOTH**: + +### **Option A – Submit Repository URL** +1. Ensure your GitHub repository is up to date: + ```bash + git add . + git commit -m "Week 4 completed" + git push + ``` +2. Submit the **URL to your GitHub repository** in Moodle. + Example: + ``` + https://github.com/yourusername/RTU_Programming_Languages_C_Lab_Fall_2025 + ``` + +### **Option B – Submit Source Files** +1. Download your source files from the Codespaces `src/` folder: + - `week4_1_dynamic_array.c` + - `week4_2_struct_student.c` + - `week4_3_struct_database.c` +2. Upload these `.c` files directly to Moodle. + +Again, I prefer option A, but you can do option B if you are having trouble with your git repository. + +--- + +## 📚 Web Resources on Dynamic Memory & Structs in C + +Note: Some of these are not formal, but should provide a reasonable overview. + +### Dynamic Memory Allocation +- [GeeksforGeeks — Dynamic Memory Allocation in C (malloc, calloc, realloc, free)](https://www.geeksforgeeks.org/c/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/) +- [Programiz — C Dynamic Memory Allocation](https://www.programiz.com/c-programming/c-dynamic-memory-allocation) +- [Learn-C.org — Dynamic Allocation (interactive)](https://www.learn-c.org/en/Dynamic_allocation) +- [cppreference — `malloc` (C)](https://en.cppreference.com/w/c/memory/malloc) *(see also `free` and `realloc` linked on that page)* + +### Structures (`struct`) +- [Microsoft Learn — Structure Declarations (C)](https://learn.microsoft.com/en-us/cpp/c-language/structure-declarations?view=msvc-170) +- [GeeksforGeeks — Structures in C](https://www.geeksforgeeks.org/c/structures-c/) +- [Programiz — C struct](https://www.programiz.com/c-programming/c-structures) + + +--- + +✅ **Reminder:** +- Your code must compile without warnings using the provided Makefile. +- Comment your code clearly — explain *why* each important step is done. +- Always free dynamically allocated memory. +- Programs that crash or leak memory will lose points. diff --git a/src/hello.c b/src/hello.c index 9d6338f..4179224 100644 --- a/src/hello.c +++ b/src/hello.c @@ -3,7 +3,7 @@ int main(int argc, char *argv[]) { // This is your first C program my friend - printf("Hello, RTU World from C Lab in 2025!\n"); + printf("Hello from Mina! \n"); printf("You passed %d argument(s).\n", argc - 1); for (int i = 1; i < argc; ++i) { printf(" arg[%d] = %s\n", i, argv[i]); diff --git a/src/lab2_1.c b/src/lab2_1.c new file mode 100644 index 0000000..699339a --- /dev/null +++ b/src/lab2_1.c @@ -0,0 +1,28 @@ +#include + +/* + Task: + Write a function `int sum_to_n(int n)` that computes + the sum of all integers from 1 up to n using a for loop. + + In main(): + - Ask user for a positive integer n + - If n < 1, print an error + - Otherwise, call sum_to_n and print the result +*/ + +int sum_to_n(int n) { + // TODO: implement sum with a for loop + return 0; // placeholder +} + +int main(void) { + int n; + + printf("Enter a positive integer n: "); + scanf("%d", &n); + + // TODO: validate input, call function, and print result + + return 0; +} diff --git a/src/lab2_2.c b/src/lab2_2.c new file mode 100644 index 0000000..d88ef6d --- /dev/null +++ b/src/lab2_2.c @@ -0,0 +1,28 @@ +#include + +/* + Task: + Write a function `long long factorial(int n)` that computes n! + using a loop (not recursion). + + In main(): + - Ask user for an integer n + - If n is negative, print an error and exit + - Otherwise, call factorial and print the result +*/ + +long long factorial(int n) { + // TODO: compute factorial iteratively + return 1; // placeholder +} + +int main(void) { + int n; + + printf("Enter a non-negative integer n: "); + scanf("%d", &n); + + // TODO: validate input, call function, print result + + return 0; +} diff --git a/src/lab2_3.c b/src/lab2_3.c new file mode 100644 index 0000000..ddc8af6 --- /dev/null +++ b/src/lab2_3.c @@ -0,0 +1,28 @@ +#include + +/* + Task: + Write a function `int is_prime(int n)` that returns 1 if n is prime, + 0 otherwise. + + In main(): + - Ask user for an integer n (>= 2) + - If invalid, print an error + - Otherwise, print all prime numbers up to n +*/ + +int is_prime(int n) { + // TODO: check if n is prime using loop up to sqrt(n) + return 0; // placeholder +} + +int main(void) { + int n; + + printf("Enter an integer n (>= 2): "); + scanf("%d", &n); + + // TODO: validate input and print all primes up to n + + return 0; +} diff --git a/src/lab3_task1.c b/src/lab3_task1.c new file mode 100644 index 0000000..f0d73ee --- /dev/null +++ b/src/lab3_task1.c @@ -0,0 +1,70 @@ +/* + * Lab 3, Task 1 + * Student Name, Student ID + * + * Implement array algorithms: + * - find minimum value + * - find maximum value + * - calculate sum + * - calculate average + * + * Rules: + * - Write separate functions for each operation. + * - Work with int arrays. + * - Average should return a float. + * + * Example: + * int arr[] = {1, 2, 3, 4, 5}; + * min = array_min(arr, 5); // 1 + * max = array_max(arr, 5); // 5 + * sum = array_sum(arr, 5); // 15 + * avg = array_avg(arr, 5); // 3.0 + */ + +#include +#include + +// Function prototypes +int array_min(int arr[], int size); +int array_max(int arr[], int size); +int array_sum(int arr[], int size); +float array_avg(int arr[], int size); + +int main(void) { + int arr[] = {10, 20, 5, 30, 15}; + int size = 5; + + printf("Min: %d\n", array_min(arr, size)); + printf("Max: %d\n", array_max(arr, size)); + printf("Sum: %d\n", array_sum(arr, size)); + printf("Avg: %.2f\n", array_avg(arr, size)); + + return 0; +} + +// Implement functions below +int array_min(int arr[], int size) { + // TODO: return smallest element + int my_min = INT_MAX; //set to max infinity + for (int i=0;i arr[i]) { + my_min = arr[i]; + } + } + return my_min; // placeholder +} + +int array_max(int arr[], int size) { + // TODO: return largest element + return 0; // placeholder +} + +int array_sum(int arr[], int size) { + // TODO: return sum of elements + return 0; // placeholder +} + +float array_avg(int arr[], int size) { + // TODO: return average as float + return 0.0f; // placeholder +} diff --git a/src/lab3_task2.c b/src/lab3_task2.c new file mode 100644 index 0000000..fcc50d8 --- /dev/null +++ b/src/lab3_task2.c @@ -0,0 +1,46 @@ +/* + * Lab 3, Task 2 + * Student Name, Student ID + * + * Practice using pointers as function parameters. + * Implement: + * - swap (exchange values of two ints) + * - modify_value (multiply given int by 2) + * + * Rules: + * - Use pointers to modify variables in the caller. + * - Demonstrate changes in main. + * + * Example: + * int a = 5, b = 10; + * swap(&a, &b); // now a = 10, b = 5 + * + * modify_value(&a); // now a = 20 + */ + +#include + +// Function prototypes +void swap(int *x, int *y); +void modify_value(int *x); + +int main(void) { + int a = 3, b = 7; + printf("Before swap: a=%d, b=%d\n", a, b); + swap(&a, &b); + printf("After swap: a=%d, b=%d\n", a, b); + + modify_value(&a); + printf("After modify_value: a=%d\n", a); + + return 0; +} + +// Implement functions below +void swap(int *x, int *y) { + // TODO: swap values using a temporary variable +} + +void modify_value(int *x) { + // TODO: multiply value by 2 +} diff --git a/src/lab3_task3.c b/src/lab3_task3.c new file mode 100644 index 0000000..55cc20f --- /dev/null +++ b/src/lab3_task3.c @@ -0,0 +1,50 @@ +/* + * Lab 3, Task 3 + * Student Name, Student ID + * + * Implement basic string handling functions. + * Write your own versions of: + * - my_strlen (finds string length) + * - my_strcpy (copies string from src to dest) + * + * Rules: + * - Do not use functions for strlen/strcpy. + * - Use loops and manual pointer/array access. + * + * Example: + * char s[] = "hello"; + * int len = my_strlen(s); // should return 5 + * + * char buffer[100]; + * my_strcpy(buffer, s); // buffer now contains "hello" + */ + +#include + +// Function prototypes +int my_strlen(const char *str); +void my_strcpy(char *dest, const char *src); + +int main(void) { + // TODO: Test your functions here + char test[] = "Programming in C"; + char copy[100]; + + int len = my_strlen(test); + printf("Length: %d\n", len); + + my_strcpy(copy, test); + printf("Copy: %s\n", copy); + + return 0; +} + +// Implement functions below +int my_strlen(const char *str) { + // TODO: count characters until '\0' + return 0; // placeholder +} + +void my_strcpy(char *dest, const char *src) { + // TODO: copy characters until '\0' +} diff --git a/src/sqrt_test.c b/src/sqrt_test.c new file mode 100644 index 0000000..bb7ea41 --- /dev/null +++ b/src/sqrt_test.c @@ -0,0 +1,66 @@ +#include +#include +#include +#include + +// Compilation instructions! +// for compiling math you need add -lm at the very end! +// 1. The C Standard vs. Implementations + +// The C standard (ISO/IEC 9899) says that functions like sqrt, sin, log, +// feclearexcept, etc. exist in the library. + +// But the standard doesn’t say how they must be organized in the actual runtime +// system. + +// Compiler vendors (like GCC on Unix) are free to put them in a separate +// library (libm) instead of the default libc. + +// 2. Why Split into libc and libm? + +// Historical reason (Unix in the 1970s): + +// Early C programs often didn’t need floating-point math (think of simple +// utilities and text processing). + +// Floating-point math routines were large and sometimes required special +// hardware support (math co-processors). + +// To avoid bloating every program, they were separated into libm. + +// That way, only programs that actually needed math functions had to pay the +// cost of linking libm. + +// 3. GCC Linking Rules + +// By default, gcc file.c -o prog links libc, because every C program needs +// basic functions (printf, malloc, etc.). + +// But it does not link libm unless you explicitly request it with -lm. + +// Linker order matters: + +// gcc file.c -lm -o prog # works +// gcc -lm file.c -o prog # usually fails + +// because the linker only searches libraries after seeing unresolved +// references. + +// #pragma STDC FENV_ACCESS ON + +int main(void) { + printf("sqrt(100) = %f\n", sqrt(100)); + + printf("sqrt(-1.0) = %f\n", sqrt(-1.0)); + + errno = 0; + feclearexcept(FE_ALL_EXCEPT); + + printf("sqrt(-1.0) = %f\n", sqrt(-1.0)); + + if (errno == EDOM) perror("errno == EDOM"); + + if (fetestexcept(FE_INVALID)) puts("FE_INVALID raised"); + + return 0; +} \ No newline at end of file diff --git a/src/week4_1_dynamic_array.c b/src/week4_1_dynamic_array.c new file mode 100644 index 0000000..575567f --- /dev/null +++ b/src/week4_1_dynamic_array.c @@ -0,0 +1,38 @@ +/* + * week4_1_dynamic_array.c + * Author: [Your Name] + * Student ID: [Your ID] + * Description: + * Demonstrates creation and usage of a dynamic array using malloc. + * Students should allocate memory for an integer array, fill it with data, + * compute something (e.g., average), and then free the memory. + */ + +#include +#include + +int main(void) { + int n; + int *arr = NULL; + + printf("Enter number of elements: "); + if (scanf("%d", &n) != 1 || n <= 0) { + printf("Invalid size.\n"); + return 1; + } + + // TODO: Allocate memory for n integers using malloc + // Example: arr = malloc(n * sizeof(int)); + + // TODO: Check allocation success + + // TODO: Read n integers from user input and store in array + + // TODO: Compute sum and average + + // TODO: Print the results + + // TODO: Free allocated memory + + return 0; +} diff --git a/src/week4_2_struct_student.c b/src/week4_2_struct_student.c new file mode 100644 index 0000000..b04fc32 --- /dev/null +++ b/src/week4_2_struct_student.c @@ -0,0 +1,30 @@ +/* + * week4_2_struct_student.c + * Author: [Your Name] + * Student ID: [Your ID] + * Description: + * Demonstrates defining and using a struct in C. + * Students should define a 'Student' struct with fields like name, id, and grade. + * Then create a few instances and print them. + */ + +#include +#include + +// TODO: Define struct Student with fields: name (char[]), id (int), grade (float) +// Example: +// struct Student { +// char name[50]; +// int id; +// float grade; +// }; + +int main(void) { + // TODO: Declare one or more Student variables + + // TODO: Assign values (either manually or via scanf) + + // TODO: Print struct contents using printf + + return 0; +} diff --git a/src/week4_3_struct_database.c b/src/week4_3_struct_database.c new file mode 100644 index 0000000..e28a272 --- /dev/null +++ b/src/week4_3_struct_database.c @@ -0,0 +1,98 @@ +/* + * week4_3_struct_database.c + * Author: [Mina Senturk] + * Student ID: [231ADB258] + * Description: + * Simple in-memory "database" using an array of structs. + * Students will use malloc to allocate space for multiple Student records, + * then input, display, and possibly search the data. + */ + +#include +#include +#include + +static void chomp_newline(char *s) { + if (!s) return; + size_t len = strlen(s); + if (len && s[len - 1] == '\n') s[len - 1] = '\0'; +} +static void discard_line(void) { + int c; + while ((c = getchar()) != '\n' && c != EOF) { + } +} + +// TODO: Define struct Student with fields name, id, grade + +struct Student { + char name[50]; + int id; + float grade; +}; + +int main(void) { + int n; + struct Student *students = NULL; + + printf("Enter number of students: "); + if (scanf("%d", &n) != 1 || n <= 0) { + printf("Invalid number.\n"); + return 1; + } + + // TODO: Allocate memory for n Student structs using malloc + + students = malloc((size_t)n * sizeof(struct Student)); + if (students == NULL) { + printf("Memory allocation failed.\n"); + return 1; + } + + // TODO: Read student data in a loop + + discard_line(); // scanf("%d",&n) sonrası \n temizle + for (int i = 0; i < n; i++) { + printf("Enter data for student %d:\n", i + 1); + + printf(" Name: "); + if (!fgets(students[i].name, sizeof(students[i].name), stdin)) { + printf(" Error reading name.\n"); + free(students); + return 1; + } + chomp_newline(students[i].name); + + printf(" ID: "); + if (scanf("%d", &students[i].id) != 1) { + printf(" Error reading ID.\n"); + free(students); + return 1; + } + + printf(" Grade: "); + if (scanf("%f", &students[i].grade) != 1) { + printf(" Error reading grade.\n"); + free(students); + return 1; + } + + discard_line(); + } + + // TODO: Display all student records in formatted output + + printf("\n%-6s %-20s %-6s\n", "ID", "Name", "Grade"); + for (int i = 0; i < n; i++) { + printf("%-6d %-20s %-6.1f\n", students[i].id, students[i].name, + students[i].grade); + } + + // Optional: Compute average grade or find top student + + // TODO: Free allocated memory + + free(students); + + return 0; +}