Introduction to computer programing
Introduction to computer programing
METHODOLOGIES
LEC I
Definitions:
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:
- Problem Definition: Clearly define the problem that the program needs to
solve. Understand the requirements and constraints.
- 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: Start with the main program and break it down into smaller,
more manageable tasks.
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:
//END OL LEC I
LEC II
PROGRAMMING PARADIGMS
1. Imperative Programming:
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;
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;
}
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;
}
2. Declarative 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.
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);
return 0;
}
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>
struct student {
char name[50];
int roll_no;
float marks;
};
void add_student() {
if (num_students >= MAX_STUDENTS) {
printf("Error: Maximum number of students reached.\n");
return;
}
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;
}
i. Event-Driven Programming:
- Examples: AspectJ.
v. Scripting Languages:
vi. Meta-Programming:
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.
//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.
The following table highlights all the significant differences between syntax and 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
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.
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.
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.
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
Similar but often longer in length, an example of the floating-point double might be:
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:
Boolean
Boolean data can help guide the logic in a code. Here are some examples of how you might use
this:
bool baseballIsBest = false;
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:
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:
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 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.
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:
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
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 .
int main() {
int 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().
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.
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-While Structure: It also uses a condition to control the loop. This structure
has the form: Repeat while condition: [Module] [End of Loop]
int main() {
int 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.
int main() {
int 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().
Utilizes if…statement
#include <stdio.h>
int main() {
int 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.
int main() {
int 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().
int main() {
int 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().
#include <stdio.h>
int main() {
int 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.
int main() {
int 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().
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
Example:
#include <stdio.h>
int main() {
int a = 5, b = 10, c = 15;
if (a > 0 || b > 0) {
printf("Either a or b is 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
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 .
#include <stdio.h>
#define PI 3.14159
int main() {
const int ARRAY_LENGTH = 10;
int aiNumbers[ARRAY_LENGTH];
enum State eState = START_STATE;
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:
- 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.
- Example: A simple program that reads input, processes data, and produces output.
#include <iostream>
int main() {
string name;
int age;
return 0;
1. We declare a `string` variable `name` to store the user's name and an `int` variable `age`
to store their age.
- **Single Alternative**:
- **Double Alternative**:
- **Multiple Alternatives**:
#include <iostream>
int main() {
int i = 20;
if (i == 10)
else if (i == 15)
else if (i == 20)
else
return 0;
In this example:
- Since `i` is equal to 20, the third condition (`i == 20`) evaluates to true.
- The message "i is 20" is printed.
#include <iostream>
int main() {
int i = 25;
else
return 0;
In this second example, the program checks the value of `i` and prints the corresponding
message based on the specified
- **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`.
- **Repeat-While Structure**:
#include <iostream>
int main() {
std::cout << "Iteration " << count << ": Hello, World!" << std::endl;
return 0;
In this example:
- The loop will execute 5 times, printing "Hello, World!" for each iteration.
HOMEWORK:
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.
```cpp
int p = 0;
while (y > 0) {
if (y % 2 == 0) {
y /= 2;
x *= 2;
} else {
p += x;
y--;
return p;
```
```cpp
int i = times(3, i + 2) + 1;
```
2. **Procedures**:
```cpp
void factors(int x) {
int f = 2;
while (x != 1) {
if (x % f == 0) {
x /= f;
} else {
f++;
```
```cpp
factors(i);
```
3. **Parameter Passing**:
- Call-by-value makes a copy of the argument, while call-by-reference passes the memory
location.
- Example:
```cpp
// Code for p
```
4. **Benefits of Subprograms**:
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.
```cpp
#include <iostream>
// Function declaration
void greet() {
}
int main() {
greet();
return 0;
```
- Output:
```
Hello there!
```
```cpp
#include <iostream>
int main() {
int num1 = 5;
double num2 = 5.5;
displayNum(num1, num2);
return 0;
```
- Output:
```
```
- A function that computes the sum of two integers and returns the result:
```cpp
#include <iostream>
return a + b;
int main() {
return 0;
```
- Output:
```
Sum: 30
```
4. **Function Templates**:
```cpp
#include <iostream>
T max(T a, T b) {
return (a > b) ? a : b;
}
int main() {
return 0;
```
- Output:
```
Max int: 20
HOMEWORK:
1. **Function**:
- Key characteristics:
int square(int x) {
return x * x;
```
2. **Procedure**:
- Key characteristics:
```cpp
void showMessage() {
```
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.
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:
Output:
Before: 5
After: 4
Output:
Before swapping: x = 10, y = 20
After swapping: x = 20, y = 10
- 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.
- 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.
- Other developers (or even your future self) can understand the purpose of a
subprogram by reading its name and parameters.
5. **Separation of Concerns**:
- For instance, you can have one subprogram for input validation, another for data
processing, and yet another for output formatting.
// 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.
- **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:
- 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:
- Example:
struct Address {
char street[100];
char city[50];
char state[20];
};
struct Employee {
int empId;
char empName[50];
double salary;
};
```
```cpp
Employee emp;
HOMEWORK:
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).
- 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).
- Example:
```cpp
3. **Differences**:
- **Purpose**:
- **Data Types**:
- **Access**:
- **Size**:
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
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;
struct Employee {
char name[50];
int age;
double salary;
};
int main() {
Employee emp1;
emp1.age = 30;
emp1.salary = 50000.0;
cout << "Age: " << emp1.age << " years" << endl;
In this example:
- We define a structure called `Employee` with three members: `name`, `age`, and
`salary`.
- We assign values to the structure members using dot notation (e.g., `emp1.name`,
`emp1.age`).
//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:
- There are two types of files: **text files** (human-readable) and **binary files**
(machine-readable).
2. **File Modes**:
- `"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).
3. **File Streams**:
#include <iostream>
#include <fstream>
int main() {
string line;
return 0;
#include <iostream>
#include <fstream>
int main() {
return 0;
}
NB:
File I/O is essential for interacting with external data and maintaining data persistence.
HOMEWORK:
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>
struct Student {
int rollNumber;
char name[50];
};
int main() {
if (!inputFile) {
return 1;
}
// Read student records from the file
Student student;
cout << "Roll Number: " << student.rollNumber << ", Name: " << student.name
<< endl;
inputFile.close();
return 0;
In this example:
- The `reinterpret_cast` is used to treat the structure as raw bytes for reading.
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.
2. **Binary Files**:
- **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).
- **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.
- 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?
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.
- In case of unexpected program crashes or system failures, you can recover data from
these backups.
3. **Configuration Files**:
4. **Data Exchange**:
- Read data from external files (e.g., CSV, JSON, XML) to populate your program.
- When dealing with large data sets (e.g., database records), reading from/writing to
files is more efficient than keeping everything in memory.
- Read data from files in chunks (streaming) rather than loading everything into
memory at once.
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.
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.
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:
Example:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt");
std::string data;
std::string line;
// Close the file (automatically done when file goes out of scope)
file.close();
return 0;
}
### Writing CSV Files:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
int main() {
std::ofstream csvFile("data.csv");
csvFile.close();
std::ifstream file("data.csv");
std::string line;
std::vector<std::string> row;
std::stringstream ss(line);
std::string cell;
row.push_back(cell);
}
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.
#include <iostream>
#include <fstream>
int main() {
std::ofstream file("example.txt");
// Close the file (automatically done when file goes out of scope)
file.close();
return 0;
}
LEC VII
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.
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:
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:
3. **Implementation (Coding)**:
- Write code based on the design.
- Follow coding standards and best practices.
- Conduct unit testing.
## Disadvantages:
HOMEWORK:
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.
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
The best practices in software development can lead to efficient, maintainable, and high-quality
code
Including:
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.
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.
HOMEWORK:
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.
Remember, applying these principles leads to more maintainable, extensible, and robust software
designs.
HOMEWORK:
1. **Platform Dependency**:
2. **Memory Management**:
3. **Object-Oriented Paradigm**:
- **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.
- **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**:
// END OF LECS