Level: 6
Session Title (Weeks 1-4): Develop a Computer Program
Learning Outcomes: By the end of this session (Weeks 1-4), the trainee will be able to:
Identify the format of a computer program.
Understand the fundamentals of structured programming in C.
Understand the fundamentals of Object-Oriented Programming (OOP) in Java.
Apply coding standards.
4.1 Identify Format of a Computer Program
Definition: The "format" or "structure" of a computer program refers to the organized layout and
arrangement of its various components (e.g., statements, functions, classes, comments) to ensure
readability, maintainability, and logical flow. While specific syntax varies by language, common
elements are universally recognized.
Key Components/Format Elements:
1. Comments:
o Definition: Non-executable lines of text within the code used to explain what the
code does, its purpose, or any complex logic. They are ignored by the
compiler/interpreter.
o Purpose: Enhance code readability, document the program, and aid future
understanding (by self or others).
o Examples:
C/Java: // Single-line comment or /* Multi-line comment */
2. Variables and Data Types:
o Definition:
Variables: Named storage locations that hold data during program
execution.
Data Types: Classifications that specify what type of value a variable can
hold (e.g., integer, floating-point, character, boolean) and the operations
that can be performed on it.
o Purpose: Store and manipulate data.
o Examples:
C: int age = 30;, float price = 19.99;, char initial = 'J';
Java: int quantity = 100;, double salary = 55000.50;, boolean
isActive = true;
3. Operators:
o Definition: Symbols that perform operations on variables and values (operands).
o Types:
Arithmetic: +, -, *, /, %
Relational: == (equal to), != (not equal to), <, >, <=, >=
Logical: && (AND), || (OR), ! (NOT)
Assignment: =
Increment/Decrement: ++, --
o Purpose: Perform calculations, comparisons, and logical evaluations.
o Examples:
total = num1 + num2;
if (age >= 18)
4. Control Structures:
o Definition: Statements that control the flow of execution in a program, allowing
for decision-making and repetition.
o Types:
Conditional (Decision Making): Execute different blocks of code based
on conditions.
if-else statement:
if (condition) {
// code if true
} else {
// code if false
}
switchstatement: For multiple choices based on a single variable's
value.
Looping (Repetition): Execute a block of code repeatedly.
for loop: For a known number of iterations.
while loop: Continues as long as a condition is true.
do-while loop: Executes at least once, then continues as long as a
condition is true.
o Purpose: Implement program logic and algorithms.
5. Functions/Methods:
o Definition: Self-contained blocks of code that perform a specific task.
In C, they are generally called "functions."
In Java (and OOP), they are called "methods" and are associated with
objects/classes.
o Purpose: Promote code reusability, modularity, and organization.
o Examples:
C Function:
int add(int a, int b) {
return a + b;
}
Java Method:
Java
public int calculateSum(int x, int y) {
return x + y;
}
6. Program Entry Point:
o Definition: The specific point where the program begins its execution.
o Examples:
C: main() function
Java: public static void main(String[] args) method
4.2 Fundamentals of Structured Programming in C
Definition: Structured programming is a programming paradigm aimed at improving the clarity,
quality, and development time of a computer program by making extensive use of control flow
structures (sequence, selection, iteration) and subroutines (functions), instead of using simple
unconditional jumps (e.g., goto statements). C is a procedural, structured programming
language.
Key Principles/Concepts in C:
1. Sequence: Statements are executed one after another in the order they appear in the code.
o Example:
int a = 5;
int b = 10;
int sum = a + b; // This statement executes after the
declarations.
printf("Sum: %d\n", sum);
2. Selection (Conditional Statements): Allows different code blocks to be executed based
on conditions.
o if-else if-else:
#include <stdio.h>
int main() {
int score = 75;
if (score >= 90) {
printf("Grade A\n");
} else if (score >= 70) {
printf("Grade B\n"); // This will be executed
} else {
printf("Grade C\n");
}
return 0;
}
o switch:
#include <stdio.h>
int main() {
char grade = 'B';
switch (grade) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Good!\n"); // This will be executed
break;
default:
printf("Needs improvement.\n");
}
return 0;
}
3. Iteration (Looping Statements): Allows a block of code to be executed repeatedly.
o for loop:
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
printf("Count: %d\n", i);
}
// Output:
// Count: 0
// Count: 1
// Count: 2
// Count: 3
// Count: 4
return 0;
}
o while loop:
#include <stdio.h>
int main() {
int i = 0;
while (i < 3) {
printf("While count: %d\n", i);
i++;
}
// Output:
// While count: 0
// While count: 1
// While count: 2
return 0;
}
o do-while loop:
#include <stdio.h>
int main() {
int i = 0;
do {
printf("Do-while count: %d\n", i);
i++;
} while (i < 0); // Condition is false, but executes once
// Output:
// Do-while count: 0
return 0;
}
4. Functions: Reusable blocks of code that perform a specific task.
o Example:
#include <stdio.h>
// Function declaration/prototype
int multiply(int x, int y);
int main() {
int result = multiply(7, 3); // Function call
printf("Result: %d\n", result); // Output: Result: 21
return 0;
}
// Function definition
int multiply(int x, int y) {
return x * y;
}
4.3 Fundamentals of OOP in Java
Definition: Object-Oriented Programming (OOP) is a programming paradigm based on the
concept of "objects," which can contain data (attributes/fields) and code (methods/functions).
Java is a pure object-oriented language. OOP aims to organize software design around data,
rather than functions and logic.
Core Concepts of OOP (Pillars):
1. Classes:
o Definition: A blueprint or a template for creating objects. It defines the common
properties (attributes) and behaviors (methods) that all objects of that type will
have.
o Example:
Java
public class Car { // This is a Class
// Attributes (data/properties)
String brand;
String model;
int year;
// Methods (behaviors)
public void start() {
[Link](brand + " " + model + " started.");
}
public void honk() {
[Link]("Beep beep!");
}
}
2. Objects:
o Definition: An instance of a class. When a class is defined, no memory is
allocated until an object of that class is created.
o Example:
Java
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // 'myCar' is an object of the Car
class
[Link] = "Toyota";
[Link] = "Camry";
[Link] = 2020;
[Link](); // Calling a method on the object
}
}
3. Encapsulation:
o Definition: The bundling of data (attributes) and the methods that operate on the
data into a single unit (class), and restricting direct access to some of an object's
components. This is typically achieved using access modifiers (private, public,
protected).
o Purpose: Data hiding and protection.
o Example:
Java
public class Account {
private double balance; // Data is private
public Account(double initialBalance) {
[Link] = initialBalance;
}
// Public method to deposit (controlled access)
public void deposit(double amount) {
if (amount > 0) {
[Link] += amount;
[Link]("Deposited: " + amount);
}
}
// Public method to get balance (controlled access)
public double getBalance() {
return balance;
}
}
4. Inheritance:
o Definition: A mechanism where a new class (subclass/child class) can inherit
properties and behaviors (attributes and methods) from an existing class
(superclass/parent class).
o Purpose: Promotes code reusability and establishes an "is-a" relationship.
o Example:
Java
// Parent Class
class Animal {
void eat() {
[Link]("Animal eats food.");
}
}
// Child Class inheriting from Animal
class Dog extends Animal { // 'extends' keyword for inheritance
void bark() {
[Link]("Dog barks.");
}
}
public class MainInheritance {
public static void main(String[] args) {
Dog myDog = new Dog();
[Link](); // Inherited method
[Link](); // Dog's own method
}
}
5. Polymorphism:
o Definition: "Many forms." The ability of an object to take on many forms. In
Java, it often refers to methods having the same name but different
implementations depending on the object type. This can be achieved through
Method Overloading (same method name, different parameters) and Method
Overriding (subclass provides specific implementation for a method already
defined in its superclass).
o Purpose: Flexibility and extensibility in design.
o Example (Method Overriding):
Java
class Shape {
void draw() {
[Link]("Drawing a shape.");
}
}
class Circle extends Shape {
@Override // Indicates this method overrides a superclass
method
void draw() {
[Link]("Drawing a circle.");
}
}
class Square extends Shape {
@Override
void draw() {
[Link]("Drawing a square.");
}
}
public class MainPolymorphism {
public static void main(String[] args) {
Shape s1 = new Circle(); // Polymorphic reference
Shape s2 = new Square();
[Link](); // Calls Circle's draw()
[Link](); // Calls Square's draw()
}
}
6. Abstraction:
o Definition: The process of hiding the implementation details and showing only
the essential features of the object. Achieved using abstract classes and interfaces.
o Purpose: Focus on "what" an object does rather than "how" it does it.
o Example (Abstract Class):
Java
abstract class Vehicle { // Abstract class
abstract void accelerate(); // Abstract method (no body)
void brake() { // Concrete method
[Link]("Vehicle stopped.");
}
}
class Motorcycle extends Vehicle {
@Override
void accelerate() {
[Link]("Motorcycle accelerates quickly.");
}
}
public class MainAbstraction {
public static void main(String[] args) {
Vehicle myBike = new Motorcycle();
[Link]();
[Link]();
}
}
4.4 Apply Coding Standards
Definition: Coding standards are a set of guidelines and best practices for writing code in a
consistent and readable manner. They cover aspects like naming conventions, formatting,
commenting, and error handling. Adhering to standards is crucial for collaborative development
and long-term maintainability.
Importance of Coding Standards:
Readability: Makes code easier to read and understand for all developers.
Maintainability: Simplifies debugging, updating, and extending code.
Consistency: Ensures a uniform style across a project or organization.
Collaboration: Facilitates teamwork by reducing conflicts and misunderstandings.
Quality: Often leads to fewer errors and more robust software.
Common Aspects of Coding Standards:
1. Naming Conventions: Consistent rules for naming variables, functions, classes, etc.
o Examples:
CamelCase: myVariable, calculateTotal (Java standard for
variables/methods)
PascalCase: MyClass, DatabaseConnection (Java standard for classes)
snake_case: my_variable, calculate_total (Common in C for
variables/functions, or lower_case_with_underscores)
MACRO_CASE: MAX_SIZE, PI (for constants)
2. Formatting and Indentation: Consistent use of spaces, tabs, and line breaks.
o Example (Java):
Java
// Good Indentation
public class MyClass {
private int data; // Indented 4 spaces
public MyClass(int value) { // Opening brace on same line
[Link] = value;
} // Closing brace on its own line
public void printData() {
for (int i = 0; i < 5; i++) { // Loop body indented
[Link](data + i);
}
}
}
3. Commenting: Clear, concise, and up-to-date comments.
o Explain why something is done, not just what.
o Document complex algorithms, tricky logic, and public APIs.
o Avoid redundant comments.
4. Error Handling: Consistent approach to handling errors and exceptions.
o C: Return error codes, check return values.
o Java: Use try-catch-finally blocks for exceptions.
5. Code Organization: How files, classes, and methods are structured within a project.
o Keep functions/methods small and focused on a single task.
o Group related code together.
6. Use of Constants: Define magic numbers or strings as named constants.
o Example: Instead of if (status == 1), use if (status == STATUS_ACTIVE).
7. Avoidance of Magic Numbers/Strings: Hardcoding values directly in the code without
explanation.
Tools for Applying Coding Standards:
Linters: (e.g., ESLint for JavaScript, Checkstyle for Java, Pylint for Python)
Automatically check code against a set of rules.
Formatters: (e.g., Prettier, Black, clang-format) Automatically reformat code to adhere
to style guidelines.
IDEs: Many Integrated Development Environments (IDEs) have built-in code formatting
and static analysis tools.