📚

CMS 705
Programming Languages

Complete Exam Cheat Sheet

Rivers State University
Lecturer: the lecturer  |  Session: 2024/2025

Topics Covered
Language Structure · Data Types · Data Structures
Control Structures · Data Flow · Runtime
Interpretive Languages · Lexical Analysis & Parsing
1

Language Structure

💡 A language is a formal system of symbols and rules to communicate with a computer. Every instruction must have a precise, single meaning.
ComponentWhat it studiesCS / C++ analogy
PhonologySound patterns · smallest units (phonemes)int, <<, age · tokens
MorphologyHow words/tokens are formedWalk + edWalked; identifiers
SyntaxRules for arranging words → sentencesfor(int i=0;i<10;i++){}
SemanticsMeaning of words / sentencesWhat the code actually does
PragmaticsLanguage in social / usage contextReadability, writability, reliability
🎯 3 Key Questions a Language Must Answer:
1. What programs look likeSyntax
2. What programs meanSemantics
3. How programs are used in practicePragmatics
CMS 705
1 / 13 CMS 705
2

Static vs Dynamic Semantics

⚙️ Static Semantics
  • Checked at compile time
  • Type compatibility
  • Variable declared before use
  • Prevents execution errors
▶️ Dynamic Semantics
  • Checked at runtime
  • How expressions are evaluated
  • How values change during execution
  • What actually happens when code runs
// STATIC SEMANTICS · compile-time error
int x;
x = "hello"; // ❌ Compile error: can't assign string to int

// DYNAMIC SEMANTICS · runtime behaviour
int c = 0;
if (flag) c = 1;   // value changes at runtime
cout << c;           // outputs: 1
⚠️ Exam tip: Static = compile time (type errors, undeclared vars). Dynamic = runtime (actual behaviour, value changes).
2 / 13 CMS 705
3

Types of Language · Levels of Abstraction

LevelTypeExampleNotes
Lowest Machine Language 01001010 Binary; CPU executes directly; no translation; machine-dependent
Low Assembly Language MOV A, B Mnemonics; needs assembler; full hardware control
Middle C Language int sum = a+b; Hardware access + structured; used in OS, compilers
High Python, Java, C++ English-like syntax Needs compiler/interpreter; machine-independent; easy to use
Middle-level (C)
  • Moderate portability
  • Faster execution
  • Manual memory management
  • Systems / embedded use
High-level (C++, Python)
  • High portability
  • Slower (compilation overhead)
  • Automatic memory
  • Application / end-user focus
3 / 13 CMS 705
4

Implementation Methods

🔧 Assembly Translates assembly language → machine code via assembler
📦 Compilation Entire program translated at once → .exe (C, C++)
▶️ Interpretation Code translated & executed line by line at runtime (Python, JS)
JIT (Just-in-Time) Bytecode compiled to machine code on demand at runtime · Java / JVM
CompiledInterpretedJIT
SpeedFastSlowerNear-compiled
Output.exeNoneNative (runtime)
Errors foundBefore runDuring runMix
ExamplesC, C++Python, JSJava (JVM)
4 / 13 CMS 705
5

Primitive Data Types

📌 Built-in, fixed size, stored directly in memory (CPU-level). Cannot be null. No built-in functions.
TypeSizeExampleUse
int4 bytesint count = 10;Counting, indexing, loops
short int2 bytesshort x = 5;Smaller integers
long int4–8 byteslong big = 99999;Large integers
unsigned int4 bytesunsigned int u = 10;Non-negative only
float4 bytesfloat t = 36.5;Single precision (7 digits)
double8 bytesdouble pi = 3.14159;Double precision (15–16 digits)
char1 bytechar g = 'A';Single character (ASCII)
bool1 bytebool ok = true;Decision / conditions
void-void display(){}Functions with no return value
🧠 int range: −2,147,483,648 to 2,147,483,647  |  char uses single quotes 'A'  |  string uses double quotes "Alex"
5 / 13 CMS 705
6

Non-Primitive Data Types

📌 Also called reference / derived types. Complex, dynamic size, have built-in functions. Built from primitive types.
String
string name = "Alex Johnson";
cout << name.length();  // 12
Array
int nums[] = {10,20,30,40};
cout << nums[0];  // 10
Struct
struct Student {
  string name; int age;
};
Pointer
int c = 10;
int* ptr = &c;
// ptr stores address of c
Enum
enum Day {Mon,Tue,Wed,Thu};
Day today = Wed;
cout << today; // 2
Class (OOP)
class Car {
public:
  string model; int year;
  void display();
};
PrimitiveNon-Primitive
Created byLanguage itselfProgrammer / library
SizeFixedDynamic
FunctionsNoneMany built-in
6 / 13 CMS 705
7

Data Structures · Overview

💡 A method of organising, storing, and managing data in a computer so it can be accessed and manipulated efficiently.
Linear
  • Sequential arrangement
  • Single level
  • Simple to traverse
  • Array, Linked List, Stack, Queue
Non-Linear
  • Hierarchical / graph-like
  • Multiple levels
  • Complex to traverse
  • Tree, Graph, Heap, Hash Table, Trie
OperationDescription
InsertionAdd element (beginning, end, or position)
DeletionRemove element + free memory
TraversalVisit ALL elements once · "go through everything"
SearchingFind specific element · "stop when found" (Linear or Binary)
UpdatingChange value of existing element
SortingArrange ascending/descending (Bubble, Selection, Insertion)
MergingCombine two data structures into one
⚠️ Traversal vs Searching: Traversal visits every element. Searching stops as soon as it finds the target.
7 / 13 CMS 705
8

Linear & Non-Linear Structures

Stack · LIFO
Push (insert)  |  Pop (remove)
Function callsUndo/redoBrowser back
Queue · FIFO
Enqueue (rear)  |  Dequeue (front)
Printer queueCPU scheduling
Array
Contiguous memory, fixed size, O(1) access by index
Binary Tree
Each node ≤ 2 children. Left < Parent < Right (BST)
Hash Table
key → hash function → index. O(1) avg. lookup/insert/delete
Heap
Max Heap: Parent ≥ Children
Min Heap: Parent ≤ Children
// Singly Linked List · key exam implementation
struct Node { int data; Node* next; };
Node* head = NULL;
void insertEnd(int value) {
  Node* newNode = new Node();
  newNode->data = value;  newNode->next = NULL;
  if (head == NULL) { head = newNode; return; }
  Node* temp = head;
  while (temp->next != NULL) temp = temp->next;
  temp->next = newNode;
}
8 / 13 CMS 705
9

Control Structures

💡 Determine the order of execution · which statement runs, when, and how many times.
#TypePurposeKeywords
1SequentialDefault top-to-bottom(none · default)
2SelectionBranch on conditionif, else, else if, switch
3IterationRepeat a blockfor, while, do-while, for-each
4JumpTransfer control unconditionallybreak, continue, return, goto
// For loop (known iterations)
for (int i=1; i<=5; i++)
  cout << i;

// While (condition-based)
int i = 1;
while (i <= 5) { cout << i; i++; }

// Do-While (runs at least ONCE)
do { cout << i; i++; }
while (i <= 5);
// For-each
int nums[] = {1,2,3,4,5};
for (int n : nums) cout << n;

// Break vs Continue
if (i==5) break;    // EXIT loop
if (i==6) continue; // SKIP iteration

// Switch
switch(day){
  case 1: cout<<"Mon"; break;
  default: cout<<"Other";
}
9 / 13 CMS 705
10

Data Flow

💡 The movement, transformation, and usage of data within a program: Input → Storage → Processing → Output
Input
Storage
Processing
Output
By Program Execution
SequentialLine by line: A→B→C→D
ConditionalBranches on condition (if/else)
IterativeData flows repeatedly through loops
ProceduralData moves between functions via parameters/return
Explicit Flow
  • Clearly written in code
  • Passed as parameters
  • Returned from functions
  • Easy to trace & debug
Implicit Flow
  • Through global variables
  • Hidden / indirect
  • Harder to trace
  • Can cause side effects
10 / 13 CMS 705
11

Runtime Considerations

💡 Runtime = the phase when a compiled/interpreted program is actually executing on the CPU.
📦 Stack
Local variables, function calls  |  LIFO, auto-freed when function ends
🌐 Heap
Dynamic allocations via new  |  Must manually free with delete
🌍 Global
Global / static variables  |  Lives for entire program lifetime
📜 Code
Compiled instructions (text segment) · read-only
int globalCounter = 100;    // Global area
int processData(int value) {
  int localVar = value * 2;   // Stack · auto freed
  int* heapVar = new int(5);  // Heap · must free!
  int result = *heapVar;
  delete heapVar;              // Free heap memory
  return result;
}
Compile TimeRuntime
WhenBefore executionDuring execution
ErrorsSyntax, type errorsLogic, null pointer, division by zero
SemanticsStaticDynamic
11 / 13 CMS 705
12

Interpretive Languages

CompiledInterpretedJIT
TranslationWhole program at onceLine by line at runtimeBytecode → machine code on demand
Output file.exe producedNo output fileNative code at runtime
SpeedFast (pre-translated)SlowerNear-compiled
PortabilityLower (platform-specific)HighHigh (via JVM)
ExamplesC, C++Python, JavaScriptJava (JVM)
How Interpretation Works
📄 Source Code (.py)
🔍 Read line 1 → Translate → Execute
🔍 Read line 2 → Translate → Execute
❌ Error on line 3 → Stop
How JIT Works (Java)
📄 Java Source (.java)
javac compiler
⚙️ Bytecode (.class)
JVM
⚡ JIT → Machine Code
🚀 Fast Execution
⚠️ Interpreter never produces a saved executable. JIT produces machine code but only at runtime · not saved to disk.
12 / 13 CMS 705
13

Lexical Analysis & Parsing

📖 Source Code Raw text written by programmer
🔡 Lexical Analysis Groups characters → TOKENS (keywords, identifiers, operators, literals)
🌳 Parsing Checks grammar rules → builds Parse Tree / AST
🧠 Semantic Analysis Checks meaning · types, declarations, compatibility
⚙️ Code Generation Produces machine code / bytecode
// Source: int age = 20;
// Tokens: [KEYWORD:int] [IDENT:age] [OP:=] [LIT:20] [DELIM:;]

// Lexical Error (invalid token):
int @age = 5;    // ❌ '@' not valid token
// Syntax Error (valid tokens, wrong grammar):
int = age 5;     // ❌ wrong arrangement
// Semantic Error (valid syntax, wrong meaning):
int age = "hello"; // ❌ type mismatch
LinguisticsProgramming LanguageCompiler Stage
PhonologyCharacters, symbolsCharacter scanning
MorphologyTokens · keywords, identifiersLexical Analysis
SyntaxValid statements & expressionsParsing
SemanticsMeaning of codeSemantic Analysis
13 / 13 CMS 705

Quick Reference

Key Definitions
SyntaxRules for valid code structure
SemanticsWhat the code means
PragmaticsReadability, writability, reliability
Data TypeWhat a variable holds + ops allowed
ParameterVariable declared in function definition
ArgumentValue passed when calling a function
StackLIFO · local vars, auto-freed
HeapDynamic alloc, manual delete
TraversalVisit every element once
SearchingStop when element found
🎯
Exam Tips
• Know Singly Linked List C++ code
• Know Binary Tree C++ code
• Know Grade Calculator (procedural data flow)
• break = exits loop; continue = skips iteration
• Static = compile time; Dynamic = runtime
• do-while runs at least ONCE
• JIT: bytecode → machine code at runtime
• Phonology→Morphology→Syntax = Lexer→Parser
📋
5 Course Topics
1. Language Definition Structure
2. Data Types & Structures
3. Runtime Considerations
4. Interpretive Languages
5. Lexical Analysis & Parsing
Rivers State University  |  CMS 705 · Programming Languages  |  the lecturer  |  2024/2025
CMS 705