Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

Introduction to computer programing

The document provides an introduction to computer programming methodologies, defining key concepts such as programming, algorithms, debugging, and testing. It outlines the program design process, including problem definition, algorithm design, and modularity, as well as various programming paradigms like imperative, declarative, and event-driven programming. Additionally, it emphasizes the importance of syntax and semantics in writing programs and the iterative nature of program design.

Uploaded by

ndungujose2441
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Introduction to computer programing

The document provides an introduction to computer programming methodologies, defining key concepts such as programming, algorithms, debugging, and testing. It outlines the program design process, including problem definition, algorithm design, and modularity, as well as various programming paradigms like imperative, declarative, and event-driven programming. Additionally, it emphasizes the importance of syntax and semantics in writing programs and the iterative nature of program design.

Uploaded by

ndungujose2441
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

COSC 104: INTRODUCTION TO COMPUTER PROGRAMMING

METHODOLOGIES
LEC I
Definitions:

 Program: A set of instructions that a computer follows to perform a specific


function .
 Programming: The process of writing instructions for a computer to execute a
task .
 Algorithm: A procedure for solving a mathematical problem or accomplishing
some end. It can also refer to the set of rules a machine follows to achieve a
goal, such as a search engine or an encryption algorithm
 Troubleshooting: is the process of identifying and resolving problems, errors,
or faults within a software or computer system 1. It enables the repair and
restoration of a computer or software when it becomes faulty, unresponsive, or
acts in an abnormal way. Troubleshooting is primarily done to keep a system or
software in desired condition
 Debugging: The process of finding and resolving bugs (defects or problems
that prevent correct operation) within computer programs, software, or systems
 Testing: The process of identifying and resolving errors, or bugs, in a software
system. It is an important aspect of software engineering because bugs can
cause a software system to malfunction, and can lead to poor performance or
incorrect results

 Compiler: A program that translates high-level programming languages into


machine code that computers can understand and execute

 Language: A set of rules and symbols used to communicate with a computer .


 Data types: A classification of data items that indicate the kind of value they
contain and how they are stored in memory
 Control structures: Statements that determine the order in which other
statements are executed in a program
 Functions: A block of code that performs a specific task and can be reused
throughout a program
 Arrays: A collection of elements of the same data type that are stored in
contiguous memory locations and can be accessed using an index
 Mechanics of running, testing, and debugging: The process of executing,
verifying, and correcting a program to ensure that it works as intended.
Computers problem Solving

Solving problems with computers involves a process of identifying and resolving


errors, or bugs, in a software system. It is an important aspect of software engineering
because bugs can cause a software system to malfunction, and can lead to poor
performance or incorrect results .

The following are general tips for troubleshooting computer problems :

 Write down your steps: Once you start troubleshooting, you may want to write
down each step you take. This way, you’ll be able to remember exactly what
you’ve done and can avoid repeating the same mistakes. If you end up asking
other people for help, it will be much easier if they know exactly what you’ve
tried already.
 Take notes about error messages: If your computer gives you an error message,
be sure to write down as much information as possible. You may be able to use
this information later to find out if other people are having the same error.
 Always check the cables: If you’re having trouble with a specific piece of
computer hardware, such as your monitor or keyboard, an easy first step is to
check all related cables to make sure they’re properly connected.
 Restart the computer: When all else fails, restarting the computer is a good
thing to try. This can solve a lot of basic issues you may experience with your
computer.
 If you’re still having trouble with your computer, you can try showing non-
printing characters by clicking on the Home tab and then clicking on the
Show/Hide button. This will show paragraph marks and other non-printing
characters, which can help you identify the source of the blank page.
PROGRAM DESIGN

Definition:

- Program design is the process of planning and creating a computer program


to solve a specific problem or perform a particular task.

Key Steps in Program Design:

- Problem Definition: Clearly define the problem that the program needs to
solve. Understand the requirements and constraints.

- Algorithm Design: Develop a step-by-step procedure (algorithm) to solve


the problem. This involves breaking down the problem into smaller,
manageable tasks.

- Data Structure Selection: Choose appropriate data structures to organize and


store data efficiently.

- Interface Design: Design the user interface and interactions if applicable.

- Testing and Debugging: Plan for thorough testing to identify and fix errors
or bugs.

Modularity:

- Break down the program into smaller, modular components. Each module
should have a specific function and be relatively independent. This enhances
readability, maintainability, and reusability.

Top-Down vs. Bottom-Up Design:

- Top-Down: Start with the main program and break it down into smaller,
more manageable tasks.

- Bottom-Up: Develop individual components and gradually combine them


to create the complete program.
Pseudocode and Flowcharts:

- Use pseudocode or flowcharts to represent the logic and flow of the


program before actual coding. This helps in clarifying the design and
identifying potential issues early on.

Comments and Documentation:

- Include comments in the code to explain complex sections or provide


context. Document the overall design and any important decisions made during
the design process.

Error Handling:

- Plan for error handling mechanisms to ensure that the program behaves
appropriately when unexpected situations occur.

Optimization:

- Optimize the program for efficiency in terms of speed, memory usage, and
other resources. However, prioritize clarity and maintainability unless
performance is critical.

Testing:

- Rigorous testing is crucial. Test the program with various inputs to ensure it
behaves as expected. Address any issues through debugging.

Iterative Process:

- Program design is often an iterative process. After implementation and


testing, feedback may lead to design modifications and improvements.

//END OL LEC I
LEC II

PROGRAMMING PARADIGMS

Programming Paradigms refers to the different styles or approaches to


programming, each with its own set of principles and methodologies.

Two common programming paradigms exist:

1. Imperative Programming:

- Focuses on describing how a program operates by providing explicit


statements that change a program's state. It uses statements that change a
program's state, often through the use of variables and loops.

There are Two common Imperative Programming classes:

i. Procedural Programming

This type of imperative programming, the Problem is broken down into procedures, or blocks of
code that perform one task each. All procedures taken together form the whole program. It is
suitable only for small programs that have low level of complexity.
Example − For a calculator program that does addition, subtraction, multiplication, division,
square root and comparison, each of these operations can be developed as separate procedures. In
the main program each procedure would be invoked on the basis of user’s choice.

- Example: in C below:
#include <stdio.h>
#include <math.h>

int main() {
char operator;
double num1, num2, result;

printf("Enter an operator (+, -, *, /, s, c): ");


scanf("%c", &operator);

printf("Enter two operands: ");


scanf("%lf %lf", &num1, &num2);

switch (operator) {
case '+':
result = num1 + num2;
printf("%.2lf + %.2lf = %.2lf", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("%.2lf - %.2lf = %.2lf", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("%.2lf * %.2lf = %.2lf", num1, num2, result);
break;
case '/':
result = num1 / num2;
printf("%.2lf / %.2lf = %.2lf", num1, num2, result);
break;
case 's':
result = sqrt(num1);
printf("sqrt(%.2lf) = %.2lf", num1, result);
break;
case 'c':
if (num1 > num2) {
printf("%.2lf > %.2lf", num1, num2);
} else if (num1 < num2) {
printf("%.2lf < %.2lf", num1, num2);
} else {
printf("%.2lf = %.2lf", num1, num2);
}
break;
default:
printf("Error! Invalid operator.");
}
return 0;
}

Run above program on Falcon SDK

ii. Object-oriented Programming

Here the solution revolves around entities or objects that are part of problem. The solution deals
with how to store data related to the entities, how the entities behave and how they interact with
each other to give a cohesive solution.

Example − If we have to develop a payroll management system, we will have entities like
employees, salary structure, leave rules, etc. around which the solution must be built.

#include <stdio.h>

struct Employee {
int id;
char name[50];
float salary;
};

int main() {
struct Employee emp;
printf("Enter employee ID: ");
scanf("%d", &emp.id);
printf("Enter employee name: ");
scanf("%s", emp.name);
printf("Enter employee salary: ");
scanf("%f", &emp.salary);
printf("\nEmployee ID: %d\n", emp.id);
printf("Employee Name: %s\n", emp.name);
printf("Employee Salary: %.2f\n", emp.salary);
return 0;
}

Run above program in Facon C

2. Declarative Programming:

- Concentrates on describing what the program should accomplish without


specifying how to achieve it. The emphasis is on expressing the logic of a
computation.

-Two common examples of declarative programming are:


i. Functional Programming

Here the problem, or the desired solution, is broken down into functional units. Each unit
performs its own task and is self-sufficient. These units are then stitched together to form the
complete solution.

Example − A payroll processing can have functional units like employee data maintenance,
basic salary calculation, gross salary calculation, leave processing, loan repayment processing,
etc.

Here is an example of a payroll processing program in C that includes functional units


like employee data maintenance, basic salary calculation, gross salary calculation,
leave processing, and loan repayment processing:
#include <stdio.h>

struct Employee {
int id;
char name[50];
float basic_salary;
float gross_salary;
float leave_balance;
float loan_balance;
};

int main() {
struct Employee emp;
printf("Enter employee ID: ");
scanf("%d", &emp.id);
printf("Enter employee name: ");
scanf("%s", emp.name);
printf("Enter employee basic salary: ");
scanf("%f", &emp.basic_salary);
printf("Enter employee leave balance: ");
scanf("%f", &emp.leave_balance);
printf("Enter employee loan balance: ");
scanf("%f", &emp.loan_balance);

emp.gross_salary = emp.basic_salary + (emp.basic_salary * 0.1);


printf("\nEmployee ID: %d\n", emp.id);
printf("Employee Name: %s\n", emp.name);
printf("Employee Basic Salary: %.2f\n", emp.basic_salary);
printf("Employee Gross Salary: %.2f\n", emp.gross_salary);
printf("Employee Leave Balance: %.2f\n", emp.leave_balance);
printf("Employee Loan Balance: %.2f\n", emp.loan_balance);

return 0;
}

Run above in Falcon


ii. Logical Programming

Here the problem is broken down into logical units rather than functional units.

Example: In a school management system, users have very defined roles like class teacher,
subject teacher, lab assistant, coordinator, academic in-charge, etc. So the software can be
divided into units depending on user roles. Each user can have different interface, permissions,
etc.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_STUDENTS 100

struct student {
char name[50];
int roll_no;
float marks;
};

struct student students[MAX_STUDENTS];


int num_students = 0;

void add_student() {
if (num_students >= MAX_STUDENTS) {
printf("Error: Maximum number of students reached.\n");
return;
}

struct student new_student;


printf("Enter name: ");
scanf("%s", new_student.name);
printf("Enter roll number: ");
scanf("%d", &new_student.roll_no);
printf("Enter marks: ");
scanf("%f", &new_student.marks);

students[num_students++] = new_student;
printf("Student added successfully.\n");
}

void display_students() {
if (num_students == 0) {
printf("No students found.\n");
return;
}

printf("Name\tRoll No.\tMarks\n");
for (int i = 0; i < num_students; i++) {
printf("%s\t%d\t\t%.2f\n", students[i].name, students[i].roll_no,
students[i].marks);
}
}
int main() {
int choice;

while (1) {
printf("\nStudent Management System\n");
printf("1. Add student\n");
printf("2. Display students\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
add_student();
break;
case 2:
display_students();
break;
case 3:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice.\n");
}
}

return 0;
}

Run above program in Falcon C

3. Other Programming Paradigms

i. Event-Driven Programming:

- Responds to events or user interactions. The program's flow is determined


by events, such as user inputs, sensor outputs, or messages from other
programs.

- Examples: JavaScript (for web development), GUI programming.

ASSIGNMENT: Create an event-driven program using Javascript

ii. Logic Programming:

- Describes relationships and constraints through logical statements. The


program's execution is determined by resolving these logical statements.
- Examples: Prolog.

iii. Aspect-Oriented Programming (AOP):

- Separates concerns by isolating cross-cutting concerns like logging,


security, and error handling. AOP allows developers to modularize these
concerns.

- Examples: AspectJ.

iv. Parallel Programming:

- Focuses on techniques to execute multiple instructions simultaneously,


taking advantage of parallel processing capabilities.

- Examples: CUDA (for GPU programming), MPI.

v. Scripting Languages:

- Emphasizes ease of use and rapid development. Scripts are often


interpreted rather than compiled.

- Examples: Python, Ruby, JavaScript (when used as a scripting language).

vi. Meta-Programming:

- Involves writing programs that manipulate other programs or themselves at


runtime. This paradigm is often used for code generation and optimization.

- Examples: Lisp macros, Template metaprogramming in C++.

Understanding these programming paradigms provides a foundation for


choosing the right approach for different programming tasks. It's common for
modern languages and systems to incorporate elements from multiple
paradigms, resulting in a multi-paradigm approach.
Software developers may choose one or a combination of more than one of these
methodologies to develop a software. Note that in each of the methodologies discussed,
problem has to be broken down into smaller units. To do this, developers use any of the
following two approaches :

 Top-down approach
 Bottom-up approach
i. Top-down or Modular Approach

The problem is broken down into smaller units, which may be further broken down into even
smaller units. Each unit is called a module. Each module is a self-sufficient unit that has
everything necessary to perform its task.

The following illustration shows an example of how you can follow modular approach to create
different modules while developing a payroll processing program.
ii. Bottom-up Approach

In bottom-up approach, system design starts with the lowest level of components, which are then
interconnected to get higher level components. This process continues till a hierarchy of all
system components is generated. However, in real-life scenario it is very difficult to know all
lowest level components at the outset. So bottoms up approach is used only for very simple
problems.

Let us look at the components of a calculator program.

ASSIGNMENT: READ UP ON PROGRAMMING LANGUAGES AND PARTS OF


A PROGRAM

//END OF LEC II
LEC III

WRITING PROGRAMS

Syntax defines the rules and regulations that help write any statement in a programming
language.

Semantics refers to the meaning of the associated line of code in the programming language.

Difference between Syntax and Semantics

The following table highlights all the significant differences between syntax and semantics −

S.No. Syntax Semantics

Syntax is one that defines the rules and Semantics is one that refers to the
1. regulations that helps to write any meaning of the associated line of
statement in a programming language. code in a programming language.

Syntax does not have any relationship Semantics tells about the meaning.
2.
with the meaning of the statement.

Syntax errors are encountered after the They are encountered at runtime.
3.
program has been executed

Syntax errors are easy to catch. Semantics errors are difficult to


4.
catch.

Essential components of programming syntax

There are several essential components of programming syntax, including:

 Keywords: Reserved words in a programming language with a specific function.


Examples include `if`, `else`, `while`, and `for`.
 Operators: Symbols that allow you to perform mathematical, logical, or assignment
operations. Examples are `+`, `-`, `*`, `/`, and `%`.
 Variables: Named memory locations that store data. Variable names follow specific rules,
such as starting with letters or underscores and avoiding reserved keywords.
 Data types: Classification of data, specifying which values a variable can hold. Examples
include integers, floating-point numbers, and strings.
 Functions: Reusable pieces of code that perform a specific task. Functions often take
input arguments and return a value as the result of their execution.
 Control structures: Techniques that control the flow of a program's execution, such as
loops or conditional statements.

Elementary Data Types

A data type is an attribute of a piece of data that tells a device how the end-user might interact
with the data.

You can also think of them as categorizations that different coding programs might combine in
order to execute certain functions.

There are 10 elementary data types:

1. Integer

Integer data types often represent whole numbers in programming. An integer's value moves
from one integer to another without acknowledging fractional numbers in between. The number
of digits can vary based on the device, and some programming languages may allow negative
values.

2. Character

In coding, alphabet letters denote characters. Programmers might represent these data types as
(CHAR) or (VARGCHAR), and they can be single characters or a string of letters. Characters
are usually fixed-length figures that default to 1 octet—an 8-bit unit of digital information—but
can increase to 65,000 octets.

3. Date

This data type stores a calendar date with other programming information. Dates are typically a
combination of integers or numerical figures. Since these are typically integer values, some
programs can store basic mathematical operations like days elapsed since certain events or days
away from an upcoming event.

4. Floating point (real)

Floating-point data types represent fractional numbers in programming. There are two main
floating-point data types, which vary depending on the number of allowable values in the string:

Float: A data type that typically allows up to seven points after a decimal.

Double: A data type that allows up to 15 points after a decimal.

5. Long
Long data types are often 32- or 64-bit integers in code. Sometimes, these can represent integers
with 20 digits in either direction, positive or negative. Programmers use an ampersand to indicate
the data type is a long variable.

6. Short

Similar to the long data type, a short is a variable integer. Programmers represent these as whole
numbers, and they can be positive or negative. Sometimes a short data type is a single integer.

7. String

A string data type is a combination of characters that can be either constant or variable. This
often incorporates a sequence of character data types that result in specific commands depending
on the programming language. Strings can include both upper and lowercase letters, numbers
and punctuation.

8. Boolean

Boolean data is what programmers use to show logic in code. It's typically one of two
values—true or false—intended to clarify conditional statements. These can be responses to
"if/when" scenarios, where code indicates if a user performs a certain action. When this happens,
the Boolean data directs the program's response, which determines the next code in the sequence.

9. Nothing

The nothing data type shows that a code has no value. This might indicate that a code is missing,
the programmer started the code incorrectly or that there were values that defy the intended
logic. It's also called the "nullable type."

10. Void

Similar to the nothing type, the void type contains a value that the code cannot process. Void
data types tell a user that the code can't return a response. Programmers might use or encounter
the void data type in early system testing when there are no responses programmed yet for future
steps.
Data type examples

Data types can vary based on size, length and use depending on the coding language. Here are
some examples of the data types listed above that you might encounter when programming:

Integer

Integers are digits that account for whole numbers only. Some integer examples include:

425

65

Character

Characters are letters or other figures that programmers might combine in a string. Examples of
characters include:

Date

Programmers can include individual dates, ranges or differences in their code. Some examples
might be:

2009-09-15

1998-11-30 09:45:87

SYSDATETIME ()

Long

Long data types are whole numbers, both positive and negative, that have many place values.
Examples include:

-398,741,129,664,271

9,000,000,125,356,546
Short

Short data types can be up to several integers, but they are always less than long data. Examples
include:

-27,400

5,428

17

Floating point (real)

Float data types might look like this:

float num1 = 1.45E2

float num2 = 9.34567

Similar but often longer in length, an example of the floating-point double might be:

double num2 = 1.87358497267482791E+222

double num2 = 3.198728764857268945

The floating-point double type can provide more accurate values, but it also may require
additional memory to process.

String

Strings are a combination of figures that includes letters and punctuation. In some code, this
might look like this:

String a = new String("Open")

String b = new String("The door")

String c = new String("Say Hello!")

These can be independent commands, or they can work together.

Boolean

Boolean data can help guide the logic in a code. Here are some examples of how you might use
this:
bool baseballIsBest = false;

bool footballIsBest = true;

Depending on the program, the code may direct the end-user to different screens based on their
selection.

Void/Nothing

Nothing means a code has no value, but the programmer coded something other than the digit 0.
This is often "Null," "NaN" or "Nothing" in code. An example of this is:

Dim option = Nothing

Program.WriteWords(x Is Nothing)

Void

The void data type in coding functions as an indicator that code might not have a function or a
response yet. This might appear as:

int function_name (void)

NB:

A variable can be thought of as a memory location that can hold values of a specific type. The
value in a variable may change during the life of the program—hence the name “variable.” In
VBA, each variable has a specific data type, which indicates which type of data it may hold.
ASSIGNMENT: What are the 5 types of variables?

Expressions and Assignments in Programming Languages

Expressions are a series of variables, operators, and method calls (constructed according to the
syntax of the language) that evaluates to a single value.

In C, expressions are combinations of variables, constants, and operators that are evaluated to
produce a value. Here is an example of an arithmetic expression in C:

#include <stdio.h>

int main() {
int a = 10;
int b = 20;
int c;

c = a + b;
printf("c = %d\n", c);
return 0;
}

This program declares three integer variables a, b, and c. The expression a + b is evaluated and
the result is stored in the variable c. The value of c is then printed to the console.

Other types of expressions in C include relational expressions, logical expressions, and


conditional expressions .

Assignment is when a program statement copies a value into the variable.

Example of Assignment:

#include <stdio.h>

int main() {
int a = 10;
int b = 20;
int c;

c = a + b;
printf("c = %d\n", c);

c += a;
printf("c = %d\n", c);

c -= a;
printf("c = %d\n", c);

c *= a;
printf("c = %d\n", c);

c /= a;
printf("c = %d\n", c);

return 0;
}

When you run this program, you will see the following output:
c = 30
c = 40
c = 30
c = 300
c = 30

ASSIGNMENT:

What are blocks in Programming?,give an example of a block


Writing a Program

Writing a program involves several key steps:

1. Problem definition: Clearly define the problem you want to solve and what you want the
program to achieve.
2. Algorithm design: Develop a step-by-step procedure for solving the problem.
3. Coding: Translate the algorithm into a programming language using a text editor or
integrated development environment (IDE).
4. Testing and debugging: Run the program and identify and fix any errors.
5. Deployment: Share the program with others or use it for your own purposes.

Programming involves several key concepts, including variables, data types, control flow
statements, functions, and expressions

To write a program in C, you can follow these steps:

1. Install a C compiler on your computer, such as Falcon C.


2. Choose a text editor or IDE to write your code, Falcon C new project.
3. Write your program using C syntax and conventions.
4. Compile your program using the C compiler.
5. Run your program and test it thoroughly.
Input and Output Statements

Input and output (I/O) statements are used in programming to communicate between a
program and the outside world, such as a user or another program.

Input statements are used to read data from an input device, such as a keyboard or
mouse, and output statements are used to display data on an output device, such as a
monitor or printer .

In C programming, there are two I/O statements: the scanf() function is used to read
input from the keyboard, and the printf() function is used to display output to the
console .

Here is an example of how to use these statements:


#include <stdio.h>

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);
printf("You entered: %d\n", num);

return 0;
}

Above program prompts the user to enter a number, reads the number from the
keyboard using scanf(), and then displays the number back to the console using
printf().

//END OF LEC III


LEC IV

CONTROL STRUCTURES:

Control structures are programming constructs that manage the flow of execution in a
program. They decide which block of code should be executed and under what
conditions. There are three basic types of control structures:

1. Sequence logic: This type of logic follows a serial or sequential flow in which the
flow depends on the series of instructions given to the computer. Unless new
instructions are given, the modules are executed in the obvious sequence. Most of the
processing, even some complex problems, will generally follow this elementary flow
pattern.

2. Selection logic: This type of logic involves a number of conditions or parameters


that decide one out of several written modules. The structures that use this type of
logic are known as conditional structures. These structures can be of three types:

Single Alternative: This structure has the form: If (condition) then: [Module A]
[End of If structure]

Double Alternative: This structure has the form: If (Condition), then: [Module A]
Else: [Module B] [End if structure]

Multiple Alternatives: This structure has the form: If (condition A), then: [Module
A] Else if (condition B), then: [Module B] .. .. Else if (condition N), then: [Module
N] [End If structure]

3. Iteration logic: This type of logic employs a loop that involves a repeat statement
followed by a module known as the body of a loop. The two types of these structures
are:

Repeat-For Structure: This structure has the form: Repeat for i = A to N by I:


[Module] [End of loop]

Repeat-While Structure: It also uses a condition to control the loop. This structure
has the form: Repeat while condition: [Module] [End of Loop]

These control structures can be used in combination to create more complex


programs.
Examples of Control Structures in C:

1. Sequence logic Control Structure


#include <stdio.h>

int main() {
int num1, num2, sum;

printf("Enter two numbers: ");


scanf("%d %d", &num1, &num2);

sum = num1 + num2;

printf("The sum of %d and %d is %d\n", num1, num2, sum);

return 0;
}

This program reads two numbers from the user using scanf(), adds them together
using the + operator, and then displays the result to the console using printf(). The
program follows a sequential flow in which each statement is executed in the order it
is written.

2. Selection Logic Control Structure


#include <stdio.h>

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

if (num > 0) {
printf("%d is positive.\n", num);
} else if (num < 0) {
printf("%d is negative.\n", num);
} else {
printf("%d is zero.\n", num);
}

return 0;
}

This program reads a number from the user using scanf() and then uses a selection
logic control structure to determine whether the number is positive, negative, or zero.
The if statement checks if the number is greater than zero, the else if statement
checks if the number is less than zero, and the else statement handles the case where
the number is zero. The program then displays the result to the console using
printf().

3. Single Alternative Selection logic

Utilizes if…statement
#include <stdio.h>

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

if (num % 2 == 0) {
printf("%d is even.\n", num);
}

return 0;
}

This program reads a number from the user using scanf() and then uses a single
alternative selection logic control structure to determine whether the number is even.
The if statement checks if the number is divisible by 2 using the modulo operator (%).
If the number is even, the program displays a message to the console using printf().
If the number is odd, the program does nothing.

4. Double Alternative Selection logic

Utilizes if..… else….


#include <stdio.h>

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

if (num > 0) {
printf("%d is positive.\n", num);
} else if (num < 0) {
printf("%d is negative.\n", num);
} else {
printf("%d is zero.\n", num);
}

return 0;
}
This program reads a number from the user using scanf() and then uses a double
alternative selection logic control structure to determine whether the number is
positive, negative, or zero. The if statement checks if the number is greater than zero,
the else if statement checks if the number is less than zero, and the else statement
handles the case where the number is zero. The program then displays the result to the
console using printf().

5. Multiple Alternatives Selection Logic

Utilizes if…else if…else.


#include <stdio.h>

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

if (num == 0) {
printf("%d is zero.\n", num);
} else if (num == 1) {
printf("%d is one.\n", num);
} else if (num == 2) {
printf("%d is two.\n", num);
} else if (num == 3) {
printf("%d is three.\n", num);
} else {
printf("%d is not between 0 and 3.\n", num);
}

return 0;
}

This program reads a number from the user using scanf() and then uses a multiple
alternatives selection logic control structure to determine whether the number is
between 0 and 3. The if statement checks if the number is equal to 0, the first else if
statement checks if the number is equal to 1, the second else if statement checks if
the number is equal to 2, and the third else if statement checks if the number is equal
to 3. If the number is not between 0 and 3, the program displays a message to the
console using printf().

6. Iteration logic Control Logic


Utilizes for statement

#include <stdio.h>

int main() {
int i;

for (i = 1; i <= 10; i++) {


printf("%d ", i);
}

printf("\n");

i = 1;
while (i <= 10) {
printf("%d ", i);
i++;
}

printf("\n");

i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 10);

printf("\n");

return 0;
}

This program demonstrates the use of three types of iteration logic control structures
in C: for, while, and do-while. The for loop prints the numbers from 1 to 10 to the
console, the while loop does the same thing using a different syntax, and the do-while
loop prints the numbers from 1 to 10 to the console using yet another syntax. Each
loop structure has its own advantages and disadvantages depending on the situation.

7. Repeat-For Structure control structure

Here is an example of a Repeat-For Structure control structure in C:


#include <stdio.h>

int main() {
int i;

for (i = 1; i <= 10; i++) {


printf("%d ", i);
}

printf("\n");

return 0;
}
This program uses a Repeat-For Structure control structure to print the numbers from
1 to 10 to the console. The for loop has the form: Repeat for i = A to N by I:
[Module] [End of loop]. In this case, A is the initial value of i, N is the end value of i,
and I is the increment value of i. The loop ends when i is greater than N. The program
then displays the result to the console using printf().

8. Repeat-While Structure control structure


#include <stdio.h>

int main() {
int i = 1;

do {
printf("%d ", i);
i++;
} while (i <= 10);

printf("\n");

return 0;
}

This program uses a Repeat-While Structure control structure to print the numbers
from 1 to 10 to the console. The do-while loop has the form: Repeat while condition:
[Module] [End of Loop]. In this case, the loop continues to execute the body of the
loop as long as the condition i <= 10 is true. The program then displays the result to
the console using printf().

//LEC IV

HOMEWORK:
Differentiate hardcoding versus softcoding?
LEC V

BOOLEAN EXPRESSIONS

Boolean expressions are used in programming to evaluate whether a condition is true


or false. A Boolean expression is an expression that produces a Boolean value when
evaluated, i.e. it produces either a true value or a false value. Instead of using
arithmetic operators like addition, subtraction, and multiplication, Boolean logic
utilizes three basic logical operators: AND, OR, and NOT. Boolean logic looks at a
reported relationship between things and determines whether the relationship holds.
Boolean expressions can be built with all kinds of data, including variables. In
programming, Boolean values are often used in conditional statements to determine
which block of code should be executed and under what conditions.

ASSIGNMENT: Write a program in C utilizing AND,OR and NOT Boolean logic

Example:

#include <stdio.h>

int main() {
int a = 5, b = 10, c = 15;

if (a > 0 && b > 0) {


printf("Both a and b are greater than 0\n");
}

if (a > 0 || b > 0) {
printf("Either a or b is greater than 0\n");
}

if (!(a > 0)) {


printf("a is not greater than 0\n");
}

return 0;
}

In this program, we have three integer variables a, b, and c. The first if statement uses
the AND operator to check if both a and b are greater than 0. If the condition is true, it
prints “Both a and b are greater than 0”. The second if statement uses the OR
operator to check if either a or b is greater than 0. If the condition is true, it prints
“Either a or b is greater than 0”. The third if statement uses the NOT operator to
check if a is not greater than 0. If the condition is true, it prints “a is not greater than
0”.

SYMBOLIC CONSTANTS

Symbolic constants are identifiers that represent a fixed value in a program.

They are used to make the code more readable and easier to maintain.

In C programming, there are three common ways to define symbolic constants: using macros,
using constant variables, and using enumerations.

Macros are defined using the #define preprocessor directive. They are simple textual
substitutions that work for any type of data. However, they have some weaknesses, such as not
respecting context and scope .

Constant variables are defined using the const keyword. They work for any type of data and are
handled by the compiler, which respects context and scope. However, they do not work for array
lengths .

Enumerations are defined using the enum keyword. They allow you to explicitly specify values
for enumeration constants and can be used to define anonymous enumeration types. They work
only for int literals .

Here is an example program in C that demonstrates the use of symbolic constants:

#include <stdio.h>

#define PI 3.14159

int main() {
const int ARRAY_LENGTH = 10;

enum State {START_STATE, POSSIBLE_COMMENT_STATE, COMMENT_STATE};

int aiNumbers[ARRAY_LENGTH];
enum State eState = START_STATE;

printf("The value of pi is %f\n", PI);


printf("The length of the array is %d\n", ARRAY_LENGTH);
printf("The current state is %d\n", eState);

return 0;
}

In this program, we define the symbolic constant PI using a macro, the symbolic
constant ARRAY_LENGTH using a constant variable, and the enumeration type State using
an enumeration. We then use these symbolic constants in the program to make it more
readable. //LEC V

//CAT 1
LEC IV

REPETITION LOGIC

These structures play a crucial role in determining how a program flows based on specific
conditions. Here are the key concepts and examples:

1. **Sequential Logic (Sequential Flow)**:

- Sequential logic follows a linear flow, executing instructions in the order they are given.

- Modules are executed one after the other unless new instructions alter the sequence.

- This basic flow pattern is common for most processing tasks.

- Example: A simple program that reads input, processes data, and produces output.

#include <iostream>

using namespace std;

int main() {

string name;

int age;

// Step 1: Read input from the user

cout << "Enter your name: ";

cin >> name;

cout << "Enter your age: ";

cin >> age;

// Step 2: Process the data

int birth_year = 2024 - age;

// Step 3: Produce output


cout << "Hello, " << name << "! You were born around " << birth_year << "." << endl;

return 0;

In this C++ program:

1. We declare a `string` variable `name` to store the user's name and an `int` variable `age`
to store their age.

2. We read input using `cin` (similar to Python's `input()`).

3. The calculation of the birth year remains the same.

4. We use `cout` to print the output message.

2. **Selection Logic (Conditional Flow)**:

- Selection logic involves conditions that determine which module to execute.

- Conditional structures include:

- **Single Alternative**:

- If a condition is met, execute a specific module.

- Example: Implementing an `if` statement in C/C++ or Java.

- **Double Alternative**:

- Choose between two modules based on a condition.

- Example: Using an `if-else` statement in C/C++ or Java.

- **Multiple Alternatives**:

- Select from multiple modules based on different conditions.


- Example: Employing an `if-else if` ladder in C++

#include <iostream>

using namespace std;

int main() {

int i = 20;

if (i == 10)

cout << "i is 10";

else if (i == 15)

cout << "i is 15";

else if (i == 20)

cout << "i is 20";

else

cout << "i is not present";

return 0;

In this example:

- We initialize `i` to 20.

- The `if-else if` ladder checks the conditions in order.

- Since `i` is equal to 20, the third condition (`i == 20`) evaluates to true.
- The message "i is 20" is printed.

Here's another example with a range-based condition:

#include <iostream>

using namespace std;

int main() {

int i = 25;

if (i >= 0 && i <= 10)

cout << "i is between 0 and 10" << endl;

else if (i >= 11 && i <= 15)

cout << "i is between 11 and 15" << endl;

else if (i >= 16 && i <= 20)

cout << "i is between 16 and 20" << endl;

else

cout << "i is greater than 20" << endl;

return 0;

In this second example, the program checks the value of `i` and prints the corresponding
message based on the specified

3. **Iteration Logic (Repetitive Flow)**:

- Iteration logic involves loops that repeat a set of instructions.

- Two common loop structures:

- **Repeat-For Structure**:
- Form: `Repeat for i = A to N by I: [Module]`

- The loop executes the module from `A` to `N`, incrementing by `I`.

- Example: Using a `for` loop in C/C++ or Java.

- **Repeat-While Structure**:

- Form: `Repeat while condition: [Module]`

- The loop continues as long as the specified condition holds true.

- Example: Implementing a `while` loop in C++.

#include <iostream>

int main() {

int count = 1; // Initialize a counter

// Execute the loop while the condition (count <= 5) is true

while (count <= 5) {

std::cout << "Iteration " << count << ": Hello, World!" << std::endl;

count++; // Increment the counter

return 0;

In this example:

- We initialize a counter variable `count` to 1.

- The `while` loop runs as long as `count` is less than or equal to 5.

- Inside the loop, we print a message and increment the counter.

- The loop will execute 5 times, printing "Hello, World!" for each iteration.
HOMEWORK:

What is the difference between a while loop and a do-while loop?

1. While Loop:
o A while loop is a control flow structure that repeatedly executes a block of code
as long as a given Boolean condition remains true.
o The condition is checked before entering the loop. If the condition is false
initially, the loop won’t execute at all.
o It is an entry-controlled loop.
o Example (in C/C++ or Java):
o #include <stdio.h>
o int main() {
o int i = 5;
o while (i < 10) {
o printf("GFG\n");
o i++;
o }
o return 0;
o }

Output:

GFG
GFG
GFG
GFG
GFG

2. Do-While Loop:
o A do-while loop is similar to a while loop, but with one key difference: it checks
the condition after executing the statements inside the loop.
o The loop body is executed at least once, even if the condition is false initially.
o It is an exit-controlled loop.
o Example (in C/C++ or Java):
o #include <stdio.h>
o int main() {
o int i = 5;
o do {
o printf("GFG\n");
o i++;
o } while (i < 10);
o return 0;
o }

Output:
GFG
GFG
GFG
GFG
GFG

3. Key Differences:
o Condition Check:
 While loop: Condition is checked before executing the loop.
 Do-while loop: Statements are executed first, then the condition is
checked.
o Execution Guarantee:
 While loop: May execute zero times if the initial condition is false.
 Do-while loop: Executes at least once, regardless of the initial condition.

In summary, while loops are more cautious, checking the condition first, while do-while loops
are more adventurous, diving into execution before verifying the condition
FUNCTIONS

1. **Functions**:

- Functions are subprograms designed to perform a specific task and return a value.

- They can take input parameters (arguments) and compute a result.

- Example function definition:

```cpp

int times(int x, int y) {

int p = 0;

while (y > 0) {

if (y % 2 == 0) {

y /= 2;

x *= 2;

} else {

p += x;

y--;

return p;

```

- Functions are used as operations within expressions:

```cpp

int i = times(3, i + 2) + 1;

```
2. **Procedures**:

- Procedures are subprograms designed to perform a series of commands without returning a


value.

- They can also take input parameters.

- Example procedure definition:

```cpp

void factors(int x) {

int f = 2;

while (x != 1) {

if (x % f == 0) {

cout << f << endl;

x /= f;

} else {

f++;

```

- Procedures are used as statements:

```cpp

factors(i);

```
3. **Parameter Passing**:

- Parameters can be passed by value (call-by-value) or by reference (call-by-reference).

- Call-by-value makes a copy of the argument, while call-by-reference passes the memory
location.

- Example:

```cpp

void p(int x, int& y) {

// Code for p

```

4. **Benefits of Subprograms**:

- Increases readability: Programs are better structured and easier to understand.

- Enables program design abstraction.

- Facilitates code reuse.

Functions allow us to break down complex tasks into smaller, reusable chunks of code. We'll
cover both basic function examples and more advanced concepts.

1. **Basic Function Example**:

- A simple function that displays a text message:

```cpp

#include <iostream>

using namespace std;

// Function declaration

void greet() {

cout << "Hello there!";

}
int main() {

// Calling the function

greet();

return 0;

```

- Output:

```

Hello there!

```

2. **Function with Parameters**:

- A function that takes parameters (arguments):

```cpp

#include <iostream>

using namespace std;

// Function to display a number

void displayNum(int n1, float n2) {

cout << "The int number is " << n1 << endl;

cout << "The double number is " << n2 << endl;

int main() {

int num1 = 5;
double num2 = 5.5;

// Calling the function with arguments

displayNum(num1, num2);

return 0;

```

- Output:

```

The int number is 5

The double number is 5.5

```

3. **Function with Return Value**:

- A function that computes the sum of two integers and returns the result:

```cpp

#include <iostream>

using namespace std;

// Function to add two numbers

int add(int a, int b) {

return a + b;

int main() {

int x = 10, y = 20;


// Calling the function and storing the result

int result = add(x, y);

cout << "Sum: " << result << endl;

return 0;

```

- Output:

```

Sum: 30

```

4. **Function Templates**:

- A template function that works with different data types:

```cpp

#include <iostream>

using namespace std;

// Template function to find the maximum of two values

template <typename T>

T max(T a, T b) {

return (a > b) ? a : b;

}
int main() {

int intMax = max(10, 20);

double doubleMax = max(3.14, 2.71);

cout << "Max int: " << intMax << endl;

cout << "Max double: " << doubleMax << endl;

return 0;

```

- Output:

```

Max int: 20

Max double: 3.14

HOMEWORK:

i. What is the difference between a function and a procedure?

1. **Function**:

- A **function** is a subprogram that performs a specific task and **returns a


value**.

- Key characteristics:

- Takes input parameters (arguments).

- Computes a result based on the input.

- Returns a value to the caller.

- Example: A function that calculates the square of a number:


```cpp

int square(int x) {

return x * x;

```

2. **Procedure**:

- A **procedure** (also known as a **void function**) is a subprogram that


performs a series of commands or actions **without returning a value**.

- Key characteristics:

- Takes input parameters (arguments).

- Executes a sequence of statements.

- Does not return any value.

- Example: A procedure that displays a message:

```cpp

void showMessage() {

cout << "Hello, World!";

```

3. **Summary**:
- Functions are used when you need to compute a value and return it.

- Procedures are used for performing actions or tasks without expecting a result.

- Both functions and procedures enhance code modularity and reusability.

ii. Can you give me an example of passing parameters by reference in C++?

When you pass a variable by reference to a function, the address of the variable is
stored in a pointer variable inside the function. This allows the function to modify the
original variable directly. Here are some examples:

1. Passing an Integer by Reference:


2. #include <iostream>
3. using namespace std;
4.
5. // Function that decrements the value by 1
6. void decrement(int& x) {
7. x--;
8. }
9.
10. int main() {
11. int a = 5;
12. cout << "Before: " << a << endl;
13. decrement(a);
14. cout << "After: " << a << endl;
15. return 0;
16. }

Output:
Before: 5
After: 4

17.Swapping Two Numbers using Pass-By-Reference:


18. #include <iostream>
19. using namespace std;
20.
21. // Function to swap two integers
22. void swap(int& a, int& b) {
23. int temp = a;
24. a = b;
25. b = temp;
26. }
27.
28. int main() {
29. int x = 10, y = 20;
30. cout << "Before swapping: x = " << x << ", y = " << y << endl;
31. swap(x, y);
32. cout << "After swapping: x = " << x << ", y = " << y << endl;
33. return 0;
34. }

Output:
Before swapping: x = 10, y = 20
After swapping: x = 20, y = 10

iii. How can I use subprograms to improve my code's efficiency?

1. **Modularity and Reusability**:

- Subprograms allow you to break down complex tasks into smaller, manageable
pieces.

- By writing subprograms for specific tasks, you create modular code that can be
reused across different parts of your program or even in other programs.

- This saves time because you don't have to rewrite the same code multiple times.

2. **Easier Debugging and Testing**:

- Smaller subprograms are easier to test and debug than large monolithic programs.

- When an issue arises, you can focus on a specific subprogram rather than
searching through the entire codebase.

- Isolating errors becomes more straightforward.

3. **Readability and Maintainability**:

- Well-structured subprograms enhance code readability.

- Other developers (or even your future self) can understand the purpose of a
subprogram by reading its name and parameters.

- Clear subprogram names and proper documentation make maintenance easier.


4. **Code Optimization**:

- Subprograms allow you to optimize specific parts of your code.

- For example, you can create a subprogram to perform a computationally expensive


operation efficiently.

- By optimizing subprograms individually, you improve overall program


performance.

5. **Separation of Concerns**:

- Subprograms help separate different concerns within your program.

- For instance, you can have one subprogram for input validation, another for data
processing, and yet another for output formatting.

- Each subprogram focuses on a specific aspect of the program's functionality.

6. **Functions vs. Procedures**:

- **Functions** return a value, allowing you to compute results (e.g., mathematical


calculations).

- **Procedures** perform actions without returning a value (e.g., printing messages,


modifying data).

- Choose the appropriate type based on your needs.

// END OF LEC IV
LEC V

Structures allow you to create custom data types by grouping related variables together.

We'll cover the need for structures, how to declare them, and explore nested structures.

## Need for Structures:

- **Organizing Related Data**: Structures help organize related data into a single unit. For
example, if you're modeling an employee, you can group their name, ID, salary, and department
into a single structure.

- **Avoiding Global Variables**: Instead of using global variables for related data, structures
provide a cleaner way to encapsulate data within a specific context.

- **Creating Custom Data Types**: Structures allow you to define your own data types based on
the problem domain.

## Structure Declarations:

- A structure declaration defines a new data type.

- Syntax:

struct Employee {

int empId;

char empName[50];

double salary;

};

- Here, `Employee` is a new data type that combines an integer (`empId`), a character array
(`empName`), and a double (`salary`).

## Nested Structures:

- A nested structure is a structure within another structure.

- It allows you to create more complex data structures.

- Example:

struct Address {
char street[100];

char city[50];

char state[20];

};

struct Employee {

int empId;

char empName[50];

double salary;

struct Address empAddress;

};

```

- In this example, `Employee` contains an `Address` structure as one of its members.

- Accessing nested structure members:

```cpp

Employee emp;

strcpy(emp.empAddress.street, "123 Main St");

HOMEWORK:

i. What is the difference between a structure and an array?

The differences between a **structure** and an **array** in **C++**:

1. **Structure**:

- A structure is a user-defined data type that allows you to group together variables of different
data types under a single name.
- Key points:

- **Heterogeneous Data**: A structure can hold variables of different data types (e.g.,
integers, characters, doubles).

- **Named Members**: Each variable within a structure is called a member or field.

- **Customizable**: You define the structure layout and member names.

- Example:

```cpp

struct Person {

int age;

char name[50];

double salary;

};

```

2. **Array**:

- An array is a collection of elements of the **same data type** stored in contiguous memory
locations.

- Key points:

- **Homogeneous Data**: All elements in an array have the same data type.

- **Indexed Access**: Elements are accessed using an index (starting from 0).

- **Fixed Size**: The size of an array is determined at compile time.

- Example:

```cpp

int scores[5]; // An array of 5 integers


```

3. **Differences**:

- **Purpose**:

- Structures group related data together (e.g., representing a person's attributes).

- Arrays store a collection of similar data (e.g., scores, temperatures).

- **Data Types**:

- Structures can hold different data types.

- Arrays hold elements of the same data type.

- **Access**:

- Structure members are accessed using dot notation (e.g., `person.age`).

- Array elements are accessed using indices (e.g., `scores[2]`).

- **Size**:

- Structure size depends on the size of its members.

- Array size is fixed during declaration.

In summary, use structures when you need to group different types of data together, and use
arrays when dealing with a collection of similar data

2. Can you give me an example of using structures in C++?

Suppose we want to store information about employees, including their name, age,
and salary. We can define a structure called `Employee` to hold this information:

#include <iostream>
using namespace std;

// Define the Employee structure

struct Employee {

char name[50];

int age;

double salary;

};

int main() {

// Declare an Employee structure variable

Employee emp1;

// Assign values to the structure members

strcpy(emp1.name, "John Doe");

emp1.age = 30;

emp1.salary = 50000.0;

// Display the information

cout << "Employee Name: " << emp1.name << endl;

cout << "Age: " << emp1.age << " years" << endl;

cout << "Salary: $" << emp1.salary << endl;


return 0;

In this example:

- We define a structure called `Employee` with three members: `name`, `age`, and
`salary`.

- We declare an `Employee` structure variable named `emp1`.

- We assign values to the structure members using dot notation (e.g., `emp1.name`,
`emp1.age`).

- Finally, we display the employee's information.

//END OF LEC V

….CAT 1
LEC VI

FILE I/O

File I/O allows you to read data from files and write data to files. It's essential for tasks
like reading configuration files, logging, and data persistence. Here are the key points:

1. **File Handling Basics**:

- A **file** is a sequence of bytes stored on disk.

- C++ provides file handling functions through the `<fstream>` library.

- There are two types of files: **text files** (human-readable) and **binary files**
(machine-readable).

2. **File Modes**:

- When opening a file, you specify a **file mode**:

- `"r"`: Read mode (opens an existing file for reading).

- `"w"`: Write mode (creates a new file for writing; overwrites if the file exists).

- `"a"`: Append mode (opens an existing file for writing; appends data at the end).

- `"rb"`, `"wb"`, `"ab"`: Binary modes (for binary files).

3. **File Streams**:

- C++ provides three file stream classes:

- `ifstream`: For reading from files.

- `ofstream`: For writing to files.

- `fstream`: For both reading and writing.


4. **Example: Reading from a Text File**:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

ifstream inputFile("mydata.txt"); // Open file for reading

string line;

while (getline(inputFile, line)) {

cout << line << endl; // Process each line

inputFile.close(); // Close the file

return 0;

5. **Example: Writing to a Text File**:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

ofstream outputFile("output.txt"); // Open file for writing

outputFile << "Hello, World!" << endl;

outputFile.close(); // Close the file

return 0;
}

NB:

File I/O is essential for interacting with external data and maintaining data persistence.

HOMEWORK:

i. Can you give me an example of reading from a binary file in C++?

Suppose we have a binary file containing records of students, where each record
consists of an integer (student ID) and a string (student name). We'll read this data from
the binary file and display it.

#include <iostream>

#include <fstream>

using namespace std;

// Define a structure to represent student records

struct Student {

int rollNumber;

char name[50];

};

int main() {

// Open the binary file for reading

ifstream inputFile("students.dat", ios::binary);

if (!inputFile) {

cout << "Error opening file!" << endl;

return 1;

}
// Read student records from the file

Student student;

while (inputFile.read(reinterpret_cast<char*>(&student), sizeof(Student))) {

cout << "Roll Number: " << student.rollNumber << ", Name: " << student.name
<< endl;

// Close the file

inputFile.close();

return 0;

In this example:

- We define a `Student` structure to hold the student records.

- We open the file `"students.dat"` in binary mode using `ifstream`.

- We read each student record using `inputFile.read()`.

- The `reinterpret_cast` is used to treat the structure as raw bytes for reading.

- Finally, we close the file.

Make sure you have a binary file named `"students.dat"` with valid student records
before running this program. Adjust the structure and file name according to your
specific use case

ii. What is the difference between text files and binary files in C++?

1. **Text Files**:
- **Human-Readable**: Text files contain data in a format that is easily readable by
humans.

- **Character Encoding**: Data in text files is encoded using character sets (e.g.,
ASCII, UTF-8).

- **Content**: Text files store plain text, including letters, numbers, symbols, and
line breaks.

- **Examples**: Configuration files, source code files, log files, CSV files.

- **File Extensions**: Common extensions include `.txt`, `.cpp`, `.csv`.

2. **Binary Files**:

- **Machine-Readable**: Binary files contain data in a format optimized for machine


processing.

- **Raw Bytes**: Data in binary files is stored as raw bytes without any specific
character encoding.

- **Content**: Binary files can hold any type of data (e.g., images, executables,
serialized objects).

- **Examples**: Image files (JPEG, PNG), compiled executables, database files.

- **File Extensions**: Extensions vary based on the specific binary format (e.g.,
`.jpg`, `.exe`, `.dat`).

3. **Characteristics**:

- **Size**: Binary files tend to be more compact because they don't include human-
readable characters.

- **Portability**: Text files are more portable across different platforms and
applications.

- **Editing**: Text files can be edited using a simple text editor, while binary files
require specialized tools.

- **End-of-Line Markers**: Text files use newline characters (`\n` or `\r\n`) to


indicate line breaks, whereas binary files don't have a fixed line structure.
4. **Reading and Writing**:

- To read from or write to text files, you can use functions like `ifstream` and
`ofstream`.

- For binary files, use the same file stream classes (`ifstream` and `ofstream`) with the
`ios::binary` flag.

In summary, choose text files for human-readable data and binary files for machine-
optimized data storage

iii. How can you use file I/O to improve my code's efficiency?

Leveraging **file I/O (Input/Output)** in your code can significantly improve


efficiency and enhance functionality. Here's how:

1. **Data Persistence**:

- File I/O allows you to save data to files, making it persistent even after your program
terminates.

- Use it for storing user settings, game states, logs, and other essential data.

2. **Backup and Recovery**:

- Regularly save critical data to files as backups.

- In case of unexpected program crashes or system failures, you can recover data from
these backups.

3. **Configuration Files**:

- Store configuration settings (such as parameters, thresholds, or preferences) in files.


- Modify these settings without recompiling your program.

4. **Data Exchange**:

- Read data from external files (e.g., CSV, JSON, XML) to populate your program.

- Write data to files for sharing with other programs or users.

5. **Large Data Sets**:

- When dealing with large data sets (e.g., database records), reading from/writing to
files is more efficient than keeping everything in memory.

- Streaming data from files reduces memory usage.

6. **Logging and Debugging**:

- Write logs to files for debugging and troubleshooting.

- Log important events, errors, and program states.

7. **Efficient Memory Usage**:

- Read data from files in chunks (streaming) rather than loading everything into
memory at once.

- This prevents memory overflow and improves performance.

Remember to handle exceptions (e.g., file not found, permission issues) gracefully when
using file I/O. Proper error handling ensures robustness and reliability in your code.
Character Sets

Character sets, also known as character encodings, are systems used to represent textual data in
computers and communication systems.

Definition:** A character set is a defined collection of characters, symbols, and glyphs, each
assigned a unique numeric code called a code point. These code points are typically represented
in binary form for processing by computers.

Types of character sets:

1. **ASCII (American Standard Code for Information Interchange):** ASCII is one of the
earliest character sets, encoding 128 characters using 7 bits. It includes uppercase and lowercase
letters, digits, punctuation marks, control characters, and special symbols.

2. **Extended ASCII:** Extended ASCII character sets use 8 bits to encode additional
characters beyond the original ASCII range. Various extended ASCII sets exist, including ISO-
8859 and Windows-1252, which include accented characters and symbols for different
languages.

3. **Unicode:** Unicode is a universal character encoding standard that aims to represent every
character from every language in the world, as well as symbols and special characters, using a
unique code point. It supports over 143,000 characters and is continually updated. Unicode can
be encoded using different transformation formats, such as UTF-8, UTF-16, and UTF-32, which
vary in the number of bytes used to represent each character.

4. **UTF-8 (Unicode Transformation Format - 8-bit):** UTF-8 is a variable-width encoding


that represents Unicode characters using 8-bit code units. It is backward compatible with ASCII
and widely used on the internet, as it efficiently represents ASCII characters while supporting
the full Unicode character set.

5. **UTF-16 (Unicode Transformation Format - 16-bit):** UTF-16 is a variable-width


encoding that represents Unicode characters using 16-bit code units. It can represent the entire
Unicode character set but may use more memory than UTF-8 for certain characters.

6. **UTF-32 (Unicode Transformation Format - 32-bit):** UTF-32 is a fixed-width encoding


that represents Unicode characters using 32-bit code units. It provides a straightforward
mapping between code points and code units but may be less space-efficient than UTF-8 and
UTF-16.

7. **Character Encoding Detection:** In some cases, it may be necessary to detect the character
encoding of a text file or data stream, especially when dealing with data from diverse sources.
Techniques such as byte order marks (BOM), heuristics, or explicit metadata can be used to
determine the character encoding.

Overall, character sets play a crucial role in enabling communication and data interchange
across different computer systems, programming languages, and human languages.
Understanding character sets and their encoding schemes is essential for ensuring proper
handling and display of textual data in software applications and communication protocols.
Reading and Writing to Files

Reading and writing to files is a fundamental operation in programming that allows data to be
stored persistently on disk and retrieved when needed. Here are some notes and examples on
reading and writing to files:

Reading from Files:

Example:

Reading from Files:

#include <iostream>

#include <fstream>

#include <string>

int main() {

// Open file in read mode

std::ifstream file("example.txt");

// Read data from the file

std::string data;

std::string line;

while (std::getline(file, line)) {

data += line + "\n";

// Close the file (automatically done when file goes out of scope)

file.close();

// Print the data

std::cout << data << std::endl;

return 0;

}
### Writing CSV Files:

#include <iostream>

#include <fstream>

#include <sstream>

#include <vector>

int main() {

// Writing CSV file

std::ofstream csvFile("data.csv");

csvFile << "Name,Age\n";

csvFile << "John,30\n";

csvFile << "Alice,25\n";

csvFile.close();

// Reading CSV file

std::ifstream file("data.csv");

std::string line;

while (std::getline(file, line)) {

std::vector<std::string> row;

std::stringstream ss(line);

std::string cell;

while (std::getline(ss, cell, ',')) {

row.push_back(cell);

// Process row here...

}
file.close();

return 0;

HOMEWORK:

a. Research in C++, using the `ifstream` and `ofstream` classes from the `<fstream>` header are
used to handle file input and output operations, respectively. Reading from files involves using a
loop to read lines from the file until reaching the end, while writing to files simply involves using
the output stream (`<<`) operator.

### Writing to Files:

#include <iostream>

#include <fstream>

int main() {

// Open file in write mode

std::ofstream file("example.txt");

// Write data to the file

file << "Hello, world!\n";

file << "This is a sample text.";

// Close the file (automatically done when file goes out of scope)

file.close();

return 0;

}
LEC VII

SOFTWARE ENGINEERING PRINCIPLES

These principles guide the development of robust, maintainable, and efficient software systems.

Overview:
1. **Better Requirement Analysis**:
- Understanding project requirements thoroughly is crucial. Clear vision and well-defined
requirements lead to successful software projects.

2. **Keep It Simple, Stupid (KISS) Principle**:


- Designs and implementations should be as simple as possible.
- Example: Avoid unnecessary complexity in code or architecture.

3. **Maintain the Vision**:


- Throughout the development process, maintain focus on the project's goals and vision.
- Consistently align development efforts with the original vision.

4. **Concepts and Principles Over Details**:


- While details matter, the underlying concepts and principles are critical.
- Understand the fundamental ideas behind software engineering practices.

5. **Relevance for CE/EE**:


- Software is pervasive in all aspects of our lives.
- Even for computer engineering (CE) and electrical engineering (EE) students, software concepts
are relevant.
- As CE/EE professionals, you'll build software systems, and understanding software engineering
principles is essential.

Process flows

Process flow in software engineering is crucial for building high-quality software.

Types of Software Process Flows:

1. **Waterfall Model**:
- A linear and sequential approach.
- Phases: Requirements gathering, design, implementation, testing, deployment, maintenance.
- Each phase depends on the completion of the previous one.
- **Advantages**: Clear milestones, well-defined scope.
- **Disadvantages**: Less flexibility for changes, long development cycles.
2. Agile Methodologies:

o Iterative and incremental approaches.


o Examples:
 Scrum: Sprints with regular reviews and adaptability.
 Kanban: Visualize work on a board, continuous delivery.
 Extreme Programming (XP): Emphasizes collaboration, testing, and simplicity.
o Advantages: Flexibility, adaptability to changing requirements.
o Disadvantages: Requires active team involvement.

3. Spiral Model:
o Combines iterative development with risk assessment.
o Iteratively builds prototypes, evaluates risks, and refines the product.
o Advantages: Risk management, accommodates changes.
o Disadvantages: Complex, resource-intensive.
4. Rapid Application Development (RAD):
o Focuses on rapid prototyping and user feedback.
o Iterative cycles to quickly develop and refine software.
o Advantages: Speed, user involvement.
o Disadvantages: May sacrifice long-term stability.

5. Incremental Development:
o Divides software into smaller modules.
o Each module is developed and integrated incrementally.
o Advantages: Early functionality, easier testing.
o Disadvantages: Integration challenges.

6. Prototyping Model:

o Creates a working model to gather user feedback.


o Refines the prototype iteratively.
o Advantages: User involvement, early visualization.
o Disadvantages: May not address all requirements.

Steps involved in Process Flow

1. **Requirements Gathering and Analysis**:


- Understand client needs and gather detailed requirements.
- Analyze requirements to identify scope, constraints, and feasibility.
2. **System Design**:
- Create high-level and detailed designs.
- Define architecture, data models, and interfaces.
- Consider scalability, security, and performance.

3. **Implementation (Coding)**:
- Write code based on the design.
- Follow coding standards and best practices.
- Conduct unit testing.

4. **Testing and Quality Assurance**:


- Verify software functionality against requirements.
- Perform unit, integration, and system testing.
- Identify and fix defects.

5. **Deployment and Release**:


- Deploy the software to production environments.
- Prepare release notes and documentation.
- Monitor performance and address issues.

6. **Maintenance and Support**:


- Provide ongoing support to users.
- Address bug fixes, enhancements, and updates.

Advantages of Following a Software Process:

- **Predictability**: Processes provide a structured approach, making outcomes more


predictable.
- **Quality Assurance**: Rigorous testing ensures software quality.
- **Collaboration**: Teams work together efficiently.
- **Traceability**: Clear documentation helps trace decisions and changes.

## Disadvantages:

- **Complexity**: Large processes can be cumbersome.


- **Rigidity**: Strict adherence may hinder flexibility.
- **Overhead**: Processes require time and resources.

HOMEWORK:

a. What is the difference between Scrum and Kanban?


1. **Scrum**:
- **Origin**: Scrum originated in software development.
- **Methodology**: Scrum is an agile process that focuses on delivering business value in short
iterations (sprints).
- **Roles**:
- **Product Owner**: Represents stakeholders and defines product backlog items.
- **Scrum Master**: Facilitates the Scrum process and removes obstacles.
- **Development Team**: Self-organizing team responsible for delivering increments.
- **Cadence**:
- Regular, fixed-length sprints (usually two weeks).
- **Practices**:
- Sprint planning, daily scrum, sprint review, sprint retrospective.
- **Goal**:
- Create learning loops to quickly gather and integrate customer feedback.

2. **Kanban**:
- **Origin**: Kanban has roots in lean manufacturing.
- **Methodology**: Kanban is a visual system for managing software development work.
- **Focus**:
- Visualize work-in-progress.
- Limit work-in-progress to improve efficiency (flow).
- **Practices**:
- Visualize the flow of work.
- Continuously improve the flow.
- Incorporate feedback loops.
- **Delivery Approach**:
- Takes a more continuous, fluid project management approach.
- **Roles**:
- No specific roles like Scrum.
- **Idealogy**:
- Learn through experiences, self-organize, prioritize, and reflect on wins and losses for
continuous improvement.

b. Can you give me an example of a Kanban board?


A Kanban board is a visual tool that helps teams manage work items and track their progress.
Here's a simple representation of a Kanban board:

markdown
# Example Kanban Board

## Columns:
1. **To Do**: Represents tasks that need to be started.
2. **In Progress**: Tasks currently being worked on.
3. **Done**: Completed tasks.
## Kanban Cards (Tasks):
- **Task 1**: Create login page UI mockup
- **Task 2**: Implement user authentication
- **Task 3**: Write unit tests for API endpoints
- **Task 4**: Bug fix: Address memory leak issue
- **Task 5**: Design database schema

### Task 1: Create login page UI mockup


- Assigned to: John
- Due date: 2023-05-20

### Task 2: Implement user authentication


- Assigned to: Sarah
- Due date: 2023-05-22

### Task 3: Write unit tests for API endpoints


- Assigned to: Alex
- Due date: 2023-05-25

### Task 4: Bug fix: Address memory leak issue


- Assigned to: Mark
- Due date: 2023-05-23

### Task 5: Design database schema


- Assigned to: Emily
- Due date: 2023-05-21
Best Practices in Software Development:

The best practices in software development can lead to efficient, maintainable, and high-quality
code
Including:

1. **Keep It Simple (KISS)**:


- Write code that is straightforward and easy to understand.
- Avoid unnecessary complexity or overengineering.
- Simplicity reduces bugs and improves maintainability.

2. **Version Control (Git)**:


- Use version control systems (e.g., Git) to track changes.
- Regularly commit code and create meaningful commit messages.
- Collaborate effectively with team members.

3. **Automate Repetitive Tasks**:


- Automate build processes, testing, and deployment.
- Continuous Integration (CI) tools can help automate workflows.

4. **Write Clean and Readable Code**:


- Follow consistent coding conventions (e.g., PEP 8 for Python).
- Use meaningful variable and function names.
- Add comments to explain complex logic.

5. **Test Thoroughly**:
- Write unit tests, integration tests, and end-to-end tests.
- Test edge cases and handle exceptions.
- Aim for high test coverage.

6. **Code Reviews**:
- Regularly review code with team members.
- Provide constructive feedback.
- Code reviews improve code quality and knowledge sharing.

7. **Refactor When Needed**:


- Refactor code to improve readability, performance, or maintainability.
- Eliminate code smells (e.g., duplicated code, long methods).

8. **Security Practices**:
- Sanitize user inputs to prevent security vulnerabilities (e.g., SQL injection, XSS).
- Keep dependencies updated to avoid known security issues.

9. **Documentation**:
- Document APIs, libraries, and codebase.
- Include README files with setup instructions.
- Good documentation aids collaboration and onboarding.

10. **Learn from Mistakes**:


- Embrace failures as learning opportunities.
- Conduct post-mortems after incidents.
- Continuously improve processes.

HOMEWORK:

a. What is the difference between unit tests and integration tests?


1. **Unit Tests**:
- **Purpose**: Unit tests verify individual components (units) of code in isolation.
- **Scope**: Each unit test focuses on a small piece of functionality (e.g., a function, method,
or class).
- **Dependencies**: Unit tests should not rely on external systems, databases, or network
services.
- **Mocking/Stubs**: External dependencies are typically mocked or stubbed out.
- **Goal**: Ensure internal consistency and correctness within a single module.
- **Developer-Focused**: Unit tests are primarily for developers during development.
- **Granularity**: Fine-grained testing.
- **Example**: Testing a specific function's behavior or a class method.

2. **Integration Tests**:
- **Purpose**: Integration tests verify interactions between different modules or components.
- **Scope**: Test the integration points where units come together.
- **Dependencies**: Integration tests involve real external systems (e.g., databases, APIs).
- **Real Environment**: Run in an environment that resembles production.
- **Goal**: Demonstrate that different pieces of the system work together correctly.
- **Team-Focused**: Integration tests benefit testers, users, and downstream stakeholders.
- **Granularity**: Coarser-grained testing.
- **Example**: Testing end-to-end flows (e.g., user registration, payment processing).
Design Principles in Software Engineering

These principles guide the development of robust, maintainable, and efficient software systems.

1. **Single Responsibility Principle (SRP)**:


- Each class/module should have only one reason to change.
- Avoid mixing multiple responsibilities within a single component.
- Example: A `FileReader` class should focus solely on file I/O operations without handling
other concerns.

2. **Open/Closed Principle (OCP)**:


- Software entities (classes, modules, functions) should be open for extension but closed for
modification.
- Extend functionality without altering existing code.
- Example: A `Shape` base class can be extended by adding new shape classes (e.g., `Circle`,
`Rectangle`) without modifying existing code.

3. **Liskov Substitution Principle (LSP)**:


- Objects of a derived class should be substitutable for objects of the base class without
affecting program correctness.
- Derived classes should adhere to the same behavior expected of the base class.
- Example: If we have a `Bird` base class, any derived bird (e.g., `Sparrow`, `Penguin`) should
satisfy bird-related behavior.

4. **Interface Segregation Principle (ISP)**:


- Break down large interfaces into smaller, more specific ones.
- Clients should not be forced to depend on methods they don't use.
- Example: Instead of a monolithic `Worker` interface, split it into separate interfaces for
specific roles (e.g., `Worker`, `Manager`, `Clerk`).

5. **Dependency Inversion Principle (DIP)**:


- Depend on abstractions (interfaces or abstract classes) rather than concrete implementations.
- High-level modules should not depend on low-level modules; both should depend on
abstractions.
- Example: Use an `ILogger` interface for logging, allowing flexibility in choosing specific
loggers (e.g., `FileLogger`, `ConsoleLogger`).

Remember, applying these principles leads to more maintainable, extensible, and robust software
designs.

HOMEWORK:

a. What is the difference between SRP and ISP?


1. Single Responsibility Principle (SRP)**:
- **Definition**: SRP tells us that a class should have only one responsibility or
reason to change.
- **Focus**: It applies at the class level, addressing the responsibilities within a single
class.
- **Goal**: Ensure that each class is cohesive and maintains a clear purpose.
- **Example**: If a `FileReader` class handles file I/O operations, it should not mix
other unrelated concerns.

2. **Interface Segregation Principle (ISP)**:


- **Definition**: ISP splits large interfaces into smaller and more specific ones,
ensuring that clients only need to know about the methods relevant to them.
- **Focus**: It applies at the interface level, addressing how interfaces are designed
and used by classes.
- **Goal**: Avoid forcing clients to depend on methods they don't need.
- **Example**: An interface with a single conceptual responsibility (e.g., `Printable`)
should not include unrelated methods (e.g., `Swim` or `Drive`).

b. What is the difference between LSP and DIP?


1. **Liskov Substitution Principle (LSP)**:
- **Definition**: The LSP states that objects of a derived class should be substitutable for
objects of the base class without affecting program correctness.
- **Focus**: It governs the relationship between classes in an inheritance hierarchy (i.e.,
classes that are parent and child).
- **Goal**: Ensure that derived classes adhere to the same behavior expected of the base class.
- **Example**: If we have a `Bird` base class, any derived bird (e.g., `Sparrow`, `Penguin`)
should satisfy bird-related behavior.

2. **Dependency Inversion Principle (DIP)**:


- **Definition**: The DIP emphasizes depending on abstractions (interfaces or abstract
classes) rather than concrete implementations.
- **Focus**: It governs relationships among classes outside an inheritance hierarchy (i.e.,
classes that are not parent and child).
- **Goal**: Allow flexibility by decoupling high-level modules from low-level modules.
- **Example**: Instead of directly coupling classes, use interfaces to allow different
implementations (e.g., `ILogger` for logging).
HOMEWORK:

a. What is the difference between C++ and Java?

The key differences between **C++** and **Java**:

1. **Platform Dependency**:

- **Java**: Java is platform-independent. It compiles source code into bytecode,


which runs on the Java Virtual Machine (JVM). This bytecode can execute on any
operating system that has a compatible JVM.

- **C++**: C++ code needs to be compiled separately for different platforms. It


interacts more effectively with hardware due to its low-level nature.

2. **Memory Management**:

- **Java**: Java provides automatic memory management (garbage collection).


Developers don't need to explicitly manage memory allocation and deallocation.

- **C++**: C++ requires manual memory management. Developers must allocate


and release memory explicitly using `new` and `delete` or smart pointers.

3. **Object-Oriented Paradigm**:

- **Java**: Java is purely object-oriented. Everything in Java is an object, and it


follows strict encapsulation.

- **C++**: C++ supports both procedural and object-oriented programming. It


allows direct memory manipulation and doesn't enforce strict encapsulation.

4. **Inheritance and Polymorphism**:

- **Java**: Java supports single inheritance (class can inherit from only one
superclass) and dynamic polymorphism (method overriding).

- **C++**: C++ supports both single and multiple inheritance (class can inherit
from multiple base classes). It also has static polymorphism (function overloading).

5. **Standard Libraries**:

- **Java**: Java has a rich standard library with built-in classes for various tasks
(e.g., collections, I/O, networking).
- **C++**: C++ also has a standard library (STL) but provides more low-level
control. It includes containers, algorithms, and I/O facilities.

6. **Performance**:

- **Java**: Java is generally slower than C++ due to the JVM overhead and
garbage collection.

- **C++**: C++ offers better performance because it compiles directly to machine


code without the JVM layer.

7. **Syntax and Language Features**:

- **Java**: Java has a simpler syntax, automatic memory management, and strong
type checking.

- **C++**: C++ has more complex syntax, pointers, and manual memory
management. It allows low-level operations.

8. **Use Cases**:

- **Java**: Widely used in web development, mobile apps (Android), enterprise


applications, and server-side programming.

- **C++**: Used for system-level programming, game development, embedded


systems, and performance-critical applications.

In summary, choose **Java** for platform independence, ease of development, and


robustness. Opt for **C++** when performance, low-level control, and hardware
interaction are critical. Both languages have their strengths and are widely used in
different domains.

// END OF LEC VII

// END OF LECS

// BEST OF LUCK WITH YOUR EXAMS

You might also like