This post contains a quick and dirty tutorial on how to use SQL to lookup, insert, update, and delete data. The first video in the series is optional, it shows how to import and setup the data.
The files used in the videos can be found below, you can look at the videos in any order, they aren’t prerequisites for each other.
The user clicks on a link to a webpage from a previous webpage.
The browser resolves the ip address from the server name and sets up a tcp connection to the server (usually on port 80 or 8080)
The browser sends a http request to the server containing the requested resource and information about itself, e.g browser type, supported language etc
The server generates a response which contains header information as well as HTML code for the browser to render.
The browser interprets the code and displays the page to the user.
Part c)
The url https://www.buythings.com would be preferred since this http protocol includes SSL (Secure sockets layer) or TLS (Transport layer security) which encrypts all HTTP information such that only the sender and the receiver can decipher the information. This is more secure, especially in the case where the http information can be intercepted by malicious entities on the network, they won’t be able to read the sensitive payment information that can be used defraud the online shopper.
Part d)
A process is a running program.
The PCB stores metadata necessary for managing the process, e.g. process id, process state, memory allocation addresses, scheduling info (priority, time slice), pointers to it’s resources (files, other processes).
Part e)
New
Running
Ready
Waiting
Terminated
Part f)
Paging is were each process in an OS is allocated memory in units called pages for easier coordination and management by the operating system. The pages can be stored physically in memory , or stored on the hard disk (in the case that the process is not running at that time). If a process is stored on the disk and needs to be run, a page fault is generated so that the process is swapped back into the physical memory for processing.
Part g)
Thrashing occurs when memory resources become limited by the amount of running processes. The need for physical memory can be exceeded, thus multiple processes that are in waiting state are stored as pages on disk. For continued running of the system, processes are constantly swapped in and out of physical memory, an execution which spends a lot of time on the cpu when compared to running the processes themselves.
Part h)
Because of the frequent process swapping by page faults, the system becomes inefficient and can run slowly. (The solution is to inefficiency increase the size of physical memory by upgrading the ram size, or configure/manage the system to run less processes.)
The system can become overwhelmed to the point of “crashing”, i.e stop working or responding altogether.
Part i)
Too little physical memory is available for a system that needs to run a lot of processes.
[1] Structured programming is a programming paradigm that emphasizes the use of a structured control flow in algorithms and programs. It is based on the idea that an algorithm or program should be broken down into smaller, self-contained blocks of code, or “constructs,” that can be easily understood and maintained.
There are several constructs commonly used in structured programming, including:
Sequential control: This construct is used to specify that a set of statements should be executed in a specific order, one after the other.
Selection control: This construct is used to specify that a certain set of statements should be executed only if a certain condition is met. Selection control is often implemented using if and else statements.
Iteration control: This construct is used to specify that a certain set of statements should be executed repeatedly, either a fixed number of times or until a certain condition is met. Iteration control is often implemented using for and while loops.
By using these and other structured programming constructs, algorithms and programs can be made more readable, maintainable, and efficient. Structured programming is widely used in many programming languages and is considered to be a fundamental concept in computer science.
Sequential control or sequence statements
Sequential control, also known as sequence statements, is a construct used in programming to specify that a set of statements should be executed in a specific order, one after the other.
Here is an example of sequential control in C:
#include <stdio.h>
int main()
{
// Sequence of statements
printf("Hello, world!\n");
printf("I am learning C programming.\n");
printf("This is a sequential control example.\n");
return 0;
}
In this example, the statements printf(“Hello, world!\n”);, printf(“I am learning C programming.\n”);, and printf(“This is a sequential control example.\n”); are executed in sequence, one after the other. The first statement is executed first, followed by the second statement, and so on.
Sequential control is a basic construct used in many programming languages and is often used to specify a simple sequence of statements that should be executed in order.
Selection Control or Selection Statements
Selection control, also known as selection statements, is a construct used in programming to specify that a certain set of statements should be executed only if a certain condition is met.
There are two main types of selection statements in C: if statements and switch statements.
Here is an example of an if statement in C:
#include <stdio.h>
int main()
{
int a = 5;
int b = 10;
// If statement
if (a < b)
{
printf("a is less than b\n");
}
else
{
printf("a is not less than b\n");
}
return 0;
}
In this example, the if statement checks the condition a < b. If the condition is true, the statement printf(“a is less than b\n”); is executed. If the condition is false, the statement printf(“a is not less than b\n”); is executed instead.
Selection control is a useful construct for making decisions and branching the flow of an algorithm or program based on certain conditions. It is widely used in many programming languages.
The various types of if statements
There are several types of if statements that can be used in programming:
Simple if statement: This is the most basic form of the if statement and is used to execute a single statement or block of statements if a certain condition is true. It has the following syntax:
if (condition)
{
// statements to be executed
}
2. if–else statement: This form of the if statement is used to execute a different set of statements if the condition is false. It has the following syntax:
if (condition)
{
// statements to be executed if condition is true
}
else
{
// statements to be executed if condition is false
}
3. cascading if or if–else if–else statement:
Cascading if statements, also known as “chained if statements” are a series of if statements that are connected using the else if construct.
This form of the if statement is used to test multiple conditions and execute different sets of statements based on the results. It has the following syntax:
if (condition 1)
{
// statements to be executed if condition 1 is true
}
else if (condition 2)
{
// statements to be executed if condition 2 is true
}
...
else if (condition n)
{
// statements to be executed if condition n is true
}
else
{
// statements to be executed if all conditions are false
}
When are the various types of if statements used?
Here is a table showing when you might want to use a simple if statement, an if–else statement, or an if–else if–else statement:
Statement
When to use
Simple if
– When you want to execute a single statement or block of statements if a certain condition is true
– When you only need to check one condition
– When you don’t need to execute any statements if the condition is false
if-else
– When you want to execute a different set of statements if the condition is false
– When you only need to check one condition and have two possible outcomes
if-else if-else
– When you want to check multiple conditions and execute different sets of statements based on the results
– When you have multiple possible outcomes and need to check multiple conditions
– When you want to specify a default action to be taken if all conditions are false
Nested if statements (if statements inside of other if statements)
Nested if statements are if statements that are placed inside the block of another if statement. They are used to test multiple conditions within the same block of code.
Here is an example of nested if statements in C:
#include <stdio.h>
int main()
{
int a = 5;
int b = 10;
// Nested if statements
if (a < b)
{
if (a % 2 == 0)
{
printf("a is even and less than b\n");
}
else
{
printf("a is odd and less than b\n");
}
}
else
{
printf("a is not less than b\n");
}
return 0;
}
In this example, the inner if statement tests the condition a % 2 == 0 and the outer if statement tests the condition a < b. The inner if statement is executed only if the outer if statement’s condition is true.
Nested if statements can be useful for testing multiple conditions within the same block of code and allowing for more complex decision-making in algorithms and programs. However, they can also make code more difficult to read and understand, so it’s important to use them judiciously.
The Switch Statement
A switch statement is a control flow construct used in programming to specify multiple branching statements based on the value of an expression. It is often used as an alternative to a series of if–else statements, particularly when there are multiple possible outcomes and a large number of conditions to check.
Here is an example of a switch statement in C:
int main()
{
int a = 5;
// Switch statement
switch (a)
{
case 1:
printf("a is 1\n");
break;
case 2:
printf("a is 2\n");
break;
case 3:
printf("a is 3\n");
break;
default:
printf("a is not 1, 2, or 3\n");
}
return 0;
}
In this example, the switch statement checks the value of the variable a. If the value of a is 1, the statement printf(“a is 1\n”); is executed. If the value of a is 2, the statement printf(“a is 2\n”); is executed. If the value of a is 3, the statement printf(“a is 3\n”); is executed. If the value of a is none of these, the statement printf(“a is not 1, 2, or 3\n”); is executed.
Switch statements can be more efficient than a series of if–else statements when there are many possible outcomes, as they use a faster lookup method to determine which branch to take. However, they are generally less flexible than if–else statements and can only be used with a limited set of data types.
Comparison of selection Constructs
Here is a table comparing the if statement and the switch statement:
Can only be used with certain data types (integer, character, and enumerated types)
Multiple conditions
Can test multiple conditions using if–else if–else
Can test multiple conditions using case and break
Range of values
Can test for any range of values
Can only test for specific values or ranges
Efficiency
May be less efficient than a switch statement when there are many possible outcomes
May be more efficient than an if statement when there are many possible outcomes
Flexibility
More flexible than a switch statement
Less flexible than an if statement
In general, you might use an if statement when you need to test multiple conditions or check for a range of values, or when you are working with data types that are not supported by switch statements. You might use a switch statement when you have a large number of possible outcomes and want to take advantage of its faster lookup method, or when you are working with integer, character, or enumerated data types.
Iteration Constructs
Iteration constructs, also known as looping constructs, are programming constructs that allow a set of statements to be repeated multiple times. There are several types of iteration constructs in most programming languages, including for loops, while loops, and do–while loops.
Iteration constructs are useful for repeating a set of statements multiple times and are widely used in many programming languages. They can be used to iterate through data structures such as arrays and lists, or to perform tasks repeatedly until a certain condition is met.
There are several types of iteration constructs that are commonly used in programming:
for loops: for loops are used to execute a set of statements a specific number of times. They have the following syntax:
for (initialization; condition; increment)
{
//statements to be executed
}
The initialization statement is executed before the loop starts. The condition is tested at the beginning of each iteration. If the condition is true, the statements in the loop are executed. If the condition is false, the loop is terminated. The increment statement is executed at the end of each iteration.
Here is an example of a for loop in C:
#include <stdio.h>
int main()
{
int i;
// For loop
for (i = 0; i < 10; i++)
{
printf("%d\n", i);
}
return 0;
}
In this example, the for loop iterates 10 times, starting at 0 and ending at 9. On each iteration, the value of i is printed to the screen.
while loops: while loops are used to execute a set of statements while a certain condition is true. They have the following syntax:
while (condition)
{
// statements to be executed
}
The condition is tested at the beginning of each iteration. If the condition is true, the statements in the loop are executed. If the condition is false, the loop is terminated.
Example:
#include <stdio.h>
int main()
{
int i = 0;
// While loop
while (i < 10)
{
printf("%d\n", i);
i++;
}
return 0;
}
This while loop iterates 10 times, starting at 0 and ending at 9. On each iteration, the value of i is printed to the screen, and then i is incremented by 1.
do–while loops: do–while loops are similar to while loops, but the condition is tested at the end of each iteration instead of at the beginning. They have the following syntax:
do
{
// statements to be executed
}while (condition);
The statements in the loop are executed first, and then the condition is tested. If the condition is true, the loop is repeated. If the condition is false, the loop is terminated.
Here is a simple example of a do–while loop in C:
int main()
{
int i = 0;
// Do-while loop
do
{
printf("%d\n", i);
i++;
}
while (i < 10);
return 0;
}
Each of these iteration constructs has its own use cases and can be useful in different situations. for loops are useful when you know how many times you want to iterate in advance, while loops are useful when you want to iterate as long as a certain condition is true, and do–while loops are useful when you want to execute the statements in the loop at least once before testing
Bounded and Unbounded iteration
Bounded iteration is a type of iteration that has a fixed number of iterations. An example of bounded iteration is finding the sum of the numbers in an array.
Here is an example of bounded iteration in C to find the sum of the numbers in an array:
#include <stdio.h>
int main()
{
int numbers[5] = {1, 2, 3, 4, 5};
int sum = 0;
int i;
// Bounded iteration
for (i = 0; i < 5; i++)
{
sum += numbers[i];
}
printf("Sum: %d\n", sum);
return 0;
}
In this example, the for loop iterates 5 times, starting at 0 and ending at 4. On each iteration, the value of numbers[i] is added to the sum variable. At the end of the loop, the value of sum is printed to the screen.
Unbounded iteration is a type of iteration that has an unknown number of iterations. An example of unbounded iteration is a guessing game where the player keeps guessing a number until they guess the correct answer.
Here is an example of unbounded iteration in C to implement a guessing game:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int secret = rand() % 100; // Generate a random number between 0 and 99
int guess;
// Unbounded iteration
while (1)
{
printf("Guess a number: ");
scanf("%d", &guess);
if (guess == secret)
{
printf("You guessed the secret number!\n");
break;
}
else if (guess < secret)
{
printf("Your guess is too low.\n");
}
else
{
printf("Your guess is too high.\n");
}
}
return 0;
}
In this example, the while loop iterates indefinitely until the player guesses the correct number. On each iteration, the player is prompted to enter a guess, and the value of the guess is checked against the secret number. If the guess is correct, the loop is terminated and a message is printed to the screen. If the guess
Comparison of Iteration constructs
Here is a table comparing the different iteration constructs:
for loop
while loop
do-while loop
Syntax
for (initialization; condition; increment) { statements; }
while (condition) { statements; }
do { statements; } while (condition);
Testing condition
At the beginning of each iteration
At the beginning of each iteration
At the end of each iteration
Termination
When the condition is false
When the condition is false
When the condition is false
Number of iterations
Fixed number of iterations
Unknown number of iterations
Unknown number of iterations
Use cases
When you know how many times you want to iterate in advance
When you want to iterate as long as a certain condition is true
When you want to execute the statements in the loop at least once before testing the condition
Each of these iteration constructs has its own use cases and can be useful in different situations. for loops are useful when you know how many times you want to iterate in advance, while loops are useful when you want to iterate as long as a certain condition is true, and do–while loops are useful when you want to execute the statements in the loop at least once before testing the condition.
Sentinel value
A sentinel value is a special value that is used to indicate the end of a sequence of data. It is often used in combination with iteration constructs, such as while loops or do–while loops, to allow the loop to terminate when the sentinel value is encountered.
Here is an example of using a sentinel value in a while loop in C to read a sequence of numbers from the user and sum them up:
#include <stdio.h>
int main()
{
int sum = 0;
int number;
printf("Enter numbers to sum, or -1 to stop: ");
scanf("%d", &number);
// While loop with sentinel value
while (number != -1)
{
sum += number;
scanf("%d", &number);
}
printf("Sum: %d\n", sum);
return 0;
}
In this example, the while loop iterates as long as the value of number is not -1. On each iteration, the value of number is added to the sum variable and then the user is prompted to enter another number. When the user enters -1, the loop is terminated and the value of sum is printed to the screen.
Sentinel values can be useful in situations where the number of data items is unknown or variable, as they allow the loop to terminate when the end of the data is reached. However, it is important to choose a sentinel value that cannot occur as a valid data item in order to avoid any confusion.
A program which contains an array of prime numbers requires functions to facilitate the persistence of data using functions to save an load data.
In this tutorial, we have some functions which can be used to achieve this.
The goal of this tutorial is to understand how we can achieve this by performing the actions in the inline comments of the main() function.
Run the code below, and perform the tasks whilst keeping track of your answers in your notebook:
#include <stdio.h>
#include <stdlib.h>
void setupDummyData();
void saveToFile();
void readFile();
void printPrimesToScreen();
int primes[100];
int result[100];
int count = 0;
int main()
{
//When answering tutorial questions, be as precise and descriptive as possible
//TUTORIAL BLOCK 1:
//a. What does the code accomplish if the following multiline comment is removed?
/* printPrimesToScreen();
setupDummyData();
printPrimesToScreen();*/
//TUTORIAL BLOCK 2:
//a. Redo the multiline comment above.
//b. What does the code accomplish if the following multiline comment is removed?
/*
printPrimesToScreen();
setupDummyData();
saveToFile();
printPrimesToScreen(); */
//TUTORIAL BLOCK 3:
//a. Redo the multiline comment above.
//b. What does the code accomplish if the following multiline comment is removed?
//c. Where did the data in the array come from on the second printPrimesToScreen()?
/*
printPrimesToScreen();
readFile();
printPrimesToScreen();//2nd printPrimesToScreen()
*/
//TUTORIAL BLOCK 4:
//a. Redo the multiline comment above.
//b. DELETE the file "primes.txt"
//c. What does the code accomplish if the following multiline comment is removed?
//d. What data exists in the file "primes.txt"
/*
printPrimesToScreen();
readFile();
saveToFile();
readFile();
printPrimesToScreen();
*/
//DELETE primes.txt if you need to retry this tutorial.
printf("Program quitting...\n");
return 0;
}
//HARDCODE Data into array
void setupDummyData()
{
count = 8;
primes[0]= 2;
primes[1]= 3;
primes[2]= 5;
primes[3]= 7;
primes[4]= 11;
primes[5]= 13;
primes[6]= 17;
primes[7]= 19;
primes[8]= 23;
primes[9]= 29;
}
//empty all contents into a file in overwritemode
void saveToFile()
{
FILE* filePtr = fopen("primes.txt","w");
if (filePtr==NULL)
printf("Error creating savefile.....Check that file is not in use\n\n");
else
{
//write the number of records in the array on the first line
fprintf(filePtr, "%d\n",count);
//write each prime number on a separate line in the file
for (int i = 0 ; i<count;i++)
fprintf(filePtr, "%d\n",primes[i]);
}
fclose(filePtr);//close file for use by other processes
printf("Datafile Saved!\n\n");
}
//read all data into array
void readFile()
{
FILE* filePtr = fopen("primes.txt","r");
if (filePtr==NULL)
printf("Error reading file, does it exist?\n\n");
else
{
//read the number of records in the file from the first line
fscanf(filePtr, "%d",&count);
//write each prime number on a separate line in the file
for (int i = 0 ; i<count;i++)
fscanf(filePtr, "%d",&primes[i]);
}
fclose(filePtr);//close file for use by other processes
}
void printPrimesToScreen()
{
printf("\n\n****Now Displaying all Primes in the array\n");
if (count==0)
printf("\nPrime Array Is empty...\n\n");
else
{
for (int i = 0 ; i<count;i++)
printf("index: %d , prime: %d \n",i,primes[i]);
printf("\n");
}
}
Thus far it is possible that we’ve made the assumption that a process usually runs to completion and then the OS runs other processes. As indicated in our process management note/discussion we now know this to be false.
It is possible for an OS to be implemented as a timing mechanism, switching between each process after say 100 instructions being executed. In theory, this is a good first approach if all instructions are executed in a very short and equal timeframe.
Below, we represent how this can be accomplished by observing what the cpu processes assuming each instruction takes about 1 second for 2 processes, P1 and P2:
Order of execution
Process/operation category
Instructions executed
Time taken (s)
1
I/O
I/O for OS and P1
2
2
P1
100 lines from P1
100
3
I/O
I/O for OS and P2
2
4
P2
100 lines from P2
100
.....
.....
.....
.....
501
I/O
I/O for OS and P1
2
502
P1
100 lines from P1
100
503
I/O
I/O for OS and P2
2
504
P2
100 lines from P2
100
.....
.....
.....
.....
In practice though, a single instruction from a running process can be waiting or very long, such as when the instruction requires data be read from a secondary storage medium. Data access on secondary storage is very slow. Let us assume that P1 has a few instructions that require some data access. Our table now becomes:
Order of execution
Process/operation category
Instructions executed
Time taken (s)
1
I/O
I/O for OS and P1
2
2
P1
100 lines from P1
1500
3
I/O
I/O for OS and P2
2
4
P2
100 lines from P2
100
.....
.....
.....
.....
501
I/O
I/O for OS and P1
2
502
P1
100 lines from P1
1200
503
I/O
I/O for OS and P2
2
504
P2
100 lines from P2
100
.....
.....
.....
.....
We observe in this analogy that p1 runs for a total of 1502 seconds P2 for 102, P1 for 1202 seconds, P2 for 102 seconds.
To the end user, It appears as if BOTH processes are running slowly, in the long run, p2 can appear to be running in slow motion!
To solve this problem, we could use a system of interrupts, i.e, interrupt the CPU whenever we anticipate a waiting period (for whatever reason I/O, system errors, device errors etc.)
In our analogy, every time P1 needs to wait on data from secondary access, we could put the rest of P1 in a waiting/blocked state and start processing P2. When the hardware is finished gathering the data for P1, it could interrupt the execution of P2 and return control to P1.
Omitting IO from the OS, An illustration of this example is shown below:
(Assume that instructions for p1 are executed in 1 second intervals until an instruction needing secondary data access is reached)
P1’s instruction include:
49 short instructions then,
1 long access instruction then,
24 short instructions then,
1 long access instruction, then
25 short instructions
Order of execution
Process/operation category
Instructions executed
Time taken (s)
1
P1
50 lines from P1
50
2
OS
(P1 Blocked),
–
3
P2
100 lines from P2
100
4
P2
100 lines from P2
100
5
P2
100 lines from P2
100
6
P2
50 lines from P2, interruption occurs
50
7
P1
25 lines from P1
25
8
OS
(P1 Blocked),
–
9
P2
50 lines from P2
50
10
P2
100 lines from P2
100
11
P2
100 lines from P2
100
12
OS
Interruption occurs to return accessed data to P1
–
13
P1
25 lines from P1
25
14
P2
100 lines from P2
100
.....
.....
.....
.....
We now observe both processes running efficiently with no excessive wait times.
Exercise
What is the total wait time for P1 and P2 Respectively?
Multiple programs are usually executed concurrently as processes (running programs). A bit of code from each process is executed at a time on the processor so that all processes are continually executed until system shutdown or they have completed their task and exit.
The operating system (OS) is programmed to start the execution of programs and manage their execution by putting them into different states. Note that the programs can be application programs intended for the end user or system programs used for self management (e.g memory management)
Discussion:
Virtual memory / page files used to simulate ram capacities larger than physical ram on the main system. (Falls under memory management).
Blackboard as Ram chiselled tablet as Secondary storage – How processes react when they must wait
Process States.
Running – The process is currently being executed
Ready – A previously interrupted process that can be expected to resume.
Waiting/blocked – a process that has been put to wait by the cpu or is waiting on a slower operation (I/O or request for data)