diff --git a/experiment/procedure.md b/experiment/procedure.md index ac60161..835624c 100644 --- a/experiment/procedure.md +++ b/experiment/procedure.md @@ -1,17 +1,42 @@ -**Call By Value** +This simulation has two modules: -1. Press Start to start the experiment. -2. Press Next to see the execution of the code. -3. Relavant line in the code is shown here. -4. The output of the code is shown in the right. +1. Call By Value +2. Call By Reference -**Call By Reference** +Open the simulation page and click the thumbnail of the module you want to run. -1. Press Start to start the experiment. -2. Press Next to see the execution of the code. -3. Relavant line in the code is shown here. -4. The output of the code is shown in the right. +#### Steps for Call By Value -#### Procedure +1. Click **Start** to begin execution. +2. Observe the first highlighted code line in the Program Code panel. +3. Click **Next** to move to the next execution step. +4. At each step, observe all three panels together: + - **Program Code**: currently executing line is highlighted. + - **Memory Map**: addresses and stored byte values are updated. + - **Code Output / Explanation**: printed output and reasoning for that step. +5. Continue clicking **Next** to trace declaration of `A`, declaration of pointer `P`, assignment `P = &A`, dereferencing `*P`, and update of `A` through pointer. +6. Use **Back** to revisit previous steps and verify how values and addresses change in reverse order. +7. Continue until program execution completes; the simulation resets to initial state for a fresh run. -In this lab you will learn the basic concepts of pointers and addresses. You will also understand the process of memory allocation and passing in reference. +#### Steps for Call By Reference + +1. Click **Start** to begin execution. +2. Click **Next** to step through `main()` and the function call to `swap(&A, &B)`. +3. Observe pointer variables in the swap function (`Pa`, `Pb`) and the temporary variable (`temp`) in the **Memory Map**. +4. Track how dereferencing updates original values: + - `temp = *Pa` + - `*Pa = *Pb` + - `*Pb = temp` +5. Compare **Code Output** before and after swap to confirm that values of `A` and `B` are exchanged in caller memory. +6. Use **Back** to inspect reverse flow and confirm each intermediate memory state. +7. Run till completion to see final swapped values and automatic reset. + +#### What to Verify During Simulation + +1. Every variable occupies a memory address. +2. A pointer stores an address, and dereferencing accesses/modifies value at that address. +3. Passing addresses to a function allows modification of original variables (call by reference behavior). + +**Note for Mobile Users:** + +This simulation is optimized for desktop computers with larger screens and mouse interaction. If you access this experiment on a mobile device, please rotate your device to **landscape mode** for the best experience. Some features may be limited or harder to use on small screens. diff --git a/experiment/references.md b/experiment/references.md index 336d94b..1f98c93 100644 --- a/experiment/references.md +++ b/experiment/references.md @@ -1,2 +1,5 @@ -1. [C pointers](http://www.exforsys.com/tutorials/c-language/c-pointers.html) -2. [Pointer](http://en.wikipedia.org/wiki/Pointer_%28computer_science%29) \ No newline at end of file +1. [Pointers in C - GeeksforGeeks](https://www.geeksforgeeks.org/c/pointers-in-c-and-c-set-1-introduction-arithmetic-and-array/) +2. [cppreference - Pointers (C language)](https://en.cppreference.com/w/c/language/pointer) +3. [cppreference - Dynamic Memory Management (malloc, calloc, realloc, free)](https://en.cppreference.com/w/c/memory) +4. [The C Programming Language (2nd Edition) - Kernighan and Ritchie](https://en.wikipedia.org/wiki/The_C_Programming_Language) +5. [Pointer (Computer Programming) - Wikipedia]() diff --git a/experiment/simulation/simulation/CallByReferencePointers/index.html b/experiment/simulation/simulation/CallByReferencePointers/index.html index 398d835..0c929e0 100644 --- a/experiment/simulation/simulation/CallByReferencePointers/index.html +++ b/experiment/simulation/simulation/CallByReferencePointers/index.html @@ -1,113 +1,227 @@ - + - - - - + + + + + - -
-
Program Code
-
-
 #include<stdio.h>
-
 void main(){
-
  int A = 5, B = 9;
-
  printf('Value of A is %d\n',A);
-
  printf('Value of B is %d\n',B);
-
  swap( &A , &B );
-
  printf('Value of A after swapping is %d\n',A);
-
  printf('Value of B after swapping is %d\n',B);
-
 }
-
    
-
 void swap( int *Pa , int *Pb){
-
  int temp = *Pa;
-
  *Pa = *Pb;
-
  *Pb = temp;
-
 }
-
-
-
-
-
-
-
- -
-
Memory Map
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Address BYTE 1 BYTE 2 BYTE 3 BYTE 4 Variable 
60
56
52
48
44
40
36
32
28
24
20
16
12
- - - - - - - - - - -
8Program Memory
4Program Memory
0Reserved By Os
-
-
-
-
Code Output
-
-
-
-
-
-
Explanation
-
-
-
-
- + +
+
+
+
Program Code
+
+
+
 #include<stdio.h>
+
 void main(){
+
  int A = 5, B = 9;
+
+   printf('Value of A is %d\n',A); +
+
+   printf('Value of B is %d\n',B); +
+
  swap( &A , &B );
+
+   printf('Value of A after swapping is %d\n',A); +
+
+   printf('Value of B after swapping is %d\n',B); +
+
 }
+
    
+
 void swap( int *Pa , int *Pb){
+
  int temp = *Pa;
+
  *Pa = *Pb;
+
  *Pb = temp;
+
 }
+
+
+ +
+
+ + +
+
+ +
+ + +
+
+
+
Memory Map
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Address BYTE 1 BYTE 2 BYTE 3 BYTE 4 Variable 
60
56
52
48
44
40
36
32
28
24
20
16
12
+ + + + + + + + + + + + + + +
8Program Memory
4Program Memory
0Reserved By Os
+ +
+ +
+ +
+
+
+
Code Output
+
+
+
+
+ +
+ +
+
+
+
Explanation
+
+
+
+
+ +
+ + diff --git a/experiment/simulation/simulation/CallByReferencePointers/js/mobile-detection.js b/experiment/simulation/simulation/CallByReferencePointers/js/mobile-detection.js new file mode 100644 index 0000000..c776ca2 --- /dev/null +++ b/experiment/simulation/simulation/CallByReferencePointers/js/mobile-detection.js @@ -0,0 +1,298 @@ +// Mobile Detection and Overlay Script +// This script detects mobile devices and shows a desktop optimization warning + +class MobileDetection { + constructor() { + this.isMobile = this.detectMobile(); + this.overlayShown = false; + this.init(); + } + + detectMobile() { + // Check for mobile user agents + const userAgent = navigator.userAgent || navigator.vendor || window.opera; + + // Mobile device patterns + const mobilePatterns = [ + /Android/i, + /webOS/i, + /iPhone/i, + /iPad/i, + /iPod/i, + /BlackBerry/i, + /Windows Phone/i, + /Opera Mini/i, + /IEMobile/i, + /Mobile/i, + ]; + + // Check screen size (additional check for small screens) + const isSmallScreen = window.innerWidth <= 768 || window.innerHeight <= 600; + + // Check touch capability + const isTouchDevice = + "ontouchstart" in window || navigator.maxTouchPoints > 0; + + // Return true if any mobile pattern matches OR if it's a small touch screen + return ( + mobilePatterns.some((pattern) => pattern.test(userAgent)) || + (isSmallScreen && isTouchDevice) + ); + } + + init() { + if (this.isMobile && !this.overlayShown) { + // Wait for DOM to be ready + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", () => this.showOverlay()); + } else { + this.showOverlay(); + } + } + } + + showOverlay() { + if (this.overlayShown) return; + + this.overlayShown = true; + + // Create overlay HTML + const overlay = document.createElement("div"); + overlay.id = "mobile-warning-overlay"; + overlay.innerHTML = ` +
+
+
+ + + + +
+

Desktop Experience Recommended

+

+ This simulation is optimized for desktop computers with larger screens and mouse interaction.
+ If you continue on mobile, please rotate your device to landscape mode for the best experience.
+ You may experience: +

+
    +
  • • Difficulty interacting with form elements
  • +
  • • Limited screen space for code and controls
  • +
  • • Reduced functionality for input validation
  • +
  • • Suboptimal user experience
  • +
+
+ + +
+ +
+
+ `; + + // Add overlay styles + const styles = ` + + `; + + // Add styles to head + document.head.insertAdjacentHTML("beforeend", styles); + + // Add overlay to body + document.body.appendChild(overlay); + + // Prevent body scrolling + document.body.style.overflow = "hidden"; + } + + continueAnyway() { + this.hideOverlay(); + } + + goBack() { + // Try to go back in history, or redirect to a homepage if available + if (window.history.length > 1) { + window.history.back(); + } else { + // You can customize this to redirect to your main page + alert( + "Please bookmark this page and open it on a desktop computer for the best experience.", + ); + } + } + + hideOverlay() { + const overlay = document.getElementById("mobile-warning-overlay"); + if (overlay) { + overlay.style.animation = "fadeOut 0.3s ease-out forwards"; + setTimeout(() => { + overlay.remove(); + document.body.style.overflow = ""; + }, 300); + } + } +} + +// Add fadeOut animation +document.head.insertAdjacentHTML( + "beforeend", + ` + +`, +); + +// Initialize mobile detection +const mobileDetection = new MobileDetection(); + +// Export for use in other scripts if needed +if (typeof module !== "undefined" && module.exports) { + module.exports = MobileDetection; +} diff --git a/experiment/simulation/simulation/CallByValuePointers/index.html b/experiment/simulation/simulation/CallByValuePointers/index.html index 48e7fa0..46601e6 100644 --- a/experiment/simulation/simulation/CallByValuePointers/index.html +++ b/experiment/simulation/simulation/CallByValuePointers/index.html @@ -3,6 +3,7 @@ + diff --git a/experiment/simulation/simulation/CallByValuePointers/js/mobile-detection.js b/experiment/simulation/simulation/CallByValuePointers/js/mobile-detection.js new file mode 100644 index 0000000..c776ca2 --- /dev/null +++ b/experiment/simulation/simulation/CallByValuePointers/js/mobile-detection.js @@ -0,0 +1,298 @@ +// Mobile Detection and Overlay Script +// This script detects mobile devices and shows a desktop optimization warning + +class MobileDetection { + constructor() { + this.isMobile = this.detectMobile(); + this.overlayShown = false; + this.init(); + } + + detectMobile() { + // Check for mobile user agents + const userAgent = navigator.userAgent || navigator.vendor || window.opera; + + // Mobile device patterns + const mobilePatterns = [ + /Android/i, + /webOS/i, + /iPhone/i, + /iPad/i, + /iPod/i, + /BlackBerry/i, + /Windows Phone/i, + /Opera Mini/i, + /IEMobile/i, + /Mobile/i, + ]; + + // Check screen size (additional check for small screens) + const isSmallScreen = window.innerWidth <= 768 || window.innerHeight <= 600; + + // Check touch capability + const isTouchDevice = + "ontouchstart" in window || navigator.maxTouchPoints > 0; + + // Return true if any mobile pattern matches OR if it's a small touch screen + return ( + mobilePatterns.some((pattern) => pattern.test(userAgent)) || + (isSmallScreen && isTouchDevice) + ); + } + + init() { + if (this.isMobile && !this.overlayShown) { + // Wait for DOM to be ready + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", () => this.showOverlay()); + } else { + this.showOverlay(); + } + } + } + + showOverlay() { + if (this.overlayShown) return; + + this.overlayShown = true; + + // Create overlay HTML + const overlay = document.createElement("div"); + overlay.id = "mobile-warning-overlay"; + overlay.innerHTML = ` +
+
+
+ + + + +
+

Desktop Experience Recommended

+

+ This simulation is optimized for desktop computers with larger screens and mouse interaction.
+ If you continue on mobile, please rotate your device to landscape mode for the best experience.
+ You may experience: +

+
    +
  • • Difficulty interacting with form elements
  • +
  • • Limited screen space for code and controls
  • +
  • • Reduced functionality for input validation
  • +
  • • Suboptimal user experience
  • +
+
+ + +
+ +
+
+ `; + + // Add overlay styles + const styles = ` + + `; + + // Add styles to head + document.head.insertAdjacentHTML("beforeend", styles); + + // Add overlay to body + document.body.appendChild(overlay); + + // Prevent body scrolling + document.body.style.overflow = "hidden"; + } + + continueAnyway() { + this.hideOverlay(); + } + + goBack() { + // Try to go back in history, or redirect to a homepage if available + if (window.history.length > 1) { + window.history.back(); + } else { + // You can customize this to redirect to your main page + alert( + "Please bookmark this page and open it on a desktop computer for the best experience.", + ); + } + } + + hideOverlay() { + const overlay = document.getElementById("mobile-warning-overlay"); + if (overlay) { + overlay.style.animation = "fadeOut 0.3s ease-out forwards"; + setTimeout(() => { + overlay.remove(); + document.body.style.overflow = ""; + }, 300); + } + } +} + +// Add fadeOut animation +document.head.insertAdjacentHTML( + "beforeend", + ` + +`, +); + +// Initialize mobile detection +const mobileDetection = new MobileDetection(); + +// Export for use in other scripts if needed +if (typeof module !== "undefined" && module.exports) { + module.exports = MobileDetection; +} diff --git a/experiment/theory.md b/experiment/theory.md index 515f1a0..d7ee2a2 100644 --- a/experiment/theory.md +++ b/experiment/theory.md @@ -1,54 +1,103 @@ -Pointers are a fundamental concept in C programming that allow variables to store memory addresses of other variables. This enables direct access and manipulation of memory, which is essential for efficient programming and advanced data structures. +Pointers are a fundamental concept in C programming. A pointer stores the memory address of another variable, which allows direct access to data in memory. This is essential for writing efficient programs, passing data to functions, and building dynamic data structures. -#### Declaring and Using Pointers +#### Memory Address of Variables -A pointer is declared by placing an asterisk (\*) before its name. For example: +Every variable is stored at some memory location. +```c +int A = 10; ``` -int *ptr; -``` -This declares a pointer to an integer. You can assign the address of a variable to a pointer using the address-of operator (&): +Here, `A` has: + +1. A value (`10`) +2. An address (obtained using `&A`) + +In the simulation, this is shown in the **Memory Map** where variable names, addresses, and bytes are displayed together. + +#### Declaring, Referencing, and Dereferencing Pointers +A pointer is declared using `*`: + +```c +int *P; ``` -int var = 5; -ptr = &var; + +Assign an address to the pointer using `&` (address-of operator): + +```c +P = &A; ``` -Now, `ptr` holds the address of `var`. To access the value stored at that address (dereferencing), use the asterisk: +Now `P` stores the address of `A`. Dereferencing accesses the value at that address: +```c + +printf("%d\n", *P); +*P = 20; ``` -printf("%d\n", *ptr); // prints 5 + +After `*P = 20`, the value of `A` also becomes `20` because `P` points to `A`. + +#### Call by Value vs Call by Reference (Simulation Context) + +In **Call By Value**, a function receives copies of values. Modifying copies does not change original variables in the caller. + +In **Call By Reference** (using pointers), a function receives addresses of variables: + +```c +swap(&A, &B); ``` +Inside the function, pointer parameters dereference those addresses and modify original data. That is why values of `A` and `B` get swapped in caller memory. + +This directly demonstrates pointer referencing (`&`) and dereferencing (`*`) in practical function design. + #### Pointers and Arrays -Arrays are closely related to pointers. The name of an array acts as a constant pointer to its first element. For example: +Array name behaves like a pointer to the first element. -``` +```c int arr[100]; ``` -Here, `arr` is equivalent to a pointer to the first element. Accessing `arr[3]` is the same as `*(arr + 3)`. +`arr[3]` and `*(arr + 3)` refer to the same element. Pointer arithmetic advances by element size, not by one byte for all types. #### Dynamic Memory Allocation -Pointers are essential for dynamic memory allocation. Using the `malloc()` function from `stdlib.h`, you can allocate memory at runtime: +Pointers are required to allocate memory at runtime. -``` -int *ptr = (int *)malloc(20 * sizeof(int)); +```c + +#include + +int n = 20; +int *ptr = (int *)malloc(n * sizeof(int)); ``` -This allocates space for 20 integers and stores the address in `ptr`. +`malloc` returns the starting address of allocated memory. This address is stored in the pointer. -#### Pointer Arithmetic +Always check allocation and free memory after use: -Pointers support arithmetic operations. Adding 1 to an integer pointer moves it to the next integer (skipping 4 bytes), while adding 1 to a char pointer moves it by 1 byte. This is useful for iterating through arrays and managing memory. +```c -#### Applications of Pointers +if (ptr == NULL) { + // allocation failed +} -Pointers allow functions to modify variables directly, enable the creation of dynamic data structures like linked lists, and are crucial for efficient memory management in C. +free(ptr); +ptr = NULL; +``` - +This is important for safe and correct C programming. + +#### Why Pointers Matter -Arithmatical operations like addition and subtraction can be performed to a pointer. The nature of these arithmatic operations is what distinguishes an integer pointer from, say, a character pointer, which otherwise just store memory addresses for another variable. Adding one to an interger pointer makes to point to the next integer, and hence, it skips 4 bytes. Adding one to a character pointer makes it to point to the next character, and hence, it skips only 1 byte. Hence, for the array arr, writing arr[3] is equivalent to writing \*(arr+3). Both refer to the value stored in the 4th cell of the array. +Pointers are used to: + +1. Access variable addresses directly. +2. Implement call by reference behavior in functions. +3. Create dynamic arrays, linked lists, trees, and other structures. +4. Manage memory efficiently in systems-level programming. + +