CS101: Module 2 (Introduction to Programming)

Computer Science Basics Course (CS101) – Module 2

Module 2: Introduction to Programming

  1. Introduction to programming languages (e.g., Python, Java, or C++)

Introduction:

Programming languages are essential tools for instructing computers to perform tasks and solve problems. In this lesson, we will explore the basics of programming languages, focusing on popular languages like Python, Java, and C++, and how they are used in software development.

  1. What is a Programming Language?

Definition: A programming language is a formal language comprising a set of instructions that can be used to produce various kinds of output, typically executed by a computer.

Role in Software Development: Programming languages serve as the medium through which developers communicate instructions to computers, enabling the creation of software applications, websites, games, and more.

  1. Overview of Programming Languages:

Python:

Characteristics: Python is known for its simplicity, readability, and versatility. It features clear and concise syntax, making it suitable for beginners and experienced programmers alike.

Common Applications: Python is widely used in web development, data analysis, artificial intelligence, scientific computing, and automation.

Example: Printing “Hello, World!” in Python:

python:-

print(“Hello, World!”)

Java:

Characteristics: Java is a high-level, object-oriented programming language known for its platform independence and robustness. It follows the “write once, run anywhere” principle, making it suitable for developing cross-platform applications.

Common Applications: Java is used in enterprise software development, mobile app development (Android), web servers, and large-scale distributed systems.

Example: Printing “Hello, World!” in Java:

java

public class HelloWorld {

    public static void main(String[] args) {

        System.out.println(“Hello, World!”);

    }

}

C++:

Characteristics: C++ is a powerful, general-purpose programming language known for its performance and efficiency. It provides low-level control over system resources and supports both procedural and object-oriented programming paradigms.

Common Applications: C++ is used in game development, system programming, embedded systems, high-performance computing, and operating systems.

Example: Printing “Hello, World!” in C++:

cpp

#include <iostream>

using namespace std;

int main() {

    cout << “Hello, World!” << endl;

    return 0;

}

  1. Writing Simple Programs:

Example Problem: Write a program to calculate the sum of two numbers.

Python Solution:

num1 = 5

num2 = 7

sum = num1 + num2

print(“The sum is:”, sum)

Java Solution:

public class SumCalculator {

    public static void main(String[] args) {

        int num1 = 5;

        int num2 = 7;

        int sum = num1 + num2;

        System.out.println(“The sum is: ” + sum);

    }

}

C++ Solution:

#include <iostream>

using namespace std;

int main() {

    int num1 = 5;

    int num2 = 7;

    int sum = num1 + num2;

    cout << “The sum is: ” << sum << endl;

    return 0;

}

  1. Variables, data types, and expressions

Introduction:

In programming, variables, data types, and expressions are fundamental concepts used to store and manipulate data. In this lesson, we will explore these concepts and how they are utilized in various programming languages.

  1. Variables:

Definition: A variable is a named storage location in computer memory that holds a value. It allows programmers to store and manipulate data during program execution.

Syntax: In most programming languages, variables are declared using a syntax that includes the variable name followed by an assignment operator (=) and an initial value.

Example: In Python, declaring a variable:

x = 5

  1. Data Types:

Definition: Data types define the type of data that can be stored in a variable and the operations that can be performed on it.

Common Data Types:

Integer: Represents whole numbers without any fractional part (e.g., 5, -10).

Float (Floating-point): Represents numbers with decimal points (e.g., 3.14, -0.25).

String: Represents a sequence of characters enclosed in quotation marks (e.g., “Hello, World!”).

Boolean: Represents a logical value indicating true or false.

Data Type Conversion: In many programming languages, data can be converted from one type to another using type conversion functions or operators.

Example: In Python, data type conversion:

x = 5         # integer

y = float(x)  # convert to float

  1. Expressions:

Definition: An expression is a combination of values, variables, operators, and functions that evaluates to a single value.

Types of Expressions:

  • Arithmetic Expressions: Combine numeric values and arithmetic operators to perform mathematical calculations (e.g., addition, subtraction, multiplication).
  • Boolean Expressions: Combine boolean values and logical operators to evaluate conditions (e.g., AND, OR, NOT).
  • String Expressions: Combine string values and string manipulation functions to perform operations on text data (e.g., concatenation).

Example: Arithmetic expression in Python:

x = 5

y = 3

z = x + y   # z is now 8

  1. Practice Exercise:

Problem: Write a program to calculate the area of a rectangle given its length and width.

Solution:

# Input length and width of the rectangle

length = 10

width = 5

# Calculate area using the formula: area = length * width

area = length * width

# Print the result

print(“The area of the rectangle is:”, area)

  1. Control structures: conditionals and loops

Introduction:

Control structures are essential components of programming languages that allow developers to control the flow of execution based on certain conditions or to repeat a set of instructions multiple times. In this lesson, we will explore two fundamental types of control structures: conditional statements and loops.

  1. Conditional Statements:

Definition: Conditional statements allow programmers to execute different sets of instructions based on the evaluation of one or more conditions.

Types of Conditional Statements:

If Statement: Executes a block of code if a specified condition is true.

If-else Statement: Executes one block of code if the condition is true and another block if the condition is false.

If-else-if Statement (or elif in Python): Executes different blocks of code based on multiple conditions.

Syntax:

If Statement:

if condition:

    # code block to execute if condition is true

If-else Statement:

if condition:

    # code block to execute if condition is true

else:

    # code block to execute if condition is false

If-else-if Statement (elif in Python):

python

if condition1:

    # code block to execute if condition1 is true

elif condition2:

    # code block to execute if condition2 is true

else:

    # code block to execute if all conditions are false

Example:

x = 10

if x > 5:

    print(“x is greater than 5”)

else:

    print(“x is less than or equal to 5”)

  1. Loops:

Definition: Loops allow programmers to execute a block of code repeatedly until a specified condition is met or for a fixed number of iterations.

Types of Loops:

For Loop: Executes a block of code for a specified number of iterations.

While Loop: Executes a block of code as long as a specified condition is true.

Syntax:

For Loop:

for variable in sequence:

    # code block to execute for each iteration

While Loop:

while condition:

    # code block to execute as long as condition is true

Example:

# Example of a for loop

for i in range(5):

    print(“Iteration”, i)

# Example of a while loop

count = 0

while count < 5:

    print(“Count:”, count)

    count += 1

  1. Practice Exercise:

Problem: Write a program to print all even numbers between 1 and 10.

Solution:

# Using a for loop

print(“Even numbers (for loop):”)

for i in range(1, 11):

    if i % 2 == 0:

        print(i)

# Using a while loop

print(“Even numbers (while loop):”)

num = 1

while num <= 10:

    if num % 2 == 0:

        print(num)

    num += 1

  1. Functions and modular programming

Introduction:

Functions are essential building blocks of programming that allow developers to organize code into reusable and manageable units. In this lesson, we will explore the concept of functions and how they contribute to modular programming practices.

  1. Functions:

Definition: A function is a self-contained block of code that performs a specific task or calculates a value. Functions are designed to be reusable and can accept input parameters and return output values.

Benefits of Using Functions:

Modularity: Functions promote modular programming by breaking down complex tasks into smaller, more manageable units.

Reusability: Functions can be reused across different parts of a program or in other programs, reducing code duplication and improving maintainability.

Abstraction: Functions encapsulate implementation details, allowing users to focus on the function’s purpose rather than its internal workings.

Syntax:

def function_name(parameters):

    # Function body

    # Perform task

    return result

Example:

def greet(name):

    return “Hello, ” + name + “!”

message = greet(“Alice”)

print(message)  # Output: Hello, Alice!

  1. Modular Programming:

Definition: Modular programming is a programming paradigm that emphasizes the separation of code into independent modules, each responsible for a specific aspect of functionality.

Benefits of Modular Programming:

Encapsulation: Modules encapsulate related functionality, making it easier to understand and maintain code.

Reusability: Modules can be reused in different projects or shared among multiple developers.

Scalability: Modular design facilitates the addition, modification, or removal of functionality without affecting other parts of the system.

Example:

In a banking application, separate modules may handle account management, transaction processing, and customer authentication.

  1. Implementing Modular Programming with Functions:

Example Problem: Write a program to calculate the area of a circle and rectangle.

Solution:

def calculate_circle_area(radius):

    return 3.14 * radius ** 2

def calculate_rectangle_area(length, width):

    return length * width

circle_area = calculate_circle_area(5)

rectangle_area = calculate_rectangle_area(4, 6)

print(“Area of circle:”, circle_area)

print(“Area of rectangle:”, rectangle_area)

  1. Practice Exercise:

Problem: Write a program to find the maximum of three numbers using a function.

Solution:

def find_maximum(a, b, c):

    return max(a, b, c)

num1 = 10

num2 = 20

num3 = 15

max_num = find_maximum(num1, num2, num3)

print(“Maximum number:”, max_num)

  1. Debugging and error handling

Introduction:

Debugging and error handling are crucial skills for programmers, allowing them to identify and fix errors in their code and handle unexpected situations gracefully. In this lesson, we will explore the concepts of debugging and error handling and how they contribute to writing robust and reliable software.

  1. Debugging:

Definition: Debugging is the process of identifying and fixing errors, or bugs, in a program. It involves systematically diagnosing issues, understanding their root causes, and applying appropriate solutions.

Common Debugging Techniques:

Print Statements: Inserting print statements at strategic points in the code to inspect variable values and trace the flow of execution.

Debugging Tools: Using integrated development environments (IDEs) or standalone debugging tools to set breakpoints, step through code, and examine variables during runtime.

Code Review: Collaborating with peers to review code for logic errors, syntax mistakes, and best practices.

Rubber Duck Debugging: Explaining the code line by line to an inanimate object or colleague, forcing the programmer to articulate their thought process and potentially uncovering hidden errors.

Example:

def divide(a, b):

    result = a / b

    return result

# Debugging with print statements

num1 = 10

num2 = 0

print(“Before division”)

result = divide(num1, num2)

print(“After division”)

  1. Error Handling:

Definition: Error handling is the process of anticipating, detecting, and responding to errors or exceptions that occur during program execution. It involves implementing mechanisms to gracefully handle errors and prevent program crashes.

Types of Errors:

Syntax Errors: Errors that occur due to violations of the programming language’s syntax rules, such as missing parentheses or incorrect indentation.

Runtime Errors: Errors that occur during program execution, such as division by zero or accessing an index out of range.

Logical Errors: Errors that result from flawed logic or incorrect assumptions in the code, leading to unexpected behavior.

Error Handling Mechanisms:

Try-Except Blocks: Using try-except blocks to catch and handle exceptions gracefully, preventing program termination.

Exception Handling: Handling specific types of exceptions or errors separately to provide tailored responses or recovery actions.

Example:

def divide(a, b):

    try:

        result = a / b

    except ZeroDivisionError:

        print(“Error: Division by zero”)

        result = None

    return result

num1 = 10

num2 = 0

result = divide(num1, num2)

if result is not None:

    print(“Result of division:”, result)

  1. Practice Exercise:

Problem: Write a program to read a number from the user and calculate its square root. Handle the case where the user enters a negative number.

Solution:

import math

def calculate_square_root(number):

    try:

        if number < 0:

            raise ValueError(“Negative number”)

        else:

            return math.sqrt(number)

    except ValueError as e:

        print(“Error:”, e)

        return None

user_input = float(input(“Enter a number: “))

square_root = calculate_square_root(user_input)

if square_root is not None:

    print(“Square root:”, square_root)

Leave a Reply

Your email address will not be published. Required fields are marked *