COS 102

6 lecture note; fundamentals of programming

Learn about 6 lecture note; fundamentals of programming in COS 102. Comprehensive study materials and practice questions.

Study notes included Document available CBT practice ready

Study Document

Open full

Study Notes

COS 102

Course Overview

This document provides a comprehensive overview of the "Problem Solving" course, focusing on Python programming concepts related to control structures.

Course Details

  • Course Codes: COS 102 / CSC 120 / CSC 100, CSC 121 / CSC 122
  • Lecturer: Dr. Ufuoma C. Ogude

Course Schedule & Policy

  • Lecture Schedule: Mondays, 10:00 AM - 12:00 PM
  • Class Venue: Physical, LT009
  • Attendance: Mandatory

Classroom Policy:

  • Review recommended material before class.
  • Be on time.
  • Turn off cell phones.

Expectations:

  • Read assigned readings.
  • Attend lectures and participate in discussions.
  • Bring ideas and concerns to class.
  • Work effectively in a group setting.
  • Learn to use tools and understand projects well.

Learning Outcomes

At the end of the course, students should be able to:

  1. Explain problem-solving processes.
  2. Demonstrate problem-solving skills.
  3. Describe the concept and properties of algorithms development.
  4. Discuss solution techniques for solving problems.
  5. Solve computer problems using algorithms, flowcharts, pseudocode, etc.
  6. Solve problems using the Python programming language.

Outlines of the Course (Wk9-11)

  • Concept of Problem Solving
  • Introduction to Programming
  • Concept & Properties of Algorithm
  • Fundamentals of Programming (1): Variable/Variable Naming Convention/Data Types in Python
  • Fundamentals of Programming (2): Operators and Expressions
  • Fundamentals of Programming (3): Control Structures

Pre-Requisite

“Knowledge isn’t free. You have to pay attention.” – Richard P. Feynman

Course Evaluation

  • Final Examination: 70%
  • Continuous Assessment: 30%
    • Written test
    • Assignments/Project

Previous Lecture Summary (Fundamentals of Programming 2)

  • Getting Started with Python
  • Installing Python, IDLE, A first program
  • For Loop, The Loop variable
  • Numbers: Integers and Decimal Numbers, Maths Operators, Order of operations

Lecture 6 Week 9: Fundamentals of Programming (3)

Topic 6: Control Structures

  • If Statements: A simple Example, Conditional Operators

Introduction to Control Flow

  • A program's control flow is the order in which its code executes.
  • The control flow in Python is regulated by conditional statements, loops, and function calls.
  • Python has three types of control structures:
    • Sequential: Default mode.
    • Selection: Used for decisions and branching.
    • Repetition: Used for looping, i.e., repeating a piece of code multiple times.

Types of Control Structures

Structured programming comprises the following logical structures:

  1. SEQUENCE
  2. SELECTION
  3. ITERATION OR LOOPING
  4. BRANCHING OR JUMPING STATEMENTS

1. Sequence

  • Sequence is the default control structure; instructions are executed one after another.
  • Example:
            a = 20
            b = 10
            c = a - b
            print("subtraction is : ", c)
            
  • Python Program Example (Adding two numbers):
            def sum_of_two_no():
                num1 = 1.5
                num2 = 6.3
                sum = float(num1) + float(num2)
                print('The sum is =', sum)
            sum_of_two_no()
            

2. Selection (Conditional Constructs / if-else Statement)

  • A selection statement causes the program control to be transferred to a specific flow based on whether a certain condition is true or not.
  • Conditional constructs (if statements) execute a chosen block of code based on the run-time evaluation of one or more Boolean expressions.
  • General form in Python:
            if first condition:
                first body
            elif second condition:
                second body
            elif third condition:
                third body
            else:
                fourth body
            

    Note: A colon (:) must follow conditions and else.

  • Each condition is a Boolean expression, and each body contains one or more commands.
  • If the first condition is true, its body executes, and no other conditions or bodies are evaluated.
  • If a condition fails, the process continues with the next `elif` or `else` clause.
  • There can be any number of `elif` clauses (including zero).
  • The final `else` clause is optional.

Selection Examples:

  • Simple If Statement:
            def if_example():
                a = 5
                if (a < 10):
                    print("5 is less than 10")
                print("Statement after if statement")
            if_example()
            

    Output: 5 is less than 10, Statement after if statement

  • If-Else Statement:
            def if_else_example():
                age = 15
                if (age >= 18):
                    print("Eligible for Voting")
                else:
                    print("Not Eligible for Voting")
                print("Statement after if statement")
            if_else_example()
            

    Output: Not Eligible for Voting, Statement after if statement

  • If-Elif-Else Statement (for Discounts):
            def if_elif_example():
                Age = 27
                if Age >= 60:
                    print('Senior Discount')
                elif 18 <= Age < 60: # Read as: 18 is less than or equal to Age AND Age is less than 60
                    print('No Discount')
                else:
                    print('Junior Discount')
            if_elif_example()
            

    Output: No Discount

Programming Exercises (if construct):

  • Below Average:
    1. Program to check if a number (n) is zero or non-zero.
    2. Program to find the largest of two numbers.
    3. Program to check if a number is positive or negative.
    4. Program to check if an entered character is a vowel or consonant.
  • Average:
    1. Program to evaluate student performance based on percentage (>=90 Excellent, >=80 Very Good, >=70 Good, >=60 Average, else Poor).
    2. Program to find the largest of three numbers.
    3. Program to find the smallest of three numbers.
  • Above Average:
    1. Program to check if a number is even or odd.
    2. Program to check if a year is a leap year.
    3. Program to determine if a driver is insured based on marital status, sex, and age (married; unmarried male > 30; unmarried female > 25).

3. Iteration or Looping

  • Loops execute a block of code multiple times until a certain condition is met.
  • Iteration statements allow instructions to be executed repeatedly until a condition is fulfilled.
  • Python provides two kinds of loops: while loop and for loop.

While Loop

  • A while loop allows general repetition based on the repeated testing of a Boolean condition.
  • Syntax:
            while condition:
                body
            

    Note: A colon (:) must follow the condition.

  • The loop iterates while the expression evaluates to true; when it becomes false, the loop terminates.

While Loop Programming Examples:

  • Natural Numbers Generation:
            def gen_nat_no_while():
                i = 1
                n = int(input("Enter the limit : "))
                while (i <= n):
                    print(i)
                    i += 1
            gen_nat_no_while()
            

    Output for input 5: 1 2 3 4 5

  • Calculating Sum of Natural Numbers (up to 9):
            def while_loop_example():
                sum1 = 0
                count = 1
                while (count < 10):
                    sum1 = sum1 + count
                    count = count + 1
                print(count) # should be 10
                print(sum1)  # should be 45
            while_loop_example()
            

    Output: 10, 45

  • Generating Fibonacci Numbers: (Code provided is extensive, focuses on generating a sequence of a given length, handling invalid inputs, and correctly iterating.)

    Example Output for length 10: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

While Loop Exercises:

  • Below Average:
    1. Print natural numbers up to n.
    2. Print even numbers up to n.
    3. Print odd numbers up to n.
    4. Print sum of natural numbers up to n.
  • Average:
    1. Print sum of odd numbers up to n.
    2. Print sum of even numbers up to n.
    3. Print natural numbers up to n in reverse order.
    4. Print Fibonacci series up to n.
    5. Find the factorial of a given number.
  • Above Average & HOTS:
    1. Check if the entered number is prime or not.
    2. Find the sum of digits of a given number.
    3. Check if the entered number is a palindrome or not.
    4. Reverse the given number.
    5. Print the multiplication table.
    6. Print the largest of n numbers.
    7. Print the smallest of n numbers.

For Loop

  • Python’s `for-loop` syntax is a more convenient alternative to a while loop when iterating through a series of elements.
  • It can be used on any type of iterable structure (list, tuple, str, set, dict, file).
  • Syntax:
            for element in iterable:
                body
            
  • The loop continues to execute until the list (iterable) is exhausted.
  • Example:
            def for_loop_example():
                numbers=[765,23,56,89,14,78]
                for i in numbers:
                    print(i)
            for_loop_example()
            

    Output: Each number from the list printed on a new line.

For Loop with range() Keyword

  • The range() function returns a sequence of numbers, starting from 0 by default, incrementing by 1 (by default), and ending at a specified number (exclusive).
  • Syntax: range(start, stop, step)
  • Example:
            for n in range(3,6):
                print(n)
            

    Output: 3, 4, 5

            x = range(3, 6)
            for n in x:
                print(n)
            

    Output: 3, 4, 5

  • Generating Series of Numbers:
            def for_loop_example():
                n = int(input("Enter number: "))
                for i in range(0,n):
                    print(i)
            for_loop_example()
            

    Output for input 4: 0 1 2 3

  • Generating Even Numbers:
            def for_loop_example():
                n = int(input("Enter number: "))
                for i in range(0,n,2): # step of 2
                    print(i)
            for_loop_example()
            

    Output for input 6: 0 2 4

For Loop with len() Function

  • Print string character by character:
            def for_loop_example():
                name = input("Enter string: ")
                for i in range(0,len(name)):
                    print(name[i])
            for_loop_example()
            

    Output for input "Sainik": Each character printed on a new line.

else statement in loop

  • else can be used in for and while loops.
  • The else body will be executed when the loop’s conditional expression evaluates to false (i.e., the loop completes normally without a break).
  • Example:
            def break_in_loop():
                for i in range(0,5):
                    print(i)
                else:
                    print("Finally! Else of for executed")
            break_in_loop()
            

    Output: 0 1 2 3 4, Finally! Else of for executed

For Loop Exercises:

  • Below Average:
    1. Print natural numbers up to n.
    2. Print even numbers up to n.
    3. Print odd numbers up to n.
    4. Print series 1 2 4 8 16 32 … n2.
    5. Sum the sequence 1 + 1/1! + 1/2! + 1/3! + … + 1/n!.
  • Average:
    1. Compute the cosine series cos(x) = 1 – x2 / 2! + x4 / 4! – x6 / 6! + … xn / n!.
    2. Check whether the square root of a number is prime or not.
    3. Produce the design:
                      A B C
                      A B C
                      A B C
                      
  • Above Average:
    1. Produce following design (n=5):
                      A
                      A B
                      A B C
                      A B C D
                      A B C D E
                      
    2. Produce following design (n=5):
                      A B C D E
                      A B C D
                      A B C
                      A B
                      A
                      
    3. Produce following design (n=5):
                      1
                      1 2
                      1 2 3
                      1 2 3 4
                      1 2 3 4 5
                      
    4. Produce following design (n=5):
                      1
                      2 2
                      3 3 3
                      4 4 4 4
                      5 5 5 5 5
                      

4. Branching or Jumping Statements

Python has unconditional branching statements:

  1. break STATEMENT
  2. continue STATEMENT
  3. pass STATEMENT (often categorized separately but related to control flow)

1. break Statement

  • break is used to unconditionally jump out of a loop.
  • It terminates the execution of the loop it is inside.
  • Used in while and for loops, typically when an external condition requires exiting the loop.
  • Flowchart: Condition -> True -> Statement 1 -> break -> Jump out of loop.
  • Example:
            def break_example():
                y = 5
                for i in range(0,y+1):
                    if i == y:
                        print("Thank you!")
                        break
                    else:
                        print(i)
                print("End of Prg")
            break_example()
            

    Output: 0 1 2 3 4, Thank you!, End of Prg

2. continue Statement

  • continue returns control to the beginning of the loop (while or for).
  • It rejects all remaining statements in the current iteration and moves to the next iteration.
  • Flowchart: Condition -> True -> Statement 1 -> continue -> Skip remaining statements in current iteration -> Back to Condition.
  • Example:
            def continue_in_loop():
                for i in range(0,5):
                    if i == 2:
                        continue
                    print(i)
            continue_in_loop()
            

    Output: 0 1 3 4 (2 is skipped because of continue)

3. pass Statement

  • The pass statement is used when a statement is required syntactically but you do not want any command or code to execute.
  • It is a null operation; nothing happens when it executes.
  • Useful as a placeholder in stubs or unfinished code.
  • Example:
            def pass_example():
                for i in range(0,10):
                    pass # Pass in loop, no output
                print("Good Bye!")
            pass_example()
            

    Output: Good Bye!

Difference Between break and continue

BREAK CONTINUE
Terminates the execution of remaining iterations of the loop. Terminates only the current iteration of the loop.
Resumes control of the program to the end of the loop enclosing that 'break'. Resumes control of the program to the next iteration of the loop enclosing 'continue'.
Causes early termination of the loop. Causes early execution of the next iteration.
'break' stops the continuation of the loop. 'continue' does not stop the continuation of the loop; it only stops the current iteration.

Class Test

Time: 40 Min | Max Marks: 20

  1. Explain the types of control structures (05 Marks)
  2. Write a program to check if a number is prime or not (05 Marks)
  3. Write a program to check if the entered number is an Armstrong number or not (05 Marks)
  4. Differentiate between break and continue (05 Marks)

Thank You

Test Your Knowledge

Challenge yourself with targeted practice questions and accelerate your mastery of 6 lecture note; fundamentals of programming.

Practice CBT Study Flashcards