CHP 8 Programming MS
CHP 8 Programming MS
8 Programming
1 Three from:
x integer: a positive or negative whole number that can be used with mathematical operators
x real: a positive or negative number with a fractional part that can be used with
mathematical operators
x Boolean: a variable or constant that can have only two values TRUE or FALSE
x char: a single alphanumeric character
x string: multiple alphanumeric characters
2 a Python
Number1 = int(input("Please enter the first whole number "))
Number2 = int(input("Please enter the second whole number "))
Number3 = int(input("Please enter the third whole number "))
Visual Basic
Console.Write("Please enter first whole number ")
Number1 = Integer.Parse(Console.ReadLine())
Console.Write("Please enter second whole number ")
Number2 = Integer.Parse(Console.ReadLine())
Console.Write("Please enter third whole number ")
Number3 = Integer.Parse(Console.ReadLine())
Java
System.out.print("Please enter the first whole number ");
Number1 = myObj.nextInt();
System.out.print("Please enter the second whole number ");
Number2 = myObj.nextInt();
System.out.print("Please enter the third whole number ");
Number3 = myObj.nextInt();
b Python
Number1 = 10
Number2 = 20
Number3 = 30
Visual Basic
Number1 = 10
Number2 = 20
Number3 = 30
Java
Number1 = 10;
Number2 = 20;
Number3 = 30;
c Python
print("Integer values assigned and stored", Number1, Number2,
Number3)
Visual Basic
Console.WriteLine("Integer values assigned and stored " &
Number1 & " " & Number2 & " " & Number3)
Java
System.out.println("Integer values assigned and stored " +
Number1 + " " + Number2 + " " + Number3);
d Python
Number1 = int(input("Please enter the first whole number "))
Number2 = int(input("Please enter the second whole number "))
Number3 = int(input("Please enter the third whole number "))
Number1 = 10
Number2 = 20
Number3 = 30
Visual Basic
Module Module1
Sub Main()
Dim Number1, Number2, Number3 As Integer
Console.Write("Please enter first whole number ")
Number1 = Integer.Parse(Console.ReadLine())
Console.Write("Please enter second whole number ")
Number2 = Integer.Parse(Console.ReadLine())
Console.Write("Please enter third whole number ")
Number3 = Integer.Parse(Console.ReadLine())
Number1 = 10
Number2 = 20
Number3 = 30
Console.ReadKey()
End Sub
End Module
Java
import java.util.Scanner;
class Q2 Java
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
Number1 = 10;
Number2 = 20;
Number3 = 30;
Java
do {
System.out.print("Please enter the weight of your parcel ");
weight = myObj.nextDouble();
}
while (weight < 0.5 || weight > 5.0);
b Python
print(" Options")
print(" 1 Guaranteed next day delivery before noon")
print(" 2 Guaranteed next day delivery")
print(" 3 24-hour delivery")
print(" 4 48-hour delivery")
print(" 5 3-5 days delivery")
option = int(input("Please enter your chosen option "))
if option == 1:
# option 1 code
elif option == 2:
# option 2 code
elif option == 3:
# option 3 code
elif option == 4:
# option 4 code
elif option == 5:
# option 5 code
else:
print("Incorrect option chosen")
Visual Basic
Console.WriteLine(" Options")
Console.WriteLine(" 1 Guaranteed next day delivery before
noon")
Console.WriteLine(" 2 Guaranteed next day delivery")
Console.WriteLine(" 3 24-hour delivery")
Console.WriteLine(" 4 48-hour delivery")
Console.WriteLine(" 5 3-5 days delivery")
case 5:
//option 5 code;
break;
default:
System.out.println("Incorrect option chosen");
}
c Python
weight = 0
while weight < 0.5 or weight > 5.0:
weight = float(input("Please enter the weight of your
parcel "))
print(" Options")
print(" 1 Guaranteed next day delivery before noon")
print(" 2 Guaranteed next day delivery")
print(" 3 24-hour delivery")
print(" 4 48-hour delivery")
print(" 5 3-5 days delivery")
option = int(input("Please enter your chosen option "))
if option == 1:
cost = weight * 10 + 1
elif option == 2:
cost = weight * 10
elif option == 3:
cost = 5
elif option == 4:
cost = 4
elif option == 5:
cost = 3
else:
print ("Incorrect option chosen")
cost = 0
Visual Basic
Module Module1
Sub Main()
Dim weight, cost As Decimal
Dim opt As Integer
weight = 0
While (weight < 0.5) Or (weight > 5.0)
Console.Write("Please enter the weight of your
parcel ")
weight = Decimal.Parse(Console.ReadLine())
End While
Console.WriteLine(" Options")
Console.WriteLine(" 1 Guaranteed next day delivery
before noon")
Console.WriteLine(" 2 Guaranteed next day delivery")
Console.WriteLine(" 3 24-hour delivery")
Console.WriteLine(" 4 48-hour delivery")
Console.WriteLine(" 5 3-5 days delivery")
Console.ReadKey()
End Sub
End Module
Java
import java.util.Scanner;
class Q3Java
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
double weight, cost;
int option;
do {
System.out.print("Please enter the weight of your
parcel ");
weight = myObj.nextDouble();
}
while (weight < 0.5 || weight > 5.0);
System.out.println(" Options");
System.out.println(" 1 Guaranteed next day delivery
before noon");
System.out.println(" 2 Guaranteed next day delivery");
System.out.println(" 3 24-hour delivery");
System.out.println(" 4 48-hour delivery");
System.out.println(" 5 3-5 days delivery");
case 2:
cost = weight * 10;
break;
case 3:
cost = 5;
break;
case 4:
cost = 4;
break;
case 5:
cost = 3;
break;
default:
System.out.println("Incorrect option chosen");
cost = 0;
}
System.out.println("Your cost is " + cost);
}
}
d Test data Expected output Actual output
0.4 Error message
Error message
í1 Error message
2SWLRQ Your cost is 6
2SWLRQ <RXUFRVWLV
2SWLRQ <RXUFRVWLV
2SWLRQ <RXUFRVWLV
2SWLRQ <RXUFRVWLV
2SWLRQ Your cost is 4
2SWLRQ Your cost is 3
1 Option 7 Incorrect option chosen
Visual Basic
Dim Weight, TotalWeight As Decimal
TotalWeight = 0
REPEAT
REPEAT
OUTPUT "Please enter a positive number "
INPUT C
UNTIL C > 0
A m A + C
B m B + 1
UNTIL B = 10
D m A / B
OUTPUT A, D
6 a Python
# Python program to total 10 numbers and find the average
Total = 0
Counter = 0 # Total and Counter initialised to zero
print(" The total is ", Total, " the average is ", Average)
# outputting the results
Visual Basic
'Visual Basic program to total 10 numbers and find the average
Module Module1
Sub Main()
Dim Total, Number, Counter As Integer
Dim Average As Decimal ' variables declared
Total = 0
Counter = 0 ' Total and Counter initialised To zero
Do
Console.Write("Please enter a positive number ")
Number = Int(Console.ReadLine())
Console.WriteLine(" The total is " & Total & " the average is " &
Average) ' outputting the results
Console.ReadLine()
End Sub
End Module
Java
// Java program to total 10 numbers and find the average
import java.util.Scanner;
class Q6Java
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
Total = 0;
Counter = 0; //Total and Counter initialised To zero
do {
7 a Python
Student = ["Alice", "Jan", "Lim", "Ian", "Min", "Sue", "Tim",
"Dee"]
for Counter in range(8):
print(Student[Counter])
print()
Counter = 0
while Counter < 8:
print(Student[Counter])
Counter = Counter + 1
print()
Visual Basic
For Counter = 0 To 7
Console.WriteLine(Student(Counter))
Next
Console.WriteLine()
Counter = 0
Do
Console.WriteLine(Student(Counter))
Counter = Counter + 1
Loop Until Counter = 8
Console.WriteLine()
Java
for (Counter = 0; Counter <= 7; Counter++) {
System.out.println(Student[Counter]);
}
System.out.println()
Counter = 0;
while (Counter <= 7){
System.out.println(Student[Counter]);
Counter++;
}
System.out.println()
b Python
NumberOfStudents = len(Student)
Counter = 0
while Counter < NumberOfStudents:
print(Student[Counter])
Counter = Counter + 1
print("Number of students", NumberOfStudents)
Visual Basic
NumberOfStudents = Student.Length
Counter = 0
Do
Console.WriteLine(Student(Counter))
Counter = Counter + 1
Loop Until Counter = NumberOfStudents
b Python
MyString = "Test String"
Length = len(MyString)
FirstChar = MyString[0:1]
UpperCase = MyString.upper()
LowerCase = MyString.lower()
9 a Python
A = ((B + C – D * E) ** F) / G
Visual Basic
A = ((B + C – D * E) ^ F) / G
Java
A = Math.pow((B + C – D * E), F) / G;
b Python
if (A == B) or (C != D):
A = 0
elif (A > B) and (C == D):
B = 0
Visual Basic
If (A = B) Or (C <> D) Then
A = 0
Else
If (A > B) And (C = D) Then
B = 0
End If
End If
Java
if (A == B) or (C != D) {
A = 0;
}
else {
if ((A > B) and (C = D)) {
B = 0;
}
}
c FOR Times = 1 TO 20
FOR Count = 1 TO 10
OUTPUT Count
NEXT Count
NEXT Times
d Python
for Times in range(20):
for Count in range(10):
print(Count + 1)
Visual Basic
Module Module1
Sub Main()
Dim Count, Times As Integer
For Times = 1 To 20
For Count = 1 To 10
Console.Write(Count)
Next
Console.WriteLine()
Next
Console.ReadKey()
End Sub
End Module
Java
import java.util.*;
class Q9Java
{
public static void main(String args[])
{
}
}
10 Tasks that are repeated many times in an algorithm make use of procedures and functions.
Use of these can reduce the size of a program.
Procedures and functions are defined once and called many times. They can be written with
and without parameters. They are the variables that store the values passed to a procedure or
function.
Functions always return a value and the value can be used on the right-hand side of an
assignment statement.
A variable that can be used in any part of a program is called a global variable. A variable that
is declared within a procedure or function is called a local variable.
11 a Library routines are fully tested and ready to be incorporated into a program …
… they perform many types of task that need to be used regularly.
b 1 MOD
2 DIV
3 ROUND
4 RANDOM
c Python
import random
Visual Basic
Module Module1
Sub Main()
Dim Number1, Number2 As Integer
Dim AnswerMod, AnswerDiv As Integer
Randomize()
Number1 = CInt(Rnd() * 10 + 10)
Number2 = CInt(Rnd() * 10 + 10)
Console.WriteLine(Number1 & " is the first random integer
between 10 and 20")
Console.WriteLine(Number2 & " is the second random integer
between 10 and 20")
Console.WriteLine(Number1 & " MOD " & Number2 & " is " &
AnswerMod)
Console.WriteLine(Number1 & " DIV " & Number2 & " is " &
AnswerDiv)
Console.ReadKey()
End Sub
End Module
Java
import java.util.Scanner;
import java.lang.Math;
import java.util.Random;
class Q11Java
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
int Number1, Number2;
Random rand = new Random();
Number1 = rand.nextInt(10) + 10;
Number2 = rand.nextInt(10) + 10;
}
}
12 a array: a data structure containing several elements of the same data type; these elements
can be accessed using the same identifier name
array dimension: dimension determined by how many index numbers are needed to
locate a piece of data, for instance a one-dimensional array only needs one index number,
a two dimensional array needs two index numbers, and so on
array index: identifies the position of an element in an array
b DECLARE OXO : ARRAY[3, 3] OF CHAR
PrintStateOfGame()
Visual Basic
Module Module1
Public OXO = New String(2, 2) {{"O", " ", " "}, {" ", "X", " "},
{" ", "X", "O"}} 'OXO must be declared as a public/global variable
Sub Main()
PrintStateOfGame()
Console.ReadKey()
End Sub
Sub PrintStateOfGame()
Dim RowCounter, ColumnCounter As Integer
For RowCounter = 0 To 2
For ColumnCounter = 0 To 2
Console.Write(OXO(RowCounter, ColumnCounter))
Next
Console.WriteLine()
Next
End Sub
End Module
Java
import java.util.*;
class Q12Java
{
public static String[][] OXO = {{"O", " ", " "}, {" ", "X", " "},
{" ", "X", "O"}};
MyFile m "MyFile.txt"
Text m "Test"
OPEN MyFile FOR WRITE
WRITEFILE, Text
CLOSEFILE(MyFile)
ii OPEN MyFile FOR READ
READFILE, Text
OUTPUT Text
CLOSEFILE(MyFile)
c Python
MyFile = open("MyFile.txt","w")
Text = "Test"
MyFile.write(Text)
Java
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class TextFile {
Text = "Test";
myPrintWriter.printf("%s" + "%n", Text);
myPrintWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileReader myFileReader = new FileReader("MyFile.txt");
BufferedReader myBufferReader = new BufferedReader(myFileReader);
Text = myBufferReader.readLine();
System.out.print("The file contains this line of text ")
System.out.println(Text);
myFileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
14 a–e:
Python
#### Part b ###
def NewPassword():
MyPassword = input("Please enter your new password ")
Valid = True
Length = len(MyPassword)
if Length > 20:
print("Too long")
Valid = False
if Length < 10:
print("Too short")
Valid = False
Counter = 0
NoSpace = True
while (Counter < Length and NoSpace):
if MyPassword[Counter:Counter + 1] == " ":
print("Spaces not allowed")
Valid = False
NoSpace = False
Counter = Counter + 1
Counter = 0
UpperCase = False
while (Counter < Length and not UpperCase):
if "A" <= MyPassword[Counter:Counter + 1] <= "Z":
UpperCase = True
Counter = Counter + 1
if (not UpperCase):
print("No uppercase letter")
Valid = False
Counter = 0
Digit = False
while (Counter < Length and not Digit):
if "0" <= MyPassword[Counter:Counter + 1] <= "9":
Digit = True
Counter = Counter + 1
if (not Digit):
print("No digit")
Valid = False
if Valid:
print("Password accepted")
MyFile = open("MyPassword.txt","w") #### Part c ###
MyFile.write(MyPassword) #### Part c ###
else:
print("Password rejected")
def CheckPassword():
MyPassword = input("Please enter your password ")
MyFile = open("MyPassword.txt","r")
StoredPassword = MyFile.read()
if MyPassword == StoredPassword:
print("Password matches")
else:
print("Password does not match")
def ChangePassword():
MyPassword = input("Please enter your password ")
MyFile = open("MyPassword.txt","r")
StoredPassword = MyFile.read()
if MyPassword == StoredPassword:
NewPassword()
else:
print("Password incorrect cannot change")
Quit = False
while not Quit:
print (" Password Management")
print (" 1. Enter a new password")
print (" 2. Check your password")
print (" 3. Change your password")
print (" 4. Quit")
if option == 1:
NewPassword()
elif option == 2:
CheckPassword()
elif option == 3:
ChangePassword()
elif option == 4:
Quit = True
else:
print ("Incorrect option chosen")
Visual Basic
Imports System.IO
Module Module1
Console.ReadKey()
End While
End Sub
'******
Valid = True
Length = Len(MyString)
If Length > 20 Then
Console.WriteLine("Too long")
Valid = False
End If
If Length < 10 Then
Console.WriteLine("Too short")
Valid = False
End If
Counter = 0
NoSpace = True
While Counter < Length And NoSpace
If MyString.Substring(Counter, 1) = " " Then
Console.WriteLine("Spaces not allowed ")
Valid = False
NoSpace = False
End If
Counter = Counter + 1
End While
Counter = 0
UpperCase = False
While Counter < Length And Not UpperCase
If MyString.Substring(Counter, 1) >= "A" And
MyString.Substring(Counter, 1) <= "Z" Then
UpperCase = True
End If
Counter = Counter + 1
End While
If Not UpperCase Then
Console.WriteLine("No uppercase letter")
Valid = False
End If
Counter = 0
Digit = False
While Counter < Length And Not Digit
If MyString.Substring(Counter, 1) >= "0" And
MyString.Substring(Counter, 1) <= "9" Then
Digit = True
End If
Counter = Counter + 1
End While
If Not Digit Then
Console.WriteLine("No digit")
Valid = False
End If
If Valid Then
Console.WriteLine("Password accepted. Press any
key to continue.")
objMyFileWrite = New
StreamWriter("MyPassword.txt")'*** Part c ***
objMyFileWrite.WriteLine(MyString)'*** Part c ***
objMyFileWrite.Close()'*** Part c ***
Else
End Sub
'******
End Sub
'******
End Sub
'******
End Module
Java
import java.util.*;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class Chapter8Q14 {
// *** Part b ***
static void NewPassword(String MyString) {
int Length;
Length = MyString.length();
boolean Valid = true;
int Counter = 0;
boolean NoSpace = true;
Counter = 0;
boolean UpperCase = false;
while ((Counter < Length) & !UpperCase) {
if (MyString.charAt(Counter) >= 'A' &&
MyString.charAt(Counter) <= 'Z') {
UpperCase = true;
}
Counter ++;
}
if(!UpperCase) {
System.out.println("No uppercase letter");
Valid = false;
}
Counter = 0;
boolean Digit = false;
while ((Counter < Length) & !Digit) {
if (Valid) {
System.out.println("Password accepted");
try {
FileWriter myFileWriter = new
FileWriter("MyPassword.txt", false); //***
Part c ***
PrintWriter myPrintWriter = new
PrintWriter(myFileWriter); //*** Part c ***
myPrintWriter.printf("%s" + "%n", MyString);
//*** Part c ***
myPrintWriter.close(); //*** Part c ***
} catch (IOException e) { //*** Part c ***
e.printStackTrace(); //*** Part c ***
}
}
else {
System.out.println("Password rejected");
}
}
// ******
try {
FileReader myFileReader = new
FileReader("MyPassword.txt");
BufferedReader myBufferReader = new
BufferedReader(myFileReader);
StoredPassword = myBufferReader.readLine();
myFileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
if (MyString.compareTo(StoredPassword) == 0) {
System.out.println("Password matches");
}
else {
System.out.println("Password does not match");
}
}
//******
try {
FileReader myFileReader = new
FileReader("MyPassword.txt");
BufferedReader myBufferReader = new
BufferedReader(myFileReader);
StoredPassword = myBufferReader.readLine();
myFileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
if (MyString.compareTo(StoredPassword) == 0) {
System.out.print("Please enter your new password ");
NewWord = myObj.nextLine();
NewPassword(NewWord);
}
else {
System.out.println("Password incorrect cannot
change");
}
}
//******
switch (option) {
case 1:
System.out.print("Please enter your
password ");
MyPassword = myObj.nextLine();
NewPassword(MyPassword);
break;
case 2:
System.out.print("Please enter your
password ");
MyPassword = myObj.nextLine();
CheckPassword(MyPassword);
break;
case 3:
System.out.print("Please enter your
password ");
MyPassword = myObj.nextLine();
ChangePassword(MyPassword);
break;
case 4:
Quit = true;
break;
default:
System.out.println("Incorrect option
chosen");
}
}
//******
}
}
b Test data Expected output Actual output
Password Too short
No digit
Password rejected
Password99 Password accepted
9 Databases
1 a • table: a collection of records …
x … where each record contains data about a similar item, e.g. a student.
x record: a collection of fields about the same item …
x … there are the same number of fields in each record.
x field: a single piece of data …
x … that is given a data type.
b Four from:
x text/alphanumeric – e.g. a description of a part
x character – e.g. S, M or L for the size of a part
x Boolean – e.g. true or false, sold or not
x integer – e.g. number of parts in stock
x real – e.g. price of an item 12.99
x date/time – e.g. a date such as 18/12/2020
2 a Field 1: Type
Data type: text
Reason: as the name given to the type of ice cream is a series of characters
Sample: choc ice
Field 2: Flavour
Data type: text
Reason: as the name given to the flavour of ice cream is a series of characters
Sample: vanilla
Field 3: Size
Data type: text
Reason: as the size of the ice cream is stored as a word
Sample: Small
Field 4: NumberInStock
Data type: integer
Reason: as the number in stock will be a whole number
Sample: