9.10.25

Understanding Arrays in C



The Bookshelf Analogy & Book-Author Example

Arrays are one of the most essential concepts in C programming. They let you store multiple items of the same type in contiguous memory, making it easier to organize, access, and manipulate data. Think of an array as a bookshelf, where each shelf holds one book simple, organized, and neat!

In this blog, we’ll go through array concepts, C programs to create, display, and manage arrays, and a book-author example using arrays of strings.

The Bookshelf Analogy

Real-world item     Programming term Example
Bookshelf         Array     int favorite_numbers[8];
Book     Array element     favorite_numbers[0] = 100;
Shelf number     Index     favorite_numbers[3]
Number of shelves     Array size     8

Array Operations in C

creating, displaying, and managing arrays:

#include <stdio.h>

void DisplayIntArray(int given_array[], int array_data_size) {
    printf("Size of array is %d elements\n", array_data_size);
    printf("Array element values are:\n");
    for (int elementIndex = 0; elementIndex < array_data_size; elementIndex++) {
        printf("%d\n", given_array[elementIndex]);
    }
}

void DisplayFloatArray(float given_array[], int array_data_size) {
    printf("Size of array is %d elements\n", array_data_size);
    printf("Array element values are:\n");
    for (int elementIndex = 0; elementIndex < array_data_size; elementIndex++) {
        printf("%f\n", given_array[elementIndex]);
    }
}

int main() {
    // Integer Array Example
    int favorite_numbers[8];
    int favourite_numbers_length = sizeof(favorite_numbers) / sizeof(int);

    favorite_numbers[0] = 100;
    favorite_numbers[1] = 99;
    favorite_numbers[2] = 5;
    favorite_numbers[3] = 23;
    favorite_numbers[4] = 7;
    favorite_numbers[5] = 18;
    favorite_numbers[6] = 4;
    favorite_numbers[7] = 47;

    DisplayIntArray(favorite_numbers, favourite_numbers_length);

    // Another Integer Array Example
    int books[4] = {1984, 2001, 2010, 2020};
    DisplayIntArray(books, sizeof(books) / sizeof(int));

    // Float Array Example
    float favourite_fractions[3] = {3.14, 1.171, 2.72};
    DisplayFloatArray(favourite_fractions, sizeof(favourite_fractions) / sizeof(float));

    return 0;
}

Program Explanation

Creating Arrays
    int favorite_numbers[8];
    float favourite_fractions[3];

We declare arrays of a specific type and size.

Assigning Values

We can assign elements individually:
favorite_numbers[0] = 100;
favourite_fractions[1] = 1.171;

Or initialize at declaration:

int books[4] = {1984, 2001, 2010, 2020};

Displaying Arrays

We use functions with loops to display elements:
for (int i = 0; i < array_size; i++) {
    printf("%d\n", given_array[i]);
}

Array Size Calculation

int length = sizeof(favorite_numbers) / sizeof(int);

sizeof(favorite_numbers) → Total bytes of array
sizeof(int) → Size of one element
Divide to get number of elements

Important Points

Arrays store multiple values of the same type.
Indexing starts at 0.
Use loops to display or modify arrays efficiently.
Contiguous memory allows fast access.

Inserting & Deleting Elements

Since arrays have a fixed size, inserting or deleting requires shifting elements:

Delete the 2nd element example:

for(int i = 1; i < length - 1; i++) {
    favorite_numbers[i] = favorite_numbers[i + 1];
}
length--; // logically reduce array size

Book-Author Example Using Arrays of Strings

#include <stdio.h>

int main() {
    // Array of book titles
    char books[5][50] = {
        "Rich Dad Poor Dad",
        "1984",
        "The Book Theif",
        "The Alchemist",
        "Animal Farm"
    };

    // Array of authors corresponding to books
    char authors[5][50] = {
        "Robert Kiyosaki",
        "George Orwell",
        "Markus Zusak",
        "Paulo Coelho",
        "George Orwell"
    };

    printf("Book List:\n\n");

    // Display book and author
    for (int i = 0; i < 5; i++) {
        printf("Book: %s\nAuthor: %s\n\n", books[i], authors[i]);
    }

    return 0;
}

Explanation

books[5][50] → 5 book titles, each up to 50 characters.

authors[5][50] → 5 authors corresponding to books.

Using the same index, we link a book with its author.
Loop through arrays to display paired data.

Output


Book List:

Book: Rich Dad Poor Dad
Author: Robert Kiyosaki

Book: 1984
Author: George Orwell

Book: The Book Theif
Author: Markus Zusak

Book: The Alchemist
Author: Paulo Coelho

Book: Animal Farm
Author: George Orwell


8.10.25

Creating Array in C







Creating Arrays in C: Create, Insert, Delete & Display

Arrays are one of the most fundamental concepts in C programming. If you’ve ever tried to store multiple values like a list of favorite numbers  you’ve already needed arrays! Let’s explore how they work and what’s happening in this simple C program.

What is an Array?



An array is like a bookshelf it has a fixed number of slots (or compartments), and each slot can hold one book (a value).

In C, we can declare an array using:

data_type array_name[size];

Example:

int numbers[5];

This creates a space for 5 integers in memory all next to each other!

The Program

#include <stdio.h>

int main() {
  int favorite_numbers[5]; // Declaration of an array of 5 integers

  // Creating (assigning values)
  favorite_numbers[0] = 100;
  favorite_numbers[1] = 99;
  favorite_numbers[2] = 5;
  favorite_numbers[3] = 23;
  favorite_numbers[4] = 7;

  // Displaying values
  printf("My favorite numbers are %d\n%d\n%d\n%d\n%d\n", 
         favorite_numbers[0],
         favorite_numbers[1],
         favorite_numbers[2],
         favorite_numbers[3],
         favorite_numbers[4]);

  return 0;
}

Explanation:

1. Declaration

int favorite_numbers[5];

Here, we tell the compiler to reserve space for 5 integers in memory.
Each integer gets its own index — from 0 to 4.

Index Value
0
1
2
3
4

2. Creation (Assigning Values)

We now assign each books (array element) a value:

favorite_numbers[0] = 100;
favorite_numbers[1] = 99;
favorite_numbers[2] = 5;
favorite_numbers[3] = 23;
favorite_numbers[4] = 7;

Index Value
0 100
1 99
2 5
3 23
4 7

3. Display (Printing)

We can display the array elements one by one:


printf("My favorite numbers are %d\n%d\n%d\n%d\n%d\n",
       favorite_numbers[0],
       favorite_numbers[1],
       favorite_numbers[2],
       favorite_numbers[3],
       favorite_numbers[4]);

Output:

My favorite numbers are 100
99
5
23
7

You can use a Loop for Display

Instead of writing multiple printfs, we can use a loop:


for (int i = 0; i < 5; i++) {
    printf("%d\n", favorite_numbers[i]);
}

This way, if you ever change the size of the array, the loop still works perfectly!

Deletion and Insertion? 

Arrays in C have a fixed size, meaning you can’t directly “delete” or “insert” new elements but you can shift values.

Example: Deleting 99
You can simply move all elements after 99 one step back:


for (int i = 1; i < 4; i++) {
    favorite_numbers[i] = favorite_numbers[i + 1];
}

Now 99 is gone, and the array looks like [100, 5, 23, 7, ?].

Summary

Operation Meaning Example
Create     Declare and assign values     int nums[5] = {1,2,3,4,5};
Insert     Place a value in an index     nums[2] = 10;
Delete     Shift elements to remove one     loop shifting technique
Display     Print array elements     for loop or printf


3.10.25

Exercise 28: Intermediate Makefiles in C


Hi! Today I’m gonna show you how to make a solid C project skeleton using Makefiles. Think of Makefiles like cooking recipes for your code—they list the ingredients (source files), the steps to prepare the dish (compiling and linking), and even how to clean up the kitchen (removing build junk). In this post, we’ll go step by step through Exercise 28: Intermediate Makefiles from Learn C the Hard Way. By the end, you’ll have a reusable skeleton that keeps your projects neat, organized, and super easy to build.

Project Skeleton Structure

what your project will look like?


c-skeleton/
├── LICENSE          # License for your project
├── README.md        # Project description (Markdown)
├── Makefile         # The magic recipe
├── bin/             # Where executables go
├── build/           # Where build artifacts go
├── src/             # Your source code (.c, .h)
│   └── dbg.h        # Debugging header (from Ex19)
└── tests/           # Automated tests

  • LICENSE → Defines usage rights.

  • README.md → Basic project instructions.

  • Makefile → The brain of the build system.

  • bin/ → Holds compiled programs.

  • build/ → Holds libraries/object files.

  • src/ → Your C source files.

  • tests/ → Automated test programs.

The Makefile Explanation 

a reference Makefile used in this project:

CFLAGS=-g -O2 -Wall -Wextra -Isrc -rdynamic -DNDEBUG $(OPTFLAGS)
LIBS=-ldl $(OPTLIBS)
PREFIX?=/usr/local

SOURCES=$(wildcard src/**/*.c src/*.c)
OBJECTS=$(patsubst %.c,%.o,$(SOURCES))

TEST_SRC=$(wildcard tests/*_tests.c)
TESTS=$(patsubst %.c,%,$(TEST_SRC))

TARGET=build/libYOUR_LIBRARY.a
SO_TARGET=$(patsubst %.a,%.so,$(TARGET))

all: $(TARGET) $(SO_TARGET) tests

dev: CFLAGS=-g -Wall -Isrc -Wall -Wextra $(OPTFLAGS)
dev: all

$(TARGET): CFLAGS += -fPIC
$(TARGET): build $(OBJECTS)
	ar rcs $@ $(OBJECTS)
	ranlib $@

$(SO_TARGET): $(TARGET) $(OBJECTS)
	$(CC) -shared -o $@ $(OBJECTS)

build:
	@mkdir -p build
	@mkdir -p bin

.PHONY: tests
tests: CFLAGS += $(TARGET)
tests: $(TESTS)
	sh ./tests/runtests.sh

clean:
	rm -rf build $(OBJECTS) $(TESTS)
	rm -f tests/tests.log
	find . -name "*.gc*" -exec rm {} \;
	rm -rf `find . -name "*.dSYM" -print`

install: all
	install -d $(DESTDIR)/$(PREFIX)/lib/
	install $(TARGET) $(DESTDIR)/$(PREFIX)/lib/

check:
	@echo Files with potentially dangerous functions.
	@egrep '[^_.>a-zA-Z0-9](str(n?cpy|n?cat|xfrm|n?dup|str|pbrk|tok|_)
	|stpn?cpy|a?sn?printf|byte_)' $(SOURCES) || true

Sections in the Makefile

1. Header Section

  • CFLAGS → Compiler options (debugging, warnings, optimizations).

  • LIBS → Linking libraries.

  • PREFIX → Default install path (/usr/local).

  • SOURCES & OBJECTS → Automatically detect .c files and create .o list.

2. Build Targets

  • all → Default target (builds everything).

  • dev → Developer build with extra warnings.

  • $(TARGET) → Builds static library .a.

  • $(SO_TARGET) → Builds shared library .so.

3. Directories

  • build: → Ensures build/ and bin/ exist.

4. Unit Tests

  • tests: → Compiles and runs unit tests.

  • Needs a helper script runtests.sh.

5. Cleaner

  • clean: → Removes build files, test logs, and compiler junk.

6. Install

  • install: → Copies library to system directory.

7. Checker

  • check: → Warns if dangerous C functions (strcpy, etc.) are used.

Unit Test Script

Create a file tests/runtests.sh:



#!/bin/sh

echo "Running unit tests:"

for i in tests/*_tests
do
    if test -f $i
    then
        if $VALGRIND ./$i 2>> tests/tests.log
        then
            echo $i PASS
        else
            echo "ERROR in test $i: see tests/tests.log"
            tail tests/tests.log
            exit 1
        fi
    fi
done

echo ""

This script runs all tests and reports if something fails.

Commands You Can Try

  • Clean build files:

make clean
  • Run security checks:

make check
  • Build everything:

make
  • Install library (needs root):

sudo make install

Extra Credit

  • Add a .c and .h file in src/ to test building.

  • Explore the regex in check: to learn about unsafe C functions.

  • Read more about automated unit testing in C.


29.9.25

Build a Simple Blog Post layout with a Rating System

Hey, I'm gonna create a simple blog post layout with a footer that includes a rating system. I’ll use just HTML, CSS, and JavaScript

Let’s start!





Step 1: The HTML Body

Every vanilla HTML page starts with this:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Blog Post</title>
</head>

<body>
  <!-- Content goes here -->
</body>

</html>
  • <!DOCTYPE html> → tells the browser this is HTML5.

  • <head> → holds info about the page (title, settings, etc).

  • <body> → everything you see on screen goes here.

Step 2: Adding Blog Content

Inside the <body>, let’s put a paragraph:

<p style="background-color: rebeccapurple;">This is my blog post.</p>
  • <p> → adds a paragraph.

  • style="background-color: rebeccapurple;" → gives it a purple background to stand out.

Step 3: Footer with Rating System

Now let’s add a footer:

<footer>
  <span style="font-family: 'Courier New', Courier, monospace;">Rate my Post</span>
  <input type="number" id="rating" name="rating" min="1" max="5" step="1">
  <button type="button" onclick="updateRating()">Submit</button>
  <p id="pCopyRight">© 2024 My Blog</p>
</footer>

Breakdown:

  • <span> → shows “Rate my Post” in Courier New font.

  • <input type="number"> → box where users enter a number:

    • min="1" → lowest rating is 1

    • max="5" → highest rating is 5

    • step="1" → only whole numbers (no 2.5)

  • <button> → calls updateRating() when clicked.

  • <p> → shows copyright.

Step 4: Adding JavaScript

Now add interactivity at the bottom:

<script type="text/javascript">
  console.log("Footer script loaded.");
  console.log("Footer script loaded again.");
  console.log(new Date().getFullYear());

  // Auto update copyright
  document.getElementById("pCopyRight").innerText =
    "© " + new Date().getFullYear() + " My Blog";

  // Handle rating
  function updateRating() {
    const ratingInput = document.getElementById("rating");
    const ratingValue = ratingInput.value;

    if (ratingValue) {
      alert("You rated this post: " + ratingValue);
    } else {
      alert("Please enter a rating between 1 and 5.");
    }
  }
</script>
  • console.log() → test messages (visible in browser console).

  • document.getElementById("pCopyRight").innerText = ... → changes footer year automatically (so it’s always current).

  • updateRating() → runs when user clicks submit:

    • Reads input value.

    • Shows alert with rating if valid.

    • Otherwise asks for a rating.

Step 5: Full Demo Code


<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Blog Post</title>
</head>

<body>
  <p style="background-color: rebeccapurple;">This is my blog post.</p>

  <footer>
    <span style="font-family: 'Courier New', Courier, monospace;">Rate my Post</span>
    <input type="number" id="rating" name="rating" min="1" max="5" step="1">
    <button type="button" onclick="updateRating()">Submit</button>
    <p id="pCopyRight">© 2024 My Blog</p>
  </footer>

  <script type="text/javascript">
    console.log("Footer script loaded.");
    console.log("Footer script loaded again.");
    console.log(new Date().getFullYear());

    // Auto update copyright year
    document.getElementById("pCopyRight").innerText =
      "© " + new Date().getFullYear() + " My Blog";

    // Rating function
    function updateRating() {
      const ratingInput = document.getElementById("rating");
      const ratingValue = ratingInput.value;
      if (ratingValue) {
        alert("You rated this post: " + ratingValue);
      } else {
        alert("Please enter a rating between 1 and 5.");
      }
    }
  </script>
</body>

</html>

Step 6: Demo Behavior

  • Type 5 → click Submit → alert says “You rated this post: 5”.

  • Leave it blank → click Submit → alert says “Please enter a rating between 1 and 5.”

  • Footer year always updates automatically.

Conclusion

You just learned how to built a simple HTML page with:

  • HTML → structure

  • CSS (inline styles) → colors & fonts

  • JavaScript → rating alerts & auto-updating footer


Exercise 18: Pointers to Functions in C

 







Hi, everyone by now, we’ve played with arrays, structs, pointers, and even some dynamic memory allocation. With Exercise 18, we move into something that really showcases the power of C: function pointers.

This might sound scary at first, but once you see it in action, it feels almost natural. Function pointers let us treat functions like data we can pass them around, store them, and call them indirectly. This is the backbone of callbacks and even simulating object oriented behavior in C.

In C, a function is just a block of code in memory. So, naturally, we can have a pointer that points to this block. That’s what a function pointer is.

Syntax

If you normally write:

int callme(int a, int b);

To make it a function pointer, you’d write:

int (*callme)(int a, int b);

The (*pointer_name) part tells the compiler: “this is a pointer to a function returning int, that takes two ints as parameters.”

And just like arrays, you can use the pointer as if it were the function itself.

Typedef Makes it easy 

The raw syntax for function pointers can get messy. So we use typedef to simplify:
typedef int (*compare_cb)(int a, int b);

Now compare_cb is a type—like int or char *—and we can pass it around without repeating that ugly syntax.

Example: Sorting with Callbacks

To see function pointers in action, let’s build a flexible bubble sort. Instead of hardcoding the comparison (ascending, descending, weird logic), we’ll let the caller decide the comparison function.

This is what object oriented languages do under the hood when they let you pass custom comparators.

Code

#include <cstdio> #include <cstdlib> #include <cerrno> #include <cstring> using namespace std; /** Error handler */ void die(const char *message) { if (errno) { perror(message); } else { printf("ERROR: %s\n", message); } exit(1); } // typedef for function pointer type typedef int (*compare_cb)(int a, int b); /** Bubble sort that uses a comparison callback */ int *bubble_sort(int *numbers, int count, compare_cb cmp) { int temp = 0; int i = 0; int j = 0; int *target = (int *)malloc(count * sizeof(int)); // cast for C++ if (!target) die("Memory error."); memcpy(target, numbers, count * sizeof(int)); for (i = 0; i < count; i++) { for (j = 0; j < count - 1; j++) { if (cmp(target[j], target[j + 1]) > 0) { temp = target[j + 1]; target[j + 1] = target[j]; target[j] = temp; } } } return target; } /** Different comparison strategies */ int sorted_order(int a, int b) { return a - b; // ascending } int reverse_order(int a, int b) { return b - a; // descending } int strange_order(int a, int b) { if (a == 0 || b == 0) { return 0; } else { return a % b; // quirky comparator } } /** Test helper */ void test_sorting(int *numbers, int count, compare_cb cmp) { int i = 0; int *sorted = bubble_sort(numbers, count, cmp); if (!sorted) die("Failed to sort as requested."); for (i = 0; i < count; i++) { printf("%d ", sorted[i]); } printf("\n"); free(sorted); // Bonus: Print raw bytes of the function unsigned char *data = (unsigned char *)cmp; for (i = 0; i < 25; i++) { printf("%02x:", data[i]); } printf("\n"); } int main(int argc, char *argv[]) { if (argc < 2) die("USAGE: ex18 4 3 1 5 6"); int count = argc - 1; int i = 0; char **inputs = argv + 1; int *numbers = (int *)malloc(count * sizeof(int)); // cast for C++ if (!numbers) die("Memory error."); for (i = 0; i < count; i++) { numbers[i] = atoi(inputs[i]); } test_sorting(numbers, count, sorted_order); test_sorting(numbers, count, reverse_order); test_sorting(numbers, count, strange_order); free(numbers); return 0; } 
How It Works
  1. typedef int (*compare_cb)(int, int);

    • Creates a shorthand type for our comparator functions.

  2. bubble_sort

    • Implements bubble sort, but instead of deciding “< or >” itself, it calls cmp(a, b).

    • This makes sorting pluggable.

  3. Comparison Functions

    • sorted_order → Ascending.

    • reverse_order → Descending.

    • strange_order → A fun, quirky modulus-based order.

  4. test_sorting

    • Runs the sorting, prints results, and even peeks into the raw machine code of the comparator .

  5. main

    • Reads numbers from the command line.

    • Runs sorting with three different comparison strategies.

Run

ERROR: USAGE: ex18 4 3 1 5 6


Takeaways

  • Function pointers allow callbacks → code becomes flexible and reusable.

  • With typedef, messy syntax becomes neat.

  • You can swap behaviors at runtime just by changing the function pointer.

  • This is how C does what other languages call interfaces, delegates, or strategy patterns.

Extra Experiments

  • Try passing NULL as the comparator → watch it crash and debug why.

  • Write your own sorting algorithm (like selection sort) and plug it into the same system.

  • Open the compiled binary in a hex editor and try spotting your functions.

Chat Application in C



Hey, everyone so I learned how to built a simple chat app in C. It’s nothing fancy like WhatsApp, but it works!

How It Works

  • Server: Listens on port 8080 and shares any client’s message with all others.

  • Client: Connects to the server, lets you type, and shows messages from others.

  • Threads & Locks: Each client runs on its own thread. Locks make sure data doesn’t crash.

Program:


#define _CRT_SECURE_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS

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

#pragma comment(lib, "ws2_32.lib")

#define PORT 8080
#define MAX_CLIENTS 10
#define BUFFER_SIZE 1024

SOCKET clients[MAX_CLIENTS];
int client_count = 0;
CRITICAL_SECTION cs;

void broadcast_message(char* msg, SOCKET sender) {
    EnterCriticalSection(&cs);
    for (int i = 0; i < client_count; i++) {
        if (clients[i] != sender) {
            send(clients[i], msg, (int)strlen(msg), 0);
        }
    }
    LeaveCriticalSection(&cs);
}

DWORD WINAPI handle_client(LPVOID arg) {
    SOCKET client_sock = *(SOCKET*)arg;
    free(arg);
    char buffer[BUFFER_SIZE];
    int read_size;

    while ((read_size = recv(client_sock, buffer, BUFFER_SIZE - 1, 0)) > 0) {
        buffer[read_size] = '\0';
        printf("Client: %s", buffer);
        broadcast_message(buffer, client_sock);
    }

    EnterCriticalSection(&cs);
    for (int i = 0; i < client_count; i++) {
        if (clients[i] == client_sock) {
            clients[i] = clients[client_count - 1];
            client_count--;
            break;
        }
    }
    LeaveCriticalSection(&cs);

    closesocket(client_sock);
    printf("Client disconnected.\\n");
    return 0;
}

DWORD WINAPI receive_messages(LPVOID arg) {
    SOCKET sock = *(SOCKET*)arg;
    char buffer[BUFFER_SIZE];
    int read_size;

    while ((read_size = recv(sock, buffer, BUFFER_SIZE - 1, 0)) > 0) {
        buffer[read_size] = '\\0';
        printf("%s", buffer);
    }

    printf("Disconnected from server.\\n");
    exit(0);
}

void start_server() {
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    InitializeCriticalSection(&cs);

    SOCKET server_sock = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = INADDR_ANY;

    bind(server_sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
    listen(server_sock, 5);

    printf("Server running on port %d\\n", PORT);

    while (1) {
        SOCKET client_sock = accept(server_sock, NULL, NULL);
        if (client_sock == INVALID_SOCKET) continue;

        EnterCriticalSection(&cs);
        if (client_count < MAX_CLIENTS) {
            clients[client_count++] = client_sock;
        }
        LeaveCriticalSection(&cs);

        SOCKET* pclient = (SOCKET*)malloc(sizeof(SOCKET));
        *pclient = client_sock;
        CreateThread(NULL, 0, handle_client, pclient, 0, NULL);
    }

    closesocket(server_sock);
    DeleteCriticalSection(&cs);
    WSACleanup();
}

void start_client() {
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);

    char ip[50];
    printf("Enter server IP (localhost=127.0.0.1): ");
    scanf("%s", ip); 
    server_addr.sin_addr.s_addr = inet_addr(ip);

    if (connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
        printf("Connection Failed\\n");
        closesocket(sock);
        WSACleanup();
        exit(1);
    }

    printf("Connected! Type messages:\\n");
    CreateThread(NULL, 0, receive_messages, &sock, 0, NULL);

    char buffer[BUFFER_SIZE];
    while (1) {
        fgets(buffer, BUFFER_SIZE, stdin);
        send(sock, buffer, (int)strlen(buffer), 0);
    }

    closesocket(sock);
    WSACleanup();
}

int main() {
    int choice;
    printf("Choose mode: 1=Server, 2=Client: ");
    scanf("%d", &choice);

    if (choice == 1) start_server();
    else if (choice == 2) start_client();
    else printf("Invalid choice.\\n");

    return 0;
}

How to make it work?

  1. Compile with MinGW:

    gcc chat.c -o chat.exe -lws2_32
    
  2. Run as Server → choose 1

  3. Run as Client → choose 2 → enter IP (127.0.0.1 for local)

What I Learned

  • Sockets = computers sending/receiving data.

  • Threads = handle many people at once.

  • Locks = prevent memory conflicts.

I

22.9.25

Build a Simple Blog Page with a Rating System


Hey, I'm gonna create a simple blog post layout with a footer that includes a rating system. I’ll use just HTML, CSS, and JavaScript

Let’s start!



 Step 1 : The HTML Body

Every web page starts. At the very top, we tell the browser using HTML5:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Blog Post</title>
</head>

<body>
  <!-- Content goes here -->
</body>

</html>
  • The <head> contains information about the page, like the title and viewport settings.

  • The <body> contains everything want to show on the screen.

Step 2 : Adding Blog Content

Inside the <body>, let’s add a paragraph:

<p style="background-color: rebeccapurple;">This is my blog post.</p>

Here’s what happens:

  • The <p> tag displays a paragraph of text.

  • The style attribute changes the background color to rebeccapurple (or any color u want), making the text stand out.

Step 3 : Creating the Footer with a Rating System

Now, let’s build a footer that lets users rate the post:

<footer>
  <span style="font-family: 'Courier New', Courier, monospace;">Rate my Post</span>
  <input type="number" id="rating" name="rating" min="1" max="5" step="1">
  <button type="button" onclick="updateRating()">Submit</button>
  <p id="pCopyRight">© 2024 My Blog</p>
</footer>

Breaking it down:

  • The <span> shows the text “Rate my Post” in Courier New font.

  • The <input> allows users to type a number:

    • type="number" ensures only numbers are accepted.

    • min="1" and max="5" limit the rating between 1 and 5.

    • step="1" means only whole numbers are allowed.

  • The <button> calls the updateRating() function when clicked.

  • The <p> shows copyright text.

Step 4 : Adding JavaScript Interactivity

Now I'll add a <script> at the bottom of the page:

<script type="text/javascript">
  console.log("Footer script loaded.");
  console.log("Footer script loaded again.");
  console.log(new Date().getFullYear());

  // Automatically update copyright year
  document.getElementById("pCopyRight").innerText =
    "© " + new Date().getFullYear() + " My Blog";

  // Handle rating submission
  function updateRating() {
    const ratingInput = document.getElementById("rating");
    const ratingValue = ratingInput.value;

    if (ratingValue) {
      alert("You rated this post: " + ratingValue);
    } else {
      alert("Please enter a rating between 1 and 5.");
    }
  }
</script>

What's this?

  • console.log() prints test messages in the developer console.

  • The copyright line:

    document.getElementById("pCopyRight").innerText =
      "© " + new Date().getFullYear() + " My Blog";
    

    Updates the footer year automatically, no need to edit it every year!

  • The updateRating() function:

    • Reads the number from the input box.

    • Shows an alert with the rating.

    • If nothing is entered, it asks the user to provide a rating.

Step 5 : Demo

  • Enter 5 in the box → click Submit → alert shows “You rated this post: 5”.

  • Leave the box empty → click Submit → alert says “Please enter a rating between 1 and 5.”

  • The footer always displays the current year automatically.

Final Code


<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Blog Post</title>
</head>

<body>
  <p style="background-color: rebeccapurple;">This is my blog post.</p>

  <footer>
    <span style="font-family: 'Courier New', Courier, monospace;">Rate my Post</span>
    <input type="number" id="rating" name="rating" min="1" max="5" step="1">
    <button type="button" onclick="updateRating()">Submit</button>
    <p id="pCopyRight">© 2024 My Blog</p>
  </footer>

  <script type="text/javascript">
    console.log("Footer script loaded.");
    console.log("Footer script loaded again.");
    console.log(new Date().getFullYear());

    document.getElementById("pCopyRight").innerText =
      "© " + new Date().getFullYear() + " My Blog";

    function updateRating() {
      const ratingInput = document.getElementById("rating");
      const ratingValue = ratingInput.value;
      if (ratingValue) {
        alert("You rated this post: " + ratingValue);
      } else {
        alert("Please enter a rating between 1 and 5.");
      }
    }
  </script>
</body>

</html>

Conclusion

And that’s it! You’ve built a simple blog post page with a footer rating system.

This example may be simple, but it shows how HTML handles structure, CSS handles styling, and JavaScript adds interactivity.

You can expand this further by:

  • Replacing the number input with star icons 

  • Saving ratings in a database 

  • Showing average ratings 


20.9.25

Heap and Stack Memory



Exercise 17 – Heap and Stack Memory in C

Hi! Today I worked on Exercise 17: Heap and Stack Memory Allocation, and it was definitely one of the toughest ones so far . This exercise makes a small database program that can store names and emails, but the real focus is on memory allocation – stack vs heap.

What This Program Does

  • Creates a tiny address book database using struct.

  • Lets us create, set, get, delete, and list records in the database.

  • Introduces file I/O in C (fopen, fread, fwrite, fclose).

  • Shows how heap memory (malloc) and stack memory are different.

Example Code 

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

#define MAX_DATA 512
#define MAX_ROWS 100

struct Address {
    int id;
    int set;
    char name[MAX_DATA];
    char email[MAX_DATA];
};

struct Database {
    struct Address rows[MAX_ROWS];
};

int main() {
    struct Database *db = malloc(sizeof(struct Database)); // Heap memory
    if (!db) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    // Example entry
    db->rows[0].id = 0;
    db->rows[0].set = 1;
    strncpy(db->rows[0].name, "Rahul", MAX_DATA);
    strncpy(db->rows[0].email, "rahul@example.com", MAX_DATA);

    printf("ID: %d, Name: %s, Email: %s\n",
           db->rows[0].id, db->rows[0].name, db->rows[0].email);

    free(db); // Release heap memory
    return 0;
}


Heap vs Stack – Easy Way to Remember

Stack

  • Stores local variables (inside functions).

  • Works like a stack of plates → last in, first out (LIFO).

  • Memory is fast but limited.

  • Freed automatically when function ends.

  • Too much use = stack overflow.

Heap

  • Stores dynamic memory (you request it using malloc / new).

  • Works like a storage warehouse → you must manage space yourself.

  • Memory is larger but slower.

  • You must free it manually (free / delete).

  • Forgetting to free = memory leak.

Shortcut to remember:

  • Stack = Automatic (fast, small)

  • Heap = Manual (big, slow)


Example Output

$ ./ex17 db.dat c
$ ./ex17 db.dat s 1 Rahul rahul@gmail.com
$ ./ex17 db.dat s 2 Daksh daksh@yahoo.com
$ ./ex17 db.dat l
1 Rahul rahul@gmail.com
2 Daksh daksh@yahoo.com


How did I learned it as?

This exercise taught me that:

  • Heap is for big, flexible memory .

  • Stack is for temporary, automatic memory (local variables).

  • Always free your malloc or your program will eat memory forever.

  • Using structs and arrays together makes database-like programs possible even in C.


18.9.25

Structs and Pointers





Structs and Pointers in C

Hey, everyone today I tried something new in C programming using structures with pointers and dynamic memory allocation. At first it looked confusing, but after working on it, I realized it’s actually super useful.

Code:

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

struct Student {
    char name[50];
    int age;
    float marks;
};

int main() {
    struct Student* ptr;

   
    ptr = (struct Student*)malloc(sizeof(struct Student));

    if (ptr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    
    printf("Enter name: ");
    scanf_s("%49s", ptr->name, (unsigned)_countof(ptr->name));
    

    printf("Enter age: ");
    scanf_s("%d", &ptr->age);

    printf("Enter marks: ");
    scanf_s("%f", &ptr->marks);

    
    printf("\n--- Student Details ---\n");
    printf("Name: %s\n", ptr->name);
    printf("Age: %d\n", ptr->age);
    printf("Marks: %.2f\n", ptr->marks);

    
    free(ptr);

    return 0;
}
Output:




What I Learned

  • struct lets me group related data like name, age, and marks into one unit called Student.

  • With pointers, I can directly access and modify this struct in memory using ptr->field.

  • malloc gives memory at runtime (on the heap). This is better than static memory because it can adjust as per need.

  • Finally, I used free(ptr) to release memory, so my program doesn’t waste RAM.

Instead of just declaring one student normally, I learned how to manage memory myself. This is like leveling up in C programming. In the future, I’ll be able to handle multiple students or even bigger data structures dynamically.


16.9.25

Pointers Project


 


Hey, everyone I recently created a small project in C using pointers and structures. The program is a simple Student Record System where the user can enter the number of students, along with their name, age, and marks. The data is then stored dynamically in memory using malloc and displayed neatly on the screen.

This project helped me understand how powerful pointers are in C programming. Instead of fixing the size of an array, I learned how to allocate memory at runtime, which makes programs more flexible and efficient. I also used structures to group related data (like name, age, and marks) for each student, making the program more organized.


Code:

#include <stdio.h>

#include <stdlib.h>


struct Student {

    char name[50];

    int age;

    float marks;

};


int main() {

    int n, i;

    struct Student* ptr;

    printf("Enter number of students: ");

    scanf_s("%d", &n);    

    ptr = (struct Student*)malloc(n * sizeof(struct Student));

    if (ptr == NULL) {

        printf("Memory not allocated!\n");

        return 1;

    }   

    for (i = 0; i < n; i++) {

        printf("\nEnter details of student %d\n", i + 1);

        printf("Name: ");

        scanf_s("%s", ptr[i].name, (unsigned)_countof(ptr[i].name));

        printf("Age: ");

        scanf_s("%d", &ptr[i].age);

        printf("Marks: ");

        scanf_s("%f", &ptr[i].marks);

    }    

    printf("\n--- Student Records ---\n");

    for (i = 0; i < n; i++) {

        printf("Student %d: %s, Age: %d, Marks: %.2f\n",

            i + 1, ptr[i].name, ptr[i].age, ptr[i].marks);

    }

    free(ptr); 

    return 0;

}

Output: 






11.9.25

My Plan





Hi! What's up. I’m an 18-year-old in my 2nd year of an IT Diploma, and I’m keeping it real: I’m focusing on C Language. Not overcomplicating things. Here’s my clear plan to become a software engineer.


Why C? 


- It’s the foundation. Learn C, and everything else makes sense.  

- Used in embedded systems, OS development, compilers stuff that needs to be fast and          efficient.  

- Understanding memory, pointers, and low-level execution will make me better in ANY        language.


The Plan – Simple and Focused:

1. Complete My Diploma in IT 

Right now, I’m focusing on finishing my diploma with good grades. I’m also learning programming languages like C/C++ on the side to improve my coding skills.

2. Do a Degree in Computer Science / IT

After my diploma, I’ll go for a degree in Computer Science or IT. This will help me learn advanced subjects like Data Structures, Algorithms, and Software Development

3. Build Skills + Internships + Job 

Along with studies, I’ll keep practicing coding on platforms like LeetCode and GitHub. I plan to do internships during college to get real-world experience. After that, I’ll apply for jobs in software companies and start my career.


After Diploma: 

Lateral Entry into B.Tech CS or IT

- Join B.Tech directly in the 2nd year.  

- My C skills and project experience will put me ahead of the curve.


Final Goal:  

Become a Systems Software Engineer or Embedded Software Engineer. C might not be trendy, but it’s powerful, respected, and in demand.


rating System

Loading...

Understanding Arrays in C

The Bookshelf Analogy & Book-Author Example Arrays are one of the most essential concepts in C programming. They let you store multiple ...