0% found this document useful (0 votes)
9 views

CSC 412Advanced Programming LECTURENOTES

The document provides comprehensive lecture notes on advanced programming concepts, emphasizing principles of good programming style, coding guidelines, and structured programming. It includes examples in QBASIC and Python, covering topics such as readability, modularity, error handling, and performance considerations. Additionally, it discusses debugging techniques, test generation, and a comparison of implementations for sorting numbers and a student grading system in both languages.

Uploaded by

lekzyadebox
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

CSC 412Advanced Programming LECTURENOTES

The document provides comprehensive lecture notes on advanced programming concepts, emphasizing principles of good programming style, coding guidelines, and structured programming. It includes examples in QBASIC and Python, covering topics such as readability, modularity, error handling, and performance considerations. Additionally, it discusses debugging techniques, test generation, and a comparison of implementations for sorting numbers and a student grading system in both languages.

Uploaded by

lekzyadebox
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

ADVANCED PROGRAMMING CONCEPTS LECTURE NOTES (CSC 412)

1. Principles of Good Programming Style

Key Concepts:

• Readability: Code should be easy to understand (proper indentation,


comments).

• Consistency: Follow naming conventions (e.g., snake_case in Python,


CamelCase in QBASIC).

• Modularity: Break code into reusable functions.

• Efficiency: Avoid redundant computations.

Examples: QBASIC (Poor vs Good Style)

qbasic

' POOR STYLE

A=5:B=10:IF A<B THEN PRINT "A is smaller" ELSE PRINT "B is smaller"

' GOOD STYLE

LET a = 5

LET b = 10

IF a < b THEN

PRINT "A is smaller"

ELSE

PRINT "B is smaller"

END IF

Python Example

python

1
# Good Style

def compare_numbers(a, b):

if a < b:

print("A is smaller")

else:

print("B is smaller")

compare_numbers(5, 10)

INTRODUCTION TO CODING GUIDELINES

What Are Coding Guidelines?

• A set of rules and best practices for writing clean, maintainable, and efficient
code used by organizations (e.g., Google, Microsoft) to ensure consistency
across teams.

Why Are They Important?

✔ Readability: Easier for others (and your future self) to understand.


✔ Maintainability: Reduces technical debt.
✔ Collaboration: Ensures uniformity in team projects.
✔ Bug Prevention: Encourages defensive programming.

Naming Conventions

1 General Rules

• Use meaningful names (calculateTotalPrice vs calc).

• Avoid abbreviations unless widely accepted (max instead of m).

• Follow language conventions (e.g., camelCase in Java, snake_case in Python).

2 Code Formatting & Indentation

2
Key Principles

• Consistent indentation (2/4 spaces or tabs).

• Line length limit (typically 80-120 characters).

• Brace placement (K&R vs Allman style).

Example (Python PEP 8)

python

# Good

def calculate_discount(price, discount_rate):

if discount_rate > 0:

return price * (1 - discount_rate)

return price

# Bad

def calc(p,dr):

if dr>0:return p*(1-dr)

return p

3. Comments & Documentation

Types of Comments

Inline Comments (Explain complex logic):

java

// Check if user is eligible for discount

if (userAge > 65) { ... }

Function Docstrings (Describe purpose, params, returns):

python
3
2. def compute_average(scores):

3. """

4. Calculates the average of a list of scores.

5. Args:

6. scores (list): List of numerical values.

7. Returns:

8. float: The arithmetic mean.

9. """

When to Avoid Comments

• Redundant comments:

java

• x++; // Increment x (Obvious)

4. Function/Method Design Principles

Single Responsibility Principle (SRP)

• A function should do one thing and do it well.

• Bad Example:

python

def process_user_data_and_send_email(user):

# 50 lines of mixed logic

Good Example:

python

• def validate_user(user): ...

4
• def save_user(user): ...

• def send_welcome_email(user): ...

Parameter & Return Best Practices

• Limit parameters (≤ 3-4). Use objects if needed.

• Avoid "out" parameters (modifying input arguments).

5. Error Handling & Defensive Programming

Key Strategies

• Validate inputs (fail fast).

• Use exceptions for unexpected errors.

• Avoid silent failures (e.g., empty catch blocks).

Example (Java)

java

public int divide(int a, int b) {

if (b == 0) {

throw new IllegalArgumentException("Divisor cannot be zero");

return a / b;

6 Code Reusability & Modularity

Techniques

• DRY (Don’t Repeat Yourself): Extract shared logic into functions.

• Use libraries instead of reinventing the wheel.

Example (JavaScript)
5
javascript

// Bad: Duplicate code

function calculateCircleArea(r) { return 3.14 * r * r; }

function calculateSphereVolume(r) { return (4/3) * 3.14 * r * r * r; }

// Good: Reusable constant

const PI = 3.14;

function calculateCircleArea(r) { return PI * r * r; }

7 Performance Considerations

Common Pitfalls

• Unnecessary computations (e.g., recalculating in loops).

• Inefficient data structures (using lists for frequent lookups).

Optimization Example

python

# Bad: O(n²)

for item in list:

if item in other_list: ...

# Good: O(1) lookups

other_set = set(other_list)

for item in list:

if item in other_set: ...

8 Security Best Practices

Critical Rules
6
• Sanitize inputs (prevent SQL injection, XSS).

• Avoid hardcoded secrets (use environment variables).

Example (SQL Injection Prevention)

python

# Bad (vulnerable)

query = "SELECT * FROM users WHERE id = " + user_input

# Good (parameterized)

query = "SELECT * FROM users WHERE id = %s"

cursor.execute(query, (user_input,))

9 Version Control & Collaboration

Git Best Practices

• Atomic commits (one logical change per commit).

• Descriptive commit messages:

• Add user authentication middleware

• Fix #123: Handle null values in payment processing

10.2 Code Review Guidelines

• Check for:

o Adherence to coding standards.

o Edge cases and error handling.

o Performance impacts.

STRUCTURED PROGRAMMING CONCEPTS

Key Principles of structured programming:

7
• Single Entry, Single Exit (SESE): Functions should have one entry and exit
point.

• Avoidance of GOTO: Use loops and conditionals instead.

• Hierarchical Design: Top-down or bottom-up approach.

Example (Avoiding GOTO in QBASIC)

qbasic

' BAD: Using GOTO

10 INPUT "Enter a number: ", num

20 IF num < 0 THEN GOTO 10

30 PRINT "Positive number entered."

' GOOD: Using a loop

DO

INPUT "Enter a number: ", num

LOOP UNTIL num >= 0

PRINT "Positive number entered."

Python Example (Structured Loop)

python

while True:

num = int(input("Enter a number: "))

if num >= 0:

break

print("Positive number entered.")

CONTROL FLOW (SEQUENTIAL, SELECTION, ITERATION)

8
Key Structures:

• Sequential: Code executes line by line.

• Selection: IF-ELSE, SELECT CASE (QBASIC), match-case (Python 3.10+).

• Iteration: FOR, WHILE loops.

QBASIC Example (SELECT CASE)

qbasic

INPUT "Enter grade (A-F): ", grade$

SELECT CASE grade$

CASE "A"

PRINT "Excellent!"

CASE "B"

PRINT "Good!"

CASE ELSE

PRINT "Try harder!"

END SELECT

Python Example (match-case)

python

grade = input("Enter grade (A-F): ").upper()

match grade:

case "A":

print("Excellent!")

case "B":

print("Good!")
9
case _:

print("Try harder!")

INVARIANT RELATIONS IN LOOPS

Definition: A condition that remains true before and after each loop iteration.

Example (Loop Invariant in QBASIC - Factorial Calculation)

qbasic

FUNCTION Factorial(n)

LET result = 1

LET i = 1

' INVARIANT: result = (i-1)!

WHILE i <= n

result = result * i

i=i+1

WEND

Factorial = result

END FUNCTION

Python Example

python

def factorial(n):

result = 1

i=1

# INVARIANT: result == (i-1)!

while i <= n:
10
result *= i

i += 1

return result

STEPWISE REFINEMENT (TOP-DOWN VS BOTTOM-UP)

Top-Down Approach:

• Start with high-level design, then break into smaller functions.

Bottom-Up Approach:

• Build small modules first, then combine them.

Example (Top-Down in Python - Calculator)

python

# High-level design

def calculator():

num1 = get_number()

num2 = get_number()

operation = get_operation()

result = compute(num1, num2, operation)

display_result(result)

# Lower-level functions

def get_number():

return float(input("Enter a number: "))

def compute(a, b, op):


11
if op == "+": return a + b

elif op == "-": return a - b

# ...

QBASIC (Bottom-Up - Math Functions First)

qbasic

FUNCTION Add(a, b)

Add = a + b

END FUNCTION

FUNCTION Subtract(a, b)

Subtract = a - b

END FUNCTION

' Later combined into a calculator

SUB Calculator

INPUT "Enter two numbers: ", x, y

PRINT "Sum: "; Add(x, y)

PRINT "Difference: "; Subtract(x, y)

END SUB

DEBUGGING & TESTING TECHNIQUES

Methods:

• Print Debugging: Insert PRINT statements (QBASIC) or print() (Python).

• Unit Testing: Use assert in Python.

• Code Inspection: Peer review.


12
Python Unit Test Example

python

def add(a, b):

return a + b

assert add(2, 3) == 5, "Test Failed!"

print("Test Passed!")

QBASIC Debugging Example

qbasic

LET x = 10

LET y = 20

PRINT "Before swap: x="; x; ", y="; y

SWAP x, y

PRINT "After swap: x="; x; ", y="; y

PROGRAM VERIFICATION & TEST GENERATION

Techniques:

• Formal Proofs: Mathematical verification of correctness.

• Test Cases: Boundary values, edge cases.

Example (QBASIC Prime Checker with Tests)

qbasic

FUNCTION IsPrime(n)

IF n <= 1 THEN IsPrime = 0: EXIT FUNCTION

FOR i = 2 TO n \ 2
13
IF n MOD i = 0 THEN IsPrime = 0: EXIT FUNCTION

NEXT

IsPrime = 1

END FUNCTION

' Test Cases

PRINT IsPrime(5) ' Expected: 1 (True)

PRINT IsPrime(4) ' Expected: 0 (False)

Python Test Generation (Random Inputs)

python

import random

def test_add():

for _ in range(5):

a = random.randint(1, 100)

b = random.randint(1, 100)

assert add(a, b) == a + b

print("All random tests passed!")

14
APPENDIX I

(SORTING NUMBERS IN ASCENDING ORDER)

QBASIC

' QBasic Program to Sort Numbers in Ascending Order

CLS

DIM numbers(10) AS INTEGER

INPUT "How many numbers to sort? "; n

PRINT "Enter the numbers one by one:"

' Input numbers

FOR i = 1 TO n

INPUT numbers(i)

NEXT i

' Bubble Sort Algorithm

FOR i = 1 TO n - 1

FOR j = 1 TO n - i

IF numbers(j) > numbers(j + 1) THEN

SWAP numbers(j), numbers(j + 1)

END IF

NEXT j

NEXT i

15
' Display sorted numbers

PRINT "Sorted numbers in ascending order:"

FOR i = 1 TO n

PRINT numbers(i);

NEXT i

END

Explanation (QBasic):

1. Input: Takes the number of elements (n) and then the numbers.

2. Sorting: Uses Bubble Sort to arrange numbers in ascending order.

3. Output: Prints the sorted list.

2. Python Program (Sorting Numbers in Ascending Order)

python

# Python Program to Sort Numbers in Ascending Order

numbers = []

n = int(input("How many numbers to sort? "))

print("Enter the numbers one by one:")

# Input numbers

for i in range(n):

num = int(input())

numbers.append(num)
16
# Built-in sort function

numbers.sort()

# Display sorted numbers

print("Sorted numbers in ascending order:")

for num in numbers:

print(num, end=" ")

Explanation (Python):

1. Input: Takes the number of elements (n) and then the numbers.

2. Sorting: Uses Python’s built-in sort() method.

3. Output: Prints the sorted list.

Alternative Python Method (Using Bubble Sort)

python

# Python Program (Bubble Sort Implementation)

numbers = []

n = int(input("How many numbers to sort? "))

print("Enter the numbers one by one:")

for i in range(n):

num = int(input())
17
numbers.append(num)

# Bubble Sort

for i in range(n - 1):

for j in range(n - i - 1):

if numbers[j] > numbers[j + 1]:

numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]

print("Sorted numbers in ascending order:")

for num in numbers:

print(num, end=" ")

Key Differences:

Feature QBasic Python

Sorting Method Bubble Sort Built-in sort()

Input Handling INPUT input()

Array Declaration DIM Dynamic Lists

Swap Mechanism SWAP a, b = b, a

STUDENT GRADING SYSTEM IN BOTH QBASIC AND PYTHON:

1. QBasic Implementation

' QBasic Student Grading System

18
CLS

DIM studentNames$(100)

DIM marks(100)

DIM grades$(100)

INPUT "Enter number of students: "; numStudents

' Input student data

FOR i = 1 TO numStudents

PRINT "Student #"; i

INPUT "Enter student name: "; studentNames$(i)

INPUT "Enter student mark (0-100): "; marks(i)

NEXT i

' Calculate grades

FOR i = 1 TO numStudents

SELECT CASE marks(i)

CASE IS >= 90

grades$(i) = "A"

CASE 80 TO 89

grades$(i) = "B"

CASE 70 TO 79

grades$(i) = "C"
19
CASE 60 TO 69

grades$(i) = "D"

CASE ELSE

grades$(i) = "F"

END SELECT

NEXT i

' Display results

PRINT "GRADING REPORT"

PRINT "----------------------------------"

PRINT "Name", "Mark", "Grade"

PRINT "----------------------------------"

FOR i = 1 TO numStudents

PRINT studentNames$(i), marks(i), grades$(i)

NEXT i

END

2. Python Implementation

python

# Python Student Grading System

def calculate_grade(mark):

if mark >= 90:

return "A"
20
elif mark >= 80:

return "B"

elif mark >= 70:

return "C"

elif mark >= 60:

return "D"

else:

return "F"

# Main program

students = []

num_students = int(input("Enter number of students: "))

# Input student data

for i in range(num_students):

print(f"\nStudent #{i+1}")

name = input("Enter student name: ")

while True:

try:

mark = float(input("Enter student mark (0-100): "))

if 0 <= mark <= 100:

break

else:
21
print("Please enter a value between 0 and 100")

except ValueError:

print("Please enter a valid number")

grade = calculate_grade(mark)

students.append({"name": name, "mark": mark, "grade": grade})

# Display results

print("\nGRADING REPORT")

print("-" * 40)

print(f"{'Name':<20}{'Mark':<10}{'Grade':<10}")

print("-" * 40)

for student in students:

print(f"{student['name']:<20}{student['mark']:<10}{student['grade']:<10}")

Key Features

1. Input Validation (Python version):

o Ensures marks are between 0-100

o Handles non-numeric input

2. Grading Scale:

o A: 90-100

o B: 80-89

o C: 70-79
22
o D: 60-69

o F: Below 60

3. Output Format:

o Clean tabular display of results

o Shows student name, mark, and grade

4. Data Structure:

o QBasic uses parallel arrays

o Python uses list of dictionaries

Appendix II

1. Succinctly explain the coding elements in coding guidelines in programming


2. What do you understand by structured programming? State and explain the
main three programming states in structured program.
3. Write a program in any programming language to find the sum of any given
20 numbers and display the output.
4. Write a code in any language to demonstrate sorting?
5. Explain the three basic structures of programming logic fully illustrated with
diagram.
6. Write a program to demonstrate looping operation using any programming
language.
7. What is nested loop? Illustrate.
8. Write an ELSE and ELSE IF construct for Examination grading system (A = 70
and above; B = 60 to 69; C = 50 to 59; D = 45 to 49; E = 40 to 44; F = below
40
9. What is modular programming?
10. Explain the concept of modularization
11. What do you understand by program testing and debugging?
12. Explain the steps in debugging.

23

You might also like