Programming Languages (Concepts)Programming Languages (Concepts)

How languages are built, how they bind names, pass parameters and manage memory — plus quick "what is the output?" tricks in Python, Java and C.Language কীভাবে তৈরি হয়, কীভাবে name bind করে, parameter pass করে আর memory manage করে — সাথে Python, Java আর C-এর ছোট ছোট "output কী হবে?" trick।

Who is this chapter for? BUET IICT admission (MSc in ICT / MSc in Information Security), test date 02.10.2026. Programming Languages is part of the compulsory MCQ test, and it is an optional topic in both written tests. This chapter covers the concepts of the "Programming Languages" course. For deep C detail read Chapter 01 (Structured Programming). For C++/Java OOP read Chapter 02 (OOP). We do not repeat those here.
এই chapter কার জন্য? BUET IICT admission (MSc in ICT / MSc in Information Security), test date 02.10.2026। Programming Languages আছে compulsory MCQ test-এ, আর দুইটা written test-এই এটা optional topic। এই chapter-এ "Programming Languages" course-এর concept-গুলো আছে। C-এর বিস্তারিত পড়তে Chapter 01 (Structured Programming) দেখো। C++/Java OOP-এর জন্য Chapter 02 (OOP) দেখো। ওগুলো এখানে আবার লেখা হয়নি।

1. Language Paradigms and History1. Language Paradigms আর History

A paradigm is a style of thinking about a program. It tells you how you describe the work to the computer. Some languages follow one paradigm. Many modern languages (Python, C++, JavaScript) mix several.

The five main paradigms

  • Imperative / Procedural — You give step-by-step commands. You change variables (state) with assignment. Code is grouped into procedures (functions). Examples: C, Fortran, COBOL, Pascal.
  • Object-Oriented (OOP) — You group data and the functions that work on it into objects. Key ideas: encapsulation, inheritance, polymorphism. Examples: Java, C++, C#, Smalltalk. (Full detail in Chapter 02.)
  • Functional — A program is a set of mathematical functions. You avoid changing state. You use recursion instead of loops. Functions can be passed like values (first-class functions). Examples: Lisp, Haskell, ML, Scheme, F#.
  • Logic (Declarative) — You write facts and rules. Then you ask a question (query). The system finds the answer by itself using logical inference. Example: Prolog.
  • Scripting — Small, quick programs, usually interpreted, dynamically typed, used to glue tools together or automate tasks. Examples: Python, Perl, JavaScript, Bash, PHP, Ruby.

There is one more big word you should know: declarative. In a declarative language you say what you want, not how to get it. Functional and logic languages are declarative. SQL is also declarative: you write SELECT name FROM student WHERE cgpa > 3.5, and the database decides how to find it.

Paradigm মানে program নিয়ে চিন্তা করার একটা style। এটা বলে দেয় computer-কে কাজটা তুমি কীভাবে বুঝিয়ে বলবে। কিছু language একটা paradigm মেনে চলে। আজকের অনেক language (Python, C++, JavaScript) কয়েকটা paradigm মিশিয়ে ব্যবহার করে।

মূল পাঁচটা paradigm

  • Imperative / Procedural — ধাপে ধাপে command দাও। Assignment দিয়ে variable (state) বদলাও। Code-গুলো procedure (function)-এ ভাগ করা থাকে। উদাহরণ: C, Fortran, COBOL, Pascal।
  • Object-Oriented (OOP) — Data আর সেই data-র ওপর কাজ করা function-গুলোকে একসাথে object-এ রাখো। মূল idea: encapsulation, inheritance, polymorphism। উদাহরণ: Java, C++, C#, Smalltalk। (বিস্তারিত Chapter 02-এ।)
  • Functional — Program হলো কিছু mathematical function-এর সেট। State বদলানো এড়িয়ে চলা হয়। Loop-এর বদলে recursion ব্যবহার হয়। Function-কে value-এর মতো pass করা যায় (first-class function)। উদাহরণ: Lisp, Haskell, ML, Scheme, F#।
  • Logic (Declarative) — তুমি fact আর rule লেখো। তারপর একটা প্রশ্ন (query) করো। System নিজেই logical inference দিয়ে উত্তর খুঁজে বের করে। উদাহরণ: Prolog।
  • Scripting — ছোট, দ্রুত লেখা program, সাধারণত interpreted আর dynamically typed; tool জোড়া লাগাতে বা কাজ automate করতে লাগে। উদাহরণ: Python, Perl, JavaScript, Bash, PHP, Ruby।

আরেকটা বড় শব্দ জানা দরকার: declarative। Declarative language-এ তুমি বলো কী চাও, কীভাবে পাবে সেটা না। Functional আর logic language declarative। SQL-ও declarative: তুমি লেখো SELECT name FROM student WHERE cgpa > 3.5, আর database নিজে ঠিক করে কীভাবে খুঁজবে।

Programming Paradigms Imperative HOW to do it (change state) Declarative WHAT you want Procedural C, Fortran, COBOL, Pascal Object-Oriented Java, C++, C#, Smalltalk Functional Lisp, Haskell, ML, Scheme Logic Prolog (facts + rules) Scripting / Multi-paradigm (mix of styles) Python, JavaScript, Perl, Ruby, Bash, PHP (SQL = declarative query language)
Paradigm map: imperative (how) vs declarative (what). Scripting languages usually mix several styles.Paradigm map: imperative (কীভাবে) vs declarative (কী)। Scripting language সাধারণত কয়েকটা style মেশায়।
Example: Sum of 1 to n in four styles. The same job looks very different in each paradigm.
Example: চার style-এ 1 থেকে n পর্যন্ত যোগফল। একই কাজ প্রতিটা paradigm-এ দেখতে একদম আলাদা।
/* Imperative (C): change a variable step by step */
int sum = 0;
for (int i = 1; i <= n; i++) sum = sum + i;

// Object-oriented (Java): behaviour lives inside a class
class Summer { int sumTo(int n) { int s = 0; for (int i = 1; i <= n; i++) s += i; return s; } }

;; Functional (Scheme/Lisp): no loop, no assignment, only recursion
(define (sum n) (if (= n 0) 0 (+ n (sum (- n 1)))))

% Logic (Prolog): state facts and rules, then ask a query
sum(0, 0).
sum(N, S) :- N > 0, N1 is N - 1, sum(N1, S1), S is S1 + N.
?- sum(4, S).     % Prolog answers: S = 10

A short Prolog example (logic paradigm)ছোট একটা Prolog example (logic paradigm)

parent(karim, rahim).        % fact: karim is parent of rahim
parent(rahim, sumi).         % fact: rahim is parent of sumi
grandparent(X, Z) :- parent(X, Y), parent(Y, Z).   % rule

?- grandparent(karim, Who).
Who = sumi.

We never wrote a loop or a search. Prolog found Who = sumi by itself using unification and backtracking. That is the heart of logic programming.

আমরা কোনো loop বা search লিখিনি। Prolog নিজেই unification আর backtracking দিয়ে Who = sumi বের করেছে। এটাই logic programming-এর মূল কথা।

Timeline of important languagesগুরুত্বপূর্ণ language-গুলোর timeline

YearLanguageCreatorCreatorWhy it mattersকেন গুরুত্বপূর্ণ
1957FortranJohn Backus (IBM)First widely used high-level language. Made for science and number crunching.প্রথম বহুল ব্যবহৃত high-level language। Science আর হিসাব-নিকাশের জন্য।
1958LispJohn McCarthyFirst functional language. Used in AI. Gave us garbage collection and recursion-heavy style.প্রথম functional language। AI-তে ব্যবহার হতো। Garbage collection আর recursion-ভিত্তিক style এখান থেকেই।
1959COBOLCommittee (Grace Hopper's ideas)Committee (Grace Hopper-এর idea)Business data processing. English-like syntax. Still runs in banks.Business data processing। English-এর মতো syntax। এখনো bank-এ চলে।
1960ALGOL 60CommitteeCommitteeIntroduced block structure and BNF grammar. Parent of Pascal and C.Block structure আর BNF grammar আনে। Pascal আর C-এর পূর্বপুরুষ।
1972CDennis Ritchie (Bell Labs)Systems programming. Used to write UNIX. Fast and close to hardware.Systems programming। UNIX লিখতে ব্যবহার হয়। দ্রুত আর hardware-এর কাছাকাছি।
1972PrologAlain ColmerauerLogic programming. Used in AI and expert systems.Logic programming। AI আর expert system-এ ব্যবহার হয়।
1983/85C++Bjarne Stroustrup"C with classes". Added OOP to C."C with classes"। C-তে OOP যোগ করে।
1991PythonGuido van RossumEasy to read, dynamically typed scripting language. Huge in AI/data today.পড়তে সহজ, dynamically typed scripting language। আজ AI/data-তে সবচেয়ে জনপ্রিয়।
1995JavaJames Gosling (Sun)"Write once, run anywhere" using bytecode + JVM. Pure OOP style.Bytecode + JVM দিয়ে "Write once, run anywhere"। OOP style।
1995JavaScriptBrendan EichLanguage of the web browser.Web browser-এর language।
Exam tip: Typical MCQ: "The first high-level language?" → Fortran. "The first functional language / language of early AI?" → Lisp. "Business-oriented language?" → COBOL. "Language used to write UNIX?" → C. "Logic programming language?" → Prolog. Python (1991) is older than Java (1995) — a common trick.
Exam tip: সাধারণ MCQ: "প্রথম high-level language?" → Fortran। "প্রথম functional language / শুরুর দিকের AI-এর language?" → Lisp। "Business-oriented language?" → COBOL। "UNIX কোন language-এ লেখা?" → C। "Logic programming language?" → Prolog। Python (1991) কিন্তু Java (1995)-এর চেয়ে পুরোনো — এটা একটা common trick।

Generations of languages (1GL to 5GL)Language-এর generation (1GL থেকে 5GL)

GenerationWhat it isএটা কীExampleExample
1GLMachine language. Pure 0s and 1s. CPU runs it directly. Machine dependent.Machine language। শুধু 0 আর 1। CPU সরাসরি চালায়। Machine dependent।10110000 01100001
2GLAssembly language. Short words (mnemonics) for machine instructions. Needs an assembler.Assembly language। Machine instruction-এর ছোট নাম (mnemonic)। Assembler লাগে।MOV AL, 61h
3GLHigh-level, procedural or OOP languages. Machine independent. Needs a compiler or interpreter.High-level, procedural বা OOP language। Machine independent। Compiler বা interpreter লাগে।C, C++, Java, Fortran, Python
4GLVery high-level, often non-procedural. Close to human language. Used for databases and reports.অনেক high-level, প্রায়ই non-procedural। মানুষের ভাষার কাছাকাছি। Database আর report-এর জন্য।SQL, MATLAB, report generators
5GLSolve problems using constraints and logic given by the programmer. Used in AI.Programmer-এর দেওয়া constraint আর logic দিয়ে problem solve করে। AI-তে ব্যবহার হয়।Prolog, Mercury, OPS5

Language evaluation criteriaLanguage evaluation criteria

How do we judge if a language is "good"? The classic textbook (Sebesta) uses four criteria:

  • Readability — How easy is it to read and understand the code? Helped by simplicity, few ways to do one thing, clear syntax, good data types. Hurt by feature multiplicity (e.g. x++, ++x, x += 1, x = x + 1 all do the same) and operator overloading used badly.
  • Writability — How easy is it to write a program for a task? Helped by abstraction (functions, classes) and expressivity (powerful short operators like count++).
  • Reliability — Does the program do what it should in all conditions? Helped by type checking, exception handling, and avoiding aliasing (two names for one memory cell).
  • Cost — Total cost: training programmers, writing code, compiling, running, the compiler/tools price, poor reliability, and maintenance (often the biggest cost).

Other criteria sometimes asked: portability (run on many machines), generality (useful for many kinds of tasks), well-definedness (clear official definition).

একটা language "ভালো" কিনা কীভাবে বিচার করব? Classic textbook (Sebesta) চারটা criterion ব্যবহার করে:

  • Readability — Code পড়া আর বোঝা কত সহজ? Simplicity, এক কাজ করার কম উপায়, পরিষ্কার syntax, ভালো data type থাকলে বাড়ে। কমে যায় feature multiplicity-তে (যেমন x++, ++x, x += 1, x = x + 1 সব একই কাজ করে) আর ভুলভাবে ব্যবহার করা operator overloading-এ।
  • Writability — কোনো কাজের জন্য program লেখা কত সহজ? Abstraction (function, class) আর expressivity (ছোট কিন্তু শক্তিশালী operator, যেমন count++) এটা বাড়ায়।
  • Reliability — সব অবস্থায় program ঠিক কাজ করে কি না? Type checking, exception handling আর aliasing (এক memory cell-এর দুই নাম) এড়ানো এটা বাড়ায়।
  • Cost — মোট খরচ: programmer training, code লেখা, compile করা, চালানো, compiler/tool-এর দাম, কম reliability-র ক্ষতি, আর maintenance (প্রায়ই সবচেয়ে বড় খরচ)।

মাঝে মাঝে আরও কিছু criterion আসে: portability (অনেক machine-এ চলে), generality (অনেক ধরনের কাজে লাগে), well-definedness (পরিষ্কার official definition)।

Trade-off to remember: Readability and writability often fight. APL can write a whole algorithm in one line (great writability) but almost nobody can read it (bad readability). Also, strong run-time checks (like Java's array bound checks) raise reliability but add execution cost.
মনে রাখার মতো trade-off: Readability আর writability প্রায়ই একে অপরের বিরুদ্ধে যায়। APL-এ এক লাইনে পুরো algorithm লেখা যায় (writability ভালো) কিন্তু প্রায় কেউ পড়তে পারে না (readability খারাপ)। আবার, বেশি run-time check (যেমন Java-র array bound check) reliability বাড়ায় কিন্তু execution cost বাড়ায়।

2. Implementation Methods (Compile, Interpret, Hybrid)2. Implementation Methods (Compile, Interpret, Hybrid)

The CPU only understands machine code. So a program written in a high-level language must be translated or run by another program. There are three main ways.

1) Pure compilation

A compiler translates the whole source program into machine code once, before running. The output (an executable file) then runs directly on the CPU. Examples: C, C++, Fortran, Go, Rust.

  • Very fast execution, because translation is already done.
  • Errors are reported before the program runs (compile-time errors).
  • The executable is tied to one machine/OS (less portable).

2) Pure interpretation

An interpreter reads the source program and runs it statement by statement. No separate machine-code file is made. Examples: early BASIC, shell scripts (Bash), classic JavaScript engines.

  • Slow execution — often 10 to 100 times slower than compiled code, because every statement is decoded every time it runs (even inside a loop).
  • Easy debugging — error messages point to the exact source line, and you can run code interactively.
  • Needs more memory space (the source and symbol table stay in memory).

3) Hybrid implementation

A hybrid system first compiles the source into an intermediate code (called bytecode), then an interpreter (a virtual machine) runs that bytecode. Examples: Java (.java → javac → .class bytecode → JVM), Python (.py → .pyc bytecode → Python VM), C# (→ CIL → .NET CLR).

Bytecode is not tied to any real CPU. So the same .class file runs on Windows, Linux, or Mac as long as a JVM exists. That is Java's famous "Write Once, Run Anywhere".

JIT (Just-In-Time) compilation

A JIT compiler sits inside the virtual machine. While the program runs, it finds "hot" code (methods or loops that run many times) and compiles that bytecode into real machine code. Next time, the fast machine code runs directly. Modern JVMs (HotSpot), .NET, and JavaScript V8 all use JIT. This is why Java today is almost as fast as C for many tasks.

CPU শুধু machine code বোঝে। তাই high-level language-এ লেখা program-কে হয় translate করতে হয়, নয়তো অন্য একটা program দিয়ে চালাতে হয়। তিনটা মূল উপায় আছে।

১) Pure compilation

Compiler চালানোর আগেই পুরো source program-কে একবারে machine code-এ translate করে। Output (একটা executable file) তারপর সরাসরি CPU-তে চলে। উদাহরণ: C, C++, Fortran, Go, Rust।

  • Execution খুব দ্রুত, কারণ translation আগেই হয়ে গেছে।
  • Program চালানোর আগেই error জানা যায় (compile-time error)।
  • Executable একটা নির্দিষ্ট machine/OS-এর সাথে বাঁধা (কম portable)।

২) Pure interpretation

Interpreter source program পড়ে আর একটা একটা statement করে চালায়। আলাদা কোনো machine-code file তৈরি হয় না। উদাহরণ: পুরোনো BASIC, shell script (Bash), পুরোনো JavaScript engine।

  • Execution ধীর — প্রায়ই compiled code-এর চেয়ে 10 থেকে 100 গুণ ধীর, কারণ প্রতিটা statement যতবার চলে ততবার decode হয় (loop-এর ভেতরেও)।
  • Debugging সহজ — error message ঠিক source line দেখায়, আর code interactively চালানো যায়।
  • বেশি memory লাগে (source আর symbol table memory-তে থাকে)।

৩) Hybrid implementation

Hybrid system প্রথমে source-কে একটা intermediate code-এ (নাম bytecode) compile করে, তারপর একটা interpreter (virtual machine) সেই bytecode চালায়। উদাহরণ: Java (.java → javac → .class bytecode → JVM), Python (.py → .pyc bytecode → Python VM), C# (→ CIL → .NET CLR)।

Bytecode কোনো আসল CPU-এর সাথে বাঁধা না। তাই JVM থাকলে একই .class file Windows, Linux বা Mac — সবখানে চলে। এটাই Java-র বিখ্যাত "Write Once, Run Anywhere"।

JIT (Just-In-Time) compilation

JIT compiler virtual machine-এর ভেতরে থাকে। Program চলার সময় এটা "hot" code খুঁজে বের করে (যেসব method বা loop অনেকবার চলে) আর সেই bytecode-কে আসল machine code-এ compile করে ফেলে। পরেরবার দ্রুত machine code সরাসরি চলে। আধুনিক JVM (HotSpot), .NET আর JavaScript V8 সবাই JIT ব্যবহার করে। এজন্যই আজকের Java অনেক কাজে প্রায় C-এর মতো দ্রুত।

Compilation (C, C++) Interpretation (Bash, old BASIC) Hybrid (Java, Python, C#) Source (.c) Compiler Object code (.o) Linker Executable runs on CPU (fast) Source (.sh) Interpreter decode + run one statement repeat for every line, every time (slow) Output Source (.java) javac Bytecode (.class) JVM interpreter + JIT for hot code Output any OS with a JVM compile once, run anywhere
Three implementation methods. Compiler: translate once, run fast. Interpreter: decode every statement each time. Hybrid: compile to bytecode, then a VM (with JIT) runs it.তিনটা implementation method। Compiler: একবার translate, দ্রুত চলে। Interpreter: প্রতিবার প্রতিটা statement decode করে। Hybrid: bytecode-এ compile, তারপর VM (JIT সহ) চালায়।

Comparison tableComparison table

Pointবিষয়CompilerInterpreterHybrid (Bytecode + VM)
Translation unitTranslate-এর এককWhole program at onceপুরো program একবারেOne statement at a timeএকবারে একটা statementWhole program to bytecode, then VM runs itপুরো program bytecode-এ, তারপর VM চালায়
Execution speedExecution speedFastestসবচেয়ে দ্রুতSlowestসবচেয়ে ধীরMedium (fast with JIT)মাঝারি (JIT থাকলে দ্রুত)
Output fileOutput fileMachine code executableMachine code executableNoneকিছু নাBytecode (.class, .pyc)Bytecode (.class, .pyc)
Error reportingError reportingAll syntax errors after full scanপুরো scan-এর পরে সব syntax errorStops at the first error lineপ্রথম error line-এ থেমে যায়Compile errors first, then run-time errorsআগে compile error, পরে run-time error
PortabilityPortabilityLow (recompile per platform)কম (প্রতি platform-এ আবার compile)High (if interpreter exists)বেশি (interpreter থাকলে)High (if VM exists)বেশি (VM থাকলে)
ExamplesExamplesC, C++, Fortran, Rust, GoBash, early BASIC, early JavaScriptJava, Python, C#, Kotlin
Exam trap: "Python is an interpreted language" is the usual MCQ answer, and it is fine to choose it. But technically CPython is hybrid: it compiles to bytecode first. If an option says "Java: compiled to bytecode, then interpreted/JIT by JVM", that is the most correct description of Java.
Exam trap: "Python একটা interpreted language" — এটাই সাধারণ MCQ answer, এটা বেছে নেওয়া ঠিক আছে। কিন্তু technically CPython hybrid: এটা আগে bytecode-এ compile করে। কোনো option-এ যদি থাকে "Java: bytecode-এ compile হয়, তারপর JVM interpret/JIT করে", তাহলে Java-র জন্য সেটাই সবচেয়ে সঠিক বর্ণনা।

Compiler phases — one-line recapCompiler phases — এক লাইনে recap

  1. Lexical analysis (scanner) — breaks characters into tokens (int, x, =, 5).
  2. Syntax analysis (parser) — checks grammar, builds a parse tree.
  3. Semantic analysis — type checking, undeclared variables.
  4. Intermediate code generation — e.g. three-address code.
  5. Code optimization — make it faster/smaller.
  6. Code generation — produce target machine code.

The symbol table and error handler are used by all phases. Full detail with parsing examples is in Chapter 07, Lexical Analysis and Parsing.

  1. Lexical analysis (scanner) — character-গুলোকে token-এ ভাগ করে (int, x, =, 5)।
  2. Syntax analysis (parser) — grammar check করে, parse tree বানায়।
  3. Semantic analysis — type checking, undeclared variable ধরা।
  4. Intermediate code generation — যেমন three-address code।
  5. Code optimization — code-কে দ্রুত/ছোট করা।
  6. Code generation — target machine code তৈরি।

Symbol table আর error handler সব phase-এ ব্যবহার হয়। Parsing example সহ বিস্তারিত আছে Chapter 07, Lexical Analysis and Parsing-এ।

Preprocessor, assembler, linker and loaderPreprocessor, assembler, linker আর loader

  • Preprocessor (C/C++) — runs before the compiler. Handles #include, #define macros, #ifdef. Pure text replacement.
  • Assembler — turns assembly code into object code (machine code with unresolved addresses).
  • Linker — joins many object files and library code into one executable. It resolves external references (e.g. your call to printf gets the real address of printf).
  • Loader — part of the OS. It copies the executable from disk into memory, fixes addresses (relocation) and starts it.

Full chain for C: prog.c → preprocessor → compiler → assembler → prog.o → linker → a.out → loader → running process.

  • Preprocessor (C/C++) — compiler-এর আগে চলে। #include, #define macro, #ifdef handle করে। শুধু text replacement।
  • Assembler — assembly code-কে object code-এ (address এখনো ঠিক না করা machine code) রূপান্তর করে।
  • Linker — অনেকগুলো object file আর library code জোড়া দিয়ে একটা executable বানায়। এটা external reference resolve করে (যেমন তোমার printf call পায় printf-এর আসল address)।
  • Loader — OS-এর অংশ। Executable-কে disk থেকে memory-তে copy করে, address ঠিক করে (relocation) আর চালু করে।

C-এর পুরো chain: prog.c → preprocessor → compiler → assembler → prog.o → linker → a.out → loader → running process।

Static vs dynamic linkingStatic vs dynamic linking

Pointবিষয়Static linkingDynamic linking
When library code is addedLibrary code কখন যোগ হয়At link time — copied into the executableLink time-এ — executable-এর ভেতরে copy হয়At load time or run time — only a reference is keptLoad time বা run time-এ — শুধু একটা reference থাকে
Library fileLibrary file.a (Linux), .lib (Windows).so (Linux), .dll (Windows)
Executable sizeExecutable sizeLargeবড়Smallছোট
Memory use (many programs)Memory ব্যবহার (অনেক program)Each program has its own copyপ্রতিটা program-এর আলাদা copyOne shared copy in memoryMemory-তে একটাই shared copy
Library updateLibrary updateMust re-link the programProgram আবার link করতে হয়Just replace the .so/.dll fileশুধু .so/.dll file বদলালেই হয়
RiskRiskNone at run time; works aloneRun time-এ ঝুঁকি নেই; একাই চলে"DLL hell" — missing or wrong version breaks the program"DLL hell" — file না থাকলে বা ভুল version হলে program ভাঙে

3. Names, Binding, Scope and Lifetime3. Names, Binding, Scope আর Lifetime

A variable is more than a name. Sebesta describes it with six attributes: name, address, value, type, lifetime, scope. The address is also called the l-value (used on the left of =). The value is the r-value.

When two different names point to the same memory cell, they are called aliases. Aliasing (through pointers, references, or unions) hurts readability and reliability.

What is binding?

A binding is a link between two things — like a name and its type, or a variable and its memory cell. The binding time is when that link is made.

Variable শুধু একটা নাম না। Sebesta এটাকে ছয়টা attribute দিয়ে বর্ণনা করেন: name, address, value, type, lifetime, scope। Address-কে l-value-ও বলে (=-এর বামে ব্যবহার হয়)। Value হলো r-value।

দুটো আলাদা নাম যখন একই memory cell-কে point করে, তাদের বলে alias। Aliasing (pointer, reference বা union দিয়ে) readability আর reliability কমায়।

Binding কী?

Binding হলো দুটো জিনিসের মধ্যে সংযোগ — যেমন একটা name আর তার type, বা একটা variable আর তার memory cell। Binding time মানে সেই সংযোগ কখন হয়।

Binding timeExample (C / Java)Example (C / Java)
Language design time* is bound to the multiplication operation; int is a keyword.* multiplication operation-এর সাথে bound; int একটা keyword।
Language implementation timeThe range of int in C (16 or 32 bits) is decided by the compiler writer.C-তে int-এর range (16 বা 32 bit) compiler writer ঠিক করেন।
Compile timeA C/Java variable is bound to its type: int count;C/Java-তে variable-এর type bind হয়: int count;
Link timeA call to a library function is bound to that function's code.Library function-এর call সেই function-এর code-এর সাথে bind হয়।
Load timeA C static or global variable is bound to a memory cell.C-এর static বা global variable একটা memory cell-এর সাথে bind হয়।
Run timeA local (non-static) variable gets a stack cell when the function is called. A value is bound to a variable by assignment. A Python variable gets its type.Function call হলে local (non-static) variable stack cell পায়। Assignment-এ variable-এর সাথে value bind হয়। Python variable-এর type bind হয়।

A binding is static if it happens before run time and never changes while the program runs. It is dynamic if it happens during run time or can change.

Static vs dynamic type binding

  • Static type binding: the type is fixed before running, by an explicit declaration (int x; in C) or by type inference (var x = 5; in Java/C#, auto x = 5; in C++, ML/Haskell). The type of x can never change later.
  • Dynamic type binding: the type is bound when a value is assigned, at run time. The same name can hold different types over time. Python, JavaScript, PHP, Ruby.

Binding যদি run time-এর আগে হয় আর program চলার সময় আর না বদলায়, তাহলে সেটা static। আর যদি run time-এর মধ্যে হয় বা বদলাতে পারে, তাহলে dynamic।

Static vs dynamic type binding

  • Static type binding: চালানোর আগেই type ঠিক হয়ে যায়, হয় explicit declaration দিয়ে (C-তে int x;), নয়তো type inference দিয়ে (Java/C#-এ var x = 5;, C++-এ auto x = 5;, ML/Haskell)। পরে x-এর type আর বদলানো যায় না।
  • Dynamic type binding: run time-এ value assign করার সময় type bind হয়। একই নাম সময়ের সাথে বিভিন্ন type রাখতে পারে। Python, JavaScript, PHP, Ruby।
# Python: dynamic type binding
x = 10          # x is bound to int
x = "BUET"      # now x is bound to str — allowed
x = [1, 2, 3]   # now a list

// Java: static type binding
int x = 10;
x = "BUET";     // compile-time ERROR: incompatible types

Dynamic typing is flexible, but a type error is found only when that line runs. It is also slower, because the type must be checked at run time.

Dynamic typing flexible, কিন্তু type error ধরা পড়ে শুধু যখন ওই line চলে। এটা ধীরও, কারণ run time-এ type check করতে হয়।

Lifetime: four categories of variablesLifetime: variable-এর চারটা category

The lifetime of a variable is the time during which it is bound to a memory cell. It starts at allocation and ends at deallocation.

Variable-এর lifetime মানে যতক্ষণ এটা একটা memory cell-এর সাথে bound থাকে। এটা শুরু হয় allocation-এ আর শেষ হয় deallocation-এ।

CategoryWhen storage is boundকখন storage bind হয়ExampleExamplePlus / minusসুবিধা / অসুবিধা
StaticBefore run (load time); lives for the whole programচালানোর আগে (load time); পুরো program জুড়ে থাকেC global and static locals, Java static fieldsC global আর static local, Java static field+ fast, history-sensitive. − no recursion support+ দ্রুত, আগের value মনে রাখে। − recursion চলে না
Stack-dynamicWhen its declaration runs (function call); freed on returnDeclaration চলার সময় (function call); return-এ freeLocal variables in C, C++, Java methodsC, C++, Java method-এর local variable+ supports recursion, saves memory. − a bit slower, no history+ recursion চলে, memory বাঁচে। − একটু ধীর, আগের value থাকে না
Explicit heap-dynamicWhen the programmer asks, using an operator/functionProgrammer যখন operator/function দিয়ে চায়new / delete (C++), malloc / free (C), new (Java objects)+ dynamic structures (linked list, tree). − pointer errors, leaks+ dynamic structure (linked list, tree)। − pointer error, leak
Implicit heap-dynamicAutomatically, every time a value is assignedValue assign করলেই আপনা-আপনিPython/JavaScript variables, JS arrays and stringsPython/JavaScript variable, JS array আর string+ very flexible. − slow, errors found late+ খুব flexible। − ধীর, error দেরিতে ধরা পড়ে
/* C example: three lifetimes in one program */
#include <stdlib.h>
int total = 0;                  // static (global) — whole program
void f(void) {
    static int calls = 0;       // static — keeps value between calls
    int temp = 5;               // stack-dynamic — dies when f returns
    int *p = malloc(sizeof(int)); // *p is explicit heap-dynamic
    calls++;
    free(p);                    // lifetime of *p ends here
}

Scope: static (lexical) vs dynamicScope: static (lexical) vs dynamic

The scope of a variable is the part of the program where the name can be seen. Lifetime is about time; scope is about text/place. They are different: a C static local lives for the whole program but can be seen only inside its function.

When a function uses a name that is not declared locally (a non-local reference), which declaration does it mean? Two rules:

  • Static (lexical) scoping — look in the block/function where the code is written, then in the enclosing block in the source text (its static parent), and so on outward. Decided at compile time. Used by C, C++, Java, Python, JavaScript, Pascal, Ada, and almost all modern languages.
  • Dynamic scoping — look in the function itself, then in the function that called it, then its caller, and so on back down the call chain at run time. Used by early Lisp, APL, SNOBOL, Perl (local), and Bash (local variables).

Variable-এর scope মানে program-এর যে অংশে নামটা দেখা যায়। Lifetime সময় নিয়ে; scope জায়গা/text নিয়ে। দুটো আলাদা: C-এর static local পুরো program জুড়ে বেঁচে থাকে, কিন্তু শুধু তার function-এর ভেতরেই দেখা যায়।

একটা function যখন এমন নাম ব্যবহার করে যেটা locally declare করা নেই (non-local reference), তখন সেটা কোন declaration বোঝায়? দুটো rule:

  • Static (lexical) scoping — code যেখানে লেখা সেই block/function-এ খোঁজো, তারপর source text-এ তাকে ঘিরে থাকা block-এ (তার static parent), এভাবে বাইরের দিকে। Compile time-এ ঠিক হয়। C, C++, Java, Python, JavaScript, Pascal, Ada — প্রায় সব আধুনিক language এটা ব্যবহার করে।
  • Dynamic scoping — function-এর নিজের ভেতরে খোঁজো, তারপর যে function তাকে call করেছে তার ভেতরে, তারপর তার caller-এ — run time-এর call chain ধরে পেছনের দিকে। পুরোনো Lisp, APL, SNOBOL, Perl (local) আর Bash (local variable) এটা ব্যবহার করে।
Classic example (very common MCQ): what does this print under static scoping and under dynamic scoping?
Classic example (খুব common MCQ): static scoping আর dynamic scoping-এ এটা কী print করবে?
int n = 10;                          // global n

void show()   { print(n); }          // n is NOT local here
void change() { n = n + 5; }         // n is NOT local here
void f()      { int n = 1;           // f has its OWN local n
                change();
                show(); }

main()        { f();
                show(); }

Static scoping trace — show and change are written at the top level. Their static parent is the global block. So their n always means the global n, no matter who calls them.

  1. main calls f. f makes local n = 1 (this one is never used by others).
  2. f calls change: global n = 10 + 5 = 15.
  3. f calls show: prints global n → 15.
  4. Back in main, show prints global n → 15.

Output (static): 15 15

Dynamic scoping trace — for a non-local n, look back through the callers. The most recent active n wins.

  1. main calls f. f makes local n = 1. Call chain: main → f.
  2. f calls change. change has no n. Its caller is f, which has n. So f's n = 1 + 5 = 6. Global n stays 10.
  3. f calls show. Caller f has n = 6 → prints 6.
  4. f returns; its n is gone. main calls show. Caller main has no n, so we reach the global n = 10 → prints 10.

Output (dynamic): 6 10

(Verified: the C version prints 15 15. The same program in Bash with local n=1 — Bash is dynamically scoped — prints 6 10.)

Static scoping trace — show আর change top level-এ লেখা। তাদের static parent হলো global block। তাই যে-ই call করুক, তাদের n সবসময় global n।

  1. main f-কে call করে। f local n = 1 বানায় (এটা আর কেউ ব্যবহার করে না)।
  2. f change-কে call করে: global n = 10 + 5 = 15।
  3. f show-কে call করে: global n print → 15।
  4. main-এ ফিরে show global n print করে → 15।

Output (static): 15 15

Dynamic scoping trace — non-local n-এর জন্য caller-দের মধ্যে পেছনে খোঁজো। সবচেয়ে সাম্প্রতিক active n-টাই নেওয়া হয়।

  1. main f-কে call করে। f local n = 1 বানায়। Call chain: main → f।
  2. f change-কে call করে। change-এ কোনো n নেই। তার caller f-এ n আছে। তাই f-এর n = 1 + 5 = 6। Global n 10-ই থাকে।
  3. f show-কে call করে। Caller f-এ n = 6 → print 6।
  4. f return করে; তার n শেষ। main show-কে call করে। Caller main-এ n নেই, তাই global n = 10 পাই → print 10।

Output (dynamic): 6 10

(Verified: C version print করে 15 15। একই program Bash-এ local n=1 দিয়ে লিখলে — Bash dynamically scoped — print করে 6 10।)

Static scope: look in SOURCE TEXT global: n = 10 show(): n? change(): n? f(): local n = 1 (invisible to show/change — they are not written inside f) Dynamic scope: look in CALL CHAIN main (global n = 10) f (local n = 1) change / show: n? caller stack grows up; newest on top
Static scope follows where the code is written (show/change see global n). Dynamic scope follows who called the function (inside f, they see f's n).Static scope দেখে code কোথায় লেখা (show/change global n দেখে)। Dynamic scope দেখে কে function-কে call করেছে (f-এর ভেতর থেকে call হলে তারা f-এর n দেখে)।
Exam tip: For a scoping question, first mark every non-local name. For static, draw arrows to the enclosing block in the text — the answer never depends on who calls. For dynamic, write the call stack at each call and search from the top of the stack down. Dynamic scoping hurts readability and reliability: you cannot know what n means just by reading show.
Exam tip: Scoping প্রশ্নে আগে প্রতিটা non-local নাম চিহ্নিত করো। Static-এর জন্য text-এ ঘিরে থাকা block-এর দিকে arrow দাও — কে call করল তাতে উত্তর বদলায় না। Dynamic-এর জন্য প্রতিটা call-এ call stack লেখো আর stack-এর ওপর থেকে নিচে খোঁজো। Dynamic scoping readability আর reliability কমায়: শুধু show পড়ে তুমি বুঝতে পারবে না n কোনটা।

Blocks, nested functions and referencing environmentBlock, nested function আর referencing environment

A block ({ ... } in C/Java) creates a new static scope. A local name hides (shadows) an outer variable with the same name. Python, Pascal, JavaScript and Ada allow nested functions, so the static parent can be another function.

The referencing environment of a statement is the set of all names visible there. In static scoping, it is the local names plus all names of its static ancestors that are not hidden.

একটা block (C/Java-তে { ... }) নতুন static scope তৈরি করে। একই নামের local variable বাইরের variable-কে hide (shadow) করে। Python, Pascal, JavaScript আর Ada-তে nested function লেখা যায়, তাই static parent আরেকটা function-ও হতে পারে।

কোনো statement-এর referencing environment হলো সেখানে দেখা যায় এমন সব নামের সেট। Static scoping-এ এটা local নামগুলো আর static ancestor-দের সব নাম, যেগুলো hide হয়নি।

# Python: nested function, static scope
x = 5
def g():
    return x * 2       # x -> global x (static parent of g is the module)
def h():
    x = 1              # local to h; g cannot see it
    return g()
print(h())             # prints 10 (static). Under dynamic scoping it would be 2.

def outer():
    count = 0
    def inner():
        nonlocal count # static parent is outer
        count += 1
        return count
    return inner
c = outer()
print(c(), c())        # 1 2  (a closure keeps outer's count alive)

4. Data Types and Type Systems4. Data Types আর Type Systems

A data type is a set of values plus the operations allowed on them. For example, int in Java = whole numbers from −231 to 231−1, with + − * / %.

Primitive vs composite types

  • Primitive types are built in and not made from other types: integer, floating point, character, boolean. (Java has 8 primitives: byte, short, int, long, float, double, char, boolean.)
  • Composite (structured) types are built from other types: arrays, strings, records (struct), unions, tuples, lists, classes, pointers/references.
  • Enumeration types list all possible values by name: enum Day {SAT, SUN, MON};

Data type হলো কিছু value-এর সেট আর সেগুলোর ওপর যেসব operation করা যায়। যেমন Java-তে int = −231 থেকে 231−1 পর্যন্ত পূর্ণসংখ্যা, সাথে + − * / %।

Primitive vs composite type

  • Primitive type built-in, অন্য type দিয়ে তৈরি না: integer, floating point, character, boolean। (Java-তে 8টা primitive: byte, short, int, long, float, double, char, boolean।)
  • Composite (structured) type অন্য type দিয়ে তৈরি: array, string, record (struct), union, tuple, list, class, pointer/reference।
  • Enumeration type সব সম্ভাব্য value নাম দিয়ে লিখে রাখে: enum Day {SAT, SUN, MON};

Strong vs weak typing, static vs dynamic typingStrong vs weak typing, static vs dynamic typing

These are two different questions. Do not mix them up.

  • Static vs dynamic typing asks WHEN types are checked. Static = at compile time. Dynamic = at run time.
  • Strong vs weak typing asks HOW STRICT the checking is. Strong = type errors are always caught; the language does not silently mix unrelated types. Weak = the language quietly converts or reinterprets values, so some type errors slip through.

এগুলো দুটো আলাদা প্রশ্ন। গুলিয়ে ফেলো না।

  • Static vs dynamic typing জিজ্ঞেস করে type কখন check হয়। Static = compile time-এ। Dynamic = run time-এ।
  • Strong vs weak typing জিজ্ঞেস করে checking কতটা কড়া। Strong = type error সবসময় ধরা পড়ে; language চুপচাপ সম্পর্কহীন type মেশায় না। Weak = language চুপচাপ value convert বা অন্যভাবে পড়ে ফেলে, তাই কিছু type error ফসকে যায়।
LanguageStatic / DynamicStatic / DynamicStrong / WeakStrong / WeakEvidenceপ্রমাণ
CStaticWeakUnions, pointer casts, and void* let you read an int as a float. No array bound check.Union, pointer cast আর void* দিয়ে একটা int-কে float হিসেবে পড়া যায়। Array bound check নেই।
C++StaticWeak-ish (safer than C)কিছুটা weak (C-এর চেয়ে নিরাপদ)Keeps C's unions and casts for compatibility.Compatibility-র জন্য C-এর union আর cast রেখে দিয়েছে।
JavaStaticStrongint x = "5"; is a compile error. Bad casts throw ClassCastException. Array bounds are checked.int x = "5"; compile error। ভুল cast করলে ClassCastException। Array bound check হয়।
PythonDynamicStrong"5" + 3 → TypeError at run time."5" + 3 → run time-এ TypeError।
JavaScriptDynamicWeak"5" + 3 → "53", "5" - 3 → 2. Silent coercion."5" + 3 → "53", "5" - 3 → 2। চুপচাপ coercion।
Haskell / MLStatic (with type inference)Static (type inference সহ)StrongYou rarely write types, yet every type is checked at compile time.Type প্রায় লিখতেই হয় না, তবু compile time-এ সব type check হয়।
// JavaScript (weak, dynamic) — verified with Node.js
"5" + 3      // "53"   (+ with a string means concatenation)
"5" - 3      // 2      (- forces a number)
"5" * "2"    // 10
1 + true     // 2      (true becomes 1)

# Python (strong, dynamic)
"5" + 3      # TypeError: can only concatenate str (not "int") to str
"5" * 2      # "55"   (repetition is a defined str operation, not coercion)
int("5") + 3 # 8      (explicit conversion is fine)

Type conversion: coercion vs castType conversion: coercion vs cast

  • Implicit conversion = coercion: the compiler converts automatically. In 3 + 2.5, C/Java change 3 to 3.0 first. This is a widening conversion (int → double): safe, no information lost.
  • Explicit conversion = cast: the programmer asks for it: (int) 3.99 → 3. This is usually a narrowing conversion (double → int): may lose information.
  • Java allows implicit widening only. int x = 3.5; is a compile error; you must write int x = (int) 3.5;. C allows both silently (maybe with a warning).

More coercions = less reliable (errors are hidden). That is why Ada and ML have almost no coercion.

  • Implicit conversion = coercion: compiler নিজে থেকেই convert করে। 3 + 2.5-এ C/Java আগে 3-কে 3.0 বানায়। এটা widening conversion (int → double): নিরাপদ, কোনো তথ্য হারায় না।
  • Explicit conversion = cast: programmer নিজে চায়: (int) 3.99 → 3। এটা সাধারণত narrowing conversion (double → int): তথ্য হারাতে পারে।
  • Java শুধু widening implicit-ভাবে করতে দেয়। int x = 3.5; compile error; লিখতে হবে int x = (int) 3.5;। C দুটোই চুপচাপ করতে দেয় (হয়তো warning দিয়ে)।

যত বেশি coercion, তত কম reliable (error লুকিয়ে যায়)। এজন্যই Ada আর ML-এ প্রায় কোনো coercion নেই।

/* Java — verified */
byte b = (byte) 130;        // narrowing: 130 does not fit in -128..127
System.out.println(b);      // -126   (130 - 256)
double d = 7 / 2;           // int division FIRST (3), then widened to 3.0
double e = 7 / 2.0;         // 2 is coerced to 2.0, result 3.5

Type equivalence: name vs structuralType equivalence: name vs structural

When are two types "the same"?

  • Name type equivalence — two variables have the same type only if they are declared with the same type name. Easy to implement, very strict. Used for C structs, Java classes, Ada.
  • Structure type equivalence — two types are the same if they have the same structure (same fields/components in the same order). More flexible but harder to check, and it can treat Celsius and Fahrenheit as the same (not what you want).

দুটো type কখন "একই"?

  • Name type equivalence — দুটো variable একই type শুধু তখনই, যখন তারা একই type name দিয়ে declare করা। Implement করা সহজ, খুব কড়া। C struct, Java class, Ada-তে ব্যবহার হয়।
  • Structure type equivalence — দুটো type একই যদি তাদের structure একই হয় (একই field/component একই order-এ)। বেশি flexible কিন্তু check করা কঠিন, আর এটা Celsius আর Fahrenheit-কে একই ধরে নিতে পারে (যেটা আমরা চাই না)।
struct A { int x; float y; };
struct B { int x; float y; };
struct A p; struct B q;
p = q;   // C: ERROR — name equivalence for structs (A and B are different names)
         // Under structural equivalence this would be allowed.
typedef int Meter;  Meter m = 5; int k = m;  // OK in C: typedef is only a new NAME for int

Arrays: four kinds by binding of size and storageArray: size আর storage binding অনুযায়ী চার ধরন

KindSize fixed?Size ঠিক কখন?Storage fromStorage কোথা থেকেExampleExample
StaticCompile timeCompile timeStatic area (before run)Static area (চালানোর আগে)static int a[10]; (C)
Fixed stack-dynamicCompile timeCompile timeStack, at declarationStack, declaration-এর সময়local int a[10]; in a C functionC function-এর local int a[10];
Stack-dynamicAt run time, then fixedRun time-এ, তারপর স্থিরStackC99 VLA: int a[n];, AdaC99 VLA: int a[n];, Ada
Fixed heap-dynamicAt run time, then fixedRun time-এ, তারপর স্থিরHeapmalloc(n * sizeof(int)), Java new int[n]
Heap-dynamicCan grow/shrink any timeযেকোনো সময় বাড়ে/কমেHeapPython list, Java ArrayList, C++ vector, JS arraysPython list, Java ArrayList, C++ vector, JS array

Address formula (row-major, like C): for a[i][j] with n columns and element size s: address = base + (i × n + j) × s. Fortran and MATLAB are column-major: base + (j × m + i) × s for m rows. (Detailed memory layout in Chapter 01.)

Address formula (row-major, C-এর মতো): n column আর element size s হলে a[i][j]-এর জন্য: address = base + (i × n + j) × s। Fortran আর MATLAB column-major: m row হলে base + (j × m + i) × s। (বিস্তারিত memory layout Chapter 01-এ।)

Records, unions, pointers and referencesRecord, union, pointer আর reference

  • Record — a group of named fields that can have different types (C struct, Pascal record). Fields are accessed by name: s.cgpa. (Arrays are same type, accessed by index.)
  • Union — fields share the same memory; only one is valid at a time. Size = size of the largest field. A free union (C) has no type check, so it breaks type safety. A discriminated union (Ada, ML) has a tag field that says which member is valid.
  • Pointer — holds a memory address. Can do arithmetic (p + 1), can be NULL, can be changed to point elsewhere. C/C++.
  • Reference — an alias for an existing object. C++ references (int &r = x;) must be initialized and never re-seated; no arithmetic. Java/Python variables of object type are references, and you cannot do pointer arithmetic on them — safer.
  • Record — কিছু নামওয়ালা field-এর group, যাদের type আলাদা হতে পারে (C struct, Pascal record)। Field নাম দিয়ে access হয়: s.cgpa। (Array-তে সব element একই type, index দিয়ে access।)
  • Union — সব field একই memory share করে; একসাথে শুধু একটাই valid। Size = সবচেয়ে বড় field-এর size। Free union (C)-এ type check নেই, তাই type safety ভাঙে। Discriminated union (Ada, ML)-এ একটা tag field থাকে যা বলে কোন member valid।
  • Pointer — memory address রাখে। Arithmetic করা যায় (p + 1), NULL হতে পারে, অন্য জায়গায় point করানো যায়। C/C++।
  • Reference — existing object-এর একটা alias। C++ reference (int &r = x;) initialize করতেই হয়, পরে আর অন্য object-এ বসানো যায় না; arithmetic নেই। Java/Python-এর object-type variable-গুলো reference, আর এগুলোর ওপর pointer arithmetic করা যায় না — বেশি নিরাপদ।
Two pointer problems (one-liners for MCQ):
Dangling reference/pointer — a pointer that still points to memory that has been freed. Example: int *p = malloc(4); free(p); *p = 5; or returning the address of a local variable.
Memory leak (lost heap-dynamic variable) — heap memory that is still allocated but no pointer reaches it, so it can never be freed. Example: p = malloc(4); p = malloc(4); (first block is lost).
Garbage collection (Java, Python) removes most leaks and all dangling pointers. More C examples in Chapter 01, Memory Concepts.
Pointer-এর দুটো সমস্যা (MCQ-এর জন্য এক লাইনে):
Dangling reference/pointer — এমন pointer যা এখনো এমন memory-কে point করছে যেটা free হয়ে গেছে। উদাহরণ: int *p = malloc(4); free(p); *p = 5; অথবা local variable-এর address return করা।
Memory leak (lost heap-dynamic variable) — heap memory এখনো allocated, কিন্তু কোনো pointer সেখানে পৌঁছায় না, তাই আর কখনো free করা যাবে না। উদাহরণ: p = malloc(4); p = malloc(4); (প্রথম block হারিয়ে গেল)।
Garbage collection (Java, Python) বেশিরভাগ leak আর সব dangling pointer দূর করে। আরও C example আছে Chapter 01, Memory Concepts-এ।

5. Expressions and Control Structures5. Expressions আর Control Structures

Precedence and associativityPrecedence আর associativity

Precedence decides which operator goes first when different operators meet: 2 + 3 * 4 = 2 + 12 = 14, because * is higher than +.

Associativity decides the order when operators of the same precedence meet. Most binary operators are left-associative: 10 - 4 - 3 = (10 - 4) - 3 = 3. A few are right-associative: assignment (a = b = 5), exponent (** in Python, Fortran, Ruby), and C's unary operators and ?:.

Precedence ঠিক করে আলাদা operator পাশাপাশি থাকলে কোনটা আগে: 2 + 3 * 4 = 2 + 12 = 14, কারণ *-এর precedence +-এর চেয়ে বেশি।

Associativity ঠিক করে একই precedence-এর operator পাশাপাশি থাকলে কোন দিক থেকে হিসাব হবে। বেশিরভাগ binary operator left-associative: 10 - 4 - 3 = (10 - 4) - 3 = 3। কয়েকটা right-associative: assignment (a = b = 5), exponent (Python, Fortran, Ruby-তে **), আর C-এর unary operator আর ?:।

# Python — verified
print(2 ** 3 ** 2)    # 512   = 2 ** (3 ** 2) = 2 ** 9   (right-assoc)
print(-2 ** 2)        # -4    = -(2 ** 2)   (** binds tighter than unary minus)
print(10 - 4 - 3)     # 3     (left-assoc)

/* C — verified */
int x = 10 - 4 - 3 * 2 / 4;   // 3*2=6, 6/4=1 (int), 10-4=6, 6-1 = 5
printf("%d", 5 > 3 > 1);        // (5>3) is 1, then 1 > 1 is 0  -> prints 0

# But Python CHAINS comparisons:
print(5 > 3 > 1)       # True, means (5 > 3) and (3 > 1)
// JavaScript: 3 > 2 > 1  ->  (true) > 1  ->  1 > 1  ->  false
Exam trap: a > b > c gives different answers in C/Java/JavaScript vs Python. In C and JS it is left-associative (compare a boolean 0/1 with c). In Java it does not even compile (boolean > int). In Python it is a chained comparison, like maths.
Exam trap: a > b > c C/Java/JavaScript আর Python-এ আলাদা উত্তর দেয়। C আর JS-এ এটা left-associative (boolean 0/1-কে c-এর সাথে তুলনা)। Java-তে compile-ই হয় না (boolean > int)। Python-এ এটা chained comparison, অঙ্কের মতো।

Short-circuit evaluationShort-circuit evaluation

In A && B, if A is false, the result must be false — so B is not evaluated at all. In A || B, if A is true, B is skipped. This is short-circuit evaluation. C, C++, Java, JavaScript use it for && and ||. Python uses it for and / or. Java's & and | on booleans do not short-circuit.

It is useful for safety: if (p != NULL && p->val > 0) never touches a NULL pointer. if (i < n && a[i] != key) never goes out of bounds.

A && B-তে A false হলে result তো false-ই — তাই B একদমই evaluate হয় না। A || B-তে A true হলে B বাদ। এটাই short-circuit evaluation। C, C++, Java, JavaScript && আর ||-এ এটা করে। Python করে and / or-এ। Java-তে boolean-এর ওপর & আর | short-circuit করে না।

এটা নিরাপত্তার জন্য কাজে লাগে: if (p != NULL && p->val > 0) কখনো NULL pointer ছোঁয় না। if (i < n && a[i] != key) কখনো bound-এর বাইরে যায় না।

Example (C, verified): What are m and n after each line? (Each line starts again with m = 0, n = 5.)
Example (C, verified): প্রতিটা line-এর পরে m আর n কত? (প্রতিটা line আবার m = 0, n = 5 দিয়ে শুরু।)
if (m++ || n++) {}   // m++ gives 0 (false), so n++ runs      -> m = 1, n = 6
if (++m || n++) {}   // ++m gives 1 (true), n++ is SKIPPED    -> m = 1, n = 5
if (m && n++) {}     // m is 0 (false), n++ is SKIPPED       -> m = 0, n = 5
Key idea: post-increment gives the OLD value to the condition, but the variable still changes.
মূল কথা: post-increment condition-কে পুরোনো value দেয়, কিন্তু variable ঠিকই বদলে যায়।

Side effects and evaluation orderSide effect আর evaluation order

A functional side effect happens when a function changes a non-local variable or a parameter, besides returning a value. Then the order of evaluating operands matters.

Example: a = 10; b = a + fun(&a); where fun sets a = 20 and returns 5. If a is read first: b = 10 + 5 = 15. If fun runs first: b = 20 + 5 = 25. In C the order is unspecified. Java fixes left-to-right order, so Java gives 15.

Also, in C, i = i++ + ++i; is undefined behaviour (a variable changed twice without a sequence point). Any output is "correct". If an exam asks it, write "undefined behaviour".

Functional side effect হয় যখন কোনো function value return করার পাশাপাশি একটা non-local variable বা parameter বদলে দেয়। তখন operand evaluate করার order গুরুত্বপূর্ণ হয়ে যায়।

উদাহরণ: a = 10; b = a + fun(&a); যেখানে fun a = 20 করে আর 5 return করে। আগে a পড়লে: b = 10 + 5 = 15। আগে fun চললে: b = 20 + 5 = 25। C-তে order unspecified। Java left-to-right order ঠিক করে দিয়েছে, তাই Java-তে 15।

আবার, C-তে i = i++ + ++i; হলো undefined behaviour (sequence point ছাড়া একটা variable দুবার বদলানো)। যেকোনো output-ই "ঠিক"। Exam-এ এলে লিখবে "undefined behaviour"।

Assignment formsAssignment-এর ধরন

FormExampleExampleMeaningমানে
Simplex = 5Store 5 in x. (Pascal/Ada use :=.)x-এ 5 রাখো। (Pascal/Ada-তে :=।)
Compoundx += 3x = x + 3
Unaryx++, ++xPost: use old value then add. Pre: add then use.Post: আগে পুরোনো value ব্যবহার, পরে যোগ। Pre: আগে যোগ, পরে ব্যবহার।
Multiple targeta = b = 0Right-assoc: a = (b = 0). Assignment is an expression in C/Java.Right-assoc: a = (b = 0)। C/Java-তে assignment নিজেও একটা expression।
Conditionalx = (a > b) ? a : bPick one value by a condition.Condition দেখে একটা value নাও।
Tuple / parallela, b = b, aPython swap in one line (right side is evaluated first).এক লাইনে Python swap (ডান পাশ আগে evaluate হয়)।
Classic bug: if (x = 0) in C assigns 0 and the condition is always false. Java refuses to compile it (condition must be boolean) — a reliability win for Java.
Classic bug: C-তে if (x = 0) 0 assign করে আর condition সবসময় false। Java এটা compile-ই করে না (condition boolean হতে হবে) — Java-র reliability-র জয়।

Selection and iteration across languagesবিভিন্ন language-এ selection আর iteration

ConstructConstructC / C++ / JavaPythonNoteNote
Two-way selectionif (c) {...} else {...}if c: ... else: ...Python uses indentation, not braces.Python brace না, indentation ব্যবহার করে।
Multi-way selectionswitch (x) { case 1: ... break; }if/elif/else, match (3.10+)Without break, C/Java fall through to the next case.break না দিলে C/Java পরের case-এ fall through করে।
Counter loopfor (i = 0; i < n; i++)for i in range(n):Python's for walks over any iterable.Python-এর for যেকোনো iterable-এর ওপর ঘোরে।
Pretest loopwhile (c) {...}while c:May run 0 times.0 বারও চলতে পারে।
Posttest loopdo {...} while (c);none (use while True: ... if not c: break)নেই (while True: ... if not c: break ব্যবহার করো)Runs at least once.অন্তত একবার চলে।
Iterator loopfor (int v : arr) (Java), for (auto v : vec) (C++)for v in lst:No index needed.Index লাগে না।
Loop else—for ... else:Python only: else runs if the loop ended without break.শুধু Python: loop break ছাড়া শেষ হলে else চলে।

The old goto statement is avoided in structured programming (Dijkstra, "Go To Statement Considered Harmful", 1968). Java reserves goto as a keyword but does not allow it. The structured program theorem (Böhm–Jacopini) says any program can be written with only sequence, selection and iteration.

Structured programming-এ পুরোনো goto statement এড়িয়ে চলা হয় (Dijkstra, "Go To Statement Considered Harmful", 1968)। Java goto-কে keyword হিসেবে রেখেছে কিন্তু ব্যবহার করতে দেয় না। Structured program theorem (Böhm–Jacopini) বলে যে কোনো program শুধু sequence, selection আর iteration দিয়ে লেখা যায়।

Recursion vs iteration (language view)Recursion vs iteration (language-এর দৃষ্টিতে)

  • Every recursive call creates a new activation record on the stack (see Section 6). So recursion uses O(depth) extra memory; a loop uses O(1).
  • Too deep recursion causes stack overflow. Python stops at about 1000 levels by default (RecursionError).
  • Tail recursion: the recursive call is the very last action. Functional languages (Scheme, Haskell) and some C compilers turn it into a loop (tail-call optimization), so no extra stack is used. Java and Python do not do this.
  • Functional languages have no loops at all — recursion is the only way to repeat.
  • প্রতিটা recursive call stack-এ একটা নতুন activation record তৈরি করে (Section 6 দেখো)। তাই recursion O(depth) বাড়তি memory নেয়; loop নেয় O(1)।
  • বেশি গভীর recursion হলে stack overflow হয়। Python default-এ প্রায় 1000 level-এ থামে (RecursionError)।
  • Tail recursion: recursive call-টাই একদম শেষ কাজ। Functional language (Scheme, Haskell) আর কিছু C compiler এটাকে loop-এ বদলে দেয় (tail-call optimization), তাই বাড়তি stack লাগে না। Java আর Python এটা করে না।
  • Functional language-এ loop-ই নেই — repeat করার একমাত্র উপায় recursion।
// Not tail recursive: after the call returns we still multiply by n
int fact(int n)            { return (n <= 1) ? 1 : n * fact(n - 1); }

// Tail recursive: the call is the last thing; 'acc' carries the answer
int factT(int n, int acc)  { return (n <= 1) ? acc : factT(n - 1, n * acc); }
// factT(4, 1) -> factT(3, 4) -> factT(2, 12) -> factT(1, 24) -> 24

6. Subprograms and Parameter Passing6. Subprograms আর Parameter Passing

A subprogram is a function or procedure. A function returns a value; a procedure (a void function in C) does not.

  • Formal parameters — the names in the subprogram header: in int add(int a, int b), a and b are formal.
  • Actual parameters (arguments) — the values/variables written in the call: in add(x, 5), x and 5 are actual.
  • Positional matching: 1st actual → 1st formal. Keyword matching (Python, Ada): add(b=5, a=x). Default values: def add(a, b=0).

Three semantic models

  • In mode — data goes into the subprogram only.
  • Out mode — data comes back to the caller only.
  • In-out mode — both ways.

Subprogram মানে function বা procedure। Function value return করে; procedure (C-এর void function) করে না।

  • Formal parameter — subprogram header-এ লেখা নাম: int add(int a, int b)-এ a আর b formal।
  • Actual parameter (argument) — call-এ লেখা value/variable: add(x, 5)-এ x আর 5 actual।
  • Positional matching: ১ম actual → ১ম formal। Keyword matching (Python, Ada): add(b=5, a=x)। Default value: def add(a, b=0)।

তিনটা semantic model

  • In mode — data শুধু subprogram-এর ভেতরে যায়।
  • Out mode — data শুধু caller-এর কাছে ফেরত আসে।
  • In-out mode — দুই দিকেই।

The four classic parameter-passing methodsচারটা classic parameter-passing method

MethodHow it worksকীভাবে কাজ করেModeUsed inকোথায় ব্যবহার
Pass-by-valueThe value of the actual is copied into the formal. Changes to the formal do not affect the caller.Actual-এর value formal-এ copy হয়। Formal বদলালে caller-এর কিছু বদলায় না।InC (all), Java (all — even object references are copied), Python (object reference copied)C (সব), Java (সব — object reference-ও copy হয়), Python (object reference copy হয়)
Pass-by-resultFormal starts empty; its final value is copied back to the actual at return.Formal খালি থেকে শুরু; return-এ তার শেষ value actual-এ copy হয়।OutAda out, C# out
Pass-by-value-result (copy-in copy-out)Copy the value in at the call; work on the local copy; copy the final value back to the actual's address at return.Call-এর সময় value copy করে ভেতরে আনো; local copy-তে কাজ করো; return-এ শেষ value actual-এর address-এ copy করে ফেরত দাও।In-outFortran (some), Ada in out (scalars)
Pass-by-referenceThe address of the actual is passed. The formal is an alias. Every change is instantly a change to the caller's variable.Actual-এর address pass হয়। Formal একটা alias। প্রতিটা পরিবর্তন সাথে সাথে caller-এর variable-এ হয়।In-outC++ &, C# ref, Pascal var, C simulated with pointersC++ &, C# ref, Pascal var, C-তে pointer দিয়ে simulate
Pass-by-nameThe actual parameter expression text is substituted for the formal. It is re-evaluated every time the formal is used (implemented with a "thunk").Formal-এর জায়গায় actual parameter-এর expression text বসিয়ে দেওয়া হয়। Formal যতবার ব্যবহার হয়, ততবার আবার evaluate হয় ("thunk" দিয়ে implement)।In-outALGOL 60, Scala (by-name params), similar to C macrosALGOL 60, Scala (by-name param), C macro-র মতো
ONE program, FOUR answers (classic written question). Arrays start at index 0. i and a are global.
একটা program, চারটা উত্তর (classic written প্রশ্ন)। Array index 0 থেকে শুরু। i আর a global।
int i = 0;
int a[3] = {5, 10, 15};

void f(int x) {
    i = i + 1;        // step 1
    a[0] = 100;       // step 2
    x = x + 1;        // step 3
}

main() {
    f(a[i]);          // the actual parameter is a[i], and i = 0 now
    print(i, a[0], a[1], a[2]);
}

(1) Pass-by-value. At the call, x = a[0] = 5 (a copy). Step 1: i = 1. Step 2: a[0] = 100. Step 3: x = 6, but x is only a local copy, so nothing else changes.
Output: i=1, a = 100 10 15

(2) Pass-by-reference. At the call, x becomes an alias of a[0] (the address is fixed at the call, when i = 0). Step 1: i = 1. Step 2: a[0] = 100, so x is also 100. Step 3: x = x + 1 means a[0] = 100 + 1 = 101.
Output: i=1, a = 101 10 15

(3) Pass-by-value-result. At the call, x = 5 (copy in) and we remember the address of a[0]. Step 1: i = 1. Step 2: a[0] = 100 (the local x does not see this). Step 3: x = 6. At return, copy out: a[0] = x = 6 — this overwrites the 100.
Output: i=1, a = 6 10 15

(4) Pass-by-name. Every x in the body is replaced by the text a[i]. Step 1: i = 1. Step 2: a[0] = 100. Step 3: a[i] = a[i] + 1, and now i is 1, so a[1] = 10 + 1 = 11.
Output: i=1, a = 100 11 15

(1) Pass-by-value। Call-এর সময় x = a[0] = 5 (একটা copy)। Step 1: i = 1। Step 2: a[0] = 100। Step 3: x = 6, কিন্তু x শুধু local copy, তাই আর কিছু বদলায় না।
Output: i=1, a = 100 10 15

(2) Pass-by-reference। Call-এর সময় x হয়ে যায় a[0]-এর alias (address call-এর সময়েই ঠিক হয়, যখন i = 0)। Step 1: i = 1। Step 2: a[0] = 100, তাই x-ও 100। Step 3: x = x + 1 মানে a[0] = 100 + 1 = 101।
Output: i=1, a = 101 10 15

(3) Pass-by-value-result। Call-এর সময় x = 5 (copy in) আর a[0]-এর address মনে রাখা হয়। Step 1: i = 1। Step 2: a[0] = 100 (local x এটা দেখে না)। Step 3: x = 6। Return-এর সময় copy out: a[0] = x = 6 — এটা 100-কে overwrite করে।
Output: i=1, a = 6 10 15

(4) Pass-by-name। Body-র প্রতিটা x-এর জায়গায় text a[i] বসে। Step 1: i = 1। Step 2: a[0] = 100। Step 3: a[i] = a[i] + 1, আর এখন i = 1, তাই a[1] = 10 + 1 = 11।
Output: i=1, a = 100 11 15

Methodia[0]a[1]a[2]
Pass-by-value11001015
Pass-by-reference11011015
Pass-by-value-result161015
Pass-by-name11001115
Verified: value and reference with a C program (pointer version); value-result and name with a Python simulation (copy-back, and a thunk that re-reads a[i]).
Verified: value আর reference C program দিয়ে (pointer version); value-result আর name Python simulation দিয়ে (copy-back, আর a[i] আবার পড়ার thunk)।
Exam tips: (1) Value-result and reference differ only when there is aliasing — the body touches the same variable through another name (a global, or the same variable passed twice). (2) Pass-by-name differs from reference only when the actual is an expression whose meaning can change, like a[i] when i changes. (3) If the question does not say when the copy-back address is computed, state your assumption (usually "at call time").
Exam tip: (১) Value-result আর reference আলাদা হয় শুধু aliasing থাকলে — body যদি অন্য নাম দিয়ে একই variable ছোঁয় (global, বা একই variable দুবার pass)। (২) Pass-by-name reference থেকে আলাদা হয় শুধু তখনই, যখন actual এমন expression যার মানে বদলাতে পারে, যেমন i বদলালে a[i]। (৩) প্রশ্নে copy-back address কখন হিসাব হয় না বললে, তোমার assumption লিখে দাও (সাধারণত "call time-এ")।
Java is ALWAYS pass-by-value. For an object, the reference is copied. So a method can change the object's fields (p.x = 5 is seen by the caller), but p = new Point() inside the method does not change the caller's variable. That is why a Java swap(Integer a, Integer b) cannot swap the caller's variables. Python works the same way ("pass by object reference" / "call by sharing").
Java সবসময় pass-by-value। Object-এর ক্ষেত্রে reference-টা copy হয়। তাই method object-এর field বদলাতে পারে (p.x = 5 caller দেখতে পায়), কিন্তু method-এর ভেতরে p = new Point() করলে caller-এর variable বদলায় না। এজন্যই Java-তে swap(Integer a, Integer b) caller-এর variable swap করতে পারে না। Python-ও একইভাবে কাজ করে ("pass by object reference" / "call by sharing")।

Activation records and the run-time stackActivation record আর run-time stack

Each time a subprogram is called, the system pushes an activation record (AR), also called a stack frame, on the run-time stack. When it returns, the AR is popped. A typical AR holds:

  • Return address — where to continue in the caller after return.
  • Dynamic link — pointer to the caller's AR (to restore the stack; also how dynamic scoping searches).
  • Static link — pointer to the AR of the static parent (the enclosing function in the source). Needed only in languages with nested functions (Pascal, Ada, Python closures) to find non-local variables under static scoping.
  • Parameters — values or addresses passed in.
  • Local variables (stack-dynamic) and temporary values.
  • Sometimes a slot for the return value and saved registers.

Because each call gets its own AR, recursion works: fact(3), fact(2), fact(1) each have their own n.

প্রতিবার কোনো subprogram call হলে system run-time stack-এ একটা activation record (AR) push করে, যাকে stack frame-ও বলে। Return করলে AR pop হয়। সাধারণ একটা AR-এ থাকে:

  • Return address — return-এর পরে caller-এর কোথা থেকে আবার চলবে।
  • Dynamic link — caller-এর AR-এর pointer (stack আগের অবস্থায় ফেরাতে; dynamic scoping এভাবেই খোঁজে)।
  • Static link — static parent-এর (source-এ যে function-এর ভেতরে লেখা) AR-এর pointer। শুধু nested function থাকা language-এ (Pascal, Ada, Python closure) static scoping-এ non-local variable খুঁজতে লাগে।
  • Parameters — pass করা value বা address।
  • Local variables (stack-dynamic) আর temporary value।
  • কখনো return value-এর জায়গা আর saved register।

প্রতিটা call নিজের AR পায় বলেই recursion কাজ করে: fact(3), fact(2), fact(1) — প্রত্যেকের নিজের n।

int fact(int n) {
    if (n <= 1) return 1;
    return n * fact(n - 1);     // return point "RA1"
}
int main() {
    int r = fact(3);            // return point "RA0"
    printf("%d\n", r);          // 6
}
Run-time stack at the deepest point (inside fact(1)) AR: fact(1) ← top parameter n = 1 return address = RA1 dynamic link → fact(2) AR: fact(2) parameter n = 2 return address = RA1 dynamic link → fact(3) AR: fact(3) parameter n = 3 return address = RA0 dynamic link → main AR: main ← bottom local r = ? (not yet set) return address → OS red arrows = dynamic links (to the caller) stack grows Unwinding (returns) 1. fact(1) returns 1 pop fact(1) 2. fact(2) = 2 * 1 = 2 pop fact(2) 3. fact(3) = 3 * 2 = 6 pop fact(3) 4. main: r = 6, print 6 Max stack depth = 4 ARs fact(n) needs n + 1 ARs (including main)
Run-time stack for fact(3): one activation record per call. Each AR has its own n, a return address and a dynamic link to its caller. Returns pop the ARs in reverse order.fact(3)-এর run-time stack: প্রতিটা call-এর জন্য একটা activation record। প্রতিটা AR-এর নিজের n, একটা return address আর caller-এর দিকে একটা dynamic link আছে। Return হলে উল্টো order-এ AR pop হয়।
Call stack layout showing stack frames for DrawSquare and DrawLine with parameters, return address and locals
A real call stack (Wikimedia Commons): each call gets its own stack frame with parameters, return address and local variables. The frame pointer marks the current frame.একটা আসল call stack (Wikimedia Commons): প্রতিটা call নিজের stack frame পায়, যেখানে parameter, return address আর local variable থাকে। Frame pointer current frame চিহ্নিত করে।
Static linkDynamic link
Points toকাকে point করেAR of the static parent (enclosing function in the source)Static parent-এর AR (source-এ ঘিরে থাকা function)AR of the callerCaller-এর AR
Used forকাজে লাগেFinding non-local variables under static scopingStatic scoping-এ non-local variable খুঁজতেRestoring the stack on return; non-local lookup under dynamic scopingReturn-এ stack ফেরাতে; dynamic scoping-এ non-local খুঁজতে
Needed in C?C-তে লাগে?No — C has no nested functions (non-locals are just globals)না — C-তে nested function নেই (non-local মানেই global)Yes (the saved frame pointer)হ্যাঁ (saved frame pointer)

Overloaded and generic subprogramsOverloaded আর generic subprogram

  • Overloaded subprogram — same name, different parameter profile (number/types/order of parameters). The compiler picks the right one at compile time. Return type alone is not enough to overload in C++/Java. C does not support overloading; Python does not either (a later def just replaces the earlier one).
  • Generic (polymorphic) subprogram — one piece of code that works for many types. C++ templates, Java generics (<T>), C# generics. This is called parametric polymorphism. (Overloading is ad hoc polymorphism; inheritance-based overriding is subtype polymorphism — see Chapter 02.)
  • Overloaded subprogram — একই নাম, আলাদা parameter profile (parameter-এর সংখ্যা/type/order)। Compiler compile time-এ ঠিকটা বেছে নেয়। C++/Java-তে শুধু return type আলাদা হলে overload হয় না। C overloading support করে না; Python-ও না (পরের def আগেরটাকে শুধু replace করে)।
  • Generic (polymorphic) subprogram — একটাই code যা অনেক type-এর জন্য কাজ করে। C++ template, Java generics (<T>), C# generics। একে বলে parametric polymorphism। (Overloading হলো ad hoc polymorphism; inheritance-ভিত্তিক overriding হলো subtype polymorphism — Chapter 02 দেখো।)
// C++ — verified output: "7 2.5 z" and "16 15 3.14"
template <typename T>
T maxOf(T a, T b) { return a > b ? a : b; }     // generic

int    area(int s)          { return s * s; }        // overloaded
int    area(int l, int w)   { return l * w; }
double area(double r)       { return 3.14 * r * r; }

cout << maxOf(3, 7) << " " << maxOf(2.5, 1.5) << " " << maxOf('a', 'z');
cout << area(4) << " " << area(3, 5) << " " << area(1.0);

// Java generic method
static <T extends Comparable<T>> T maxOf(T a, T b) { return a.compareTo(b) > 0 ? a : b; }

Closures: a subprogram plus the referencing environment where it was defined. In Python/JavaScript a nested function can return and still use its parent's variables (see the outer/inner example in Section 3). The parent's variables must then live on the heap, not the stack.

Closure: একটা subprogram আর যেখানে এটা define হয়েছে সেখানকার referencing environment — একসাথে। Python/JavaScript-এ nested function return হয়ে যাওয়ার পরেও parent-এর variable ব্যবহার করতে পারে (Section 3-এর outer/inner example দেখো)। তখন parent-এর variable-গুলো stack-এ না, heap-এ রাখতে হয়।

7. Memory Management and Exceptions7. Memory Management আর Exceptions

Static, stack and heap allocation — recapStatic, stack আর heap allocation — recap

AreaWhat lives thereকী থাকেAllocated / freedAllocate / free কখনSpeedSpeed
StaticGlobals, static variables, constants, codeGlobal, static variable, constant, codeAt load time / at program endLoad time-এ / program শেষেFastestসবচেয়ে দ্রুত
StackActivation records: parameters, locals, return addressActivation record: parameter, local, return addressAutomatically on call / return (LIFO)Call / return-এ আপনা-আপনি (LIFO)Very fast (move stack pointer)খুব দ্রুত (stack pointer সরানো)
HeapObjects created with new/malloc, dynamic structuresnew/malloc দিয়ে তৈরি object, dynamic structureAny order; freed by free/delete or by a garbage collectorযেকোনো order-এ; free/delete বা garbage collector দিয়ে freeSlower; can fragmentধীর; fragment হতে পারে

Picture of a C process memory layout (text, data, BSS, heap, stack) is in Chapter 01, Memory Concepts. OS-level paging is in Chapter 14.

C process-এর memory layout-এর ছবি (text, data, BSS, heap, stack) আছে Chapter 01, Memory Concepts-এ। OS-level paging আছে Chapter 14-এ।

Garbage collection (GC)Garbage collection (GC)

Garbage = heap objects that the program can no longer reach from any root (globals, local variables on the stack, registers). A garbage collector finds garbage and frees it automatically. Java, Python, C#, JavaScript, Lisp, Go have GC. C and C++ do not (C++ uses destructors and smart pointers instead).

1) Reference counting (eager)

Every object keeps a counter: how many pointers point to it. When a pointer is added, count +1. When a pointer is removed, count −1. When the count becomes 0, free the object immediately.

  • Plus: memory is freed at once, work is spread out (no long pauses).
  • Minus: extra space for each counter; extra time on every pointer assignment; and it cannot free cycles. If A points to B and B points to A, and nothing else points to them, both counts stay at 1 forever → memory leak.
  • Python (CPython) uses reference counting plus a separate cycle detector to fix this.

2) Mark-and-sweep (lazy / tracing)

Let garbage pile up. When memory runs low, stop the program and run two phases:

  1. Mark: start from every root; follow every pointer (like DFS on a graph); mark every object you reach as "alive".
  2. Sweep: walk through the whole heap; every unmarked object is garbage → put it back on the free list. Clear the marks for next time.
  • Plus: handles cycles correctly; no cost on every assignment.
  • Minus: "stop-the-world" pauses; the heap can become fragmented (small free holes).

3) Copying collector

Split the heap into two halves: from-space and to-space. Allocate only in from-space. When it is full, copy every reachable object into to-space (packed together), then swap the roles. Everything left behind is garbage.

  • Plus: no fragmentation (objects are compacted); very fast allocation (just bump a pointer); time depends only on live objects.
  • Minus: only half the memory is usable at a time; pointers must be updated after copying.

Modern JVMs use generational GC: most objects die young, so a small "young generation" is collected often with copying, and the "old generation" rarely with mark-sweep-compact.

Garbage = heap-এর সেইসব object যেগুলোতে program আর কোনো root (global, stack-এর local variable, register) থেকে পৌঁছাতে পারে না। Garbage collector garbage খুঁজে বের করে আপনা-আপনি free করে। Java, Python, C#, JavaScript, Lisp, Go-তে GC আছে। C আর C++-এ নেই (C++ এর বদলে destructor আর smart pointer ব্যবহার করে)।

১) Reference counting (eager)

প্রতিটা object একটা counter রাখে: কয়টা pointer তাকে point করছে। Pointer যোগ হলে count +1। Pointer সরে গেলে count −1। Count 0 হলে object-টা সাথে সাথে free।

  • সুবিধা: memory সাথে সাথে free হয়, কাজ ছড়িয়ে থাকে (লম্বা pause নেই)।
  • অসুবিধা: প্রতিটা counter-এর জন্য বাড়তি জায়গা; প্রতিটা pointer assignment-এ বাড়তি সময়; আর এটা cycle free করতে পারে না। A যদি B-কে আর B যদি A-কে point করে, আর বাইরে থেকে কেউ তাদের point না করে, তাহলে দুজনের count চিরকাল 1 থাকে → memory leak।
  • Python (CPython) reference counting-এর সাথে আলাদা একটা cycle detector ব্যবহার করে এই সমস্যা ঠিক করতে।

২) Mark-and-sweep (lazy / tracing)

Garbage জমতে দাও। Memory কমে গেলে program থামিয়ে দুইটা phase চালাও:

  1. Mark: প্রতিটা root থেকে শুরু করো; প্রতিটা pointer অনুসরণ করো (graph-এ DFS-এর মতো); যেখানে পৌঁছাও সেই object-কে "alive" mark করো।
  2. Sweep: পুরো heap ঘুরে দেখো; যে object unmarked সেটা garbage → free list-এ ফেরত দাও। পরেরবারের জন্য mark মুছে দাও।
  • সুবিধা: cycle ঠিকমতো handle করে; প্রতি assignment-এ খরচ নেই।
  • অসুবিধা: "stop-the-world" pause; heap fragmented হয়ে যেতে পারে (ছোট ছোট ফাঁকা জায়গা)।

৩) Copying collector

Heap-কে দুই ভাগ করো: from-space আর to-space। শুধু from-space-এ allocate করো। ভরে গেলে প্রতিটা reachable object to-space-এ copy করো (গায়ে গায়ে সাজিয়ে), তারপর দুই ভাগের ভূমিকা বদলাও। যা পেছনে রয়ে গেল সব garbage।

  • সুবিধা: fragmentation নেই (object-গুলো compact হয়); allocation খুব দ্রুত (শুধু একটা pointer বাড়ানো); সময় লাগে শুধু live object-এর ওপর।
  • অসুবিধা: একসাথে memory-র মাত্র অর্ধেক ব্যবহার করা যায়; copy করার পরে pointer update করতে হয়।

আধুনিক JVM generational GC ব্যবহার করে: বেশিরভাগ object অল্প বয়সেই মারা যায়, তাই ছোট একটা "young generation" ঘন ঘন copying দিয়ে collect হয়, আর "old generation" মাঝে মাঝে mark-sweep-compact দিয়ে।

Roots local p global g Heap A ✓ B ✓ C ✓ D ✗ E ✗ F ✗ cycle: D ⇄ E MARK: from roots p and g reach A, B, C → marked ✓ (alive) SWEEP: D, E, F are unmarked → freed ✗ (the D⇄E cycle is freed too) Reference counting would free only F (count 0). D and E keep count 1 each → leak.
Mark-and-sweep: everything reachable from the roots is marked; the rest (including the D⇄E cycle) is swept. Reference counting cannot free the cycle.Mark-and-sweep: root থেকে যা পৌঁছানো যায় সব mark হয়; বাকিগুলো (D⇄E cycle সহ) sweep হয়। Reference counting cycle free করতে পারে না।
Animation of the naive mark-and-sweep garbage collector: reachable objects get marked, then unmarked objects are swept
Animation (Wikimedia Commons): the mark phase walks from the roots and marks reachable objects; the sweep phase frees everything left unmarked.Animation (Wikimedia Commons): mark phase root থেকে হেঁটে reachable object-গুলো mark করে; sweep phase unmarked সবকিছু free করে।
Reference countingMark-and-sweepCopying
When it freesকখন free করেImmediately (count = 0)সাথে সাথে (count = 0)When memory runs lowMemory কমে গেলেWhen from-space is fullFrom-space ভরে গেলে
CyclesCycleNOT freed (leak)Free হয় না (leak)FreedFree হয়FreedFree হয়
PausesPauseSmall, spread outছোট, ছড়ানোLong (stop-the-world)লম্বা (stop-the-world)Proportional to live dataLive data-র সমানুপাতিক
FragmentationFragmentationYesহ্যাঁYes (unless compacted)হ্যাঁ (compact না করলে)No (compacts)না (compact করে)
Memory overheadMemory overheadA counter per objectপ্রতি object-এ একটা counterA mark bit per objectপ্রতি object-এ একটা mark bitHalf the heap is idleHeap-এর অর্ধেক অলস থাকে

Exception handlingException handling

An exception is an unusual event at run time (divide by zero, array index out of range, file not found, null pointer). The exception handler is the code that deals with it. Without exception handling, you would check error codes after every call (C style: if (fp == NULL) ...).

The model: raise → search → handle

  1. Code in a try block raises / throws an exception.
  2. The rest of the try block is skipped.
  3. The system looks for a matching catch / except in the same function. If none matches, the function ends and the exception propagates to the caller (the stack unwinds, popping ARs), and so on up to main. If nobody catches it, the program stops with an error message and stack trace.
  4. A finally block (Java, Python, C#) always runs — normal exit, exception, or even return. Use it to close files/locks. C++ has no finally; it uses destructors (RAII) instead.
  5. After a handler finishes, execution continues after the whole try-catch (the termination model) — not back at the line that failed.

Exception হলো run time-এ অস্বাভাবিক কোনো ঘটনা (zero দিয়ে ভাগ, array index range-এর বাইরে, file পাওয়া যায়নি, null pointer)। যে code এটা সামলায় তাকে বলে exception handler। Exception handling না থাকলে প্রতিটা call-এর পরে error code check করতে হতো (C style: if (fp == NULL) ...)।

Model: raise → search → handle

  1. try block-এর code একটা exception raise / throw করে।
  2. try block-এর বাকি অংশ skip হয়।
  3. System একই function-এ মিলে যায় এমন catch / except খোঁজে। না মিললে function শেষ হয়ে যায় আর exception caller-এর কাছে propagate করে (stack unwind হয়, AR pop হয়), এভাবে main পর্যন্ত। কেউ catch না করলে program error message আর stack trace দিয়ে থেমে যায়।
  4. finally block (Java, Python, C#) সবসময় চলে — স্বাভাবিকভাবে বের হলে, exception হলে, এমনকি return হলেও। File/lock বন্ধ করতে এটা ব্যবহার করো। C++-এ finally নেই; তার বদলে destructor (RAII) ব্যবহার হয়।
  5. Handler শেষ হলে execution পুরো try-catch-এর পরে চলতে থাকে (termination model) — যে line-এ error হয়েছিল সেখানে ফেরে না।
Same idea in three languages (all verified).
তিন language-এ একই idea (সব verified)।
// C++                                         Output:
double divide(int a, int b) {                  // 5
    if (b == 0) throw runtime_error("b is zero");  // Error: b is zero
    return (double)a / b;                      // end
}
int main() {
    try {
        cout << divide(10, 2) << endl;
        cout << divide(1, 0) << endl;         // throws here
        cout << "not printed" << endl;         // skipped
    } catch (const runtime_error& e) {
        cout << "Error: " << e.what() << endl;
    }
    cout << "end" << endl;
}

# Python                                       Output:
def f(x):                                      # ok
    try:                                       # cleanup
        r = 10 / x                             # 5.0
    except ZeroDivisionError:                  # div by zero
        print("div by zero"); r = -1           # cleanup
    else:                                      # -1
        print("ok")          # runs only if NO exception
    finally:
        print("cleanup")     # runs ALWAYS
    return r
print(f(2)); print(f(0))

// Java: finally runs even when try has a return   Output:
static int test() {                                // finally
    try { return 1; }                              // 1
    finally { System.out.println("finally"); }
}
System.out.println(test());
C++JavaPython
KeywordsKeywordtry / catch / throwtry / catch / finally / throw / throwstry / except / else / finally / raise
What can be thrownকী throw করা যায়Any type (even int)যেকোনো type (এমনকি int)Only Throwable objectsশুধু Throwable objectOnly BaseException objectsশুধু BaseException object
finallyNo (use destructors)নেই (destructor ব্যবহার)YesআছেYesআছে
Checked exceptionsChecked exceptionNoনেইYes — must catch or declare with throws (e.g. IOException). RuntimeExceptions are unchecked.আছে — catch করতে হবে বা throws দিয়ে declare করতে হবে (যেমন IOException)। RuntimeException unchecked।Noনেই
Divide int by zeroInt-কে zero দিয়ে ভাগUndefined behaviour (usually crash), NOT an exceptionUndefined behaviour (সাধারণত crash), exception নাArithmeticExceptionZeroDivisionError
Exam tip: In a catch list, put the most specific exception first. In Java, catch (Exception e) before catch (ArithmeticException e) is a compile error ("already caught"). Java's order: Throwable → Error (don't catch) / Exception → RuntimeException (unchecked) / other checked exceptions.
Exam tip: Catch list-এ সবচেয়ে specific exception আগে দাও। Java-তে catch (ArithmeticException e)-এর আগে catch (Exception e) দিলে compile error ("already caught")। Java-র hierarchy: Throwable → Error (catch কোরো না) / Exception → RuntimeException (unchecked) / অন্য checked exception।

Concurrency one-linersConcurrency এক লাইনে

  • Thread — a light-weight unit of execution inside a process; threads share the process's heap and globals but each has its own stack.
  • Race condition — two threads update shared data at the same time and the result depends on timing. Fix with mutual exclusion (locks, semaphores, monitors). Full detail in Chapter 14, Synchronization.
  • Java: Thread class / Runnable, synchronized methods (a built-in monitor). C++11: std::thread, std::mutex. Python: threading module, but the GIL lets only one thread run Python bytecode at a time (use multiprocessing for CPU work).
  • Deadlock — threads wait for each other forever (see Chapter 14, Deadlocks).
  • Go uses goroutines and channels; Erlang uses message passing (no shared memory).
  • Thread — process-এর ভেতরে হালকা একটা execution unit; thread-গুলো process-এর heap আর global share করে, কিন্তু প্রত্যেকের নিজের stack থাকে।
  • Race condition — দুটো thread একই সময়ে shared data update করে আর result timing-এর ওপর নির্ভর করে। Mutual exclusion (lock, semaphore, monitor) দিয়ে ঠিক করা হয়। বিস্তারিত Chapter 14, Synchronization-এ।
  • Java: Thread class / Runnable, synchronized method (built-in monitor)। C++11: std::thread, std::mutex। Python: threading module, কিন্তু GIL একসাথে শুধু একটা thread-কে Python bytecode চালাতে দেয় (CPU-র কাজের জন্য multiprocessing ব্যবহার করো)।
  • Deadlock — thread-গুলো একে অপরের জন্য চিরকাল অপেক্ষা করে (Chapter 14, Deadlocks দেখো)।
  • Go ব্যবহার করে goroutine আর channel; Erlang ব্যবহার করে message passing (shared memory নেই)।

8. Multi-language MCQ Corner8. Multi-language MCQ Corner

Ten tiny "what is the output?" snippets. Try each one yourself before reading the answer. Every output below was checked by actually running the code (Python 3, Java 17+, GCC on 64-bit Linux).

দশটা ছোট "output কী হবে?" snippet। Answer পড়ার আগে নিজে চেষ্টা করো। নিচের প্রতিটা output আসলে code চালিয়ে check করা হয়েছে (Python 3, Java 17+, 64-bit Linux-এ GCC)।

PythonPython

Snippet 1 — integer division vs true division
Snippet 1 — integer division vs true division
print(7 // 2, -7 // 2, 7 / 2, -7 % 3)
Output: 3 -4 3.5 2
// is floor division: it rounds down toward −∞, so −3.5 becomes −4 (C and Java give −3, because they round toward 0). / is always true division in Python 3 → float 3.5. The % result takes the sign of the divisor: -7 = 3 × (-3) + 2, so -7 % 3 = 2 (C/Java give −1).
Output: 3 -4 3.5 2
// হলো floor division: এটা −∞-এর দিকে নিচে round করে, তাই −3.5 হয় −4 (C আর Java দেয় −3, কারণ তারা 0-এর দিকে round করে)। Python 3-এ / সবসময় true division → float 3.5। %-এর result divisor-এর sign নেয়: -7 = 3 × (-3) + 2, তাই -7 % 3 = 2 (C/Java দেয় −1)।
Snippet 2 — list slicing
Snippet 2 — list slicing
a = [10, 20, 30, 40, 50]
print(a[1:4], a[::-2], a[-2:])
Output: [20, 30, 40] [50, 30, 10] [40, 50]
a[start:stop] includes start but excludes stop → indexes 1, 2, 3. a[::-2] starts at the end and takes every 2nd item backward. a[-2:] = last two items.
Output: [20, 30, 40] [50, 30, 10] [40, 50]
a[start:stop]-এ start থাকে কিন্তু stop থাকে না → index 1, 2, 3। a[::-2] শেষ থেকে শুরু করে পেছনের দিকে প্রতি ২য় item নেয়। a[-2:] = শেষ দুইটা item।
Snippet 3 — mutable default argument (famous trap)
Snippet 3 — mutable default argument (বিখ্যাত trap)
def add(x, lst=[]):
    lst.append(x)
    return lst
print(add(1))
print(add(2))
print(add(3, []))
Output:
[1]
[1, 2]
[3]
The default value [] is created once, when the def runs (binding at function-definition time), not on every call. So calls without lst share the same list. The third call passes its own new list. Fix: def add(x, lst=None): if lst is None: lst = [].
Output:
[1]
[1, 2]
[3]
Default value [] তৈরি হয় একবারই, যখন def চলে (function-definition time-এ binding), প্রতি call-এ না। তাই lst ছাড়া করা call-গুলো একই list share করে। তৃতীয় call নিজের নতুন list পাঠায়। Fix: def add(x, lst=None): if lst is None: lst = []।
Snippet 4 — is vs ==
Snippet 4 — is vs ==
a = [1, 2]; b = [1, 2]; c = a
print(a == b, a is b, a is c)
Output: True False True
== compares values (same content). is compares identity (same object in memory). a and b are two different lists with equal content. c = a makes an alias, not a copy. (Same idea as Java's == vs .equals() — see Chapter 02 Java Corner.)
Output: True False True
== value তুলনা করে (content একই কি না)। is identity তুলনা করে (memory-তে একই object কি না)। a আর b একই content-এর দুটো আলাদা list। c = a একটা alias বানায়, copy না। (Java-র == vs .equals()-এর মতোই idea — Chapter 02 Java Corner দেখো।)

JavaJava

Snippet 5 — integer overflow
Snippet 5 — integer overflow
int x = Integer.MAX_VALUE;   // 2147483647
x = x + 1;
System.out.println(x);
Output: -2147483648
Java int is 32-bit two's complement. Going past the maximum wraps around to the minimum. Java does not throw an exception for integer overflow. (In C, signed overflow is undefined behaviour. In Python, integers never overflow — they grow as big as needed.)
Output: -2147483648
Java-র int 32-bit two's complement। Maximum পার হলে ঘুরে minimum-এ চলে যায়। Integer overflow-এর জন্য Java কোনো exception দেয় না। (C-তে signed overflow undefined behaviour। Python-এ integer কখনো overflow হয় না — যত বড় দরকার তত বড় হয়।)
Snippet 6 — char arithmetic
Snippet 6 — char arithmetic
char c = 'A';
System.out.println(c + 1);
System.out.println((char)(c + 1));
System.out.println("" + c + 1);
Output:
66
B
A1
Line 1: char + int → the char is promoted to int ('A' = 65), so 66. Line 2: cast back to char → 'B'. Line 3: evaluation is left to right; "" + c is the String "A", then "A" + 1 is string concatenation → "A1".
Output:
66
B
A1
Line 1: char + int → char promote হয়ে int হয় ('A' = 65), তাই 66। Line 2: আবার char-এ cast → 'B'। Line 3: evaluation বাম থেকে ডানে; "" + c হলো String "A", তারপর "A" + 1 string concatenation → "A1"।
Snippet 7 — String immutability and + order
Snippet 7 — String immutability আর +-এর order
String s = "hi";
s.concat(" there");
System.out.println(s);
s = s.concat(" there");
System.out.println(s);
System.out.println(1 + 2 + "3" + 4 + 5);
Output:
hi
hi there
3345
Java String is immutable: concat returns a new String; if you ignore the result, s does not change. For the last line, + is left-associative: 1 + 2 = 3 (both ints), then 3 + "3" = "33" (now a String), then "334", then "3345". (More on the String pool in Chapter 02.)
Output:
hi
hi there
3345
Java-র String immutable: concat একটা নতুন String return করে; result ফেলে দিলে s বদলায় না। শেষ line-এ + left-associative: 1 + 2 = 3 (দুটোই int), তারপর 3 + "3" = "33" (এখন String), তারপর "334", তারপর "3345"। (String pool নিয়ে আরও আছে Chapter 02-এ।)

CC

Snippet 8 — sizeof vs strlen
Snippet 8 — sizeof vs strlen
char s[] = "BUET";
char *p = "BUET";
printf("%zu %zu %zu\n", sizeof(s), strlen(s), sizeof(p));
Output (64-bit): 5 4 8
sizeof(s) counts the array bytes including the hidden '\0' → 5. strlen counts characters before '\0' → 4. sizeof(p) is the size of a pointer, not the string → 8 on a 64-bit machine (4 on 32-bit). sizeof is worked out at compile time.
Output (64-bit): 5 4 8
sizeof(s) লুকানো '\0' সহ array-র byte গোনে → 5। strlen '\0'-এর আগের character গোনে → 4। sizeof(p) হলো একটা pointer-এর size, string-এর না → 64-bit machine-এ 8 (32-bit-এ 4)। sizeof compile time-এ হিসাব হয়।
Snippet 9 — pre vs post increment
Snippet 9 — pre vs post increment
int i = 5;
int j = i++ + 10;
int k = ++i * 2;
printf("%d %d %d\n", i, j, k);
Output: 7 15 14
i++ gives the old value 5, then i becomes 6 → j = 5 + 10 = 15. ++i makes i = 7 first, then uses 7 → k = 14. (Each statement changes i only once, so this is well-defined. Something like i++ + ++i would be undefined behaviour.)
Output: 7 15 14
i++ পুরোনো value 5 দেয়, তারপর i হয় 6 → j = 5 + 10 = 15। ++i আগে i = 7 করে, তারপর 7 ব্যবহার করে → k = 14। (প্রতিটা statement i-কে একবারই বদলায়, তাই এটা well-defined। i++ + ++i-এর মতো কিছু হলে undefined behaviour।)
Snippet 10 — integer division in C
Snippet 10 — C-তে integer division
int a = 7, b = 2;
float f = a / b;
printf("%.2f %.2f %d %d\n", f, (float)a / b, -7 / 2, -7 % 3);
Output: 3.00 3.50 -3 -1
a / b is int / int, so the answer is 3 first; only then is it converted to float 3.00. Cast one operand first ((float)a / b) to get 3.50. C (since C99) truncates toward zero: -7 / 2 = -3, and -7 % 3 = -1 (sign follows the dividend). Compare with Python's -4 and 2 in Snippet 1!
Output: 3.00 3.50 -3 -1
a / b হলো int / int, তাই আগে answer হয় 3; তারপরে float 3.00-এ convert হয়। 3.50 পেতে আগে একটা operand cast করো ((float)a / b)। C (C99 থেকে) শূন্যের দিকে truncate করে: -7 / 2 = -3, আর -7 % 3 = -1 (sign dividend-এর মতো)। Snippet 1-এর Python-এর -4 আর 2-এর সাথে তুলনা করো!
Cross-language cheat sheet: -7 / 2 → C/Java: −3, Python //: −4, Python /: −3.5. -7 % 3 → C/Java: −1, Python: 2. Integer overflow → C: undefined, Java: wraps, Python: never. a > b > c → C/JS: left-assoc trick, Java: compile error, Python: chained comparison.
Cross-language cheat sheet: -7 / 2 → C/Java: −3, Python //: −4, Python /: −3.5। -7 % 3 → C/Java: −1, Python: 2। Integer overflow → C: undefined, Java: wrap হয়, Python: কখনো না। a > b > c → C/JS: left-assoc trick, Java: compile error, Python: chained comparison।

Practice Questions (IICT Style)Practice Questions (IICT Style)

20 questions, easy → hard. Q1–Q12 are IICT MCQ style; Q13–Q20 are IICT written style (trace / explain). Every code output was verified by running it.

২০টা প্রশ্ন, সহজ → কঠিন। Q1–Q12 IICT MCQ style; Q13–Q20 IICT written style (trace / ব্যাখ্যা)। প্রতিটা code output চালিয়ে verify করা।

Q1. (IICT MCQ style) Prolog belongs to which programming paradigm?
  • (a) Imperative
  • (b) Object-oriented
  • (c) Logic
  • (d) Functional
Q1. (IICT MCQ style) Prolog কোন programming paradigm-এর অন্তর্ভুক্ত?
  • (a) Imperative
  • (b) Object-oriented
  • (c) Logic
  • (d) Functional
Show Answerউত্তর দেখুন
Answer: (c) — In Prolog you write facts and rules, then ask queries. The system finds answers by unification and backtracking. That is logic (declarative) programming. Lisp/Haskell are functional; C is imperative; Java is OOP.
Answer: (c) — Prolog-এ তুমি fact আর rule লেখো, তারপর query করো। System unification আর backtracking দিয়ে উত্তর বের করে। এটাই logic (declarative) programming। Lisp/Haskell functional; C imperative; Java OOP।
Q2. (IICT MCQ style) Which was the first widely used high-level programming language, designed mainly for scientific computing?
  • (a) COBOL
  • (b) Fortran
  • (c) Lisp
  • (d) C
Q2. (IICT MCQ style) প্রথম বহুল ব্যবহৃত high-level programming language কোনটা, যা মূলত scientific computing-এর জন্য বানানো?
  • (a) COBOL
  • (b) Fortran
  • (c) Lisp
  • (d) C
Show Answerউত্তর দেখুন
Answer: (b) — Fortran (FORmula TRANslation, IBM, 1957) came first and was made for scientific number crunching. Lisp (1958) is the first functional language; COBOL (1959) is for business; C came in 1972.
Answer: (b) — Fortran (FORmula TRANslation, IBM, 1957) সবার আগে এসেছে আর scientific হিসাব-নিকাশের জন্য বানানো। Lisp (1958) প্রথম functional language; COBOL (1959) business-এর জন্য; C এসেছে 1972-এ।
Q3. (IICT MCQ style) Which statement best describes how a Java program is executed?
  • (a) Source is compiled directly into native machine code
  • (b) Source is interpreted line by line
  • (c) Source is compiled to bytecode, which the JVM interprets and JIT-compiles
  • (d) Source is translated by an assembler
Q3. (IICT MCQ style) Java program কীভাবে execute হয় — কোন statement সবচেয়ে ভালো বর্ণনা করে?
  • (a) Source সরাসরি native machine code-এ compile হয়
  • (b) Source line by line interpret হয়
  • (c) Source bytecode-এ compile হয়, যা JVM interpret আর JIT-compile করে
  • (d) Source assembler দিয়ে translate হয়
Show Answerউত্তর দেখুন
Answer: (c) — Java is a hybrid implementation: javac makes platform-independent .class bytecode; the JVM runs it, and its JIT compiler turns hot code into machine code at run time. This gives "write once, run anywhere".
Answer: (c) — Java একটা hybrid implementation: javac platform-independent .class bytecode বানায়; JVM সেটা চালায়, আর তার JIT compiler run time-এ hot code-কে machine code বানায়। এজন্যই "write once, run anywhere"।
Q4. (IICT MCQ style) Python's type system is best described as:
  • (a) Static and strong
  • (b) Static and weak
  • (c) Dynamic and strong
  • (d) Dynamic and weak
Q4. (IICT MCQ style) Python-এর type system-কে সবচেয়ে ভালোভাবে বলা যায়:
  • (a) Static আর strong
  • (b) Static আর weak
  • (c) Dynamic আর strong
  • (d) Dynamic আর weak
Show Answerউত্তর দেখুন
Answer: (c) — Dynamic: types are bound and checked at run time (x = 5 then x = "hi" is fine). Strong: Python refuses to silently mix unrelated types — "5" + 3 raises TypeError. JavaScript would be dynamic and weak ("5" + 3 gives "53").
Answer: (c) — Dynamic: type run time-এ bind আর check হয় (x = 5 তারপর x = "hi" — কোনো সমস্যা নেই)। Strong: Python চুপচাপ সম্পর্কহীন type মেশায় না — "5" + 3 দিলে TypeError। JavaScript হলো dynamic আর weak ("5" + 3 দেয় "53")।
Q5. (IICT MCQ style) In C, a non-static local variable of a function is bound to its memory cell at:
  • (a) Language design time
  • (b) Compile time
  • (c) Load time
  • (d) Run time
Q5. (IICT MCQ style) C-তে একটা function-এর non-static local variable তার memory cell-এর সাথে bind হয়:
  • (a) Language design time-এ
  • (b) Compile time-এ
  • (c) Load time-এ
  • (d) Run time-এ
Show Answerউত্তর দেখুন
Answer: (d) — Such a variable is stack-dynamic: its cell is allocated in the activation record when the function is called (run time) and freed on return. Its type is bound at compile time, and a static/global variable's cell at load time — those are the distractors.
Answer: (d) — এমন variable হলো stack-dynamic: function call হলে (run time) activation record-এ তার cell allocate হয়, আর return-এ free হয়। এর type bind হয় compile time-এ, আর static/global variable-এর cell load time-এ — ওগুলো হলো ভুল option-এর ফাঁদ।
Q6. (IICT MCQ style) What does this Python code print? print(2 ** 3 ** 2)
  • (a) 64
  • (b) 512
  • (c) 36
  • (d) SyntaxError
Q6. (IICT MCQ style) এই Python code কী print করবে? print(2 ** 3 ** 2)
  • (a) 64
  • (b) 512
  • (c) 36
  • (d) SyntaxError
Show Answerউত্তর দেখুন
Answer: (b) — ** is right-associative: 2 ** (3 ** 2) = 2 ** 9 = 512. If you wrongly go left to right you get (2 ** 3) ** 2 = 64, which is the trap option.
Answer: (b) — ** right-associative: 2 ** (3 ** 2) = 2 ** 9 = 512। ভুল করে বাম থেকে ডানে করলে পাবে (2 ** 3) ** 2 = 64, যেটা trap option।
Q7. (IICT MCQ style) What is the output of this C code?
int a = 0, b = 5;
if (a && ++b) {}
if (a || ++b) {}
printf("%d %d", a, b);
  • (a) 0 5
  • (b) 0 6
  • (c) 0 7
  • (d) 1 6
Q7. (IICT MCQ style) এই C code-এর output কী?
int a = 0, b = 5;
if (a && ++b) {}
if (a || ++b) {}
printf("%d %d", a, b);
  • (a) 0 5
  • (b) 0 6
  • (c) 0 7
  • (d) 1 6
Show Answerউত্তর দেখুন
Answer: (b) — Short-circuit evaluation. First if: a is 0 (false), so && skips ++b. Second if: a is false, so || must check the right side → ++b runs, b = 6. a is never changed. Output 0 6 (verified).
Answer: (b) — Short-circuit evaluation। প্রথম if: a 0 (false), তাই && ++b skip করে। দ্বিতীয় if: a false, তাই ||-কে ডান পাশ দেখতেই হবে → ++b চলে, b = 6। a কখনো বদলায় না। Output 0 6 (verified)।
Q8. (IICT MCQ style) Consider the pseudocode below. What is printed under static scoping and under dynamic scoping, respectively?
int x = 1;
void p() { print(x); }
void q() { int x = 2; p(); }
main()   { q(); }
  • (a) 1 and 1
  • (b) 2 and 2
  • (c) 1 and 2
  • (d) 2 and 1
Q8. (IICT MCQ style) নিচের pseudocode দেখো। Static scoping আর dynamic scoping-এ যথাক্রমে কী print হবে?
int x = 1;
void p() { print(x); }
void q() { int x = 2; p(); }
main()   { q(); }
  • (a) 1 আর 1
  • (b) 2 আর 2
  • (c) 1 আর 2
  • (d) 2 আর 1
Show Answerউত্তর দেখুন
Answer: (c) — x is non-local in p. Static: p is written at the top level, so its x is the global x = 1. Dynamic: look at the caller of p, which is q; q has x = 2, so it prints 2. (Checked in Bash, which is dynamically scoped: prints 2.)
Answer: (c) — p-তে x non-local। Static: p top level-এ লেখা, তাই তার x হলো global x = 1। Dynamic: p-এর caller q-তে দেখো; q-তে x = 2, তাই print হয় 2। (Bash-এ check করা, যেটা dynamically scoped: 2 print করে।)
Q9. (IICT MCQ style) Which garbage collection technique, used alone, CANNOT reclaim a group of objects that point to each other in a cycle but are unreachable from the program?
  • (a) Mark-and-sweep
  • (b) Copying collection
  • (c) Reference counting
  • (d) Generational collection
Q9. (IICT MCQ style) কোন garbage collection technique একা ব্যবহার করলে এমন object-এর group ফেরত নিতে পারে না, যারা cycle-এ একে অপরকে point করে কিন্তু program থেকে unreachable?
  • (a) Mark-and-sweep
  • (b) Copying collection
  • (c) Reference counting
  • (d) Generational collection
Show Answerউত্তর দেখুন
Answer: (c) — In a cycle each object is pointed to by another member of the cycle, so no count ever drops to 0. The tracing collectors (a), (b), (d) start from the roots, never reach the cycle, and free it.
Answer: (c) — Cycle-এ প্রতিটা object-কে cycle-এর অন্য একজন point করে, তাই কারও count কখনো 0 হয় না। Tracing collector-গুলো (a), (b), (d) root থেকে শুরু করে, cycle-এ পৌঁছায় না, তাই সেটা free করে দেয়।
Q10. (IICT MCQ style) What does this Java statement print? System.out.println('a' + 'b' + "c");
  • (a) abc
  • (b) 195c
  • (c) 97 98c
  • (d) Compile error
Q10. (IICT MCQ style) এই Java statement কী print করবে? System.out.println('a' + 'b' + "c");
  • (a) abc
  • (b) 195c
  • (c) 97 98c
  • (d) Compile error
Show Answerউত্তর দেখুন
Answer: (b) — + goes left to right. 'a' + 'b' is char + char, which is numeric addition after promotion to int: 97 + 98 = 195. Then 195 + "c" is String concatenation → "195c" (verified).
Answer: (b) — + বাম থেকে ডানে চলে। 'a' + 'b' হলো char + char, যা int-এ promote হয়ে সংখ্যার যোগ: 97 + 98 = 195। তারপর 195 + "c" String concatenation → "195c" (verified)।
Q11. (IICT MCQ style) A Java object created with new belongs to which lifetime category?
  • (a) Static
  • (b) Stack-dynamic
  • (c) Explicit heap-dynamic
  • (d) Implicit heap-dynamic
Q11. (IICT MCQ style) new দিয়ে তৈরি Java object কোন lifetime category-র?
  • (a) Static
  • (b) Stack-dynamic
  • (c) Explicit heap-dynamic
  • (d) Implicit heap-dynamic
Show Answerউত্তর দেখুন
Answer: (c) — The programmer explicitly asks for heap memory with the new operator. (Java frees it implicitly via garbage collection, but allocation is explicit.) Implicit heap-dynamic means storage is bound just by assigning, like Python/JavaScript variables.
Answer: (c) — Programmer new operator দিয়ে explicitly heap memory চায়। (Java garbage collection দিয়ে implicitly free করে, কিন্তু allocation explicit।) Implicit heap-dynamic মানে শুধু assign করলেই storage bind হয়, যেমন Python/JavaScript variable।
Q12. (IICT MCQ style) What does this Python code print?
x = [[0] * 2] * 2
x[0][0] = 1
print(x)
  • (a) [[1, 0], [0, 0]]
  • (b) [[1, 0], [1, 0]]
  • (c) [[1, 1], [0, 0]]
  • (d) TypeError
Q12. (IICT MCQ style) এই Python code কী print করবে?
x = [[0] * 2] * 2
x[0][0] = 1
print(x)
  • (a) [[1, 0], [0, 0]]
  • (b) [[1, 0], [1, 0]]
  • (c) [[1, 1], [0, 0]]
  • (d) TypeError
Show Answerউত্তর দেখুন
Answer: (b) — [inner] * 2 copies the reference to the same inner list twice, so x[0] and x[1] are aliases of one list. Changing x[0][0] shows up in both rows. Correct way: x = [[0] * 2 for _ in range(2)] (verified).
Answer: (b) — [inner] * 2 একই inner list-এর reference দুবার copy করে, তাই x[0] আর x[1] একটা list-এরই alias। x[0][0] বদলালে দুই row-তেই দেখা যায়। ঠিক উপায়: x = [[0] * 2 for _ in range(2)] (verified)।
Q13. (IICT written style) Distinguish between a compiler, an interpreter and a hybrid implementation system. Why is Java called "platform independent"? What is a JIT compiler and why does it help?
Q13. (IICT written style) Compiler, interpreter আর hybrid implementation system-এর পার্থক্য লেখো। Java-কে কেন "platform independent" বলে? JIT compiler কী আর এটা কীভাবে সাহায্য করে?
Show Answerউত্তর দেখুন
Answer:
  • Compiler: translates the whole program into machine code once; the executable then runs fast; errors reported before running; output depends on the target CPU/OS (C, C++).
  • Interpreter: reads and runs the source one statement at a time; no executable; slow (each statement is decoded every time it runs); easy to debug (Bash, early BASIC).
  • Hybrid: compile to an intermediate bytecode, then a virtual machine interprets it (Java, Python, C#). Faster than pure interpretation, and portable.
Platform independence: javac produces bytecode, not machine code. Bytecode is the same on every OS. Any machine with a JVM can run it → "write once, run anywhere". Only the JVM itself is platform-specific.
JIT: a compiler inside the JVM that, at run time, compiles frequently used ("hot") bytecode into native machine code and caches it. Later calls run native code directly, so the cost of interpreting is removed from loops and hot methods. It can even optimize using real run-time information.
Answer:
  • Compiler: পুরো program একবারে machine code-এ translate করে; তারপর executable দ্রুত চলে; চালানোর আগেই error জানায়; output target CPU/OS-এর ওপর নির্ভরশীল (C, C++)।
  • Interpreter: source একবারে একটা statement পড়ে আর চালায়; executable নেই; ধীর (প্রতিটা statement যতবার চলে ততবার decode হয়); debug করা সহজ (Bash, পুরোনো BASIC)।
  • Hybrid: intermediate bytecode-এ compile, তারপর virtual machine সেটা interpret করে (Java, Python, C#)। Pure interpretation-এর চেয়ে দ্রুত, আর portable।
Platform independence: javac machine code না, bytecode বানায়। Bytecode সব OS-এ একই। JVM আছে এমন যেকোনো machine এটা চালাতে পারে → "write once, run anywhere"। শুধু JVM নিজে platform-specific।
JIT: JVM-এর ভেতরের একটা compiler, যা run time-এ বারবার ব্যবহৃত ("hot") bytecode-কে native machine code-এ compile করে cache করে রাখে। পরের call-গুলো সরাসরি native code চালায়, তাই loop আর hot method থেকে interpret করার খরচ চলে যায়। এটা আসল run-time তথ্য দেখে optimize-ও করতে পারে।
Q14. (IICT written style) Explain "strong vs weak" and "static vs dynamic" typing. Classify C, Java, Python and JavaScript. Give the result of "5" + 3 and "5" - 3 in JavaScript and "5" + 3 in Python, and say what each shows.
Q14. (IICT written style) "Strong vs weak" আর "static vs dynamic" typing ব্যাখ্যা করো। C, Java, Python আর JavaScript-কে classify করো। JavaScript-এ "5" + 3 আর "5" - 3, আর Python-এ "5" + 3-এর result লেখো, আর প্রতিটা কী বোঝায় বলো।
Show Answerউত্তর দেখুন
Answer: Static/dynamic = when types are checked (compile time vs run time). Strong/weak = how strictly (strong: every type error is caught, no silent mixing; weak: the language silently converts or reinterprets).
  • C: static, weak (unions, pointer casts, no bound check).
  • Java: static, strong.
  • Python: dynamic, strong.
  • JavaScript: dynamic, weak.
JavaScript: "5" + 3 → "53" (number coerced to string, then concatenation); "5" - 3 → 2 (string coerced to number). Same-looking operations give different kinds of result — silent coercion = weak typing.
Python: "5" + 3 → TypeError at run time. The error is caught (strong), but only when the line runs (dynamic). You must convert explicitly: int("5") + 3 = 8. (All verified with Node.js and Python 3.)
Answer: Static/dynamic = type কখন check হয় (compile time vs run time)। Strong/weak = কতটা কড়াভাবে (strong: প্রতিটা type error ধরা পড়ে, চুপচাপ মেশানো নেই; weak: language চুপচাপ convert বা অন্যভাবে পড়ে ফেলে)।
  • C: static, weak (union, pointer cast, bound check নেই)।
  • Java: static, strong।
  • Python: dynamic, strong।
  • JavaScript: dynamic, weak।
JavaScript: "5" + 3 → "53" (number string-এ coerce হয়ে concatenation); "5" - 3 → 2 (string number-এ coerce)। দেখতে একই রকম operation আলাদা ধরনের result দেয় — চুপচাপ coercion = weak typing।
Python: "5" + 3 → run time-এ TypeError। Error ধরা পড়ে (strong), কিন্তু শুধু line চলার সময় (dynamic)। Explicitly convert করতে হয়: int("5") + 3 = 8। (সব Node.js আর Python 3 দিয়ে verified।)
Q15. (IICT written style) For int fib(int n) { if (n < 2) return n; return fib(n-1) + fib(n-2); } called as fib(3) from main: (i) How many times is fib called in total? (ii) What is the maximum number of activation records on the stack at one time (count main)? (iii) List what one activation record of fib contains.
Q15. (IICT written style) int fib(int n) { if (n < 2) return n; return fib(n-1) + fib(n-2); }-কে main থেকে fib(3) হিসেবে call করা হলো: (i) মোট কতবার fib call হয়? (ii) একসাথে stack-এ সর্বোচ্চ কয়টা activation record থাকে (main সহ)? (iii) fib-এর একটা activation record-এ কী কী থাকে লেখো।
Show Answerউত্তর দেখুন
Answer: Call tree: fib(3) → fib(2) + fib(1); fib(2) → fib(1) + fib(0).
  1. Calls: fib(3), fib(2), fib(1), fib(0), fib(1) = 5 calls. Result = 2.
  2. Deepest path: main → fib(3) → fib(2) → fib(1) (or fib(0)). That is 4 ARs (3 for fib + 1 for main). Note: the second fib(1) (called from fib(3)) is pushed only after fib(2) has been popped, so the stack never holds all 5 fib calls at once. Depth grows as O(n) while total calls grow exponentially.
  3. An AR of fib holds: parameter n; return address (inside the caller's expression); dynamic link (caller's AR / saved frame pointer); a temporary to hold the result of fib(n-1) while fib(n-2) runs; space for the return value (or a register). No static link is needed in C (no nested functions).
(Counts verified by an instrumented Python version: 5 calls, max fib depth 3.)
Answer: Call tree: fib(3) → fib(2) + fib(1); fib(2) → fib(1) + fib(0)।
  1. Call: fib(3), fib(2), fib(1), fib(0), fib(1) = ৫টা call। Result = 2।
  2. সবচেয়ে গভীর path: main → fib(3) → fib(2) → fib(1) (বা fib(0))। মোট ৪টা AR (fib-এর ৩টা + main-এর ১টা)। খেয়াল করো: দ্বিতীয় fib(1) (fib(3) থেকে call) push হয় শুধু fib(2) pop হওয়ার পরে, তাই stack-এ কখনো ৫টা fib call একসাথে থাকে না। Depth বাড়ে O(n) হারে, কিন্তু মোট call বাড়ে exponential হারে।
  3. fib-এর একটা AR-এ থাকে: parameter n; return address (caller-এর expression-এর ভেতরে); dynamic link (caller-এর AR / saved frame pointer); fib(n-2) চলার সময় fib(n-1)-এর result রাখার একটা temporary; return value-এর জায়গা (বা register)। C-তে static link লাগে না (nested function নেই)।
(Count-গুলো instrumented Python version দিয়ে verified: ৫টা call, fib-এর max depth 3।)
Q16. (IICT written style) Give the output of the program below (a) with static scoping, (b) with dynamic scoping. Show the steps.
int a = 1, b = 2;
void g()  { a = a + b; print(a, b); }
void f()  { int a = 10; b = b + 1; g(); print(a, b); }
main()    { f(); print(a, b); }
Q16. (IICT written style) নিচের program-এর output লেখো (a) static scoping-এ, (b) dynamic scoping-এ। ধাপগুলো দেখাও।
int a = 1, b = 2;
void g()  { a = a + b; print(a, b); }
void f()  { int a = 10; b = b + 1; g(); print(a, b); }
main()    { f(); print(a, b); }
Show Answerউত্তর দেখুন
Answer: Only f has a local a. Nobody has a local b, so b is always the global b in both rules.
(a) Static scoping — g is written at top level, so its a is the global a.
  1. f: local a = 10; global b = 2 + 1 = 3.
  2. g: global a = 1 + 3 = 4 → prints 4 3.
  3. Back in f: its local a = 10, b = 3 → prints 10 3.
  4. main: global a = 4, b = 3 → prints 4 3.
(b) Dynamic scoping — g's a is found in its caller f.
  1. f: local a = 10; b (global) = 3.
  2. g: f's a = 10 + 3 = 13 → prints 13 3.
  3. Back in f: its a is now 13 → prints 13 3.
  4. main: f is gone; global a was never changed = 1, b = 3 → prints 1 3.
Verified: C gives 4 3 / 10 3 / 4 3; the same program in Bash (dynamic scoping, local a=10) gives 13 3 / 13 3 / 1 3.
Answer: শুধু f-এর local a আছে। কারও local b নেই, তাই দুই rule-এই b সবসময় global b।
(a) Static scoping — g top level-এ লেখা, তাই তার a global a।
  1. f: local a = 10; global b = 2 + 1 = 3।
  2. g: global a = 1 + 3 = 4 → print 4 3।
  3. f-এ ফিরে: তার local a = 10, b = 3 → print 10 3।
  4. main: global a = 4, b = 3 → print 4 3।
(b) Dynamic scoping — g-এর a পাওয়া যায় তার caller f-এ।
  1. f: local a = 10; b (global) = 3।
  2. g: f-এর a = 10 + 3 = 13 → print 13 3।
  3. f-এ ফিরে: তার a এখন 13 → print 13 3।
  4. main: f শেষ; global a কখনো বদলায়নি = 1, b = 3 → print 1 3।
Verified: C দেয় 4 3 / 10 3 / 4 3; একই program Bash-এ (dynamic scoping, local a=10) দেয় 13 3 / 13 3 / 1 3।
Q17. (IICT written style) Find the value of a printed by main if parameters are passed (i) by value, (ii) by reference, (iii) by value-result (copy back x first, then y). Explain why (ii) and (iii) differ.
void f(int x, int y) { x = x + 1; y = y * 2; }
main() { int a = 3; f(a, a); print(a); }
Q17. (IICT written style) Parameter যদি (i) by value, (ii) by reference, (iii) by value-result (আগে x, তারপর y copy back) pass হয়, তাহলে main a-এর কোন value print করবে? (ii) আর (iii) কেন আলাদা, ব্যাখ্যা করো।
void f(int x, int y) { x = x + 1; y = y * 2; }
main() { int a = 3; f(a, a); print(a); }
Show Answerউত্তর দেখুন
Answer:
  1. By value: x = 3, y = 3 are copies. Changes stay local. a = 3.
  2. By reference: x and y are both aliases of a. x = x + 1 → a = 4. y = y * 2 → a = 4 × 2 = 8.
  3. By value-result: copy in: x = 3, y = 3 (separate locals). x = 4, y = 6. Copy out: a = x = 4, then a = y = 6 → 6. (If the copy-back order were y then x, the answer would be 4 — so value-result with aliasing depends on the copy-back order.)
They differ because of aliasing: the same variable is passed twice. With reference, the second statement sees the first change (a is already 4). With value-result, each formal works on its own copy, so y still starts from 3. Verified with C++ references (8), value (3), and a copy-in/copy-out simulation (6).
Answer:
  1. By value: x = 3, y = 3 — copy। পরিবর্তন local-এই থাকে। a = 3।
  2. By reference: x আর y দুটোই a-এর alias। x = x + 1 → a = 4। y = y * 2 → a = 4 × 2 = 8।
  3. By value-result: copy in: x = 3, y = 3 (আলাদা local)। x = 4, y = 6। Copy out: a = x = 4, তারপর a = y = 6 → 6। (Copy-back order যদি আগে y পরে x হতো, উত্তর হতো 4 — তাই aliasing থাকলে value-result copy-back order-এর ওপর নির্ভর করে।)
পার্থক্যের কারণ aliasing: একই variable দুবার pass হয়েছে। Reference-এ দ্বিতীয় statement প্রথম পরিবর্তন দেখতে পায় (a আগেই 4)। Value-result-এ প্রতিটা formal নিজের copy-তে কাজ করে, তাই y তখনো 3 থেকে শুরু করে। C++ reference (8), value (3), আর copy-in/copy-out simulation (6) দিয়ে verified।
Q18. (IICT written style) The procedure below is called as swap(i, a[i]) with i = 1 and a[1] = 3, a[2] = 5, a[3] = 7. Find i and the array after the call using (a) pass-by-reference and (b) pass-by-name. Does swap work in both?
procedure swap(x, y) {
    t = x;
    x = y;
    y = t;
}
Q18. (IICT written style) নিচের procedure-কে i = 1 আর a[1] = 3, a[2] = 5, a[3] = 7 অবস্থায় swap(i, a[i]) হিসেবে call করা হলো। (a) pass-by-reference আর (b) pass-by-name-এ call-এর পরে i আর array কী হবে? দুই ক্ষেত্রেই কি swap কাজ করে?
procedure swap(x, y) {
    t = x;
    x = y;
    y = t;
}
Show Answerউত্তর দেখুন
Answer:
(a) By reference: at the call, x → i, y → a[1] (addresses fixed now, since i = 1). t = i = 1; i = a[1] = 3; a[1] = t = 1. Result: i = 3, a = [1, 5, 7]. Correct swap ✓.
(b) By name: x means the text i, y means the text a[i], re-evaluated at each use.
  1. t = i → t = 1.
  2. i = a[i] → i = a[1] = 3.
  3. a[i] = t → now i is 3, so a[3] = 1.
Result: i = 3, a = [3, 5, 1]. a[1] was never changed, and a[3] was wrongly overwritten. Swap fails ✗. This famous example shows why it is impossible to write a correct general swap using pass-by-name in ALGOL 60. (Both results verified by simulation.)
Answer:
(a) By reference: call-এর সময় x → i, y → a[1] (address এখনই ঠিক, কারণ i = 1)। t = i = 1; i = a[1] = 3; a[1] = t = 1। Result: i = 3, a = [1, 5, 7]। ঠিকমতো swap ✓।
(b) By name: x মানে text i, y মানে text a[i], প্রতিবার ব্যবহারে আবার evaluate হয়।
  1. t = i → t = 1।
  2. i = a[i] → i = a[1] = 3।
  3. a[i] = t → এখন i = 3, তাই a[3] = 1।
Result: i = 3, a = [3, 5, 1]। a[1] কখনো বদলায়নি, আর a[3] ভুল করে overwrite হয়েছে। Swap ব্যর্থ ✗। এই বিখ্যাত example দেখায় কেন ALGOL 60-এ pass-by-name দিয়ে একটা সঠিক general swap লেখা অসম্ভব। (দুই result-ই simulation দিয়ে verified।)
Q19. (IICT written style) A heap has objects P, Q, R, S, T. The only root is a local variable r that points to P. Pointers: P → Q, Q → P, R → S, S → R, T → Q. (i) Give the reference count of each object. (ii) Which objects does reference counting free? (iii) Which objects does mark-and-sweep free? (iv) Explain the difference.
Q19. (IICT written style) একটা heap-এ P, Q, R, S, T object আছে। একমাত্র root হলো local variable r, যেটা P-কে point করে। Pointer: P → Q, Q → P, R → S, S → R, T → Q। (i) প্রতিটা object-এর reference count লেখো। (ii) Reference counting কোন object free করবে? (iii) Mark-and-sweep কোনগুলো free করবে? (iv) পার্থক্য ব্যাখ্যা করো।
Show Answerউত্তর দেখুন
Answer:
  1. Counts: P = 2 (from r and Q), Q = 2 (from P and T), R = 1 (from S), S = 1 (from R), T = 0.
  2. Reference counting: only T has count 0 → T is freed. Freeing T removes the pointer T → Q, so Q drops to 1 (still alive, correctly). R and S keep count 1 forever → leaked. Freed: {T}.
  3. Mark-and-sweep: mark from root r → P → Q (→ P already marked). Marked = {P, Q}. Sweep the unmarked: {R, S, T}.
  4. Reference counting only knows "how many pointers", not "reachable from a root". The unreachable cycle R ⇄ S keeps its own counts above 0. Mark-and-sweep asks the right question (reachability from roots), so it frees cycles. Note the P ⇄ Q cycle is reachable, so both methods correctly keep it.
Answer:
  1. Count: P = 2 (r আর Q থেকে), Q = 2 (P আর T থেকে), R = 1 (S থেকে), S = 1 (R থেকে), T = 0।
  2. Reference counting: শুধু T-এর count 0 → T free। T free হলে T → Q pointer চলে যায়, তাই Q-এর count হয় 1 (ঠিকভাবেই বেঁচে থাকে)। R আর S-এর count চিরকাল 1 → leak। Free হয়: {T}।
  3. Mark-and-sweep: root r থেকে mark → P → Q (→ P আগেই marked)। Marked = {P, Q}। Unmarked-গুলো sweep: {R, S, T}।
  4. Reference counting শুধু জানে "কয়টা pointer", জানে না "root থেকে পৌঁছানো যায় কি না"। Unreachable cycle R ⇄ S নিজেরাই নিজেদের count 0-এর ওপরে রাখে। Mark-and-sweep সঠিক প্রশ্ন করে (root থেকে reachability), তাই cycle free করে। খেয়াল করো, P ⇄ Q cycle reachable, তাই দুই method-ই সেটা ঠিকভাবে রেখে দেয়।
Q20. (IICT written style) Write the exact output of this Java program. Then write the output if b(0) is changed to b(1). Explain exception propagation and the role of finally.
public class Ex {
  static void c(int n) {
    try {
      System.out.println("c start");
      if (n == 0) throw new ArithmeticException("zero");
      System.out.println("c end");
    } finally {
      System.out.println("c finally");
    }
  }
  static void b(int n) {
    try { c(n); System.out.println("b after c"); }
    catch (NullPointerException e) { System.out.println("b caught NPE"); }
  }
  public static void main(String[] args) {
    try { b(0); System.out.println("main after b"); }
    catch (ArithmeticException e) { System.out.println("main caught " + e.getMessage()); }
    finally { System.out.println("main finally"); }
    System.out.println("done");
  }
}
Q20. (IICT written style) এই Java program-এর হুবহু output লেখো। তারপর b(0)-কে b(1) করলে output কী হবে লেখো। Exception propagation আর finally-এর ভূমিকা ব্যাখ্যা করো।
public class Ex {
  static void c(int n) {
    try {
      System.out.println("c start");
      if (n == 0) throw new ArithmeticException("zero");
      System.out.println("c end");
    } finally {
      System.out.println("c finally");
    }
  }
  static void b(int n) {
    try { c(n); System.out.println("b after c"); }
    catch (NullPointerException e) { System.out.println("b caught NPE"); }
  }
  public static void main(String[] args) {
    try { b(0); System.out.println("main after b"); }
    catch (ArithmeticException e) { System.out.println("main caught " + e.getMessage()); }
    finally { System.out.println("main finally"); }
    System.out.println("done");
  }
}
Show Answerউত্তর দেখুন
Answer (with b(0)):
c start
c finally
main caught zero
main finally
done
  1. c prints "c start", then throws ArithmeticException. "c end" is skipped.
  2. c has no catch, but its finally always runs → "c finally". Then the exception propagates to b (c's AR is popped).
  3. b only catches NullPointerException — no match. "b after c" is skipped; the exception propagates to main.
  4. main's catch matches → "main caught zero". "main after b" was skipped.
  5. main's finally runs → "main finally". The exception is handled, so execution continues after the try statement → "done".
With b(1) (no exception):
c start
c end
c finally
b after c
main after b
main finally
done
finally runs in both cases. Both outputs verified with javac/java.
Answer (b(0) দিয়ে):
c start
c finally
main caught zero
main finally
done
  1. c "c start" print করে, তারপর ArithmeticException throw করে। "c end" skip হয়।
  2. c-তে catch নেই, কিন্তু তার finally সবসময় চলে → "c finally"। তারপর exception b-তে propagate করে (c-এর AR pop হয়)।
  3. b শুধু NullPointerException catch করে — মেলে না। "b after c" skip হয়; exception main-এ propagate করে।
  4. main-এর catch মিলে যায় → "main caught zero"। "main after b" skip হয়েছিল।
  5. main-এর finally চলে → "main finally"। Exception handle হয়ে গেছে, তাই try statement-এর পরে execution চলতে থাকে → "done"।
b(1) দিয়ে (কোনো exception নেই):
c start
c end
c finally
b after c
main after b
main finally
done
দুই ক্ষেত্রেই finally চলে। দুটো output-ই javac/java দিয়ে verified।