diff --git a/app/components/CodeBlock.tsx b/app/components/CodeBlock.tsx new file mode 100644 index 0000000..494a019 --- /dev/null +++ b/app/components/CodeBlock.tsx @@ -0,0 +1,86 @@ +"use client"; + +import { useState } from "react"; +import { Copy, Check } from "lucide-react"; + +interface CodeBlockProps { + code: string; +} + +export const CodeBlock = ({ code }: CodeBlockProps) => { + const [copied, setCopied] = useState(false); + + const handleCopy = async () => { + try { + await navigator.clipboard.writeText(code.trim()); + + setCopied(true); + + setTimeout(() => { + setCopied(false); + }, 2000); + } catch (error) { + console.error("Failed to copy:", error); + } + }; + + return ( +
+ + {/* Copy Button */} + + + {/* Code Block */} +
+        
+          {code.trim()}
+        
+      
+
+ ); +}; \ No newline at end of file diff --git a/app/sem1/c/content/chapter1.tsx b/app/sem1/c/content/chapter1.tsx index ac626c1..ee57622 100644 --- a/app/sem1/c/content/chapter1.tsx +++ b/app/sem1/c/content/chapter1.tsx @@ -1,4 +1,7 @@ +"use client"; + import Image from "next/image"; +import { CodeBlock } from "../../../components/CodeBlock"; export const Ch1Content = () => { return ( @@ -16,16 +19,27 @@ export const Ch1Content = () => { {/* Fundamentals */}

Fundamentals of Computing

+
-
Quick Example
+
+ Quick Example +
+
- Input: [72, 89, 34, 91]
+ Input: [72, 89, 34, 91] +
Output: [91, 89, 72, 34]
@@ -36,11 +50,15 @@ export const Ch1Content = () => { {/* History */}

Historical Perspective

+ @@ -51,7 +69,6 @@ export const Ch1Content = () => { width={1000} height={350} /> -

@@ -61,9 +78,15 @@ export const Ch1Content = () => {

Early Computers and Machines

{ width={850} height={380} /> -

@@ -98,23 +120,30 @@ export const Ch1Content = () => { width={900} height={400} /> -
{/* Problems */}
-

Problems and Algorithm Characteristics

+

+ Problems and Algorithm Characteristics +

- Tip: In exam answers, clearly state if the problem is well-defined and list algorithm characteristics. + Tip: In exam answers, clearly state if the problem is well-defined + and list algorithm characteristics.
@@ -123,36 +152,51 @@ export const Ch1Content = () => { {/* Pseudocode */}

Pseudo-code and Flowcharts

+
-
Pseudo-code Example: Sum of first n numbers
-
-            {`READ n
+          
+ Pseudo-code Example: Sum of first n numbers +
+ + + />
-
Flowchart Structure
+
+ Flowchart Structure +
+

- Start → Input n → Initialize sum → Loop (i ≤ n?) → Add → Update → Output sum → End + Start → Input n → Initialize sum → Loop (i ≤ n?) → Add → Update → + Output sum → End

- flowchart-sum-n + flowchart-sum-n
@@ -165,26 +209,31 @@ PRINT sum`}
-
Memory Layout Example
-
-            {`Address   Content
+          
+ Memory Layout Example +
+ + - memory-layout + /> + memory-layout
@@ -202,13 +251,16 @@ PRINT sum`}
-
Assembly-like Example
-
-            {`LOAD R1, 5
+          
+ Assembly-like Example +
+ + + />
@@ -219,9 +271,15 @@ STORE R3, 0x200`}

Programs

- ); -}; +}; \ No newline at end of file diff --git a/app/sem1/c/content/chapter2.tsx b/app/sem1/c/content/chapter2.tsx index 3309ad3..572f917 100644 --- a/app/sem1/c/content/chapter2.tsx +++ b/app/sem1/c/content/chapter2.tsx @@ -1,161 +1,191 @@ import Image from "next/image"; +import { CodeBlock } from "../../../components/CodeBlock"; export const Ch2Content = () => { return (
-

Concise notes covering the language, program development phases, importance, - program structure, a minimal sample program, compilation and execution commands, - key concepts, programming style, and a short debugging example. +

Introduction to C — Chapter 2

+ +

+ Concise notes covering the language, program development phases, + importance, program structure, sample programs, compilation, + execution, key concepts, programming style, and debugging.

-
+
{/* Language of C */}

The Language of C

+
-
+
{/* Phases */}

Phases of Developing a C Program

+ +
-
+
{/* Importance */}

Importance of C

+
-
+
{/* Basic Structure */}

Basic Structure of a C Program

+ -
-
Minimal example
-
-{`#include 
+        
 
 int main(void) {
     int a = 10;
-    printf("Value of a = %d\n", a);
+
+    printf("Value of a = %d\\n", a);
+
     return 0;
 }`}
-          
-
+ />
-
+
{/* Executing */}

Compiling and Executing

+ - compile-run-flow +
+ compile-run-flow +
-
+
{/* Key Concepts */}

Key Concepts

+
-
+
- {/* Programming Style */} + {/* Style */}
-

Programming Style (exam checklist)

+

Programming Style

+
-
+
{/* Debugging */}

Common Debugging Points

-
-
Typical mistakes to spot
-
    -
  • Missing ampersand in `scanf` call: use scanf("%d", &x).
  • -
  • Forgotten semicolon after statements.
  • -
  • Using uninitialized variables.
  • -
  • Buffer overflow with strings; always ensure space for null terminator.
  • +
    +
    Typical Mistakes
    + +
      +
    • Missing ampersand in scanf()
    • +
    • Missing semicolon
    • +
    • Using uninitialized variables
    • +
    • Buffer overflow in strings
    +
    -
    Faulty snippet
    -
    -{`#include 
    +        
     
     int main() {
         int a;
    +
         printf("Enter number: ");
    -    scanf("%d", a);   // wrong: should be &a
    -    printf("Value is: %d", a)  // wrong: missing semicolon
    +
    +    scanf("%d", a);   // wrong: missing &
    +
    +    printf("Value is: %d", a) // wrong: missing semicolon
    +
         return 0;
     }`}
    -          
    + /> + + Corrected
-
-{`scanf("%d", &a);
 printf("Value is: %d", a);`}
-          
-
+ /> ); -}; +}; \ No newline at end of file diff --git a/app/sem1/c/content/chapter3.tsx b/app/sem1/c/content/chapter3.tsx index a5b9147..528f364 100644 --- a/app/sem1/c/content/chapter3.tsx +++ b/app/sem1/c/content/chapter3.tsx @@ -1,296 +1,381 @@ -import Image from 'next/image'; +import Image from "next/image"; +import { CodeBlock } from "../../../components/CodeBlock"; export const Ch3Content = () => { return (

- This chapter highlights definitions, sizes, operator precedence, control - constructs, common pitfalls, and a short debugging example. + This chapter explains C data concepts, data types, storage classes, + operators, statements, control flow, loops, overflow handling, + and debugging basics.

-
+
{/* Data concepts */}

Data Concepts in C

+
-
+
- {/* Data types and sizes */} + {/* Data types */}

Data Types, Size and Values

-

Standard fundamental types commonly used in exams are listed below.

- -
-
Common C types (typical 32-bit system)
-
-
    -
  • - char — 1 byte, stores a character, range: - typically -128 to 127 (signed) or 0 to 255 (unsigned). -
  • -
  • - int — 4 bytes, range implementation-defined; commonly - -2,147,483,648 to 2,147,483,647. -
  • -
  • - short — 2 bytes; long — 4 or 8 bytes depending on platform. -
  • -
  • - float — 4 bytes (single precision); double — 8 bytes (double precision). -
  • -
-
-
+

+ Standard C data types and their typical sizes are listed below. +

- c-data-sizes +
+
Common C Types
+ +
    +
  • + char → 1 byte +
  • + +
  • + int → 4 bytes +
  • + +
  • + short → 2 bytes +
  • + +
  • + long → 4 or 8 bytes +
  • + +
  • + float → 4 bytes +
  • +
  • + double → 8 bytes +
  • +
+
+ +
+ c-data-sizes +
-
+
{/* Storage classes */}

Storage Classes

-

Remember exam questions often ask for scope and lifetime of each storage class.

+

+ Questions about scope and lifetime are common in exams. +

-
+
- {/* Operators & precedence */} + {/* Operators */}

Operators and Precedence

-
-
Important precedence (high → low)
-
    -
  • Unary: ++ -- + - !
  • -
  • Multiplicative: * / %
  • -
  • Additive: + -
  • -
  • Relational: < > <= >=
  • -
  • Equality: == !=
  • -
  • Logical: && then ||
  • -
  • Assignment: = and compound assignments
  • +
    +
    Important Precedence Order
    + +
      +
    • Unary → ++ -- !
    • + +
    • Multiplicative → * / %
    • + +
    • Additive → + -
    • + +
    • Relational → < > <= >=
    • + +
    • Equality → == !=
    • + +
    • Logical → && ||
    • + +
    • Assignment → = += -=
    -
    - Note: use parentheses to enforce evaluation order when needed. -
    - operator-precedence -

    Operator associativity is usually left-to-right; assignment and some unary operators associate right-to-left.

    + +
    + operator-precedence +
    + +

    + Use parentheses whenever evaluation order may be unclear. +

-
+
- {/* Statements and expressions */} + {/* Statements */}

Statements and Expressions

-
+
- {/* Input-Output */} + {/* Input output */}

Input-Output Statements

-
-
I/O Example
-
-            {`int x;
+        
-        
+ +printf("You entered %d\\n", x);`} + />
-
+
- {/* Selection statements */} + {/* Selection */}

Selection Statements

-
-
if-else example
-
-            {`if (a > b) {
-  printf("a is greater\n");
+         b) {
+    printf("a is greater\\n");
 } else {
-  printf("b is greater or equal\n");
+    printf("b is greater or equal\\n");
 }`}
-          
-
+ /> -
-
switch example
-
-            {`switch (ch) {
-  case 'a': doA(); break;
-  case 'b': doB(); break;
-  default: doDefault();
+        
-        
+ />
-
+
- {/* Loop constructs */} + {/* Loops */}

Loop Constructs

-
-
Loop examples
-
-            {`// for loop
+        
-        
- loop-flowcharts + +
+ loop-flowcharts +
-
+
{/* Overflow */}

Overflow

-
+
- {/* Debugging exercise */} + {/* Debugging */}

Debugging Exercise

-
-
Find and fix the errors
-
-            {`#include 
+        
 
 int main() {
-  char s[5];
-  printf("Enter string: ");
-  scanf("%s", s);   // possible overflow if user types >4 chars
-  printf("You entered: %s\n", s)
-  return 0;
+    char s[5];
+
+    printf("Enter string: ");
+
+    scanf("%s", s);   // possible overflow
+
+    printf("You entered: %s\\n", s)
+
+    return 0;
 }`}
-          
+ /> + +
+
Corrections
-
Correct points
-
    -
  • Ensure buffer size and use width specifier: scanf("%4s", s);
  • -
  • Add missing semicolon after printf.
  • -
  • Prefer fgets for safer input.
  • +
      +
    • + Use width specifier: + scanf("%4s", s); +
    • + +
    • Add missing semicolon after printf.
    • + +
    • Prefer fgets() for safer input.
-
+
- {/* Programming exercise placeholder (short) */} + {/* Exercises */}

Programming Exercise

+
); -}; +}; \ No newline at end of file diff --git a/app/sem1/c/content/chapter4.tsx b/app/sem1/c/content/chapter4.tsx index e09af1e..b6cebe5 100644 --- a/app/sem1/c/content/chapter4.tsx +++ b/app/sem1/c/content/chapter4.tsx @@ -1,11 +1,14 @@ import Image from "next/image"; +import { CodeBlock } from "../../../components/CodeBlock"; export const Ch4Content = () => { return (
-

This module contains essential notes on one/two/multidimensional arrays, character arrays and strings, - user-defined functions, recursion, and basic searching and sorting concepts. +

+ This module contains essential notes on one/two/multidimensional arrays, + character arrays and strings, user-defined functions, recursion, + and basic searching and sorting concepts.


@@ -13,65 +16,126 @@ export const Ch4Content = () => { {/* Arrays */}

Arrays

+ -
-
Static vs dynamic
-
{`// static
+        
+
+ Static vs Dynamic Arrays +
+ + + +if (b == NULL) { + // handle error +} + +free(b);`} + language="c" + />
array-memory-layout -

- {/* Character arrays and strings */} + {/* Strings */}

Character Arrays and Strings

-
-
String example
-
{`char s[6] = "Hello";
-printf("%s\n", s);
-if (strcmp(s, "Hello") == 0) { /* equal */ }`}
+
+
+ String Example +
+ +
string-functions-table - + src="/string-functions-table.png" + alt="string-functions-table" + width={850} + height={500} + className="my-6 rounded-xl border border-[#c7a669] shadow-md max-w-full" + />

@@ -81,22 +145,52 @@ if (strcmp(s, "Hello") == 0) { /* equal */ }`}

Functions (User-defined)

-
-
Pass by value vs. pointer
-
{`void inc_val(int x) { x = x + 1; }     // caller not changed
-void inc_ref(int *p) { *p = *p + 1; }  // caller changed
+        
+
+ Pass by Value vs Pointer +
+ + + +inc_val(a); // still 5 +inc_ref(&a); // becomes 6`} + language="c" + />
@@ -107,98 +201,176 @@ inc_ref(&a); // a becomes 6`}

Recursion

-
-
Factorial (recursive vs iterative)
-
{`// recursive
+        
+
+ Factorial Using Recursion +
+ + + int r = 1; + + for (int i = 2; i <= n; i++) { + r *= i; + } + + return r; +}`} + language="c" + />
recursion-tree
- {/* Searching and Sorting basics */} + {/* Searching and Sorting */}
-

Searching and Sorting — Basics

+

+ Searching and Sorting — Basics +

    -
  • Linear search: scan sequentially; O(n) worst-case.
  • -
  • Binary search: requires sorted array; O(log n).
  • -
  • Sorting (intro): be familiar with bubble, insertion, selection; know their basic complexities.
  • +
  • + Linear Search: sequential scan, complexity O(n). +
  • + +
  • + Binary Search: works only on sorted arrays, complexity O(log n). +
  • + +
  • + Basic sorting techniques include bubble sort, insertion sort, and selection sort. +
-
-
Linear search
-
{`int linear_search(int a[], int n, int key) {
-  for (int i = 0; i < n; i++)
-    if (a[i] == key) return i;
-  return -1;
-}`}
+
+
+ Linear Search Example +
+ +

- {/* Debugging exercise */} + {/* Debugging */}

Debugging Exercise

-
-
Find and fix the errors
-
{`#include 
+        
+
+ Find and Fix the Errors +
+ + int sum_rows(int m[][3], int r) { - int s = 0; - for (int i = 0; i <= r; i++) { // error: loop bounds (<=) incorrect - for (int j = 0; j < 3; j++) - s += m[i][j]; - } - return s; -}`}
- -
Correct points
-
    -
  • Fix row loop to {`for (int i = 0; i < r; i++)`} if {`r`} is the row count.
  • -
  • Array parameter requires known second dimension: {`m[][3]`}.
  • + + int s = 0; + + for (int i = 0; i <= r; i++) { + + for (int j = 0; j < 3; j++) + s += m[i][j]; + } + + return s; +}`} + language="c" + /> +
+ +
+
Corrections
+ +
    +
  • + Replace{" "} + + for (int i = 0; i <= r; i++) + {" "} + with{" "} + + for (int i = 0; i < r; i++) + +
  • + +
  • + The second dimension in multidimensional arrays must be known. +

- {/* Programming exercise */} + {/* Exercises */}

Programming Exercise

+
    -
  • Write a function to search for a string in an array of strings and return index or -1.
  • -
  • Implement insertion sort on an integer array and state its time complexity.
  • +
  • + Write a function to search a string in an array of strings. +
  • + +
  • + Implement insertion sort and state its time complexity. +
  • + +
  • + Write a recursive Fibonacci program. +
); -}; +}; \ No newline at end of file diff --git a/app/sem1/c/content/chapter5.tsx b/app/sem1/c/content/chapter5.tsx index 581a763..59d9cb3 100644 --- a/app/sem1/c/content/chapter5.tsx +++ b/app/sem1/c/content/chapter5.tsx @@ -1,104 +1,164 @@ import Image from "next/image"; +import { CodeBlock } from "../../../components/CodeBlock"; export const Ch5Content = () => { return (
-

Concise notes on pointers, pointer arithmetic, pointers with arrays/strings/functions/structures, - and user-defined aggregate types (structures and unions) with essential examples and common pitfalls. +

+ Concise notes on pointers, pointer arithmetic, pointers with arrays, + strings, functions, structures, and unions with important examples + and debugging concepts.


- {/* Pointers: basics */} + {/* Pointer Basics */}

Pointers — Basics

    -
  • Pointer variable stores address of another variable. Example declaration: {`int *p;`}.
  • -
  • Initialization: assign address: {`p = &x;`}.
  • -
  • Dereference: access value: {`*p`} (value at address).
  • -
  • Pointer arithmetic: adding 1 advances by size of pointed type: {`p + 1`}.
  • +
  • + Pointer variable stores the address of another variable. +
  • + +
  • + Declaration: + int *p; +
  • + +
  • + Address operator: + &x +
  • + +
  • + Dereference operator: + *p +
  • + +
  • + Pointer arithmetic increments according to datatype size. +
-
-
Pointer example
-
{`int x = 10;
+        
+
+ Pointer Example +
+ + + +printf("%d\\n", *p); + +*p = 20; + +printf("%d", x);`} + language="c" + />
pointer-basics -

- {/* Pointers with arrays & strings */} + {/* Arrays and Strings */}
-

Pointers with Arrays and Strings

+

+ Pointers with Arrays and Strings +

    -
  • Arrays and pointers: array name decays to pointer to first element: {`a`} ~ {`&a[0]`}.
  • -
  • Access via pointer: {`*(a + i)`} equals {`a[i]`}.
  • -
  • Strings: are character arrays; pointers to chars can traverse strings.
  • -
  • Pointer types: type of pointer determines arithmetic increment size.
  • +
  • + Array names behave like pointers to the first element. +
  • + +
  • + a[i] is equivalent to{" "} + *(a + i) +
  • + +
  • + Strings are arrays of characters terminated with{" "} + '\\0' +
  • + +
  • + Pointer datatype determines increment size in memory. +
-
-
Array access via pointer
-
{`int a[5] = {1,2,3,4,5};
-int *p = a; // points to a[0]
-int x = *(p + 2); // x == a[2] == 3`}
+
+
+ Array Access Using Pointer +
+ +
+ + array-pointer

- {/* Pointers and functions */} + {/* Functions */}

Pointers and Functions

    -
  • Pointers as arguments: to modify caller data pass pointer: {`void set(int *p)`}.
  • -
  • Functions returning pointers: return pointer to dynamically allocated memory or static data; avoid returning pointer to local stack variable.
  • -
  • Pointers and functions: use pointers to pass large data (arrays, structures) efficiently.
  • -
+
  • + Pointers allow functions to modify original variables. +
  • -
    -
    Function modifies caller via pointer
    -
    {`void inc(int *p) { (*p)++; }
    +          
  • + Arrays and structures are efficiently passed using pointers. +
  • -int x = 5; -inc(&x); // x becomes 6`}
    -
    -
    +
  • + Avoid returning pointers to local variables. +
  • + -
    +
    +
    + Pass by Reference +
    - {/* Pointers and structures */} -
    -

    Pointers and Structures

    + -
  • Structure access via pointer: use {`->`} operator: {`p->field`} when {`p`} is {`struct`} pointer.
  • -
  • Passing structures: pass pointer to structure for efficiency: {`void f(struct S *p)`}.
  • -
  • Functions returning pointers to structures: return dynamically allocated structure pointers with care.
  • - +int x = 5; + +increment(&x); -
    -
    Structure pointer example
    -
    {`struct Point { int x, y; };
    -struct Point p = {1,2};
    -struct Point *pp = &p;
    -printf("%d\n", pp->x);`}
    +printf("%d", x);`} + language="c" + />
    @@ -109,34 +169,69 @@ printf("%d\n", pp->x);`}

    Structures

      -
    • Definition: aggregate user-defined type: {`struct S { int a; float b; };`}
    • -
    • Declaration/initialization: {`struct S s = {1, 2.5};`}
    • -
    • Array of structures: {`struct S arr[10];`}
    • -
    • Size and alignment: depends on member types and padding; use {`sizeof`} to know size.
    • -
    • Nested structures: structure can contain another structure as a member.
    • -
    • Self-referential structures: used for linked lists: {`struct Node { int val; struct Node *next; };`}
    • +
    • + Structures group variables of different data types. +
    • + +
    • + Members are accessed using dot operator. +
    • + +
    • + Structure pointers use arrow operator{" "} + -> +
    • + +
    • + Self-referential structures are used in linked lists. +
    -
    -
    Structure example
    -
    {`struct Student {
    -  char name[30];
    -  int id;
    -  float gpa;
    +        
    +
    + Structure Example +
    + + +struct Student s = {"Alex", 101, 89.5}; + +printf("%s", s.name);`} + language="c" + /> +
    + +
    +
    + Structure Pointer Example +
    + + x);`} + language="c" + />
    struct-memory -
    @@ -146,68 +241,158 @@ printf("%s\n", s.name);`}

    Unions

      -
    • Union: a data type where all members share the same memory location. Declaration: {`union U { int i; float f; };`}
    • -
    • Size: size of union equals size of its largest member.
    • -
    • Use cases: memory-efficient variants, type punning (careful), embedded systems.
    • -
    • Access: use dot or arrow similar to structures.
    • +
    • + All members of a union share the same memory location. +
    • + +
    • + Size of union equals size of largest member. +
    • + +
    • + Used for memory optimization. +
    -
    -
    Union example
    -
    {`union Number {
    -  int i;
    -  float f;
    +        
    +
    + Union Example +
    + + + +n.f = 5.5; + +printf("%f", n.f);`} + language="c" + />
    + union-layout + + +
    + + {/* Dynamic Memory */} +
    +

    Dynamic Memory Allocation

    + +
      +
    • + Dynamic memory is allocated during runtime using{" "} + malloc() +
    • + +
    • + Memory should always be released using{" "} + free() +
    • + +
    • + Check for NULL after allocation. +
    • +
    + +
    +
    + malloc() Example +
    + + +

    - {/* Debugging exercise */} + {/* Debugging */}

    Debugging Exercise

    -
    -
    Find and fix the errors
    -
    {`#include 
    -#include 
    -
    -int *make_array(int n) {
    -  int a[n]; // local VLA on stack
    -  for (int i = 0; i < n; i++) a[i] = i;
    -  return a; // error: returning address of stack memory
    -}`}
    - -
    Correct points
    -
      -
    • Do not return pointer to local stack array. Allocate with {`malloc`} and return pointer, or pass buffer from caller.
    • -
    • Always check result of {`malloc`} for NULL.
    • +
      +
      + Find and Fix the Errors +
      + + + +int *makeArray() { + + int arr[5] = {1,2,3,4,5}; + + return arr; +}`} + language="c" + /> +
      + +
      +
      + Corrections +
      + +
        +
      • + Never return address of local array variables. +
      • + +
      • + Use dynamic allocation for returning arrays. +
      • + +
      • + Local variables are destroyed after function ends. +

    - {/* Programming Exercise */} + {/* Exercises */}

    Programming Exercise

    +
      -
    • Implement linked list insert/delete using self-referential structures and pointers.
    • -
    • Create a function that returns a dynamically allocated array (use {`malloc`}) and document proper ownership and free semantics.
    • +
    • + Implement linked list insertion using structures and pointers. +
    • + +
    • + Write a function to swap two numbers using pointers. +
    • + +
    • + Create a dynamically allocated integer array. +
    +
    ); -}; +}; \ No newline at end of file diff --git a/app/sem1/c/content/chapter6.tsx b/app/sem1/c/content/chapter6.tsx index 8ba2ade..c96d6c1 100644 --- a/app/sem1/c/content/chapter6.tsx +++ b/app/sem1/c/content/chapter6.tsx @@ -1,4 +1,5 @@ import Image from "next/image"; +import { CodeBlock } from "../../../components/CodeBlock"; export const Ch6Content = () => { return ( @@ -16,20 +17,25 @@ export const Ch6Content = () => {

    File Management and Streams

      -
    • File operations: open, read, write, close using {`fopen`}, {`fclose`}, {`fread`}, {`fwrite`}, {`fseek`}, {`ftell`}.
    • -
    • Streams: standard streams {`stdin`}, {`stdout`}, {`stderr`}.
    • -
    • Command-line arguments: {`int main(int argc, char *argv[])`}, where {`argc`} is count and {`argv`} holds arguments.
    • -
    • Error handling: check return values (e.g., {`fopen`} may return {`NULL`}), use {`perror`} or {`strerror(errno)`}.
    • -
    • Random access: use {`fseek`} and {`ftell`} to move and query file position for binary I/O.
    • +
    • File operations: open, read, write, close using fopen, fclose, fread, fwrite, fseek, ftell.
    • +
    • Streams: stdin, stdout, stderr.
    • +
    • Command-line arguments: int main(int argc, char *argv[]).
    • +
    • Error handling: check return values, use perror.
    File Read (simple)
    -
    {`FILE *fp = fopen("data.bin", "rb");
    +
    +          
    +
    +fclose(fp);`}
    +          />
             
    width={780} height={400} /> - - - -
    - - {/* Command-line & Error */} -
    -

    Command-line Arguments & Error Handling

    - -
      -
    • Access arguments via {`argv[1]`} etc.; convert strings to numbers with {`atoi`}, {`strtol`}.
    • -
    • Always validate {`argc`} and check conversions for errors.
    • -
    • Use {`errno`}, {`perror`} and return non-zero exit code on failure.
    • -

    - {/* Dynamic Memory Allocation */} + {/* Dynamic Memory */}

    Dynamic Memory Allocation

    -
      -
    • malloc: allocate uninitialized block: {`void *malloc(size_t size)`}. Check for {`NULL`}.
    • -
    • calloc: allocate and zero-initialize: {`void *calloc(nmemb, size)`}.
    • -
    • realloc: resize previously allocated block: {`void *realloc(ptr, new_size)`}. Use carefully to avoid leaks.
    • -
    • free: release memory: {`free(ptr)`}. Avoid double-free and use-after-free.
    • -
    -
    -
    Dynamic array (simple)
    -
    {`int *a = malloc(n * sizeof(int));
    +          
    Dynamic array
    + + -
    - malloc-layout +free(a);`} + /> +

    - {/* Linked list basics */} + {/* Linked list */}

    Basic Idea — Linked List

    -
      -
    • Self-referential structure where each node points to next: {`struct Node { int val; struct Node *next; };`}.
    • -
    • Create nodes with {`malloc`}, set fields, and link via pointers; free nodes when removed.
    • -
    • Common ops: insert at head, delete node, traverse; watch for NULL checks.
    • -
    -
    -
    Insert at head (sketch)
    -
    {`struct Node *n = malloc(sizeof *n);
    +          
    Insert at head
    + + val = v; n->next = head; -head = n;`}
    +head = n;`} + />
    + linkedlist width={800} height={350} /> -

    @@ -120,62 +101,40 @@ head = n;`}

    Preprocessor Directives

    -
      -
    • Macro definition: {`#define PI 3.14`} — text substitution before compilation.
    • -
    • Macro substitution: use parentheses in macros to avoid precedence bugs: {`#define SQR(x) ((x)*(x))`}.
    • -
    • File inclusion: {`#include `} or {`#include "file.h"`}.
    • -
    • Conditional compilation: {`#ifdef`}, {`#ifndef`}, {`#if`}, {`#endif`}.
    • -
    -
    Macro example
    -
    {`#define MAX(a,b) ((a) > (b) ? (a) : (b))
    -int m = MAX(x, y);`}
    + + (b) ? (a) : (b)) +int m = MAX(x, y);`} + />

    - {/* Debugging exercise */} + {/* Debugging */}

    Debugging Exercise

    Find and fix the errors
    -
    {`#include 
    +
    +          
     #include 
     
     char *make_message() {
       char buf[64];
       snprintf(buf, sizeof(buf), "hello");
    -  return buf; // error: returning pointer to local stack buffer
    -}`}
    - -
    Correct points
    -
      -
    • Do not return pointer to local buffer. Allocate with {`malloc`} or let caller provide buffer.
    • -
    • Check allocations and use {`free`} to avoid leaks.
    • -
    • Always close files with {`fclose`} even on error paths.
    • -
    + return buf; +}`} + />
    -
    - - {/* Programming exercise */} -
    -

    Programming Exercise

    - -
      -
    • Write a program that reads a binary file of integers and prints statistics (min, max, mean) using {`fread`}.
    • -
    • Implement a simple singly linked list with insert and delete operations using dynamic memory.
    • -
    -
    - -

    - Diagrams to paste: file-i-o.png, malloc-layout.png, linkedlist.png. - This module includes the core points required for college exams. If you want a one-page revision sheet, say "Make Ch6 cheat sheet". -

    ); -}; +}; \ No newline at end of file diff --git a/app/sem2/oops/content/chapter1.tsx b/app/sem2/oops/content/chapter1.tsx index a732d6c..f7dd901 100644 --- a/app/sem2/oops/content/chapter1.tsx +++ b/app/sem2/oops/content/chapter1.tsx @@ -1,3 +1,5 @@ +import { CodeBlock } from "../../../components/CodeBlock"; + export const Ch1Content = () => { return (
    @@ -33,13 +35,16 @@ export const Ch1Content = () => {
    -
    Code Example
    -
    -{`int age = 19;
    +          
    + Code Example +
    + + + />

    @@ -51,7 +56,9 @@ boolean isValid = true;`} {/* Variables & Type Casting */}

    -

    Variables, Type Conversion and Casting

    +

    + Variables, Type Conversion and Casting +

    Java automatically performs widening conversions (small to large type), @@ -59,18 +66,22 @@ boolean isValid = true;`}

      -
    • Widening: int to long, float to double (automatic)
    • -
    • Narrowing: double to int, long to short (explicit cast)
    • +
    • + Widening: int to long, float to double (automatic) +
    • +
    • + Narrowing: double to int, long to short (explicit cast) +
    -
    -{`int a = 10;
    +          
    +          />
             
    @@ -86,12 +97,13 @@ int y = (int) x; // narrowing, y = 9`}

    -
    -{`int[] marks = {85, 90, 75};
    +          
    +          />
             

    @@ -106,16 +118,17 @@ for (int i = 0; i < marks.length; i++) {

    Strings

    - Strings are immutable objects. Java stores them in a special "String pool" - for memory optimization. + Strings are immutable objects. Java stores them in a special + "String pool" for memory optimization.

    -
    -{`String s = "openCSE";
    +          
    +          />
             
    @@ -131,15 +144,17 @@ System.out.println(s.toUpperCase());`}

    -
    -{`int a = 2 + 3 * 4;     // 14
    +          
    +          />
             
    -

    Diagram: operator-precedence-java.png

    +

    + Diagram: operator-precedence-java.png +


    @@ -160,8 +175,8 @@ boolean result = (a < b) && (b < 50);`}
    -
    -{`int n = 7;
    +           0) System.out.println("positive");
    @@ -177,12 +192,14 @@ for (int i = 0; i < 5; i++) {
       if (i == 3) continue;
       System.out.println(i);
     }`}
    -          
    + />
    -

    Diagram: loop-flowcharts.png

    +

    + Diagram: loop-flowcharts.png +

    ); -}; +}; \ No newline at end of file diff --git a/app/sem2/oops/content/chapter2.tsx b/app/sem2/oops/content/chapter2.tsx index e27d7a5..e66d957 100644 --- a/app/sem2/oops/content/chapter2.tsx +++ b/app/sem2/oops/content/chapter2.tsx @@ -1,51 +1,72 @@ +import { CodeBlock } from "../../../components/CodeBlock"; + export const Ch2Content = () => { return (

    - Module II: Classes and Objects. - This module explains how Java organizes programs using classes, objects, - constructors, access control, methods, and common built-in classes. These - concepts form the core of object-oriented programming. + + Module II: Classes and Objects + . + This module explains how Java organizes programs using classes, + objects, constructors, access control, methods, and common built-in + classes. These concepts form the core of object-oriented programming.


    {/* OOP Basics */}
    -

    Object-Oriented Programming Basics

    +

    + Object-Oriented Programming Basics +

    Java is built around OOP principles. The key ideas are:

      -
    • Encapsulation – grouping data and methods inside a class
    • -
    • Abstraction – exposing only essential features to users
    • -
    • Inheritance – reusing and extending existing classes
    • -
    • Polymorphism – performing actions in different ways
    • +
    • + Encapsulation – grouping data and methods inside a class +
    • +
    • + Abstraction – exposing only essential features +
    • +
    • + Inheritance – reusing existing classes +
    • +
    • + Polymorphism – performing actions differently +

    - A class defines structure and behavior. An object is a runtime instance of the class. + A class defines structure and behavior. An object is a runtime + instance of the class.


    - {/* Class Definition */} + {/* Classes and Objects */}
    -

    Classes and Object Creation

    +

    + Classes and Object Creation +

    - A class contains fields (data) and methods (operations). Objects are created - using the new keyword. + A class contains fields (data) and methods (operations). Objects are + created using the{" "} + new keyword.

    -
    Example: Defining and Using a Class
    -
    -{`class Student {
    +          
    + Example: Defining and Using a Class +
    + + { } Student s = new Student(); + s.roll = 101; s.name = "Pushkar"; + s.show();`} -
    + />
    -

    Diagram: class-object-diagram.png

    +

    + Diagram: class-object-diagram.png +


    {/* Constructors */}
    -

    Constructors and Finalizer

    +

    + Constructors and Finalizer +

    - A constructor initializes an object at creation. It has no return type, not even void. - Java supports constructor overloading. + A constructor initializes an object at creation. It has no return + type, not even void. Java supports constructor overloading.

    -
    -{`class Point {
    +          
    +          />
             

    - Java no longer recommends using finalizers. Modern Java uses try-with-resources and - garbage collection. + Java no longer recommends using finalizers. Modern Java uses{" "} + try-with-resources and garbage collection.

    @@ -105,24 +133,32 @@ Point p2 = new Point(5, 8);`} {/* Access Modifiers */}
    -

    Visibility and Access Modifiers

    +

    + Visibility and Access Modifiers +

    -

    Java provides four levels of access control:

    +

    + Java provides four levels of access control: +

    • public – accessible everywhere
    • private – accessible only inside class
    • -
    • protected – class + subclasses + same package
    • -
    • default – class + same package
    • +
    • + protected – class + subclasses + same package +
    • +
    • + default – class + same package +
    -
    -{`class Employee {
    +          
    +          />
             

    - {/* Methods & this */} + {/* Methods */}
    -

    Methods and the this Reference

    +

    + Methods and the this Reference +

    - Methods operate on object data. The this keyword refers to - the current object and resolves naming conflicts. + Methods operate on object data. The{" "} + this keyword refers to the + current object.

    -
    -{`class Box {
    +          
    +          />
             

    - {/* Built-in classes */} + {/* Built-in Classes */}
    -

    Useful Built-in Classes (String, Character, StringBuffer)

    +

    + Useful Built-in Classes + (String, Character, StringBuffer) +

    Java provides several commonly used classes for text processing. @@ -179,21 +221,25 @@ Point p2 = new Point(5, 8);`}

    -
    -{`String name = "Pushkar";
    +          
    +
    +sb.append("CSE");`}
    +          />
             
    -

    Diagram: string-immutability.png

    +

    + Diagram: string-immutability.png +

    ); -}; +}; \ No newline at end of file diff --git a/app/sem2/oops/content/chapter3.tsx b/app/sem2/oops/content/chapter3.tsx index e91526a..7537a0e 100644 --- a/app/sem2/oops/content/chapter3.tsx +++ b/app/sem2/oops/content/chapter3.tsx @@ -1,47 +1,70 @@ +import { CodeBlock } from "../../../components/CodeBlock"; + export const Ch3Content = () => { return (

    - Module III: Inheritance and Polymorphism. - This module introduces how classes can reuse and extend existing functionality, - and how Java resolves overridden methods at runtime. These concepts are central - to object-oriented programming. + + Module III: Inheritance and Polymorphism + . + This module introduces how classes can reuse and extend existing + functionality, and how Java resolves overridden methods at runtime. + These concepts are central to object-oriented programming.


    {/* Inheritance Basics */}
    -

    Understanding Inheritance

    +

    + Understanding Inheritance +

    - Inheritance lets a class (subclass) acquire the properties and methods of another class (superclass). - It promotes code reuse and logical hierarchy. + Inheritance lets a class (subclass) acquire the properties and + methods of another class (superclass). It promotes code reuse and + logical hierarchy.

      -
    • Superclass – the class whose features are inherited
    • -
    • Subclass – the class that extends the superclass
    • -
    • extends keyword is used for inheritance
    • -
    • Java supports single inheritance of classes
    • +
    • + Superclass – the class whose features are inherited +
    • +
    • + Subclass – the class that extends the superclass +
    • +
    • + extends keyword is used for inheritance +
    • +
    • + Java supports single inheritance of classes +
    -
    Simple Inheritance Example
    -
    -{`class Animal {
    -  void eat() { System.out.println("eating"); }
    +          
    + Simple Inheritance Example +
    + + + />

    @@ -53,17 +76,20 @@ d.bark(); // own method`} {/* Super Keyword */}

    -

    Using the super Keyword

    +

    + Using the super Keyword +

    - The super keyword is used to access superclass members: - fields, methods, and constructors. + The super keyword is used to + access superclass members: fields, methods, and constructors.

    -
    -{`class Person {
    +          
    +          />
             
    -

    Diagram: super-call-flow.png

    +

    + Diagram: super-call-flow.png +


    {/* Multilevel Inheritance */}
    -

    Multilevel Hierarchy

    +

    + Multilevel Hierarchy +

    - In multilevel inheritance, a subclass becomes a superclass for another class. - Java supports **multilevel** but not **multiple** inheritance of classes. + In multilevel inheritance, a subclass becomes a superclass for another + class. Java supports multilevel but not multiple inheritance of + classes.

    -
    -{`class A { }
    +           B -> C`}
    -          
    + +class C extends B { } // A -> B -> C`} + />
    -

    Diagram: multilevel-hierarchy.png

    +

    + Diagram: multilevel-hierarchy.png +


    {/* Method Overriding */}
    -

    Method Overriding

    +

    + Method Overriding +

    - When a subclass declares a method with the same name and signature as the - superclass method, it is called overriding. + When a subclass declares a method with the same name and signature as + the superclass method, it is called{" "} + overriding.

    • Used to provide specific implementation
    • -
    • Must have same method name, return type and parameters
    • +
    • + Must have same method name, return type and parameters +
    • Only instance methods can be overridden
    -
    -{`class Shape {
    -  void draw() { System.out.println("drawing shape"); }
    +          
    +          />
             

    - {/* Polymorphism */} + {/* Runtime Polymorphism */}
    -

    Dynamic Method Dispatch (Run-time Polymorphism)

    +

    + Dynamic Method Dispatch + (Run-time Polymorphism) +

    - Runtime polymorphism determines the method to execute based on the actual - object type, not reference type. + Runtime polymorphism determines the method to execute based on the + actual object type, not reference type.

    -
    -{`Shape s = new Circle();  // reference of Shape, object of Circle
    -s.draw();                 // calls Circle's draw (runtime)`}
    -          
    +

    @@ -159,50 +209,72 @@ s.draw(); // calls Circle's draw (runtime)`}


    - {/* final & Object class */} + {/* final Keyword */}
    -

    final Keyword with Inheritance

    +

    + final Keyword with Inheritance +

      -
    • final class – cannot be inherited
    • -
    • final method – cannot be overridden
    • +
    • + final class – cannot be inherited +
    • +
    • + final method – cannot be overridden +
    -
    -{`final class Constants { }       // cannot be extended
    +        
    + + /> +

    - {/* Object class */} + {/* Object Class */}
    -

    The Object Class

    +

    + The Object Class +

    - Every Java class implicitly extends Object, the root of the class hierarchy. + Every Java class implicitly extends{" "} + Object, the root of the class hierarchy. Important methods include:

      -
    • toString() – returns string representation
    • -
    • equals() – compares two objects
    • +
    • + toString() – returns string representation +
    • +
    • + equals() – compares two objects +
    • hashCode()
    • getClass()
    -
    -{`class Demo { }
    +        
    + + /> +
    ); -}; +}; \ No newline at end of file diff --git a/app/sem2/oops/content/chapter4.tsx b/app/sem2/oops/content/chapter4.tsx index a74fc39..6fe1d62 100644 --- a/app/sem2/oops/content/chapter4.tsx +++ b/app/sem2/oops/content/chapter4.tsx @@ -1,37 +1,56 @@ +import { CodeBlock } from "../../../components/CodeBlock"; + export const Ch4Content = () => { return (

    - Module IV: Packages and Interfaces. - This module introduces how Java organizes code into logical units (packages) - and how interfaces define abstract contracts that classes can implement. Both - are essential for modular, maintainable Java programs. + + Module IV: Packages and Interfaces + . + This module introduces how Java organizes code into logical units + (packages) and how interfaces define abstract contracts that classes + can implement. Both are essential for modular, maintainable Java + programs.


    {/* Packages */}
    -

    Understanding Packages

    +

    + Understanding Packages +

    - A package is a collection of related classes and interfaces grouped under a - unique namespace. They help avoid name conflicts and improve program structure. + A package is a collection of related classes and interfaces grouped + under a unique namespace. They help avoid name conflicts and improve + program structure.

      -
    • Built-in packages: java.lang, java.util, java.io, java.awt
    • -
    • User-defined packages: created using the package keyword
    • +
    • + Built-in packages: java.lang, java.util, + java.io, java.awt +
    • + +
    • + User-defined packages: created using the + package keyword +
    -
    Example: Creating and Using a Package
    -
    -{`// file: src/com/demo/Calculator.java
    +          
    + Example: Creating and Using a Package +
    + + + />

    @@ -56,27 +78,37 @@ public class Main {


    - {/* Importing */} + {/* Importing Packages */}
    -

    Importing Packages

    +

    + Importing Packages +

    - The import statement allows classes in one package to be - visible in another file. + The import statement allows + classes in one package to be visible in another file.

      -
    • Specific import: import java.util.ArrayList;
    • -
    • Wildcard import: import java.util.*;
    • +
    • + Specific import:{" "} + import java.util.ArrayList; +
    • + +
    • + Wildcard import:{" "} + import java.util.*; +
    -
    -{`import java.util.ArrayList;
    +           list = new ArrayList<>();
    +
     list.add(5);`}
    -          
    + />
    @@ -84,71 +116,105 @@ list.add(5);`} {/* Interfaces */}
    -

    Interfaces

    +

    + Interfaces +

    - An interface specifies a set of abstract methods that implementing classes must define. - Interfaces support abstraction and multiple inheritance in Java. + An interface specifies a set of abstract methods that implementing + classes must define. Interfaces support abstraction and multiple + inheritance in Java.

      -
    • Methods are abstract by default (before Java 8)
    • -
    • Variables are public, static, and final
    • -
    • A class uses implements to implement an interface
    • +
    • + Methods are abstract by default (before Java 8) +
    • + +
    • + Variables are public, static, and final +
    • + +
    • + A class uses{" "} + implements{" "} + to implement an interface +
    -
    -{`interface Drawable {
    +          
    +          />
             
    -

    Diagram: interface-implementation.png

    +

    + Diagram: interface-implementation.png +


    - {/* Default & Static Methods */} + {/* Default and Static Methods */}
    -

    Default and Static Methods in Interfaces

    +

    + Default and Static Methods in Interfaces +

    - From Java 8 onwards, interfaces can include default and static methods, - allowing common functionality without breaking existing implementations. + From Java 8 onwards, interfaces can include{" "} + default and static methods, + allowing common functionality without breaking existing + implementations.

    -
    -{`interface Vehicle {
    +          
    +          />
             
    @@ -156,19 +222,24 @@ int v = Vehicle.version();`} {/* Final Thoughts */}
    -

    Putting It All Together

    +

    + Putting It All Together +

    - Packages organize code. Interfaces define contracts. When combined, they allow - large Java applications to be structured cleanly and extended easily. This - module prepares the foundation for frameworks, APIs and modular application design. + Packages organize code. Interfaces define contracts. When combined, + they allow large Java applications to be structured cleanly and + extended easily. This module prepares the foundation for frameworks, + APIs and modular application design.

    - Diagrams to add: interface-hierarchy.png, package-namespace.png + Diagrams to add:{" "} + interface-hierarchy.png,{" "} + package-namespace.png

    ); -}; +}; \ No newline at end of file diff --git a/app/sem2/oops/content/chapter5.tsx b/app/sem2/oops/content/chapter5.tsx index 054cc20..8275143 100644 --- a/app/sem2/oops/content/chapter5.tsx +++ b/app/sem2/oops/content/chapter5.tsx @@ -1,62 +1,100 @@ +import { CodeBlock } from "../../../components/CodeBlock"; + export const Ch5Content = () => { return (

    - Module V: Exception Handling. - This module explains how Java deals with unexpected conditions during runtime. - Exception handling ensures that programs do not crash when errors occur and - instead allow controlled recovery. + + Module V: Exception Handling + . + This module explains how Java deals with unexpected conditions during + runtime. Exception handling ensures that programs do not crash when + errors occur and instead allow controlled recovery.


    {/* Fundamentals */}
    -

    Exception Handling Fundamentals

    +

    + Exception Handling Fundamentals +

    - An exception is an event that disrupts the normal flow of the program. - Java uses a robust, object-oriented model for error handling. + An exception is an event that disrupts the normal flow of the + program. Java uses a robust, object-oriented model for error + handling.

      -
    • Exception – indicates runtime errors that can be handled
    • -
    • Error – serious issues not expected to be handled (e.g. OutOfMemoryError)
    • -
    • All exceptions derive from the class Throwable
    • +
    • + Exception – indicates runtime errors that can + be handled +
    • + +
    • + Error – serious issues not expected to be + handled +
    • + +
    • + All exceptions derive from the class{" "} + Throwable +

    - The main advantage of Java's exception system is **separation of error-handling code from normal logic**. + The main advantage of Java's exception system is separation + of error-handling code from normal logic.

    -

    Diagram: exception-hierarchy.png

    +

    + Diagram: exception-hierarchy.png +


    {/* Exception Types */}
    -

    Types of Exceptions

    +

    + Types of Exceptions +

      -
    • Checked exceptions – must be caught or declared (IOException, SQLException)
    • -
    • Unchecked exceptions – inherit from RuntimeException (ArithmeticException, NullPointerException)
    • -
    • Errors – not meant to be handled (StackOverflowError)
    • +
    • + Checked exceptions – must be caught or declared +
    • + +
    • + Unchecked exceptions – inherit from + RuntimeException +
    • + +
    • + Errors – not meant to be handled +
    -
    Unchecked Exception Example
    -
    -{`int x = 10 / 0;   // ArithmeticException`}
    -          
    +
    + Unchecked Exception Example +
    + +
    -
    Checked Exception Example
    -
    -{`FileReader fr = new FileReader("abc.txt");   // must be handled`}
    -          
    +
    + Checked Exception Example +
    + +
    @@ -64,29 +102,43 @@ export const Ch5Content = () => { {/* Try Catch */}
    -

    Using try, catch, and finally

    +

    + Using try, catch, and finally +

    - A try block contains statements that may throw an exception. - catch blocks handle the specific exception types. - The finally block executes whether or not an exception occurs. + A try block contains statements that may throw an + exception. catch blocks handle specific exception + types. The finally block executes whether or not + an exception occurs.

    -
    -{`try {
    +          
    +          />
             
      -
    • Use multiple catch blocks for multiple exception types
    • -
    • finally is often used to close files, connections, or release resources
    • +
    • + Use multiple catch blocks for multiple exception types +
    • + +
    • + finally is often used to + close files or release resources +
    @@ -94,24 +146,30 @@ export const Ch5Content = () => { {/* Throw and Throws */}
    -

    throw and throws

    +

    + throw and throws +

    - throw explicitly throws an exception. - throws declares that a method may throw an exception. + throw explicitly throws an exception. + throws declares that a method may throw an + exception.

    -
    -{`void checkAge(int age) {
    +          
    +          />
             
    @@ -119,9 +177,13 @@ void readFile() throws IOException { {/* Built-in Exceptions */}
    -

    Java’s Built-in Exceptions

    +

    + Java’s Built-in Exceptions +

    -

    Commonly asked in exams:

    +

    + Commonly asked in exams: +

    • ArithmeticException
    • @@ -136,25 +198,32 @@ void readFile() throws IOException { {/* Custom Exceptions */}
      -

      Creating Custom Exceptions

      +

      + Creating Custom Exceptions +

      - User-defined exceptions extend the Exception class. + User-defined exceptions extend the{" "} + Exception class.

      -
      -{`class InvalidMarksException extends Exception {
      +           100)
      +
           throw new InvalidMarksException("Invalid marks");
       }`}
      -          
      + />
      @@ -162,20 +231,25 @@ void check(int m) throws InvalidMarksException { {/* Summary */}
      -

      Summary

      +

      + Summary +

      - Exception handling improves program reliability by allowing controlled - error management. Using try-catch-finally, throwing exceptions, - and understanding the exception class hierarchy are essential skills for - robust Java development. + Exception handling improves program reliability by allowing + controlled error management. Using{" "} + try-catch-finally, throwing exceptions, and + understanding the exception class hierarchy are essential skills + for robust Java development.

      - Diagrams to insert: try-catch-flowchart.png, exception-types-table.png + Diagrams to insert:{" "} + try-catch-flowchart.png,{" "} + exception-types-table.png

    ); -}; +}; \ No newline at end of file diff --git a/app/sem2/oops/content/chapter6.tsx b/app/sem2/oops/content/chapter6.tsx index b10d55d..ec97cab 100644 --- a/app/sem2/oops/content/chapter6.tsx +++ b/app/sem2/oops/content/chapter6.tsx @@ -1,9 +1,13 @@ +import { CodeBlock } from "../../../components/CodeBlock"; + export const Ch6Content = () => { return (

    - Module VI: Threads. + + Module VI: Threads + . This module explains Java’s multithreading model, how threads work, how to create and manage threads, and how to safely share resources.

    @@ -12,18 +16,24 @@ export const Ch6Content = () => { {/* Java Thread Model */}
    -

    The Java Thread Model

    +

    + The Java Thread Model +

    - Multithreading allows multiple parts of a program to run concurrently. - Each part runs in a separate thread. Java provides built-in - support for threading at the language level. + Multithreading allows multiple parts of a program to run + concurrently. Each part runs in a separate{" "} + thread.

    • Thread – a lightweight process
    • -
    • Multithreading – executing multiple threads
    • -
    • Context switching – CPU switching between threads
    • +
    • + Multithreading – executing multiple threads +
    • +
    • + Context switching – CPU switching between threads +

    @@ -33,24 +43,31 @@ export const Ch6Content = () => {


    - {/* Main thread */} + {/* Main Thread */}
    -

    The Main Thread

    +

    + The Main Thread +

    - Every Java program starts with one thread: the main thread. + Every Java program starts with one thread: + the main thread.

    -
    -{`public class MainThreadDemo {
    +          
    +          />
             
    @@ -58,43 +75,62 @@ export const Ch6Content = () => { {/* Creating Threads */}
    -

    Creating Threads

    +

    + Creating Threads +

    Java supports two ways to create threads:

      -
    • Extending the Thread class
    • -
    • Implementing the Runnable interface
    • +
    • + Extending the Thread class +
    • + +
    • + Implementing the Runnable interface +
    -
    Method 1: Extending Thread
    -
    -{`class MyThread extends Thread {
    +          
    + Method 1: Extending Thread +
    + + + />
    -
    Method 2: Implementing Runnable
    -
    -{`class MyTask implements Runnable {
    +          
    + Method 2: Implementing Runnable +
    + + + />

    @@ -106,17 +142,24 @@ t.start();`} {/* Multiple Threads */}

    -

    Creating Multiple Threads

    +

    + Creating Multiple Threads +

    -
    -{`for (int i = 1; i <= 3; i++) {
    +           {
    -    System.out.println("Running: " + Thread.currentThread().getName());
    +
    +    System.out.println(
    +      "Running: " + Thread.currentThread().getName()
    +    );
       });
    +
       t.start();
     }`}
    -          
    + />

    @@ -128,40 +171,55 @@ t.start();`} {/* Thread Priorities */}

    -

    Thread Priorities

    +

    + Thread Priorities +

    - Every thread has a priority (1 to 10). Higher priority increases the chance - of being scheduled first. + Every thread has a priority (1 to 10). Higher priority increases + the chance of being scheduled first.

    -
    -{`Thread t = new Thread(new MyTask());
    -t.setPriority(Thread.MAX_PRIORITY);  // 10`}
    -        
    +
    + +

    {/* Synchronization */}
    -

    Synchronization

    +

    + Synchronization +

    When multiple threads access shared data, race conditions may occur. - Synchronization ensures only one thread accesses critical code at a time. + Synchronization ensures only one thread accesses critical code at a + time.

    -
    -{`class Counter {
    +        
    + + /> +

    - Only one thread can execute a synchronized method or block on an object at once. + Only one thread can execute a synchronized method or block on an + object at once.

    @@ -173,28 +231,40 @@ t.setPriority(Thread.MAX_PRIORITY); // 10`} {/* Interthread Communication */}

    -

    Interthread Communication

    +

    + Interthread Communication +

    - Java provides wait(), notify(), and notifyAll() - for threads to communicate inside synchronized blocks. + Java provides wait(), + notify(), and + notifyAll() for threads to communicate inside + synchronized blocks.

    -
    -{`synchronized(obj) {
    -  obj.wait();       // thread waits
    -  obj.notify();     // wakes one thread
    +        
    + + /> +
    -

    Used in producer-consumer problems and buffering.

    +

    + Used in producer-consumer problems and buffering. +


    - {/* Multithreading use */} + {/* Uses */}
    -

    Using Multithreading

    +

    + Using Multithreading +

    • Parallel computation
    • @@ -208,20 +278,22 @@ t.setPriority(Thread.MAX_PRIORITY); // 10`} {/* Summary */}
      -

      Summary

      +

      + Summary +

      - Threads enable concurrent execution in Java. Learning how to create threads, - synchronize them, and manage communication is essential for advanced Java - programming and real-world applications such as GUI programming, networking, - and server-side processing. + Threads enable concurrent execution in Java. Learning how to create + threads, synchronize them, and manage communication is essential + for advanced Java programming and real-world applications.

      - Add diagrams: thread-cycle.png, synchronization-flow.png + Add diagrams: thread-cycle.png, + synchronization-flow.png

    ); -}; +}; \ No newline at end of file diff --git a/app/sem2/oops/content/chapter7.tsx b/app/sem2/oops/content/chapter7.tsx index 0f599d8..7cad555 100644 --- a/app/sem2/oops/content/chapter7.tsx +++ b/app/sem2/oops/content/chapter7.tsx @@ -1,74 +1,111 @@ +import { CodeBlock } from "../../../components/CodeBlock"; + export const Ch7Content = () => { return (

    - Module VII: Generics. - Generics allow you to create classes, methods, and interfaces that operate on - data of specific types while ensuring type-safety at compile time. They are - widely used in Java Collections, utility classes, and reusable APIs. + + Module VII: Generics + . + Generics allow you to create classes, methods, and interfaces + that operate on specific types while ensuring type-safety at + compile time.


    {/* Basics */}
    -

    Basics of Generics

    +

    + Basics of Generics +

    - Generics enable writing type-independent code. - Instead of using Object or casting manually, - generics ensure compile-time checking. + Generics enable writing type-independent code. + Instead of using{" "} + Object, + generics provide compile-time checking.

    • Eliminates unsafe type casting
    • Enables strong type-checking
    • -
    • Allows reusable, flexible classes and methods
    • +
    • + Allows reusable and flexible classes and methods +
    -
    -{`ArrayList list = new ArrayList<>();
    +           list = new ArrayList<>();
    +
     list.add("hello");
    -// list.add(10);   // compile-time error`}
    -          
    + +// list.add(10); // compile-time error`} + />
    -

    Diagram: generic-type-parameter.png

    +

    + Diagram: generic-type-parameter.png +


    {/* Generic Class */}
    -

    Generic Class

    +

    + Generic Class +

    - A generic class defines one or more type parameters to be used in the class. + A generic class defines one or more type parameters + to be used in the class.

    -
    Example: A Simple Generic Box
    -
    -{`class Box {
    +          
    + Example: A Simple Generic Box +
    + + { + T value; Box(T value) { + this.value = value; } - T get() { return value; } + T get() { + + return value; + } } Box b = new Box<>(100); + System.out.println(b.get());`} -
    + />
      -
    • T, E, K, V are common type parameter names
    • -
    • You can define multiple type parameters, e.g. Box<T, U>
    • +
    • + T, + E, + K, + V + are common type parameter names +
    • + +
    • + Multiple type parameters can be used like{" "} + + Box<T, U> + +
    @@ -76,26 +113,34 @@ System.out.println(b.get());`} {/* Two Type Parameters */}
    -

    Generic Class with Two Type Parameters

    +

    + Generic Class with Two Type Parameters +

    -
    -{`class Pair {
    +           {
    +
       K key;
    +
       V value;
     
       Pair(K key, V value) {
    +
         this.key = key;
    +
         this.value = value;
       }
     }
     
    -Pair p = new Pair<>("age", 20);`}
    -          
    +Pair p = + new Pair<>("age", 20);`} + />

    - Useful in maps, key-value data storage, and utility methods. + Useful in maps, key-value storage, + and utility methods.

    @@ -103,23 +148,29 @@ Pair p = new Pair<>("age", 20);`} {/* Generic Methods */}
    -

    Generic Methods

    +

    + Generic Methods +

    - A method can declare its own type parameter independent of the class. + A method can declare its own type parameter + independent of the class.

    -
    -{`class Utils {
    +           void print(T value) {
    +
         System.out.println(value);
       }
     }
     
     Utils.print("hello");
    +
     Utils.print(123);`}
    -          
    + />

    @@ -131,26 +182,38 @@ Utils.print(123);`} {/* Bounded Type Parameters */}

    -

    Bounded Type Parameters

    +

    + Bounded Type Parameters +

    Bounds restrict the types that can be passed to generics.

    -
    -{`class Numbers {   // only Number subclasses allowed
    +           {
    +
       T num;
    -  Numbers(T num) { this.num = num; }
    +
    +  Numbers(T num) {
    +
    +    this.num = num;
    +  }
     }
     
    -Numbers n1 = new Numbers<>(10);
    -Numbers n2 = new Numbers<>("hi"); // error`}
    -          
    +Numbers n1 = + new Numbers<>(10); + +// error +Numbers n2 = + new Numbers<>("hi");`} + />

    - Bounded generics are widely used in sorting, comparisons, and collections. + Bounded generics are widely used in sorting, + comparisons, and collections.

    @@ -158,23 +221,39 @@ Numbers n2 = new Numbers<>("hi"); // error`} {/* Wildcards */}
    -

    Wildcards

    +

    + Wildcards +

    - Wildcards allow flexibility when working with unknown or partially known types. + Wildcards allow flexibility when working + with unknown or partially known types.

    • ? – unknown type
    • -
    • ? extends T – upper bounded
    • -
    • ? super T – lower bounded
    • + +
    • + ? extends T – upper bounded +
    • + +
    • + ? super T – lower bounded +
    -
    -{`void show(List list) { }           // accepts any type
    -void showNum(List l) // only Number or its subclasses`}
    -          
    + list) { + +} + +void showNum( + List l +) { + +}`} + />

    @@ -184,47 +263,71 @@ void showNum(List l) // only Number or its subclasses`}


    - {/* Erasure */} + {/* Type Erasure */}
    -

    Type Erasure

    +

    + Type Erasure +

    - Java implements generics using type erasure. After compilation, - all generic type information is removed and replaced with raw types. + Java implements generics using{" "} + type erasure. + After compilation, generic type information + is removed and replaced with raw types.

      -
    • Generic type parameters exist only at compile time
    • -
    • Ensures backward compatibility with older Java versions
    • -
    • Restrictions: no primitive generics, no runtime type-checking of generic types
    • +
    • + Generic type parameters exist only at compile time +
    • + +
    • + Ensures backward compatibility +
    • + +
    • + Restrictions include no primitive generics + and no runtime checking of generic types +
    -
    -{`ArrayList a1 = new ArrayList<>();
    -ArrayList a2 = new ArrayList<>();
    +        
    + a1 = + new ArrayList<>(); + +ArrayList a2 = + new ArrayList<>(); -// at runtime: -a1.getClass() == a2.getClass(); // true`} -
    +// at runtime +a1.getClass() == +a2.getClass(); // true`} + /> +

    {/* Summary */}
    -

    Summary

    +

    + Summary +

    - Generics help ensure type-safety and reusable code. Understanding generic - classes, methods, wildcards, and type erasure prepares you for Java Collections, - frameworks, and industry-level application development. + Generics help ensure type-safety and reusable code. + Understanding generic classes, methods, wildcards, + and type erasure prepares you for Java Collections, + frameworks, and enterprise-level development.

    - Diagrams to insert: generic-class-diagram.png, wildcard-usage.png + Diagrams to insert: + generic-class-diagram.png, + wildcard-usage.png

    ); -}; +}; \ No newline at end of file diff --git a/app/sem2/oops/content/chapter8.tsx b/app/sem2/oops/content/chapter8.tsx index 3001f2e..2f9ac5f 100644 --- a/app/sem2/oops/content/chapter8.tsx +++ b/app/sem2/oops/content/chapter8.tsx @@ -1,113 +1,169 @@ +import { CodeBlock } from "../../../components/CodeBlock"; + export const Ch8Content = () => { return (

    - Module VIII: The Java Library and GUI Programming with Swing. - This module introduces essential parts of the Java Standard Library—string handling, - math utilities, collections—and then provides a practical introduction to graphical - programming using Swing components. + + Module VIII: The Java Library and GUI Programming with Swing + . + This module introduces important parts of the Java Standard + Library and provides a practical introduction to GUI + programming using Swing.


    {/* String Handling */}
    -

    String Handling in Java

    +

    + String Handling in Java +

    - Java provides three main classes for working with textual data: - String (immutable), StringBuffer (mutable, synchronized), - and StringBuilder (mutable, unsynchronized). + Java provides three important classes for text handling: + String, + StringBuffer, and + StringBuilder.

      -
    • String objects cannot be changed once created
    • -
    • StringBuffer is used when thread-safety is required
    • -
    • StringBuilder is faster but not synchronized
    • +
    • + String objects are immutable +
    • + +
    • + StringBuffer is mutable and synchronized +
    • + +
    • + StringBuilder is mutable and faster +
    -
    -{`String s = "Hello";
    -String s2 = s.replace("H", "Y"); // new object
    +          
    +          />
             

    - Diagram: string-vs-stringbuffer.png + Diagram: + string-vs-stringbuffer.png


    - {/* Java Lang */} + {/* java.lang */}
    -

    Exploring java.lang

    +

    + Exploring java.lang +

    - The java.lang package is automatically imported and contains - core classes essential to Java programming. + The{" "} + java.lang + package is automatically imported and contains + core Java classes.

    • Math – mathematical functions
    • +
    • Object – root of all classes
    • -
    • System – standard I/O and environment
    • -
    • Wrapper classes: Integer, Double, Character
    • + +
    • + System – standard I/O and environment +
    • + +
    • + Wrapper classes – + Integer, Double, Character +
    -
    -{`double r = Math.sqrt(49);        // 7.0
    -int m = Math.max(5, 12);          // 12
    -char c = Character.toUpperCase('a');`}
    -          
    +

    - Wrapper classes help convert between primitives and objects. + Wrapper classes help convert primitives into objects.


    - {/* Collections Framework */} + {/* Collections */}
    -

    The Collections Framework

    +

    + The Collections Framework +

    - The collections framework provides data structures like lists, sets, - queues, and maps. Generics are heavily used here. + The collections framework provides useful + data structures like lists, sets, queues, + and maps.

    • ArrayList – dynamic array
    • -
    • LinkedList – doubly-linked list
    • -
    • HashSet – stores unique elements
    • -
    • HashMap – key-value storage
    • + +
    • + LinkedList – linked list +
    • + +
    • + HashSet – unique elements +
    • + +
    • + HashMap – key-value storage +
    -
    -{`ArrayList names = new ArrayList<>();
    +           names =
    +  new ArrayList<>();
    +
     names.add("Alice");
    +
     names.add("Bob");
     
    -HashMap marks = new HashMap<>();
    +HashMap marks =
    +  new HashMap<>();
    +
     marks.put("Math", 95);
    +
     marks.put("Physics", 88);`}
    -          
    + />

    - Diagram: collections-hierarchy.png + Diagram: + collections-hierarchy.png

    @@ -115,42 +171,60 @@ marks.put("Physics", 88);`} {/* Swing Intro */}
    -

    Introduction to Swing

    +

    + Introduction to Swing +

    - Swing is Java’s lightweight GUI toolkit built on top of AWT. Components are - platform-independent and provide modern GUI widgets. + Swing is Java’s lightweight GUI toolkit built + on top of AWT.

    • JFrame – main window
    • +
    • JButton – clickable button
    • -
    • JLabel – display text
    • + +
    • JLabel – text display
    • +
    • JTextField – input field
    -
    Simple Swing Program
    -
    -{`import javax.swing.*;
    +          
    + Simple Swing Program +
    + + + />

    - Each Swing program must run on the Event Dispatch Thread (EDT). + Swing applications should run on the + Event Dispatch Thread (EDT).

    @@ -158,31 +232,57 @@ public class FirstGUI { {/* Swing Components */}
    -

    Exploring Swing Components

    +

    + Exploring Swing Components +

      -
    • JPanel – container for grouping components
    • -
    • JMenu, JMenuItem – for building menus
    • -
    • JTextArea – multi-line text box
    • -
    • JScrollPane – adds scrollbars
    • +
    • + JPanel – groups components +
    • + +
    • + JMenu and + JMenuItem – menus +
    • + +
    • + JTextArea – multiline text +
    • + +
    • + JScrollPane – adds scrolling +
    -
    Menu Example
    -
    -{`JFrame f = new JFrame();
    -JMenuBar mb = new JMenuBar();
    -JMenu file = new JMenu("File");
    -JMenuItem exit = new JMenuItem("Exit");
    +          
    + Menu Example +
    + + + />

    - Diagram: swing-components-overview.png + Diagram: + swing-components-overview.png

    @@ -190,21 +290,23 @@ f.setJMenuBar(mb);`} {/* Summary */}
    -

    Summary

    +

    + Summary +

    - This module introduces essential parts of the Java Standard Library and gives - a practical foundation in GUI application development with Swing. Mastering - strings, the math library, collections, and Swing provides the toolkit needed - for building desktop applications and Core Java utilities. + This module introduces important parts of the Java + Standard Library and provides a foundation for + GUI application development using Swing.

    - Add diagrams: awt-vs-swing.png, - swing-event-flow.png + Add diagrams: + awt-vs-swing.png, + swing-event-flow.png

    ); -}; +}; \ No newline at end of file