Show description
CSE240: Programming Language Concepts
CSE240: Programming Language Concepts
☰
Course Navigation
Introduction
Module 1: Data Types
1.1: Common Terminology
1.2: Type Equivalence
1.3: Strong vs Weak Typing
1.4: Orthogonality
Module 2: C/C++ I/O
2.1: Imperative Paradigm
2.2: Program Structure
2.3: Basic I/O
2.4: Formatted I/O
2.5: Unformatted I/O
2.6: Data Storage
2.7: Scoping Rules
Module 3: Data Types
3.1: Primitive Types
3.2: Memory Addressing
3.3: Byte Addressable Memory
3.4: C-Style Strings
3.5: String Manipulation
CSE240: Programming Language Concepts
Data Types and C/C++ Fundamentals
Welcome to this comprehensive course on programming language concepts, focusing on data types and fundamental C/C++ programming. This course will provide you with a solid foundation in understanding how programming languages handle data and how to effectively program in C and C++.
Course Overview
This module covers three main learning objectives:
LO1: Data typing terminology and approaches
LO2: Basic I/O development in C and C++
LO3: Working with basic data types and C-style strings
Learning Philosophy
Programming is best learned through hands-on practice. As you progress through this course:
Read each section carefully
Run the provided code examples
Experiment with modifications
Predict outcomes before testing
Build your mental model of how code works
💡 Pro Tip
Don't just read code—tinker with it! Try removing features, adding new ones, or combining concepts. This empirical approach will dramatically improve your understanding.
Module 1: Data Types and Terminology
Understanding data types is fundamental to programming language design and usage. This module explores the terminology, approaches, and concepts that underpin how programming languages handle different kinds of data.
Module Objectives
Master common terminology for types
Understand type equivalence concepts
Distinguish between strong and weak typing
Appreciate orthogonality in language design
1.1: Common Terminology for Types
Before diving into programming with types, we need to establish a common vocabulary.…
CSE240: Programming Language Concepts
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSE240: Programming Language Concepts</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 100%);
color: #e0e0e0;
line-height: 1.6;
}
.container {
display: flex;
min-height: 100vh;
}
.sidebar {
width: 300px;
background: rgba(22, 27, 34, 0.95);
backdrop-filter: blur(10px);
padding: 20px;
border-right: 2px solid #2563eb;
position: fixed;
height: 100vh;
overflow-y: auto;
z-index: 100;
}
.sidebar h2 {
color: #60a5fa;
margin-bottom: 20px;
font-size: 1.2em;
border-bottom: 2px solid #3b82f6;
padding-bottom: 10px;
}
.nav-item {
display: block;
padding: 10px 15px;
margin: 5px 0;
background: rgba(37, 99, 235, 0.1);
border: 1px solid rgba(37, 99, 235, 0.3);
border-radius: 6px;
color: #cbd5e1;
text-decoration: none;
transition: all 0.3s ease;
cursor: pointer;
}
.nav-item:hover {
background: rgba(37, 99, 235, 0.3);
color: #60a5fa;
transform: translateX(5px);
}
.nav-item.active {
background: rgba(37, 99, 235, 0.5);
color: #ffffff;
border-color: #3b82f6;
}
.main-content {
flex: 1;
margin-left: 300px;
padding: 40px;
max-width: 1200px;
}
.section {
display: none;
margin-bottom: 40px;
}
.section.active {
display: block;
animation: fadeIn 0.5s ease-in;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
h1 {
color: #60a5fa;
font-size: 2.5em;
margin-bottom: 30px;
text-align: center;
background: linear-gradient(45deg, #3b82f6, #60a5fa);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
h2 {
color: #93c5fd;
font-size: 2em;
margin: 30px 0 20px 0;
border-left: 4px solid #3b82f6;
padding-left: 15px;
}
h3 {
color: #a5b4fc;
font-size: 1.5em;
margin: 25px 0 15px 0;
}
h4 {
color: #c7d2fe;
font-size: 1.2em;
margin: 20px 0 10px 0;
}
p {
margin-bottom: 15px;
color: #d1d5db;
}
.code-block {
background: rgba(15, 23, 42, 0.8);
border: 1px solid #334155;
border-radius: 8px;
padding: 20px;
margin: 20px 0;
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
overflow-x: auto;
position: relative;
}
.code-block::before {
content: "C/C++";
position: absolute;
top: 5px;
right: 10px;
background: #3b82f6;
color: white;
padding: 2px 8px;
border-radius: 4px;
font-size: 0.8em;
}
.code-block code {
color: #94a3b8;
}
.highlight {
background: rgba(59, 130, 246, 0.2);
padding: 2px 4px;
border-radius: 3px;
color: #60a5fa;
}
.info-box {
background: rgba(37, 99, 235, 0.1);
border-left: 4px solid #3b82f6;
padding: 20px;
margin: 20px 0;
border-radius: 0 8px 8px 0;
}
.warning-box {
background: rgba(245, 101, 101, 0.1);
border-left: 4px solid #ef4444;
padding: 20px;
margin: 20px 0;
border-radius: 0 8px 8px 0;
}
.example-box {
background: rgba(16, 185, 129, 0.1);
border-left: 4px solid #10b981;
padding: 20px;
margin: 20px 0;
border-radius: 0 8px 8px 0;
}
ul, ol {
margin-left: 30px;
margin-bottom: 15px;
}
li {
margin-bottom: 8px;
color: #d1d5db;
}
.interactive-demo {
background: rgba(30, 41, 59, 0.8);
border: 2px solid #3b82f6;
border-radius: 10px;
padding: 20px;
margin: 20px 0;
}
.demo-input {
background: rgba(15, 23, 42, 0.9);
border: 1px solid #475569;
color: #e2e8f0;
padding: 10px;
border-radius: 5px;
width: 100%;
margin: 10px 0;
}
.demo-button {
background: #3b82f6;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s ease;
}
.demo-button:hover {
background: #2563eb;
transform: translateY(-2px);
}
.demo-output {
background: rgba(15, 23, 42, 0.9);
border: 1px solid #10b981;
color: #34d399;
padding: 15px;
border-radius: 5px;
margin-top: 15px;
font-family: monospace;
white-space: pre-wrap;
}
.progress-bar {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 4px;
background: rgba(37, 99, 235, 0.3);
z-index: 1000;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, #3b82f6, #60a5fa);
width: 0;
transition: width 0.3s ease;
}
.mobile-nav-toggle {
display: none;
position: fixed;
top: 20px;
left: 20px;
z-index: 1001;
background: #3b82f6;
color: white;
border: none;
padding: 10px;
border-radius: 5px;
cursor: pointer;
}
@media (max-width: 768px) {
.mobile-nav-toggle {
display: block;
}
.sidebar {
transform: translateX(-100%);
transition: transform 0.3s ease;
}
.sidebar.open {
transform: translateX(0);
}
.main-content {
margin-left: 0;
padding: 20px;
}
}
</style>
</head>
<body>
<div class="progress-bar">
<div class="progress-fill" id="progressFill"></div>
</div>
<button class="mobile-nav-toggle" onclick="toggleSidebar()">☰</button>
<div class="container">
<nav class="sidebar" id="sidebar">
<h2>Course Navigation</h2>
<a href="#" class="nav-item active" data-section="intro">Introduction</a>
<a href="#" class="nav-item" data-section="lo1">Module 1: Data Types</a>
<a href="#" class="nav-item" data-section="lo1-1">1.1: Common Terminology</a>
<a href="#" class="nav-item" data-section="lo1-2">1.2: Type Equivalence</a>
<a href="#" class="nav-item" data-section="lo1-3">1.3: Strong vs Weak Typing</a>
<a href="#" class="nav-item" data-section="lo1-4">1.4: Orthogonality</a>
<a href="#" class="nav-item" data-section="lo2">Module 2: C/C++ I/O</a>
<a href="#" class="nav-item" data-section="lo2-1">2.1: Imperative Paradigm</a>
<a href="#" class="nav-item" data-section="lo2-2">2.2: Program Structure</a>
<a href="#" class="nav-item" data-section="lo2-3">2.3: Basic I/O</a>
<a href="#" class="nav-item" data-section="lo2-4">2.4: Formatted I/O</a>
<a href="#" class="nav-item" data-section="lo2-5">2.5: Unformatted I/O</a>
<a href="#" class="nav-item" data-section="lo2-6">2.6: Data Storage</a>
<a href="#" class="nav-item" data-section="lo2-7">2.7: Scoping Rules</a>
<a href="#" class="nav-item" data-section="lo3">Module 3: Data Types</a>
<a href="#" class="nav-item" data-section="lo3-1">3.1: Primitive Types</a>
<a href="#" class="nav-item" data-section="lo3-2">3.2: Memory Addressing</a>
<a href="#" class="nav-item" data-section="lo3-3">3.3: Byte Addressable Memory</a>
<a href="#" class="nav-item" data-section="lo3-4">3.4: C-Style Strings</a>
<a href="#" class="nav-item" data-section="lo3-5">3.5: String Manipulation</a>
</nav>
<main class="main-content">
<!-- Introduction Section -->
<section id="intro" class="section active">
<h1>CSE240: Programming Language Concepts</h1>
<h2>Data Types and C/C++ Fundamentals</h2>
<p>Welcome to this comprehensive course on programming language concepts, focusing on data types and fundamental C/C++ programming. This course will provide you with a solid foundation in understanding how programming languages handle data and how to effectively program in C and C++.</p>
<div class="info-box">
<h3>Course Overview</h3>
<p>This module covers three main learning objectives:</p>
<ul>
<li><strong>LO1:</strong> Data typing terminology and approaches</li>
<li><strong>LO2:</strong> Basic I/O development in C and C++</li>
<li><strong>LO3:</strong> Working with basic data types and C-style strings</li>
</ul>
</div>
<h3>Learning Philosophy</h3>
<p>Programming is best learned through hands-on practice. As you progress through this course:</p>
<ol>
<li>Read each section carefully</li>
<li>Run the provided code examples</li>
<li>Experiment with modifications</li>
<li>Predict outcomes before testing</li>
<li>Build your mental model of how code works</li>
</ol>
<div class="example-box">
<h4>💡 Pro Tip</h4>
<p>Don't just read code—tinker with it! Try removing features, adding new ones, or combining concepts. This empirical approach will dramatically improve your understanding.</p>
</div>
</section>
<!-- Module 1: Data Types -->
<section id="lo1" class="section">
<h1>Module 1: Data Types and Terminology</h1>
<p>Understanding data types is fundamental to programming language design and usage. This module explores the terminology, approaches, and concepts that underpin how programming languages handle different kinds of data.</p>
<div class="info-box">
<h3>Module Objectives</h3>
<ul>
<li>Master common terminology for types</li>
<li>Understand type equivalence concepts</li>
<li>Distinguish between strong and weak typing</li>
<li>Appreciate orthogonality in language design</li>
</ul>
</div>
</section>
<!-- LO1.1: Common Terminology -->
<section id="lo1-1" class="section">
<h2>1.1: Common Terminology for Types</h2>
<p>Before diving into programming with types, we need to establish a common vocabulary. Understanding these terms will help you communicate effectively about programming languages and their type systems.</p>
<h3>What is a Type?</h3>
<p>A <span class="highlight">type</span> is a classification of data that tells the compiler or interpreter how the programmer intends to use the data. Types determine:</p>
<ul>
<li>What values are possible</li>
<li>What operations can be performed</li>
<li>How much memory is required</li>
<li>How the data is represented in memory</li>
</ul>
<h3>Key Terminology</h3>
<h4>Primitive Types</h4>
<p><span class="highlight">Primitive types</span> are the basic data types provided by a programming language. They are not composed of other types.</p>
<div class="code-block">
<code>// Examples of primitive types in C
int age = 25; // Integer type
float temperature = 98.6f; // Floating-point type
char grade = 'A'; // Character type
</code>
</div>
<h4>Composite Types</h4>
<p><span class="highlight">Composite types</span> are constructed from one or more primitive or other composite types.</p>
<div class="code-block">
<code>// Examples of composite types in C
int numbers[10]; // Array type
struct Point { // Structure type
float x, y;
};
</code>
</div>
<h4>Type System</h4>
<p>A <span class="highlight">type system</span> is a logical system comprising a set of rules that assigns a property called a type to every expression in a programming language.</p>
<div class="info-box">
<h4>Static vs Dynamic Typing</h4>
<ul>
<li><strong>Static Typing:</strong> Types are determined at compile time (C, C++, Java)</li>
<li><strong>Dynamic Typing:</strong> Types are determined at runtime (Python, JavaScript)</li>
</ul>
</div>
<h4>Type Declaration vs Type Inference</h4>
<p><span class="highlight">Type declaration</span> requires the programmer to explicitly specify the type, while <span class="highlight">type inference</span> allows the compiler to deduce the type automatically.</p>
<div class="code-block">
<code>// Explicit type declaration in C
int count = 10;
// Type inference in C++ (auto keyword)
auto count = 10; // Compiler infers int type
</code>
</div>
<div class="interactive-demo">
<h4>Interactive Type Explorer</h4>
<p>Enter a value and see how it might be typed:</p>
<input type="text" id="typeInput" class="demo-input" placeholder="Enter a value (e.g., 42, 3.14, 'A')" />
<button class="demo-button" onclick="analyzeType()">Analyze Type</button>
<div id="typeOutput" class="demo-output"></div>
</div>
</section>
<!-- LO1.2: Type Equivalence -->
<section id="lo1-2" class="section">
<h2>1.2: Structural and Name Equivalence</h2>
<p>When are two types considered equivalent? This question is crucial for type checking and determines when assignments and parameter passing are allowed.</p>
<h3>Name Equivalence</h3>
<p><span class="highlight">Name equivalence</span> means two types are equivalent only if they have the same name. This is the strictest form of type equivalence.</p>
<div class="code-block">
<code>// Example of name equivalence issues
typedef int Celsius;
typedef int Fahrenheit;
Celsius temp1 = 25;
Fahrenheit temp2 = 77;
// In strict name equivalence, this would be an error:
// temp1 = temp2; // Different type names!
</code>
</div>
<h3>Structural Equivalence</h3>
<p><span class="highlight">Structural equivalence</span> means two types are equivalent if they have the same structure, regardless of their names.</p>
<div class="code-block">
<code>// Structural equivalence example
struct Point2D_A {
float x, y;
};
struct Point2D_B {
float x, y;
};
// These would be structurally equivalent
// (same structure, different names)
</code>
</div>
<div class="warning-box">
<h4>⚠️ C/C++ Type Equivalence</h4>
<p>C and C++ use name equivalence for user-defined types (structs, unions, enums) but structural equivalence for built-in types and pointers.</p>
</div>
<h3>Implications of Type Equivalence</h3>
<h4>Assignment Compatibility</h4>
<p>Type equivalence determines when assignments are valid:</p>
<div class="code-block">
<code>// C example showing type compatibility
int a = 10;
float b = 3.14f;
a = b; // Usually allowed (with possible warning)
// Involves implicit conversion
</code>
</div>
<h4>Function Parameter Matching</h4>
<p>Function calls must match parameter types according to the language's equivalence rules:</p>
<div class="code-block">
<code>void process_temperature(Celsius temp) {
printf("Temperature: %d°C\n", temp);
}
Fahrenheit f_temp = 77;
// process_temperature(f_temp); // May be error under strict name equivalence
</code>
</div>
<div class="example-box">
<h4>Real-World Application</h4>
<p>Understanding type equivalence helps you design APIs that are both type-safe and flexible. Many bugs occur when programmers assume structural equivalence but the language enforces name equivalence.</p>
</div>
</section>
<!-- LO1.3: Strong vs Weak Typing -->
<section id="lo1-3" class="section">
<h2>1.3: Strong versus Weak Type Checking</h2>
<p>The strength of a type system determines how strictly the language enforces type rules and how it handles type mismatches.</p>
<h3>Strong Typing</h3>
<p><span class="highlight">Strong typing</span> means the language prevents type errors by restricting or forbidding implicit conversions between different types.</p>
<div class="info-box">
<h4>Characteristics of Strong Typing:</h4>
<ul>
<li>Type errors are caught at compile time or runtime</li>
<li>Implicit conversions are limited</li>
<li>Type safety is prioritized</li>
<li>Programs are more predictable</li>
</ul>
</div>
<div class="code-block">
<code>// Example: Java (strongly typed)
String name = "Alice";
int age = 25;
// String result = name + age; // Error in strongly typed system
String result = name + String.valueOf(age); // Explicit conversion required
</code>
</div>
<h3>Weak Typing</h3>
<p><span class="highlight">Weak typing</span> allows more implicit conversions between types, potentially leading to unexpected behavior.</p>
<div class="warning-box">
<h4>Characteristics of Weak Typing:</h4>
<ul>
<li>More implicit conversions allowed</li>
<li>Flexibility over safety</li>
<li>Potential for subtle bugs</li>
<li>May require runtime type checking</li>
</ul>
</div>
<div class="code-block">
<code>// Example: C (relatively weakly typed)
char ch = 'A';
int ascii_val = ch; // Implicit conversion allowed
printf("%d\n", ascii_val); // Prints 65
// Pointer conversions (dangerous!)
void* ptr = malloc(sizeof(int));
int* int_ptr = ptr; // Implicit conversion from void*
</code>
</div>
<h3>C and C++ on the Spectrum</h3>
<p>C and C++ fall somewhere in the middle of the strong/weak typing spectrum:</p>
<h4>C: Moderately Weak</h4>
<ul>
<li>Allows many implicit conversions</li>
<li>Pointer arithmetic and void* conversions</li>
<li>Limited compile-time type checking</li>
</ul>
<h4>C++: Stronger than C</h4>
<ul>
<li>More restrictive than C</li>
<li>Better type checking</li>
<li>Templates provide type safety</li>
<li>Still allows some dangerous operations</li>
</ul>
<div class="code-block">
<code>// C++ being stricter than C
#include <iostream>
int main() {
void* ptr = malloc(sizeof(int));
// int* iptr = ptr; // Error in C++, OK in C
int* iptr = static_cast<int*>(ptr); // Explicit cast required
return 0;
}
</code>
</div>
<div class="interactive-demo">
<h4>Type Conversion Tester</h4>
<p>See how C handles different type conversions:</p>
<select id="fromType" class="demo-input">
<option value="int">int</option>
<option value="float">float</option>
<option value="char">char</option>
<option value="double">double</option>
</select>
<span style="color: #60a5fa; margin: 0 10px;">→</span>
<select id="toType" class="demo-input">
<option value="int">int</option>
<option value="float">float</option>
<option value="char">char</option>
<option value="double">double</option>
</select>
<button class="demo-button" onclick="checkConversion()">Check Conversion</button>
<div id="conversionOutput" class="demo-output"></div>
</div>
</section>
<!-- LO1.4: Orthogonality -->
<section id="lo1-4" class="section">
<h2>1.4: Orthogonality in Language Design</h2>
<p>Orthogonality is a principle from mathematics applied to programming language design. It refers to the ability to combine language features in all possible ways without restrictions or unexpected interactions.</p>
<h3>What is Orthogonality?</h3>
<p><span class="highlight">Orthogonality</span> in programming languages means that language features can be combined freely without arbitrary restrictions. A highly orthogonal language has:</p>
<ul>
<li>Few restrictions on how features combine</li>
<li>Consistent behavior across contexts</li>
<li>Minimal special cases</li>
<li>Predictable feature interactions</li>
</ul>
<h3>Benefits of Orthogonality</h3>
<div class="info-box">
<h4>Advantages:</h4>
<ul>
<li><strong>Simplicity:</strong> Fewer rules to remember</li>
<li><strong>Regularity:</strong> Consistent patterns</li>
<li><strong>Expressiveness:</strong> More ways to express ideas</li>
<li><strong>Learnability:</strong> Easier to master the language</li>
</ul>
</div>
<h3>Examples of Orthogonality</h3>
<h4>Orthogonal: Pascal Arrays</h4>
<div class="code-block">
<code>// Pascal - highly orthogonal
var
int_array: array[1..10] of integer;
real_array: array[1..10] of real;
char_array: array[1..10] of char;
// Arrays can be of ANY type - fully orthogonal
</code>
</div>
<h4>Less Orthogonal: C Arrays</h4>
<div class="code-block">
<code>// C - less orthogonal due to restrictions
int int_array[10]; // OK
float float_array[10]; // OK
// int variable_array[n]; // Not allowed in older C (VLA added in C99)
// Functions cannot return arrays directly
// int[10] get_array(); // Error - not orthogonal
</code>
</div>
<h3>Orthogonality vs Simplicity Trade-off</h3>
<p>While orthogonality generally improves language design, perfect orthogonality can sometimes lead to complexity:</p>
<div class="warning-box">
<h4>⚠️ Potential Issues</h4>
<ul>
<li>Too much flexibility can be overwhelming</li>
<li>Some combinations might be inefficient</li>
<li>Error checking becomes more complex</li>
<li>Implementation complexity increases</li>
</ul>
</div>
<h3>C/C++ Orthogonality Analysis</h3>
<h4>Areas of Good Orthogonality:</h4>
<ul>
<li>Pointers can point to any type</li>
<li>Most operators work with compatible types</li>
<li>Functions can take most types as parameters</li>
</ul>
<h4>Areas of Poor Orthogonality:</h4>
<ul>
<li>Arrays and functions have special rules</li>
<li>void type has restrictions</li>
<li>Some operators don't work with all types</li>
</ul>
<div class="code-block">
<code>// C orthogonality examples
int x = 5;
int *ptr = &x; // Can take address of variable
// int *ptr2 = &(x + 1); // Cannot take address of expression
// Good orthogonality: pointers to any type
char *char_ptr;
float *float_ptr;
struct Point *point_ptr;
// Poor orthogonality: array limitations
int arr[10];
// sizeof(arr[10]) works, but sizeof(parameter_array) in function doesn't
</code>
</div>
<div class="example-box">
<h4>Design Lesson</h4>
<p>When designing systems or APIs, strive for orthogonality where it makes sense. This makes your code more predictable and easier to use, but don't sacrifice performance or safety for perfect orthogonality.</p>
</div>
</section>
<!-- Module 2: C/C++ I/O -->
<section id="lo2" class="section">
<h1>Module 2: C and C++ Basic I/O</h1>
<p>This module introduces you to programming in C and C++, focusing on input and output operations. You'll learn the fundamental structure of programs and how to interact with users through the console.</p>
<div class="info-box">
<h3>Module Objectives</h3>
<ul>
<li>Understand C/C++ as imperative languages</li>
<li>Master basic program structure</li>
<li>Implement console I/O operations</li>
<li>Use formatted and unformatted I/O functions</li>
<li>Understand data storage and scoping</li>
</ul>
</div>
</section>
<!-- LO2.1: Imperative Paradigm -->
<section id="lo2-1" class="section">
<h2>2.1: C and C++ as Imperative Languages</h2>
<p>C and C++ are primarily <span class="highlight">imperative programming languages</span>. Understanding this paradigm is crucial for effective programming in these languages.</p>
<h3>What is Imperative Programming?</h3>
<p>Imperative programming is a programming paradigm that describes computation in terms of statements that change program state. It focuses on:</p>
<ul>
<li><strong>How</strong> to solve a problem (not just what the solution is)</li>
<li>Step-by-step instructions</li>
<li>Mutable state and variables</li>
<li>Control flow structures (loops, conditionals)</li>
</ul>
<h3>Key Characteristics of Imperative Languages</h3>
<h4>1. Sequential Execution</h4>
<p>Statements are executed in order, one after another:</p>
<div class="code-block">
<code>#include <stdio.h>
int main() {
int x = 10; // Step 1: Assign 10 to x
int y = 20; // Step 2: Assign 20 to y
int sum = x + y; // Step 3: Calculate sum
printf("Sum: %d\n", sum); // Step 4: Print result
return 0; // Step 5: Exit program
}
</code>
</div>
<h4>2. Mutable State</h4>
<p>Variables can be modified after creation:</p>
<div class="code-block">
<code>int counter = 0; // Initial state
counter = counter + 1; // Modify state
counter += 1; // Another modification
counter++; // Yet another way to modify
</code>
</div>
<h4>3. Control Flow</h4>
<p>Programs use control structures to determine execution path:</p>
<div class="code-block">
<code>// Conditional execution
if (temperature > 100) {
printf("Water boils\n");
} else {
printf("Water is liquid\n");
}
// Repetitive execution
for (int i = 0; i < 10; i++) {
printf("Count: %d\n", i);
}
</code>
</div>
<h3>Imperative vs Other Paradigms</h3>
<div class="info-box">
<h4>Paradigm Comparison</h4>
<ul>
<li><strong>Imperative:</strong> Focus on how (C, C++, Java)</li>
<li><strong>Declarative:</strong> Focus on what (SQL, HTML)</li>
<li><strong>Functional:</strong> Focus on functions (Haskell, Lisp)</li>
<li><strong>Object-Oriented:</strong> Focus on objects (C++, Java)</li>
</ul>
</div>
<h3>Why C/C++ Are Imperative</h3>
<h4>Historical Design</h4>
<p>C was designed for system programming, requiring:</p>
<ul>
<li>Direct control over memory</li>
<li>Efficient execution</li>
<li>Clear mapping to machine instructions</li>
</ul>
<h4>Performance Considerations</h4>
<p>The imperative style maps well to computer architecture:</p>
<div class="code-block">
<code>// This C code maps directly to machine instructions
int a = 5; // LOAD 5 into register/memory
int b = 10; // LOAD 10 into register/memory
int result = a + b; // ADD registers, STORE result
</code>
</div>
<div class="example-box">
<h4>Practical Impact</h4>
<p>Understanding the imperative nature of C/C++ helps you:</p>
<ul>
<li>Write efficient code</li>
<li>Debug effectively by tracking state changes</li>
<li>Understand memory management</li>
<li>Optimize performance</li>
</ul>
</div>
<div class="interactive-demo">
<h4>Imperative vs Declarative Thinking</h4>
<p>Compare how you might express "find the sum of numbers 1 to 10":</p>
<button class="demo-button" onclick="showParadigms()">Show Examples</button>
<div id="paradigmOutput" class="demo-output"></div>
</div>
</section>
<!-- LO2.2: Program Structure -->
<section id="lo2-2" class="section">
<h2>2.2: Minimal Elements of C and C++ Programs</h2>
<p>Every C and C++ program has certain essential components. Understanding these minimal elements is crucial for writing any program, no matter how simple or complex.</p>
<h3>The Simplest C Program</h3>
<div class="code-block">
<code>#include <stdio.h>
int main() {
return 0;
}</code>
</div>
<p>Let's break down each component:</p>
<h4>1. Preprocessor Directives</h4>
<p><code>#include <stdio.h></code> is a <span class="highlight">preprocessor directive</span> that tells the preprocessor to include the contents of the stdio.h header file.</p>
<div class="info-box">
<h4>Common Header Files:</h4>
<ul>
<li><code><stdio.h></code> - Standard input/output</li>
<li><code><stdlib.h></code> - Standard library functions</li>
<li><code><string.h></code> - String manipulation</li>
<li><code><math.h></code> - Mathematical functions</li>
</ul>
</div>
<h4>2. The main() Function</h4>
<p>Every C program must have exactly one <code>main()</code> function. This is where program execution begins.</p>
<div class="code-block">
<code>int main() { // Function declaration
// Program statements go here
return 0; // Return statement
} // Function end</code>
</div>
<h4>3. Return Statement</h4>
<p><code>return 0;</code> indicates successful program termination. Non-zero values typically indicate errors.</p>
<h3>Anatomy of a Complete Program</h3>
<div class="code-block">
<code>/*
* Program: Hello World
* Author: Student
* Purpose: Demonstrate basic C program structure
*/
#include <stdio.h> // Preprocessor directive
#include <stdlib.h> // Another header
// Global variable (optional)
int global_var = 42;
// Function prototype (declaration)
void greet_user(void);
// Main function - program entry point
int main() {
printf("Hello, World!\n"); // Function call
greet_user(); // Call our function
return EXIT_SUCCESS; // Return success code
}
// Function definition
void greet_user(void) {
printf("Welcome to C programming!\n");
}</code>
</div>
<h3>C++ Minimal Program</h3>
<p>C++ programs are similar but use different header files and syntax:</p>
<div class="code-block">
<code>#include <iostream> // C++ style header
using namespace std; // Use standard namespace
int main() {
cout << "Hello, World!" << endl;
return 0;
}</code>
</div>
<h3>Program Structure Components</h3>
<h4>Comments</h4>
<p>Document your code for clarity:</p>
<div class="code-block">
<code>// Single-line comment in C99 and C++
/*
Multi-line comment
Works in all C versions
*/</code>
</div>
<h4>Preprocessing Phase</h4>
<p>Before compilation, the preprocessor:</p>
<ul>
<li>Includes header files</li>
<li>Expands macros</li>
<li>Handles conditional compilation</li>
<li>Removes comments</li>
</ul>
<h4>Compilation Units</h4>
<p>Each <code>.c</code> file is a separate <span class="highlight">translation unit</span> that gets compiled independently.</p>
<div class="warning-box">
<h4>⚠️ Common Beginner Mistakes</h4>
<ul>
<li>Forgetting to include necessary headers</li>
<li>Missing semicolons after statements</li>
<li>Incorrect main() function signature</li>
<li>Forgetting return statement in main()</li>
</ul>
</div>
<h3>Program Execution Flow</h3>
<ol>
<li><strong>Preprocessing:</strong> Headers included, macros expanded</li>
<li><strong>Compilation:</strong> C code translated to machine code</li>
<li><strong>Linking:</strong> External libraries linked</li>
<li><strong>Loading:</strong> Program loaded into memory</li>
<li><strong>Execution:</strong> main() function called</li>
</ol>
<div class="interactive-demo">
<h4>Program Structure Checker</h4>
<p>Check if a program has the essential components:</p>
<textarea id="codeInput" class="demo-input" rows="8" placeholder="Paste C code here..."></textarea>
<button class="demo-button" onclick="checkProgram()">Analyze Structure</button>
<div id="structureOutput" class="demo-output"></div>
</div>
</section>
<!-- LO2.3: Basic I/O -->
<section id="lo2-3" class="section">
<h2>2.3: Basic Input and Output Programming</h2>
<p>Input and output operations are fundamental to most programs. This section covers how to read data from the keyboard and display information to the console in C.</p>
<h3>Output with printf()</h3>
<p>The <code>printf()</code> function is the most common way to display output in C:</p>
<div class="code-block">
<code>#include <stdio.h>
int main() {
printf("Hello, World!\n");
printf("This is line 2\n");
return 0;
}</code>
</div>
<h4>Basic printf() Usage</h4>
<ul>
<li><code>\n</code> creates a new line</li>
<li>Strings must be enclosed in double quotes</li>
<li>printf() returns the number of characters printed</li>
</ul>
<h3>Input with scanf()</h3>
<p>The <code>scanf()</code> function reads formatted input from the keyboard:</p>
<div class="code-block">
<code>#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You are %d years old.\n", age);
return 0;
}</code>
</div>
<div class="warning-box">
<h4>⚠️ The Address-of Operator (&)</h4>
<p>Notice the <code>&age</code> in scanf(). The & operator gets the memory address of the variable so scanf() can store the input there.</p>
</div>
<h3>Complete Input/Output Example</h3>
<div class="code-block">
<code>#include <stdio.h>
int main() {
char name[50];
int age;
float height;
// Get input from user
printf("What's your name? ");
scanf("%s", name); // No & needed for strings
printf("How old are you? ");
scanf("%d", &age);
printf("How tall are you (in meters)? ");
scanf("%f", &height);
// Display the information
printf("\n--- Your Information ---\n");
printf("Name: %s\n", name);
printf("Age: %d years\n", age);
printf("Height: %.2f meters\n", height);
return 0;
}</code>
</div>
<h3>Common I/O Patterns</h3>
<h4>Reading Multiple Values</h4>
<div class="code-block">
<code>int x, y;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
printf("Sum: %d\n", x + y);</code>
</div>
<h4>Input Validation Loop</h4>
<div class="code-block">
<code>int num;
printf("Enter a positive number: ");
while (scanf("%d", &num) != 1 || num <= 0) {
printf("Invalid input. Enter a positive number: ");
while (getchar() != '\n'); // Clear input buffer
}</code>
</div>
<h3>C++ Style I/O</h3>
<p>C++ provides stream-based I/O that's often easier to use:</p>
<div class="code-block">
<code>#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
int age;
cout << "Enter your name: ";
getline(cin, name); // Read entire line including spaces
cout << "Enter your age: ";
cin >> age;
cout << "Hello, " << name << "! You are " << age << " years old." << endl;
return 0;
}</code>
</div>
<div class="info-box">
<h4>C vs C++ I/O Comparison</h4>
<ul>
<li><strong>C:</strong> printf/scanf - format specifiers, manual address handling</li>
<li><strong>C++:</strong> cout/cin - type-safe, easier syntax</li>
<li><strong>Performance:</strong> C is typically faster</li>
<li><strong>Safety:</strong> C++ is more type-safe</li>
</ul>
</div>
<h3>Common Input/Output Challenges</h3>
<h4>Buffer Issues</h4>
<p>Input buffering can cause unexpected behavior:</p>
<div class="code-block">
<code>int num;
char letter;
printf("Enter a number: ");
scanf("%d", &num);
printf("Enter a letter: ");
scanf("%c", &letter); // May skip due to buffered newline
// Better approach:
scanf(" %c", &letter); // Space before %c consumes whitespace</code>
</div>
<h4>String Input with Spaces</h4>
<div class="code-block">
<code>char name[100];
// This only reads one word
scanf("%s", name);
// This reads entire line
fgets(name, sizeof(name), stdin);</code>
</div>
<div class="interactive-demo">
<h4>I/O Practice</h4>
<p>Try different input scenarios:</p>
<input type="text" id="userInput" class="demo-input" placeholder="Enter some text..." />
<button class="demo-button" onclick="processInput()">Process Input</button>
<div id="ioOutput" class="demo-output"></div>
</div>
</section>
<!-- LO2.4: Formatted I/O -->
<section id="lo2-4" class="section">
<h2>2.4: Formatted Library Functions</h2>
<p>Formatted I/O functions in C provide powerful control over how data is read and displayed. Understanding format specifiers and their options is essential for professional C programming.</p>
<h3>printf() Format Specifiers</h3>
<p>Format specifiers tell printf() how to interpret and display data:</p>
<div class="code-block">
<code>#include <stdio.h>
int main() {
int integer = 42;
float decimal = 3.14159f;
char character = 'A';
char string[] = "Hello";
printf("Integer: %d\n", integer);
printf("Float: %f\n", decimal);
printf("Character: %c\n", character);
printf("String: %s\n", string);
return 0;
}</code>
</div>
<h3>Common Format Specifiers</h3>
<div class="info-box">
<h4>Basic Format Specifiers</h4>
<ul>
<li><code>%d</code> or <code>%i</code> - signed decimal integer</li>
<li><code>%u</code> - unsigned decimal integer</li>
<li><code>%f</code> - floating-point number</li>
<li><code>%c</code> - single character</li>
<li><code>%s</code> - string</li>
<li><code>%p</code> - pointer address</li>
<li><code>%x</code> - hexadecimal (lowercase)</li>
<li><code>%X</code> - hexadecimal (uppercase)</li>
<li><code>%o</code> - octal</li>
</ul>
</div>
<h3>Format Modifiers</h3>
<p>Modifiers control the appearance and precision of output:</p>
<h4>Width and Precision</h4>
<div class="code-block">
<code>float pi = 3.14159;
printf("Default: %f\n", pi); // 3.141590
printf("2 decimals: %.2f\n", pi); // 3.14
printf("Width 10: %10.2f\n", pi); // " 3.14"
printf("Left-aligned: %-10.2f|\n", pi); // "3.14 |"
printf("Zero-padded: %010.2f\n", pi); // "0000003.14"</code>
</div>
<h4>Integer Formatting</h4>
<div class="code-block">
<code>int number = 42;
printf("Decimal: %d\n", number); // 42
printf("Hexadecimal: %x\n", number); // 2a
printf("Octal: %o\n", number); // 52
printf("With signs: %+d\n", number); // +42
printf("Space for positive: % d\n", number); // 42
printf("Zero-padded: %05d\n", number); // 00042</code>
</div>
<h3>scanf() Format Specifiers</h3>
<p>scanf() uses similar format specifiers for reading input:</p>
<div class="code-block">
<code>#include <stdio.h>
int main() {
int age;
float height;
char grade;
char name[50];
printf("Enter age, height, grade, and name: ");
scanf("%d %f %c %s", &age, &height, &grade, name);
printf("Age: %d\n", age);
printf("Height: %.2f\n", height);
printf("Grade: %c\n", grade);
printf("Name: %s\n", name);
return 0;
}</code>
</div>
<h3>Advanced scanf() Features</h3>
<h4>Field Width Limiting</h4>
<div class="code-block">
<code>char name[20];
printf("Enter name (max 19 chars): ");
scanf("%19s", name); // Prevents buffer overflow</code>
</div>
<h4>Skipping Characters</h4>
<div class="code-block">
<code>int day, month, year;
printf("Enter date (DD/MM/YYYY): ");
scanf("%d/%d/%d", &day, &month, &year);</code>
</div>
<h4>Reading Different Bases</h4>
<div class="code-block">
<code>int decimal, hex, octal;
printf("Enter decimal, hex (0x...), octal (0...): ");
scanf("%d %x %o", &decimal, &hex, &octal);</code>
</div>
<h3>sprintf() and sscanf()</h3>
<p>These functions work with strings instead of console I/O:</p>
<div class="code-block">
<code>#include <stdio.h>
int main() {
char buffer[100];
int age = 25;
char name[] = "Alice";
// Write formatted data to string
sprintf(buffer, "Name: %s, Age: %d", name, age);
printf("Buffer contains: %s\n", buffer);
// Read formatted data from string
char parsed_name[50];
int parsed_age;
sscanf(buffer, "Name: %s, Age: %d", parsed_name, &parsed_age);
printf("Parsed: %s is %d years old\n", parsed_name, parsed_age);
return 0;
}</code>
</div>
<div class="warning-box">
<h4>⚠️ Security Considerations</h4>
<ul>
<li>Always limit string input length with scanf()</li>
<li>Check return values to detect input errors</li>
<li>Be careful with buffer sizes in sprintf()</li>
<li>Consider using safer functions like snprintf()</li>
</ul>
</div>
<h3>Error Handling</h3>
<div class="code-block">
<code>int number;
printf("Enter a number: ");
if (scanf("%d", &number) == 1) {
printf("You entered: %d\n", number);
} else {
printf("Invalid input!\n");
// Clear input buffer
while (getchar() != '\n');
}</code>
</div>
<div class="interactive-demo">
<h4>Format Specifier Tester</h4>
<p>See how different format specifiers work:</p>
<input type="number" id="numberInput" class="demo-input" placeholder="Enter a number" value="42" />
<select id="formatSelect" class="demo-input">
<option value="d">%d (decimal)</option>
<option value="x">%x (hex)</option>
<option value="o">%o (octal)</option>
<option value="f">%f (float)</option>
<option value=".2f">%.2f (2 decimals)</option>
<option value="08d">%08d (zero-padded)</option>
</select>
<button class="demo-button" onclick="testFormat()">Test Format</button>
<div id="formatOutput" class="demo-output"></div>
</div>
</section>
<!-- Continue with remaining sections... -->
<!-- For brevity, I'll add a few more key sections -->
<!-- LO3.4: C-Style Strings -->
<section id="lo3-4" class="section">
<h2>3.4: Structure of C-Style Strings</h2>
<p>C-style strings are fundamental to C programming. Unlike higher-level languages, C doesn't have a built-in string type. Instead, strings are implemented as arrays of characters with a special terminating character.</p>
<h3>What is a C-Style String?</h3>
<p>A <span class="highlight">C-style string</span> is an array of characters terminated by a null character (<code>'\0'</code>).</p>
<div class="code-block">
<code>char greeting[] = "Hello";
// Internally stored as: ['H', 'e', 'l', 'l', 'o', '\0']
// [0] [1] [2] [3] [4] [5]</code>
</div>
<h3>String Declaration Methods</h3>
<h4>Method 1: String Literal</h4>
<div class="code-block">
<code>char message[] = "Hello, World!";
// Compiler automatically adds '\0' and calculates size</code>
</div>
<h4>Method 2: Character Array</h4>
<div class="code-block">
<code>char message[14] = {'H','e','l','l','o',',',' ','W','o','r','l','d','!','\0'};
// Manual specification - tedious but explicit</code>
</div>
<h4>Method 3: Fixed-Size Array</h4>
<div class="code-block">
<code>char message[50] = "Hello";
// Array has 50 characters, string uses first 6 (including '\0')</code>
</div>
<h3>The Null Terminator</h3>
<p>The null character <code>'\0'</code> is crucial:</p>
<ul>
<li>Marks the end of the string</li>
<li>Has ASCII value 0</li>
<li>Automatically added by string literals</li>
<li>Must be manually added when building strings character by character</li>
</ul>
<div class="warning-box">
<h4>⚠️ Missing Null Terminator</h4>
<p>Forgetting the null terminator leads to undefined behavior. String functions won't know where the string ends!</p>
</div>
<div class="code-block">
<code>char bad_string[5] = {'H', 'e', 'l', 'l', 'o'}; // No '\0'!
// printf("%s", bad_string); // Undefined behavior - may print garbage
char good_string[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Correct
printf("%s", good_string); // Safe to print</code>
</div>
<h3>String vs Character Array</h3>
<div class="info-box">
<h4>Key Differences:</h4>
<ul>
<li><strong>String:</strong> Null-terminated character array</li>
<li><strong>Character Array:</strong> Just an array of chars (may not be null-terminated)</li>
<li><strong>String Functions:</strong> Work only with null-terminated strings</li>
</ul>
</div>
<h3>Common String Operations</h3>
<h4>String Length</h4>
<div class="code-block">
<code>#include <string.h>
char name[] = "Alice";
int length = strlen(name); // Returns 5 (doesn't count '\0')</code>
</div>
<h4>String Copy</h4>
<div class="code-block">
<code>char source[] = "Hello";
char destination[20];
strcpy(destination, source); // Copies "Hello\0" to destination</code>
</div>
<h4>String Comparison</h4>
<div class="code-block">
<code>char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
// Returns: negative if str1 < str2
// zero if str1 == str2
// positive if str1 > str2</code>
</div>
<div class="interactive-demo">
<h4>String Structure Explorer</h4>
<p>Enter a string to see its internal structure:</p>
<input type="text" id="stringInput" class="demo-input" placeholder="Enter a string" value="Hello" />
<button class="demo-button" onclick="exploreString()">Explore Structure</button>
<div id="stringOutput" class="demo-output"></div>
</div>
</section>
</main>
</div>
<script>
// Navigation functionality
document.addEventListener('DOMContentLoaded', function() {
const navItems = document.querySelectorAll('.nav-item');
const sections = document.querySelectorAll('.section');
navItems.forEach(item => {
item.addEventListener('click', function(e) {
e.preventDefault();
// Remove active class from all nav items and sections
navItems.forEach(nav => nav.classList.remove('active'));
sections.forEach(section => section.classList.remove('active'));
// Add active class to clicked nav item
this.classList.add('active');
// Show corresponding section
const targetSection = document.getElementById(this.dataset.section);
if (targetSection) {
targetSection.classList.add('active');
}
// Update progress bar
updateProgress();
});
});
// Initialize progress bar
updateProgress();
});
function updateProgress() {
const navItems = document.querySelectorAll('.nav-item');
const activeIndex = Array.from(navItems).findIndex(item => item.classList.contains('active'));
const progress = ((activeIndex + 1) / navItems.length) * 100;
document.getElementById('progressFill').style.width = progress + '%';
}
function toggleSidebar() {
document.getElementById('sidebar').classList.toggle('open');
}
// Interactive demo functions
function analyzeType() {
const input = document.getElementById('typeInput').value;
const output = document.getElementById('typeOutput');
let analysis = "Input Analysis:\n";
analysis += `Value: "${input}"\n`;
if (input.match(/^-?\d+$/)) {
analysis += "Likely type: int\n";
analysis += "Reason: Contains only digits (and optional minus sign)\n";
} else if (input.match(/^-?\d*\.\d+$/)) {
analysis += "Likely type: float/double\n";
analysis += "Reason: Contains decimal point\n";
} else if (input.match(/^'.'$/)) {
analysis += "Likely type: char\n";
analysis += "Reason: Single character in quotes\n";
} else if (input.length === 1) {
analysis += "Likely type: char\n";
analysis += "Reason: Single character\n";
} else {
analysis += "Likely type: string (char array)\n";
analysis += "Reason: Multiple characters\n";
}
output.textContent = analysis;
}
function checkConversion() {
const fromType = document.getElementById('fromType').value;
const toType = document.getElementById('toType').value;
const output = document.getElementById('conversionOutput');
let result = `Converting from ${fromType} to ${toType}:\n\n`;
if (fromType === toType) {
result += "No conversion needed - same type!";
} else {
const conversions = {
'int-float': 'Implicit conversion allowed. Precision may increase.',
'float-int': 'Implicit conversion allowed. Precision WILL be lost!',
'char-int': 'Implicit conversion allowed. ASCII value used.',
'int-char': 'Implicit conversion allowed. May lose data if > 255!',
'double-float': 'Implicit conversion allowed. Precision may be lost.',
'float-double': 'Implicit conversion allowed. Precision increases.'
};
const key = `${fromType}-${toType}`;
result += conversions[key] || 'Conversion behavior depends on specific values.';
}
output.textContent = result;
}
function showParadigms() {
const output = document.getElementById('paradigmOutput');
output.textContent = `IMPERATIVE (C/C++ way):
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
printf("Sum: %d\\n", sum);
DECLARATIVE (SQL-like way):
SELECT SUM(number) FROM numbers WHERE number BETWEEN 1 AND 10;
FUNCTIONAL (Mathematical way):
sum = reduce(+, range(1, 11))
Notice how imperative focuses on HOW (step-by-step),
while others focus more on WHAT we want.`;
}
function checkProgram() {
const code = document.getElementById('codeInput').value;
const output = document.getElementById('structureOutput');
let analysis = "Program Structure Analysis:\n\n";
// Check for includes
if (code.includes('#include')) {
analysis += "✓ Has #include statements\n";
} else {
analysis += "✗ Missing #include statements\n";
}
// Check for main function
if (code.includes('main')) {
analysis += "✓ Has main() function\n";
} else {
analysis += "✗ Missing main() function\n";
}
// Check for return statement
if (code.includes('return')) {
analysis += "✓ Has return statement\n";
} else {
analysis += "⚠ Consider adding return statement\n";
}
// Check for braces
const openBraces = (code.match(/{/g) || []).length;
const closeBraces = (code.match(/}/g) || []).length;
if (openBraces === closeBraces && openBraces > 0) {
analysis += "✓ Balanced braces\n";
} else if (openBraces !== closeBraces) {
analysis += "✗ Unbalanced braces\n";
}
output.textContent = analysis;
}
function processInput() {
const input = document.getElementById('userInput').value;
const output = document.getElementById('ioOutput');
let result = "Input Processing Results:\n\n";
result += `Raw input: "${input}"\n`;
result += `Length: ${input.length} characters\n`;
result += `First character: '${input[0] || 'none'}'\n`;
result += `Last character: '${input[input.length - 1] || 'none'}'\n`;
if (input.match(/^\d+$/)) {
result += `As integer: ${parseInt(input)}\n`;
}
if (input.match(/^\d*\.?\d+$/)) {
result += `As float: ${parseFloat(input)}\n`;
}
result += `Uppercase: ${input.toUpperCase()}\n`;
result += `Contains spaces: ${input.includes(' ') ? 'Yes' : 'No'}`;
output.textContent = result;
}
function testFormat() {
const number = parseInt(document.getElementById('numberInput').value) || 42;
const format = document.getElementById('formatSelect').value;
const output = document.getElementById('formatOutput');
let result = `Input: ${number}\nFormat: %${format}\n\nResult: `;
switch(format) {
case 'd':
result += number.toString();
break;
case 'x':
result += number.toString(16);
break;
case 'o':
result += number.toString(8);
break;
case 'f':
result += number.toFixed(6);
break;
case '.2f':
result += number.toFixed(2);
break;
case '08d':
result += number.toString().padStart(8, '0');
break;
default:
result += number.toString();
}
output.textContent = result;
}
function exploreString() {
const input = document.getElementById('stringInput').value;
const output = document.getElementById('stringOutput');
let result = `String: "${input}"\n\n`;
result += "Character-by-character breakdown:\n";
for (let i = 0; i < input.length; i++) {
const char = input[i];
const ascii = char.charCodeAt(0);
result += `[${i}] '${char}' (ASCII: ${ascii})\n`;
}
result += `[${input.length}] '\\0' (null terminator - ASCII: 0)\n\n`;
result += `Total array size needed: ${input.length + 1} bytes\n`;
result += `String length (strlen): ${input.length}`;
output.textContent = result;
}
</script>
</body>
</html>