SlideShare a Scribd company logo
SOKOINE UNIVERSITY OF AGRICULTURE
COLLEGE OF AGRICULTURE
DEPARTMENT OF ENGINEERING SCIENCE AND TECHNOLOGY
AE 219
BASICS OF COMPUTER PROGRAMMING
GROUP 09-ASSIGNMENT, IWRE 2
NO. NAME OF A STUDENT REGISTRATION NUMBER SIGNATURE
1. DOTO, MUSA GESE IWR/D/2016/0011
2. KOYI, PERIS J IWR/D/2016/0021
3. KWEKA, DANIEL IWR/D/2016/0023
4. DAUDI, DERICK IWR/D/2016/0009
5. KILINDO, ABUBAKARI IWR/D/2016/0065
INSTRUCTOR: DR. BAANDA A. SALIM
SUBMISSION DATE: FRIDAY ,29TH
JUNE 2018
PART 1
TP- Lecture 4.1
Self- Check 1
Which of the following are Pascal reserved words, standard identifiers, valid identifiers, invalid
identifiers?
end ReadLn Bill
program Sues‟s Rate
Start begin const
Y=Z Prog#2 &Up
First Name „MaxScores‟ A*B
CostaMesa,CA Barnes&Noble CONST
XYZ123 ThisIsALongOne 123XYZANSWER
ANSWERS
Paschal reserved words:
begin, end, program, Start, CONST, const
Standard identifiers:
ReadLn, „MaxScores‟, Bill, Rate
Valid identifiers:
XYZ123, ThisIsALongOne, A*B, Y=Z, CostaMesa, CA, First Name
Invalid identifiers:
123XYZ, Sues‟s, &UpFirstName, Barnes&Noble, Prog#2
Self- Check 2
Which of the following literal values are legal and what are their types? Which are illegal and
why?
15 „XYZ‟ „*‟
$25.123 15; -999
.123 „x‟ “X”
„9‟ „-5‟ True
ANSWER:
The following values are legal and their type
Legal Type Illegal
15 Integer literal $25.123
„
XYZ‟ String Literal .123
„X‟ Character Literal „9‟
True Boolean Literal 15;
-999 Integer Literal -„5‟
Operator literal „*‟
TP- Lecture 4.2
Self- Checked 1
Which of the following are valid program headings? Which are invalid and why?
(i) Program program; - INVALID using reserved ID
(ii) program 2ndCourseInCS; -INVALID because starts with digit
(iii) program PascalIsFun;- VALID program heading
(iv) program Rainy Day; -INVALID – contains space
Self- Checked 2
Rewrite the following code so that it has no syntax errors and follows the writing conventions we
adopted
(i) Program SMALL;
VAR X, Y, Z : real;
BEGIN
Y := 15.0;
Z := -Y + 3.5;
X :=Y + z;
writeln (x, Y, z);
END.
ANSWER:
Program SMALL;
VAR
X, Y, Z :real;
BEGIN
Y := 15.0;
Z := -Y + 3.5;
x := Y + z;
writeln (x, Y, z);
END.
(ii) PROGRM 2time5 {input,output};
CONST two := 2; five := 5;
VAR multip; dummy ; integer;
BEGIN ;
multip = two * five ; dummy := multip ;
write (two) , write (five)
END ;
ANSWER:
PROGRAM p2time5(INPUT,OUTPUT);
CONST
two = 2;
five = 5;
VAR
multip, dummy :integer;
BEGIN
multip := two * five ;
dummy := multip ;
write (dummy)
END .
Self- Check 3
Write the following numbers in normal decimal notation:
(i) 103E-4 = 0.0103
(ii) 1.2345E+6 = 1234500000.0
(iii) 123.45E+3 = 123450.0
Self-Check 4
Write the following numbers in Pascal scientific notation
(i) 1300= 1.3E+3
(ii) 123.45= 1.2345E+2
(iii) 0.00426= 4.26E-3
TP- Lecture 5.1
Self- Checked 1
What are the results of the following expressions?
22 div 7 = 3
7 div 22 = 0
22 mod 7 =1
7 mod 22 = 7
Self- Checked 2
What is valid & what is invalid in the following
const PI = 3.14159;
MaxI = 1000;
var
X, Y : Real;
A, B, I : Integer;
. . .
I := A mod B; I := A mod Y;
X := A / B; I := A / B; X := A / Y;
I := B div 0; I := A mod 0; X := PI div Y;
X := A mod (A / B);
I := (MaxI - 990) div A;
I := A mod (MaxI - 990);
SEE TURBO PASCAL COMPILATION ERRORS
ANSWER:
PROGRAM Types;
CONST PI = 3.14159;
MaxI = 1000;
VAR
X, Y : Real;
A, B, I : Integer;
BEGIN
I := A mod B;{ I := A mod Y; }
X := A / B; { I := A / B; }
X := A / Y; { I := B div 0; }
I := A mod 0; { X := PI div Y; }{ X := A mod (A / B); }
I := (MaxI - 990) div A;
I := A mod (MaxI - 990);
END.
TP- Lecture 5.2
Self- Checked 1:
What is the output if the entered data are 5 7?
writeln („Enter two integers>‟);
readln(M, N);
M := M + 5;
N := 3 + N;
writeln („M = „, M);
writeln („N = „, N);
ANSWER:
The output of the program is
Enter two intergers>5 7
M= 10
N= 10
Self- Checked 2:
What is the output of this code?
write („My name is‟);
writeln („Doe, Jane‟);
writeln ;
write(„I live in „);
write(„Ann Arbor, MI‟);
writeln („and my zip code is „, 48109);
ANSWER:
The output of this code will be,
My name is Doe, Jane
I live in Ann Arbor, MIA
and my zip code is 48109
Self- Checked 3:
Show how the value -15.564 (stored in X) would be displayed using the following formats
(i) X :8:4= -15.5640
(ii) X:8:3 = -15.564
(iii) X:8:1 = -15.6
(iv) X:8:0 = -16.0
(v) X:8 = -15
Self- Checked 4:
Assuming X = 12.345 (type Real) and I = 100 (type Integer). What will the output of the
following statements look like?
writeln(„X is „ :10, X :6:2, „I is „ :4, I :5);
write(„I is „ :10, I : 1);
writeln(„X is „ :10, X :2:1);
ANSWER:
The output will be as follows
X is 12.35 I is 100
I is 100 X is 12.4
TP- Lecture 8
Self- Checked 1:
(i) Write the Boolean expression to check if a character variable Ch is a digit.
ANSWER:
(ORD(InputChar) > 47) AND (ORD(InputChar) < 58)
(ii) Write a Boolean expression to check if a character variable Chis an upper-case letter.
ANSWER:
(ORD(InputChar) > 64 ) AND (ORD(InputChar) < 91)
iii. Write a Boolean expression to check if a character variable Ch is a lower-case letter.
ANSWER:
(ORD(InputChar) > 96 ) AND (ORD(InputChar) < 123)
iv. Using a Boolean test, convert upper-case character Ch to a lower-case character.
ANSWER:
IF Upper-case THEN
Name[I] := CHR(ORD(Name[I])+32);
Self- Check 2:
Write Boolean assignment statements:
1. Assign true to variable Between if the value of N is in the range -K to +K, inclusive;
otherwise, assign a value of false
ANSWER:
Boolean assignment statement is,
IF (N <= -k) AND (N <=+k)
WRITELN(„This is True‟)
ELSE
WRITELN(„This is False‟)
(a) Assign a value of true to variable Uppercase if Ch is an uppercase letter;
otherwise, assign false
ANSWER:
Boolean statement is,
IF M DivN THEN
WRITELN („This is True‟)
ELSE
WRITELN(„This is False)
(b) Assign a value of true to variable Divisor if M is a divisor of N; otherwise,
assign false
ANSWER:
Boolean statement is,
IF (ORD(InputChar) > 64 ) AND (ORD(InputChar) <
91) THEN
WRITELN(„This is True‟)
ELSE
WRITELN(„This is False‟)
Self- Check 3:
What do these statements display?
(i) IF 12 < 12 THEN
writeln(„Less‟)
ELSE
writeln(„Not less‟)
ANSWER:
It will display,
Not less
(ii) Var1 := 25.12;
Var2 := 15.00;
IF Var1
(iii) <= Var2 THEN
writeln(„Less or equal‟)
ELSE
writeln(„Greater than‟)
ANSWER:
It will display, Greater than
Self- Check 4:
What value is assigned to X when Y is 15.0?
a. X := 25.0;
IF Y <> (X - 10.0) THEN
X := X - 10.0
ELSE
X := X / 2.0
ANSWER: The value assigned to X is 12.5
b. IF (Y < 15.0) AND (Y >= 0.0) THEN
X := 5 * Y
ELSE
X := 2 * Y
c. ANSWER
The value assigned to X is 30.0
Self- checked 5:
Write Pascal statements to perform the following:
If Item is nonzero, then multiply Product by Item and save the result
in Product; otherwise, skip the multiplication. In either case, print the
value of Product.
Store the absolute difference of X and Y in Y, where the absolute
difference is (X - Y) or
(Y - X), whichever is positive.
Don’t use the abs() function in your solution
ANSWER:
IF item <> 0 THEN
Multip = product*item
WRITELN;
WRITELN(„Product‟)
Self-Check 6:
Evaluate the following expressions, with and without short-circuit evaluation
-Assumptions:
i. X = 6
ii. Y = 7
-(X > 5) and (Y div X <= 10)
-(X <= 10) or (X / (Y - 7) > 3)
ANSWER:
With short circuit
X = 6
Y = 7
IF (X >5) AND (YdivX<=10)
IF(X<= 10) OR (X/(Y-7)>3)
Without shot circuit-evaluation
X = 6
Y = 7
IF (X > 5) THEN
(Y divX<= 10)
IF (X <= 10) THEN
(X/(Y-7) > 3)
TP-Lecture 9
Self- Checked 5.1:
Trace the following program fragment:
J := 10;
FOR I := 1 to 5 DO
BEGIN
writeln(I, J);
J := J - 2
END; { FOR }
• How many times will the loop body be executed?
ANSWER:
The loop body will be executed 5 times.
Self- Checked 5.2
(a) Write FOR loop headers that process all values of Celsius (type integer) in the following
ranges:
-10 through +10
100 through 1
15 through 50
50 through -75
(b) What types can be used as FOR loop counters?
(c) Write a FOR statement that computes the sum of the ODD integers in the range 0 to
100 inclusive
ANSWER:
FOR Celcius := -10 TO 10 DO
FOR Celcius := 100 DOWN TO 1 DO
FOR Celcius := 15 TO 50 DO
FOR Celcius := 50 DOWN TO -75DO
Self- Check 5.3:
For the following loop:
X := 3;
Count := 0;
while Count < 3 do
begin
X := X * X;
writeln(X);
Count := Count + 1
end; { while }
writeln(Count);
• How many times is the loop body repeated?
• What is printed during each repetition of the loop body, and at the very end?
• What happens if the last statement in the loop body is: Count := Count + 2;
• What happens if the last statement in the loop body is removed?
ANSWER:
The time that the loop body repeated are 3 time
The result which can be printed during each repeation of the
loop is 0
When the last statement in the loop is count:= count+2 =215
can be printed
When the last statement in the loop body is removed Nothing
will be printed
Self-Checked 5.10:
(i) Write a while loop that displays each integer from 1 to 5 on a separate line, along with its
square.
(ii) Write a while loop that displays each integer from 4 down to -6 on a separate line. Display
the values in the sequence 4, 2, 0, and so on.
ANSWER
NOT(X <= Y) OR (X <> 15)
NOT(X <= Y) AND (Z = 7.5)
NOT(X <> 15) AND (Z = 7.5)
NOT Flag AND (X <> 15.7)32
Flag OR NOT (x <= 8)
TP- Lecture 11.1
Self- Checked 1:
What is displayed by the following program fragment, assuming N is 5?
FOR I := 1 TO N DO
BEGIN
FOR J := 1 TO I DO
write(„*‟);
writeln
END;
ANSWER:
- The display that the program can produce are
*
* *
* * *
* * * *
* * * * *
Self- Checked 2 :
What is displayed by the following program fragment, assuming
M is 3 and N is 5?
FOR I := N DOWNTO 1 DO
BEGIN
FOR J := M DOWNTO 1 DO
write(„*‟);
writeLn
END;
ANSWER:
The display that the program can execute are
* * *
* * *
* * *
* * *
Self-checked 3:
Show the output printed by the following nested loops:
FOR I := 1 TO 2 DO
BEGIN
writeln(„Outer‟ : 5, I : 5);
FOR J := 1 TO 3 DO
writeln(„Inner‟ : 7, I : 3, J : 3)
FOR K := 2 DOWNTO 1 DO
writeln(„Inner‟ :7, I : 3, K : 3)
END;
ANSWER:
 The output that can be printed in the nested loop are
OUTPUT 1
Inner 1 1
Inner 1 2
Inner 1 3
Inner 1 2
Inner 1 1
OUTPUT 2
Inner 2 1
Inner 2 2
Inner 2 3
Inner 2 2
Inner 2 1
Self- Check 4:
Write a program fragment that, given an input value N, displays N rows in the form 1 2 ... N, 2 3
... N + 1, and so forth
PROGRAM Check;
VAR I,J,N : integer;
BEGIN
write('What is N? ');
read(N);
FOR I := 1 TO N DO
BEGIN
FOR J := I TO I + N - 1 DO
write(J:2);
writeln
END;
readln
END.
ANSWER:
PROGRAM Fragment(INPUT,OUTPUT);
VAR
J, I, N :INTEGER;
BEGIN
WRITE(„Enter the value of N‟);
READLN(N);
FOR
I := 1 TO N DO
BEGIN
FOR J := I TO I +N-1 DO
WRITE(J : 2)
WRITELN;
READLN
END.
Self- Check 5:
Write a program that prints a nicely labeled multiplication table for the digits 1 through 9.
ANSWER:
PROGRAM MultiplicationTable;
VAR I,J : integer;
BEGIN
FOR I := 1 TO 9 DO
BEGIN
FOR J := 1 TO 9 DO
write(I*J:3);
writeln
END;
readln
END.
The outputs of the program are
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
TP- Lecture 12.2
Self- Check 1:
What is wrong with this program?
assign(„MyData.txt‟, InFile);
rewrite(Infile); /* ?? */
reset(Infile);
WHILE NOT eoln DO /* ?? */
BEGIN
read(InFile, Next);
write(Next)
END; {while}
ANSWER:
The wrong of this statement can be corrected as
PROGRAM Self(OUTPUT);
VAR
InFile : TEXT;
BEGIN
Assign(InFile, „MyData.Txt‟);
Rewrite(InFile);
WHILE NOT eoln (inFile) DO
BEGIN
WRITE( Next);
READLN(Infile,Next);
END; {WHILE};
READLN;
Reset(InFile)
END.
PART II.
QUESTION 1
In the following program, two integers, a and b, are declared in the declaration part, then
assigned integer values in the program block. The WRITELN statement is then used to evaluate
and display the results of different arithmetic operations performed on those variables.
PROGRAM Arithmetic(OUTPUT);
{ Variable Declarations }
VAR
a, b :INTEGER;
{ Program Block }
BEGIN
a := 50;
b := 4;
WRITELN('a=',a);
WRITELN('b=',b);
WRITELN('a+b=',a+b);
WRITELN('a-b=',a-b);
WRITELN('a*b=',a*b);
WRITELN('a/b=',a/b);
WRITELN('a div b=',a DIV b); { used with integers only }
WRITELN('a mod b=',a MOD b) { used with integers only }
END.
ANSWER
To write output of the program:
a=50
b=4
a+b=54
a-b=46
a*b=200
a/b= 1.2500000000000000E+0001
a div b=12
a mod b=2
QUESTION 2
Write a program to calculate employee wages according to the formula: Wages :=HoursWorked
* PayRate; inputHoursWorked and PayRate from the keyboard and display Wages preceded by
the string ‘USD’.
ANSWER
PROGRAM Payroll(INPUT,OUTPUT);
VAR
HoursWorked, PayRate, Wages :REAL;
{ Program Block }
BEGIN
WRITE('Please enter hours worked: ');
READLN(HoursWorked);
WRITE('Please enter pay rate: ');
READLN(PayRate);
Wages :=HoursWorked * PayRate;
WRITELN;
WRITELN('Wages = $', Wages:0:2)
END.
QUESTION 3
Write the Pascal expressions for the following:
i. The quadratic equation: Ax2
+ Bx + C
ii. The determinant: B2 – 4AC
iii. The square root of the determinant
iv. The absolute value of the determinant
Then, write a program to produce the roots of the equation according to the input values
of A, B, and C. Use test values for A, B, and C that give real roots. Typical values
are:
A=1, B=2, C=1, give the solution: X1= X2= –1.00
A=1, B=4, C=2, give the solution: X1= –0.59, X2= –3.41
ANSWERS
i. A*SQR(X)+B*X+C
ii. SQR(B)-4*A*C
iii. SQRT((SQR(B)-4*A*C))
iv ABS(SQR(B)-4*A*C)
PROGRAM Quadratic(INPUT,OUTPUT);
VAR
D, X1, X2 :REAL;
A, B, C: INTEGER;
BEGIN
WRITE('Enter the values of A,B and C for the quadratic
equation:');
READLN(A,B,C);
{ Determinant}
D:=SQR(B)-4.0*A*C;
{ Roots }
X1:=(-B+SQRT(D))/(2*A);
X2:=(-B-SQRT(D))/(2*A);
WRITELN('X1=',X1:2:2,' X2=',X2:2:2);
WRITELN('Press ENTER to continue...');
READLN
END.
Sample runs:
A=1, B=2, C=1
X1=X2=-1.00
A=1, B=4, C=2
X1= -0.59
X2= -3.41
QUESTION 4
Modify the program you wrote in Qn3 to solve a quadratic equation (Ax² + Bx +C) for both real
and imaginary roots.
ANSWER
Modified Complete Solution of a Quadratic Equation will be:
PROGRAM Quadratic2(INPUT,OUTPUT);
VAR
A, B, C, D, X1, X2 :REAL;
BEGIN
WRITE('Enter the values of A,B,C separated by spaces:');
READLN(A,B,C);
{ Determinant}
D:=SQR(B)-4.0*A*C;
IF D < 0 THEN
BEGIN
WRITELN('Roots are imaginary.');
WRITELN('X1=',-B/(2*A):0:2,'+j',SQRT(ABS(D))/(2*A):0:2);
WRITELN('X2=',-B/(2*A):0:2,'-j',SQRT(ABS(D))/(2*A):0:2)
END
ELSE
BEGIN
WRITELN('Roots are real.');
WRITELN('X1=',(-B+SQRT(D))/(2*A):0:2);
WRITELN('X2=',(-B-SQRT(D))/(2*A):0:2)
END;
WRITELN('Press ENTER to continue ...');
READLN
END.
{ Sample runs:
Real roots:
A=2, B=4, C=1
X1=0.29
X2=1.70
Equal real roots:
A=1, B=2, C=1
X1=-1
X2=-1
Imaginary roots:
A=1, B=1,C=1
X1=-0.5+j0.87
X2=-0.5-j0.87
QUESTION 5
Write a program to describe the weather according to the following temperature classifications:
Temperature Classification
24 and greater Hot
10 to 23 Cool
0 to 9 Cold
less than 0 Freezing
ANSWER
PROGRAM WeatherTester(INPUT,OUTPUT);
VAR
Temperature :INTEGER;
Hot, Cool, Cold, Freezing :BOOLEAN;
BEGIN
WRITE('Please enter the temperature:');
READLN(Temperature);
Hot := (Temperature >= 24);
Cool := (Temperature >= 10) AND (Temperature < 24);
Cold := (Temperature >= 0) AND (Temperature < 10);
Freezing := (Temperature < 0);
WRITELN;
{ Beginning of the IF construct }
IF Hot THEN
WRITELN('IT‟S VERY HOT!!!')
ELSE IF Cool THEN
WRITELN('IT‟S COOL OUT THERE!!!!!.')
ELSE IF Cold THEN
WRITELN('Oh, it is cold. ')
ELSE IF Freezing THEN
WRITELN(' It is freezing.')
ELSE
WRITELN('Hey, It is below the normal temperature!');
{ End of the IF construct }
{ ----------------------- }
WRITELN('Press ENTER to continue..');
READLN
END.
QUESTION 6
The number 2 and its powers are very important numbers in the computer field. Some of the
numbers, such as 1024 bytes (equivalent to 1 KB) and 65,536 bytes (64 KB) are commonly used.
In the following program a FOR loop is used to display the powers of two, using the same logic
that was used to calculate the power in Example 2-2. The program output gives the power and the
number 2 raised to this power. The initial and final values of the counter are supplied by the user
during the execution. Thus, you can determine the range of numbers you would like to examine.
PROGRAM ForLoop(INPUT, OUTPUT);
VAR
Base, Power, Start, Final :INTEGER;
BEGIN
Base := 2;
WRITE('Enter starting exponent:');
READLN(Start);
WRITE('Enter ending exponent:');
READLN(Final);
WRITELN;
WRITELN('Number Power of two');
FOR Power := Start TO Final DO
BEGIN
WRITE(Power:3);
WRITELN(EXP(LN(Base)*Power):20:0)
END;
WRITELN;
WRITELN('Press ENTER to continue..');
READLN
END.
Modify the program to save the output of the program in file (instead of seeing the output in the
screen). Plot the data of the output file (using Matlab or Excel). Label your plot. Use exponent
value from 1 to 30.
ANSWER
The following is a sample run using exponent values from 1 to 30:
Enter starting exponent:1
Enter ending exponent:30
Number Power of two
1 2
2 4
3 8
4 16
5 32
6 64
7 128
8 256
9 512
10 1024
11 2048
12 4096
13 8192
14 16384
15 32768
16 65536
17 131072
18 262144
19 524288
20 1048576
21 2097152
22 4194304
23 8388608
24 16777216
25 33554432
26 67108864
27 13417728
28 268435456
29 536870912
30 1073741824
Press ENTER to continue..
By using MatLab
QUESTION 7
Write down the output of the following program for a sample run of 10 elements
PROGRAM AverageProg3(INPUT,OUTPUT);
VAR
Average, Sum, Number :REAL;
Kounter :INTEGER;
BEGIN
Sum := 0;
Average := 0;
Number := 0;
Kounter := 0;
WHILE Number<>-1 DO
BEGIN
Kounter :=Kounter + 1;
Sum := Sum + Number;
WRITE('Enter element #',Kounter,' (or –1 to end): ');
READLN(Number)
END;
IF Kounter> 1 THEN
Average := Sum / (Kounter - 1);
WRITELN;
WRITELN('Sum of Numbers = ', Sum:0:2);
WRITELN('Average of Numbers = ', Average:0:2);
WRITELN;
WRITELN('Press ENTER to continue..');
READLN
END.
ANSWER
The following is a sample run of 10 elements:
Enter element #1 (or -1 to end): 1
Enter element #2 (or -1 to end): 2
Enter element #3 (or -1 to end): 3
Enter element #4 (or -1 to end): 4
Enter element #5 (or -1 to end): 5
Enter element #6 (or -1 to end): 6
Enter element #7 (or -1 to end): 7
Enter element #8 (or -1 to end): 8
Enter element #9 (or -1 to end): 9
Enter element #10 (or -1 to end): -1
Sum of the numbers =45.00
Average of Numbers = 5.00
Press ENTER to continue…
QUESTION 8
Write the output of the program below for the following sample run:
Enter score for class #1: 90.5
Enter score for class #2: 80.5
Enter score for class #3: 86.2
Enter score for class #4: 90.3
Enter score for class #5: 74.8
Enter score for class #6: 98.5
PROGRAM Scores2(INPUT,OUTPUT);
CONST
NumberOfClasses = 6;
Tab = ' '; { 9 spaces }
VAR
Score :ARRAY[1..NumberOfClasses] OF REAL;
Average, SumOfScores :REAL;
Index :INTEGER;
BEGIN
{ Read the scores array }
{ --------------------- }
FOR Index := 1 TO NumberOfClasses DO
BEGIN
WRITE('Enter score for class #', Index,': ');
READLN(Score[Index])
END;
{ Calculate the sum }
{ ----------------- }
SumOfScores := 0;
FOR Index := 1 TO NumberOfClasses DO
SumOfScores :=SumOfScores + Score[Index];
{ Calculate the average }
{ --------------------- }
Average :=SumOfScores / NumberOfClasses;
{ Display Results }
{ --------------- }
WRITELN;
WRITELN(Tab,'CLASS #');
WRITE(' '); { 6 spaces }
FOR Index := 1 TO NumberOfClasses DO
WRITE(Index:7);
WRITELN;
WRITE(Tab);
FOR Index := 1 TO NumberOfClasses DO
WRITE('-------');
WRITELN;
WRITE('SCORES ');
FOR Index := 1 TO NumberOfClasses DO
WRITE(Score[Index]:7:2);
WRITELN;
WRITE(Tab);
FOR Index := 1 TO NumberOfClasses DO
WRITE('-------');
WRITELN;
WRITELN(Tab,'Sum of scores = ', SumOfScores:0:2);
WRITELN(Tab,'Average of scores = ', Average:0:2);
WRITELN;
WRITELN('Press ENTER to continue..');
READLN
END.
This is a sample run:
Enter score for class #1: 90.5
Enter score for class #2: 80.5
Enter score for class #3: 86.2
Enter score for class #4: 90.3
Enter score for class #5: 74.8
Enter score for class #6: 98.5
CLASS
1 2 3 4 5 6
------------------------------------------
SCORES 90.50 80.50 86.20 90.30 74.80 98.50
------------------------------------------
ANSWER
output of the program
Sum of scores = 520.80
Average of scores = 86.80
Press ENTER to continue…
QUESTION 9
Write a Pascal program to read and store the test scores of ten students, then display
the output as shown below:
Student # Score
-----------------------
1 90.00
2 88.00
3 91.00
4 78.00
5 75.00
6 65.00
7 70.00
8 67.00
9 80.00
10 95.00
-----------------------
Average score = 79.90
ANSWER
PROGRAM Scores4(INPUT,OUTPUT);
CONST
NumberOfStudents = 10;
Tab = ' '; { 18 spaces }
Dash = '-';
NumberOfDashes = 46;
VAR
Score :ARRAY[1..NumberOfStudents] OF REAL;
Average, SumOfScores :REAL;
Index :INTEGER;
BEGIN
{ Read the scores array }
{ --------------------- }
FOR Index := 1 TO NumberOfStudents DO
BEGIN
WRITE('Enter Score of Student #', Index,': ');
READLN(Score[Index])
END;
{ Calculate the average score }
{ --------------------------- }
SumOfScores := 0;
FOR Index := 1 TO NumberOfStudents DO
SumOfScores :=SumOfScores + Score[Index];
Average :=SumOfScores / NumberOfStudents;
{ Display Results }
{ --------------- }
WRITELN;
WRITE(Tab, 'Student #');
WRITE(Tab, 'Score');
WRITELN;
WRITE(Tab);
FOR Index := 1 TO NumberOfDashes DO
WRITE(Dash);
WRITELN;
FOR Index := 1 TO NumberOfStudents DO
WRITELN(Tab,Index:3,tab,Score[Index]:10:2);
WRITE(Tab);
FOR Index := 1 TO NumberOfDashes DO
WRITE(Dash);
WRITELN;
WRITELN(Tab,'Average score = ', Average:0:2);
WRITELN;
WRITELN('Press ENTER to continue..');
READLN
END.
QUESTION 10
Write the output of the program below for the following sample run:
Enter element #1: 44
Enter element #2: 22
Enter element #3: 8
Enter element #4: 1
Enter element #5: 667
Enter element #6: 3
PROGRAM Sorting(INPUT,OUTPUT);
CONST
ArraySize = 6;
TYPE
Range = 1..ArraySize;
NumbersArray = ARRAY[Range] OF INTEGER;
VAR
Numbers :NumbersArray;
{ ----------------- Read procedure --------------- }
PROCEDURE ReadNumbers(L: INTEGER; VAR R :NumbersArray);
VAR
I :INTEGER;
BEGIN
FOR I := 1 TO L DO
BEGIN
WRITE('Enter element #', I,': ');
READLN(R[I])
END
END;
{ ----------------- Sort procedure --------------- }
PROCEDURE SortNumbers(M: INTEGER; VAR S :NumbersArray);
VAR
I, J, Pot :INTEGER;
BEGIN
FOR I := 1 TO M-1 DO
FOR J := I+1 TO M DO
IF S[I] > S[J] THEN
BEGIN { Swap contents }
Pot := S[J];
S[J] := S[I];
S[I] := Pot
END
END;
{ ---------------- Print procedure --------------- }
PROCEDURE PrintNumbers(N: INTEGER; T :NumbersArray);
VAR
I :INTEGER;
BEGIN
WRITELN;
WRITE('The sorted array is: ');
FOR I := 1 TO N DO
WRITE(T[I],' ');
WRITELN;
END;
{ --------------- Main Program ------------------- }
BEGIN
ReadNumbers(ArraySize, Numbers);
SortNumbers(ArraySize, Numbers);
PrintNumbers(ArraySize, Numbers);
WRITELN('Press ENTER to continue..');
READLN
END.
ANSWER
Sample run:
Enter element #1: 44
Enter element #2: 22
Enter element #3: 8
Enter element #4: 1
Enter element #5: 667
Enter element #6: 3
Output of the program
The sorted array is: 1 38 22 44 667
Press ENTER to continue

More Related Content

PDF
CIS 115 Education for Service--cis115.com
PDF
CIS 115 Redefined Education--cis115.com
DOCX
CIS 115 Education Counseling--cis115.com
DOCX
CIS 115 Achievement Education--cis115.com
PPT
PPT
FP 201 Unit 3
DOCX
CIS 115 Inspiring Innovation/tutorialrank.com
PPTX
Iterative control structures, looping, types of loops, loop working
CIS 115 Education for Service--cis115.com
CIS 115 Redefined Education--cis115.com
CIS 115 Education Counseling--cis115.com
CIS 115 Achievement Education--cis115.com
FP 201 Unit 3
CIS 115 Inspiring Innovation/tutorialrank.com
Iterative control structures, looping, types of loops, loop working

What's hot (19)

PPT
Verilogforlab
PPT
FP 201 Unit 2 - Part 3
DOCX
Cis 115 Extraordinary Success/newtonhelp.com
RTF
PDF
Chapter 4 : Balagurusamy Programming ANSI in C
DOC
Cis 115 Effective Communication / snaptutorial.com
PPT
DOC
CIS 115 Exceptional Education - snaptutorial.com
PDF
Chapter 2 : Balagurusamy_ Programming ANsI in C
PDF
Chapter 5 exercises Balagurusamy Programming ANSI in c
DOC
Cis 115 Education Organization / snaptutorial.com
PDF
Chapter 3 : Balagurusamy Programming ANSI in C
PDF
C language questions_answers_explanation
PDF
Chapter 6 Balagurusamy Programming ANSI in c
PPT
L3 control
PPTX
From clever code to better code
PDF
CIS 115 Effective Communication - tutorialrank.com
Verilogforlab
FP 201 Unit 2 - Part 3
Cis 115 Extraordinary Success/newtonhelp.com
Chapter 4 : Balagurusamy Programming ANSI in C
Cis 115 Effective Communication / snaptutorial.com
CIS 115 Exceptional Education - snaptutorial.com
Chapter 2 : Balagurusamy_ Programming ANsI in C
Chapter 5 exercises Balagurusamy Programming ANSI in c
Cis 115 Education Organization / snaptutorial.com
Chapter 3 : Balagurusamy Programming ANSI in C
C language questions_answers_explanation
Chapter 6 Balagurusamy Programming ANSI in c
L3 control
From clever code to better code
CIS 115 Effective Communication - tutorialrank.com
Ad

Similar to BASICS OF COMPUTER PROGRAMMING-TAKE HOME ASSIGNMENT 2018 (20)

DOCX
CSC8503 Principles of Programming Languages Semester 1, 2015.docx
PDF
Mmt 001
PDF
Chapter 6 Flow control Instructions
PDF
C in 10 Hours learn programming easily.pdf.pdf
PDF
Exercise1 java
DOCX
Java Practice Set
DOCX
Functions Practice Sheet.docx
DOCX
Important C program of Balagurusamy Book
PDF
AMCAT_Computer Programming questions and ans
PDF
Computer Science Paper 1 (Theory) - 2017.pdf
DOC
Useful c programs
DOCX
CIS 115 Become Exceptional--cis115.com
DOCX
CIS 115 Education Specialist / snaptutorial.com
DOC
Devry cis 115 final exam 1
DOC
Devry cis 115 final exam 1
PDF
C - Programming Assignment 1 and 2
DOC
Devry cis 115 final exam 2
DOC
Devry cis 115 final exam 2
DOCX
CIS 115 Education in iCounseling ---cis115.com
CSC8503 Principles of Programming Languages Semester 1, 2015.docx
Mmt 001
Chapter 6 Flow control Instructions
C in 10 Hours learn programming easily.pdf.pdf
Exercise1 java
Java Practice Set
Functions Practice Sheet.docx
Important C program of Balagurusamy Book
AMCAT_Computer Programming questions and ans
Computer Science Paper 1 (Theory) - 2017.pdf
Useful c programs
CIS 115 Become Exceptional--cis115.com
CIS 115 Education Specialist / snaptutorial.com
Devry cis 115 final exam 1
Devry cis 115 final exam 1
C - Programming Assignment 1 and 2
Devry cis 115 final exam 2
Devry cis 115 final exam 2
CIS 115 Education in iCounseling ---cis115.com
Ad

More from musadoto (20)

PDF
The design of Farm cart 0011 report 1 2020
PDF
IRRIGATION SYSTEMS AND DESIGN - IWRE 317 questions collection 1997 - 2018 ...
PDF
CONSTRUCTION [soil treatment, foundation backfill, Damp Proof Membrane[DPM] a...
PDF
Assignment thermal 2018 . ...
PDF
ENGINEERING SYSTEM DYNAMICS-TAKE HOME ASSIGNMENT 2018
PDF
Hardeninig of steel (Jominy test)-CoET- udsm
PDF
Ultrasonic testing report-JUNE 2018
PDF
Ae 219 - BASICS OF PASCHAL PROGRAMMING-2017 test manual solution
DOCX
Fluid mechanics ...
PDF
Fluid mechanics (a letter to a friend) part 1 ...
PDF
Fluids mechanics (a letter to a friend) part 1 ...
PPTX
Fresh concrete -building materials for engineers
PPT
surveying- lecture notes for engineers
PDF
Fresh concrete -building materials for engineers
DOCX
DIESEL ENGINE POWER REPORT -AE 215 -SOURCES OF FARM POWER
PDF
Farm and human power REPORT - AE 215-SOURCES OF FARM POWER
PDF
ENGINE POWER PETROL REPORT-AE 215-SOURCES OF FARM POWER
PDF
TRACTOR POWER REPORT -AE 215 SOURCES OF FARM POWER 2018
PDF
WIND ENERGY REPORT AE 215- 2018 SOURCES OF FARM POWER
PDF
Hydro electric power report-AE 215 2018
The design of Farm cart 0011 report 1 2020
IRRIGATION SYSTEMS AND DESIGN - IWRE 317 questions collection 1997 - 2018 ...
CONSTRUCTION [soil treatment, foundation backfill, Damp Proof Membrane[DPM] a...
Assignment thermal 2018 . ...
ENGINEERING SYSTEM DYNAMICS-TAKE HOME ASSIGNMENT 2018
Hardeninig of steel (Jominy test)-CoET- udsm
Ultrasonic testing report-JUNE 2018
Ae 219 - BASICS OF PASCHAL PROGRAMMING-2017 test manual solution
Fluid mechanics ...
Fluid mechanics (a letter to a friend) part 1 ...
Fluids mechanics (a letter to a friend) part 1 ...
Fresh concrete -building materials for engineers
surveying- lecture notes for engineers
Fresh concrete -building materials for engineers
DIESEL ENGINE POWER REPORT -AE 215 -SOURCES OF FARM POWER
Farm and human power REPORT - AE 215-SOURCES OF FARM POWER
ENGINE POWER PETROL REPORT-AE 215-SOURCES OF FARM POWER
TRACTOR POWER REPORT -AE 215 SOURCES OF FARM POWER 2018
WIND ENERGY REPORT AE 215- 2018 SOURCES OF FARM POWER
Hydro electric power report-AE 215 2018

Recently uploaded (20)

PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
Lecture Notes Electrical Wiring System Components
PDF
composite construction of structures.pdf
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
Digital Logic Computer Design lecture notes
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
DOCX
573137875-Attendance-Management-System-original
PPTX
Welding lecture in detail for understanding
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Sustainable Sites - Green Building Construction
PPTX
additive manufacturing of ss316l using mig welding
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
UNIT 4 Total Quality Management .pptx
Lecture Notes Electrical Wiring System Components
composite construction of structures.pdf
Automation-in-Manufacturing-Chapter-Introduction.pdf
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Digital Logic Computer Design lecture notes
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
573137875-Attendance-Management-System-original
Welding lecture in detail for understanding
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
Model Code of Practice - Construction Work - 21102022 .pdf
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
R24 SURVEYING LAB MANUAL for civil enggi
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Sustainable Sites - Green Building Construction
additive manufacturing of ss316l using mig welding

BASICS OF COMPUTER PROGRAMMING-TAKE HOME ASSIGNMENT 2018

  • 1. SOKOINE UNIVERSITY OF AGRICULTURE COLLEGE OF AGRICULTURE DEPARTMENT OF ENGINEERING SCIENCE AND TECHNOLOGY AE 219 BASICS OF COMPUTER PROGRAMMING GROUP 09-ASSIGNMENT, IWRE 2 NO. NAME OF A STUDENT REGISTRATION NUMBER SIGNATURE 1. DOTO, MUSA GESE IWR/D/2016/0011 2. KOYI, PERIS J IWR/D/2016/0021 3. KWEKA, DANIEL IWR/D/2016/0023 4. DAUDI, DERICK IWR/D/2016/0009 5. KILINDO, ABUBAKARI IWR/D/2016/0065 INSTRUCTOR: DR. BAANDA A. SALIM SUBMISSION DATE: FRIDAY ,29TH JUNE 2018
  • 2. PART 1 TP- Lecture 4.1 Self- Check 1 Which of the following are Pascal reserved words, standard identifiers, valid identifiers, invalid identifiers? end ReadLn Bill program Sues‟s Rate Start begin const Y=Z Prog#2 &Up First Name „MaxScores‟ A*B CostaMesa,CA Barnes&Noble CONST XYZ123 ThisIsALongOne 123XYZANSWER ANSWERS Paschal reserved words: begin, end, program, Start, CONST, const Standard identifiers: ReadLn, „MaxScores‟, Bill, Rate Valid identifiers: XYZ123, ThisIsALongOne, A*B, Y=Z, CostaMesa, CA, First Name Invalid identifiers: 123XYZ, Sues‟s, &UpFirstName, Barnes&Noble, Prog#2 Self- Check 2 Which of the following literal values are legal and what are their types? Which are illegal and why? 15 „XYZ‟ „*‟ $25.123 15; -999 .123 „x‟ “X” „9‟ „-5‟ True
  • 3. ANSWER: The following values are legal and their type Legal Type Illegal 15 Integer literal $25.123 „ XYZ‟ String Literal .123 „X‟ Character Literal „9‟ True Boolean Literal 15; -999 Integer Literal -„5‟ Operator literal „*‟ TP- Lecture 4.2 Self- Checked 1 Which of the following are valid program headings? Which are invalid and why? (i) Program program; - INVALID using reserved ID (ii) program 2ndCourseInCS; -INVALID because starts with digit (iii) program PascalIsFun;- VALID program heading (iv) program Rainy Day; -INVALID – contains space Self- Checked 2 Rewrite the following code so that it has no syntax errors and follows the writing conventions we adopted (i) Program SMALL; VAR X, Y, Z : real; BEGIN Y := 15.0; Z := -Y + 3.5; X :=Y + z; writeln (x, Y, z); END. ANSWER: Program SMALL; VAR X, Y, Z :real; BEGIN Y := 15.0; Z := -Y + 3.5; x := Y + z; writeln (x, Y, z); END.
  • 4. (ii) PROGRM 2time5 {input,output}; CONST two := 2; five := 5; VAR multip; dummy ; integer; BEGIN ; multip = two * five ; dummy := multip ; write (two) , write (five) END ; ANSWER: PROGRAM p2time5(INPUT,OUTPUT); CONST two = 2; five = 5; VAR multip, dummy :integer; BEGIN multip := two * five ; dummy := multip ; write (dummy) END . Self- Check 3 Write the following numbers in normal decimal notation: (i) 103E-4 = 0.0103 (ii) 1.2345E+6 = 1234500000.0 (iii) 123.45E+3 = 123450.0 Self-Check 4 Write the following numbers in Pascal scientific notation (i) 1300= 1.3E+3 (ii) 123.45= 1.2345E+2 (iii) 0.00426= 4.26E-3 TP- Lecture 5.1 Self- Checked 1 What are the results of the following expressions? 22 div 7 = 3 7 div 22 = 0 22 mod 7 =1 7 mod 22 = 7
  • 5. Self- Checked 2 What is valid & what is invalid in the following const PI = 3.14159; MaxI = 1000; var X, Y : Real; A, B, I : Integer; . . . I := A mod B; I := A mod Y; X := A / B; I := A / B; X := A / Y; I := B div 0; I := A mod 0; X := PI div Y; X := A mod (A / B); I := (MaxI - 990) div A; I := A mod (MaxI - 990); SEE TURBO PASCAL COMPILATION ERRORS ANSWER: PROGRAM Types; CONST PI = 3.14159; MaxI = 1000; VAR X, Y : Real; A, B, I : Integer; BEGIN I := A mod B;{ I := A mod Y; } X := A / B; { I := A / B; } X := A / Y; { I := B div 0; } I := A mod 0; { X := PI div Y; }{ X := A mod (A / B); } I := (MaxI - 990) div A; I := A mod (MaxI - 990); END. TP- Lecture 5.2 Self- Checked 1: What is the output if the entered data are 5 7? writeln („Enter two integers>‟); readln(M, N); M := M + 5; N := 3 + N; writeln („M = „, M); writeln („N = „, N);
  • 6. ANSWER: The output of the program is Enter two intergers>5 7 M= 10 N= 10 Self- Checked 2: What is the output of this code? write („My name is‟); writeln („Doe, Jane‟); writeln ; write(„I live in „); write(„Ann Arbor, MI‟); writeln („and my zip code is „, 48109); ANSWER: The output of this code will be, My name is Doe, Jane I live in Ann Arbor, MIA and my zip code is 48109 Self- Checked 3: Show how the value -15.564 (stored in X) would be displayed using the following formats (i) X :8:4= -15.5640 (ii) X:8:3 = -15.564 (iii) X:8:1 = -15.6 (iv) X:8:0 = -16.0 (v) X:8 = -15 Self- Checked 4: Assuming X = 12.345 (type Real) and I = 100 (type Integer). What will the output of the following statements look like? writeln(„X is „ :10, X :6:2, „I is „ :4, I :5); write(„I is „ :10, I : 1); writeln(„X is „ :10, X :2:1);
  • 7. ANSWER: The output will be as follows X is 12.35 I is 100 I is 100 X is 12.4 TP- Lecture 8 Self- Checked 1: (i) Write the Boolean expression to check if a character variable Ch is a digit. ANSWER: (ORD(InputChar) > 47) AND (ORD(InputChar) < 58) (ii) Write a Boolean expression to check if a character variable Chis an upper-case letter. ANSWER: (ORD(InputChar) > 64 ) AND (ORD(InputChar) < 91) iii. Write a Boolean expression to check if a character variable Ch is a lower-case letter. ANSWER: (ORD(InputChar) > 96 ) AND (ORD(InputChar) < 123) iv. Using a Boolean test, convert upper-case character Ch to a lower-case character. ANSWER: IF Upper-case THEN Name[I] := CHR(ORD(Name[I])+32); Self- Check 2: Write Boolean assignment statements: 1. Assign true to variable Between if the value of N is in the range -K to +K, inclusive; otherwise, assign a value of false ANSWER: Boolean assignment statement is, IF (N <= -k) AND (N <=+k) WRITELN(„This is True‟) ELSE WRITELN(„This is False‟)
  • 8. (a) Assign a value of true to variable Uppercase if Ch is an uppercase letter; otherwise, assign false ANSWER: Boolean statement is, IF M DivN THEN WRITELN („This is True‟) ELSE WRITELN(„This is False) (b) Assign a value of true to variable Divisor if M is a divisor of N; otherwise, assign false ANSWER: Boolean statement is, IF (ORD(InputChar) > 64 ) AND (ORD(InputChar) < 91) THEN WRITELN(„This is True‟) ELSE WRITELN(„This is False‟) Self- Check 3: What do these statements display? (i) IF 12 < 12 THEN writeln(„Less‟) ELSE writeln(„Not less‟) ANSWER: It will display, Not less (ii) Var1 := 25.12; Var2 := 15.00; IF Var1 (iii) <= Var2 THEN writeln(„Less or equal‟) ELSE writeln(„Greater than‟) ANSWER: It will display, Greater than
  • 9. Self- Check 4: What value is assigned to X when Y is 15.0? a. X := 25.0; IF Y <> (X - 10.0) THEN X := X - 10.0 ELSE X := X / 2.0 ANSWER: The value assigned to X is 12.5 b. IF (Y < 15.0) AND (Y >= 0.0) THEN X := 5 * Y ELSE X := 2 * Y c. ANSWER The value assigned to X is 30.0 Self- checked 5: Write Pascal statements to perform the following: If Item is nonzero, then multiply Product by Item and save the result in Product; otherwise, skip the multiplication. In either case, print the value of Product. Store the absolute difference of X and Y in Y, where the absolute difference is (X - Y) or (Y - X), whichever is positive. Don’t use the abs() function in your solution ANSWER: IF item <> 0 THEN Multip = product*item WRITELN; WRITELN(„Product‟) Self-Check 6: Evaluate the following expressions, with and without short-circuit evaluation -Assumptions: i. X = 6 ii. Y = 7 -(X > 5) and (Y div X <= 10) -(X <= 10) or (X / (Y - 7) > 3)
  • 10. ANSWER: With short circuit X = 6 Y = 7 IF (X >5) AND (YdivX<=10) IF(X<= 10) OR (X/(Y-7)>3) Without shot circuit-evaluation X = 6 Y = 7 IF (X > 5) THEN (Y divX<= 10) IF (X <= 10) THEN (X/(Y-7) > 3) TP-Lecture 9 Self- Checked 5.1: Trace the following program fragment: J := 10; FOR I := 1 to 5 DO BEGIN writeln(I, J); J := J - 2 END; { FOR } • How many times will the loop body be executed? ANSWER: The loop body will be executed 5 times. Self- Checked 5.2 (a) Write FOR loop headers that process all values of Celsius (type integer) in the following ranges: -10 through +10 100 through 1 15 through 50 50 through -75 (b) What types can be used as FOR loop counters?
  • 11. (c) Write a FOR statement that computes the sum of the ODD integers in the range 0 to 100 inclusive ANSWER: FOR Celcius := -10 TO 10 DO FOR Celcius := 100 DOWN TO 1 DO FOR Celcius := 15 TO 50 DO FOR Celcius := 50 DOWN TO -75DO Self- Check 5.3: For the following loop: X := 3; Count := 0; while Count < 3 do begin X := X * X; writeln(X); Count := Count + 1 end; { while } writeln(Count); • How many times is the loop body repeated? • What is printed during each repetition of the loop body, and at the very end? • What happens if the last statement in the loop body is: Count := Count + 2; • What happens if the last statement in the loop body is removed? ANSWER: The time that the loop body repeated are 3 time The result which can be printed during each repeation of the loop is 0 When the last statement in the loop is count:= count+2 =215 can be printed When the last statement in the loop body is removed Nothing will be printed Self-Checked 5.10: (i) Write a while loop that displays each integer from 1 to 5 on a separate line, along with its square. (ii) Write a while loop that displays each integer from 4 down to -6 on a separate line. Display the values in the sequence 4, 2, 0, and so on.
  • 12. ANSWER NOT(X <= Y) OR (X <> 15) NOT(X <= Y) AND (Z = 7.5) NOT(X <> 15) AND (Z = 7.5) NOT Flag AND (X <> 15.7)32 Flag OR NOT (x <= 8) TP- Lecture 11.1 Self- Checked 1: What is displayed by the following program fragment, assuming N is 5? FOR I := 1 TO N DO BEGIN FOR J := 1 TO I DO write(„*‟); writeln END; ANSWER: - The display that the program can produce are * * * * * * * * * * * * * * * Self- Checked 2 : What is displayed by the following program fragment, assuming M is 3 and N is 5? FOR I := N DOWNTO 1 DO BEGIN FOR J := M DOWNTO 1 DO write(„*‟); writeLn END;
  • 13. ANSWER: The display that the program can execute are * * * * * * * * * * * * Self-checked 3: Show the output printed by the following nested loops: FOR I := 1 TO 2 DO BEGIN writeln(„Outer‟ : 5, I : 5); FOR J := 1 TO 3 DO writeln(„Inner‟ : 7, I : 3, J : 3) FOR K := 2 DOWNTO 1 DO writeln(„Inner‟ :7, I : 3, K : 3) END; ANSWER:  The output that can be printed in the nested loop are OUTPUT 1 Inner 1 1 Inner 1 2 Inner 1 3 Inner 1 2 Inner 1 1 OUTPUT 2 Inner 2 1 Inner 2 2 Inner 2 3 Inner 2 2 Inner 2 1 Self- Check 4: Write a program fragment that, given an input value N, displays N rows in the form 1 2 ... N, 2 3 ... N + 1, and so forth PROGRAM Check; VAR I,J,N : integer; BEGIN write('What is N? '); read(N); FOR I := 1 TO N DO BEGIN FOR J := I TO I + N - 1 DO write(J:2);
  • 14. writeln END; readln END. ANSWER: PROGRAM Fragment(INPUT,OUTPUT); VAR J, I, N :INTEGER; BEGIN WRITE(„Enter the value of N‟); READLN(N); FOR I := 1 TO N DO BEGIN FOR J := I TO I +N-1 DO WRITE(J : 2) WRITELN; READLN END. Self- Check 5: Write a program that prints a nicely labeled multiplication table for the digits 1 through 9. ANSWER: PROGRAM MultiplicationTable; VAR I,J : integer; BEGIN FOR I := 1 TO 9 DO BEGIN FOR J := 1 TO 9 DO write(I*J:3); writeln END; readln END.
  • 15. The outputs of the program are 1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 4 8 12 16 20 24 28 32 36 5 10 15 20 25 30 35 40 45 6 12 18 24 30 36 42 48 54 7 14 21 28 35 42 49 56 63 8 16 24 32 40 48 56 64 72 9 18 27 36 45 54 63 72 81 TP- Lecture 12.2 Self- Check 1: What is wrong with this program? assign(„MyData.txt‟, InFile); rewrite(Infile); /* ?? */ reset(Infile); WHILE NOT eoln DO /* ?? */ BEGIN read(InFile, Next); write(Next) END; {while} ANSWER: The wrong of this statement can be corrected as PROGRAM Self(OUTPUT); VAR InFile : TEXT;
  • 16. BEGIN Assign(InFile, „MyData.Txt‟); Rewrite(InFile); WHILE NOT eoln (inFile) DO BEGIN WRITE( Next); READLN(Infile,Next); END; {WHILE}; READLN; Reset(InFile) END. PART II. QUESTION 1 In the following program, two integers, a and b, are declared in the declaration part, then assigned integer values in the program block. The WRITELN statement is then used to evaluate and display the results of different arithmetic operations performed on those variables. PROGRAM Arithmetic(OUTPUT); { Variable Declarations } VAR a, b :INTEGER; { Program Block } BEGIN a := 50; b := 4; WRITELN('a=',a); WRITELN('b=',b); WRITELN('a+b=',a+b); WRITELN('a-b=',a-b); WRITELN('a*b=',a*b); WRITELN('a/b=',a/b); WRITELN('a div b=',a DIV b); { used with integers only } WRITELN('a mod b=',a MOD b) { used with integers only } END. ANSWER To write output of the program: a=50
  • 17. b=4 a+b=54 a-b=46 a*b=200 a/b= 1.2500000000000000E+0001 a div b=12 a mod b=2 QUESTION 2 Write a program to calculate employee wages according to the formula: Wages :=HoursWorked * PayRate; inputHoursWorked and PayRate from the keyboard and display Wages preceded by the string ‘USD’. ANSWER PROGRAM Payroll(INPUT,OUTPUT); VAR HoursWorked, PayRate, Wages :REAL; { Program Block } BEGIN WRITE('Please enter hours worked: '); READLN(HoursWorked); WRITE('Please enter pay rate: '); READLN(PayRate); Wages :=HoursWorked * PayRate; WRITELN; WRITELN('Wages = $', Wages:0:2) END. QUESTION 3 Write the Pascal expressions for the following: i. The quadratic equation: Ax2 + Bx + C ii. The determinant: B2 – 4AC iii. The square root of the determinant iv. The absolute value of the determinant Then, write a program to produce the roots of the equation according to the input values of A, B, and C. Use test values for A, B, and C that give real roots. Typical values are: A=1, B=2, C=1, give the solution: X1= X2= –1.00 A=1, B=4, C=2, give the solution: X1= –0.59, X2= –3.41
  • 18. ANSWERS i. A*SQR(X)+B*X+C ii. SQR(B)-4*A*C iii. SQRT((SQR(B)-4*A*C)) iv ABS(SQR(B)-4*A*C) PROGRAM Quadratic(INPUT,OUTPUT); VAR D, X1, X2 :REAL; A, B, C: INTEGER; BEGIN WRITE('Enter the values of A,B and C for the quadratic equation:'); READLN(A,B,C); { Determinant} D:=SQR(B)-4.0*A*C; { Roots } X1:=(-B+SQRT(D))/(2*A); X2:=(-B-SQRT(D))/(2*A); WRITELN('X1=',X1:2:2,' X2=',X2:2:2); WRITELN('Press ENTER to continue...'); READLN END. Sample runs: A=1, B=2, C=1 X1=X2=-1.00 A=1, B=4, C=2 X1= -0.59 X2= -3.41 QUESTION 4 Modify the program you wrote in Qn3 to solve a quadratic equation (Ax² + Bx +C) for both real and imaginary roots. ANSWER Modified Complete Solution of a Quadratic Equation will be: PROGRAM Quadratic2(INPUT,OUTPUT); VAR A, B, C, D, X1, X2 :REAL; BEGIN WRITE('Enter the values of A,B,C separated by spaces:'); READLN(A,B,C); { Determinant} D:=SQR(B)-4.0*A*C; IF D < 0 THEN BEGIN WRITELN('Roots are imaginary.'); WRITELN('X1=',-B/(2*A):0:2,'+j',SQRT(ABS(D))/(2*A):0:2); WRITELN('X2=',-B/(2*A):0:2,'-j',SQRT(ABS(D))/(2*A):0:2)
  • 19. END ELSE BEGIN WRITELN('Roots are real.'); WRITELN('X1=',(-B+SQRT(D))/(2*A):0:2); WRITELN('X2=',(-B-SQRT(D))/(2*A):0:2) END; WRITELN('Press ENTER to continue ...'); READLN END. { Sample runs: Real roots: A=2, B=4, C=1 X1=0.29 X2=1.70 Equal real roots: A=1, B=2, C=1 X1=-1 X2=-1 Imaginary roots: A=1, B=1,C=1 X1=-0.5+j0.87 X2=-0.5-j0.87 QUESTION 5 Write a program to describe the weather according to the following temperature classifications: Temperature Classification 24 and greater Hot 10 to 23 Cool 0 to 9 Cold less than 0 Freezing ANSWER PROGRAM WeatherTester(INPUT,OUTPUT); VAR Temperature :INTEGER; Hot, Cool, Cold, Freezing :BOOLEAN; BEGIN WRITE('Please enter the temperature:'); READLN(Temperature); Hot := (Temperature >= 24); Cool := (Temperature >= 10) AND (Temperature < 24); Cold := (Temperature >= 0) AND (Temperature < 10); Freezing := (Temperature < 0); WRITELN; { Beginning of the IF construct } IF Hot THEN WRITELN('IT‟S VERY HOT!!!') ELSE IF Cool THEN WRITELN('IT‟S COOL OUT THERE!!!!!.')
  • 20. ELSE IF Cold THEN WRITELN('Oh, it is cold. ') ELSE IF Freezing THEN WRITELN(' It is freezing.') ELSE WRITELN('Hey, It is below the normal temperature!'); { End of the IF construct } { ----------------------- } WRITELN('Press ENTER to continue..'); READLN END. QUESTION 6 The number 2 and its powers are very important numbers in the computer field. Some of the numbers, such as 1024 bytes (equivalent to 1 KB) and 65,536 bytes (64 KB) are commonly used. In the following program a FOR loop is used to display the powers of two, using the same logic that was used to calculate the power in Example 2-2. The program output gives the power and the number 2 raised to this power. The initial and final values of the counter are supplied by the user during the execution. Thus, you can determine the range of numbers you would like to examine. PROGRAM ForLoop(INPUT, OUTPUT); VAR Base, Power, Start, Final :INTEGER; BEGIN Base := 2; WRITE('Enter starting exponent:'); READLN(Start); WRITE('Enter ending exponent:'); READLN(Final); WRITELN; WRITELN('Number Power of two'); FOR Power := Start TO Final DO BEGIN WRITE(Power:3); WRITELN(EXP(LN(Base)*Power):20:0) END; WRITELN; WRITELN('Press ENTER to continue..'); READLN END. Modify the program to save the output of the program in file (instead of seeing the output in the screen). Plot the data of the output file (using Matlab or Excel). Label your plot. Use exponent value from 1 to 30.
  • 21. ANSWER The following is a sample run using exponent values from 1 to 30: Enter starting exponent:1 Enter ending exponent:30 Number Power of two 1 2 2 4 3 8 4 16 5 32 6 64 7 128 8 256 9 512 10 1024 11 2048 12 4096 13 8192 14 16384 15 32768 16 65536 17 131072 18 262144 19 524288 20 1048576 21 2097152 22 4194304 23 8388608 24 16777216 25 33554432 26 67108864 27 13417728 28 268435456 29 536870912 30 1073741824 Press ENTER to continue.. By using MatLab
  • 22. QUESTION 7 Write down the output of the following program for a sample run of 10 elements PROGRAM AverageProg3(INPUT,OUTPUT); VAR Average, Sum, Number :REAL; Kounter :INTEGER; BEGIN Sum := 0; Average := 0; Number := 0; Kounter := 0; WHILE Number<>-1 DO BEGIN Kounter :=Kounter + 1; Sum := Sum + Number; WRITE('Enter element #',Kounter,' (or –1 to end): '); READLN(Number) END; IF Kounter> 1 THEN Average := Sum / (Kounter - 1); WRITELN; WRITELN('Sum of Numbers = ', Sum:0:2); WRITELN('Average of Numbers = ', Average:0:2); WRITELN; WRITELN('Press ENTER to continue..'); READLN END.
  • 23. ANSWER The following is a sample run of 10 elements: Enter element #1 (or -1 to end): 1 Enter element #2 (or -1 to end): 2 Enter element #3 (or -1 to end): 3 Enter element #4 (or -1 to end): 4 Enter element #5 (or -1 to end): 5 Enter element #6 (or -1 to end): 6 Enter element #7 (or -1 to end): 7 Enter element #8 (or -1 to end): 8 Enter element #9 (or -1 to end): 9 Enter element #10 (or -1 to end): -1 Sum of the numbers =45.00 Average of Numbers = 5.00 Press ENTER to continue… QUESTION 8 Write the output of the program below for the following sample run: Enter score for class #1: 90.5 Enter score for class #2: 80.5 Enter score for class #3: 86.2 Enter score for class #4: 90.3 Enter score for class #5: 74.8 Enter score for class #6: 98.5 PROGRAM Scores2(INPUT,OUTPUT); CONST NumberOfClasses = 6; Tab = ' '; { 9 spaces } VAR Score :ARRAY[1..NumberOfClasses] OF REAL; Average, SumOfScores :REAL; Index :INTEGER; BEGIN { Read the scores array } { --------------------- } FOR Index := 1 TO NumberOfClasses DO BEGIN WRITE('Enter score for class #', Index,': '); READLN(Score[Index]) END; { Calculate the sum } { ----------------- } SumOfScores := 0; FOR Index := 1 TO NumberOfClasses DO SumOfScores :=SumOfScores + Score[Index]; { Calculate the average } { --------------------- } Average :=SumOfScores / NumberOfClasses;
  • 24. { Display Results } { --------------- } WRITELN; WRITELN(Tab,'CLASS #'); WRITE(' '); { 6 spaces } FOR Index := 1 TO NumberOfClasses DO WRITE(Index:7); WRITELN; WRITE(Tab); FOR Index := 1 TO NumberOfClasses DO WRITE('-------'); WRITELN; WRITE('SCORES '); FOR Index := 1 TO NumberOfClasses DO WRITE(Score[Index]:7:2); WRITELN; WRITE(Tab); FOR Index := 1 TO NumberOfClasses DO WRITE('-------'); WRITELN; WRITELN(Tab,'Sum of scores = ', SumOfScores:0:2); WRITELN(Tab,'Average of scores = ', Average:0:2); WRITELN; WRITELN('Press ENTER to continue..'); READLN END. This is a sample run: Enter score for class #1: 90.5 Enter score for class #2: 80.5 Enter score for class #3: 86.2 Enter score for class #4: 90.3 Enter score for class #5: 74.8 Enter score for class #6: 98.5 CLASS 1 2 3 4 5 6 ------------------------------------------ SCORES 90.50 80.50 86.20 90.30 74.80 98.50 ------------------------------------------ ANSWER output of the program Sum of scores = 520.80 Average of scores = 86.80 Press ENTER to continue…
  • 25. QUESTION 9 Write a Pascal program to read and store the test scores of ten students, then display the output as shown below: Student # Score ----------------------- 1 90.00 2 88.00 3 91.00 4 78.00 5 75.00 6 65.00 7 70.00 8 67.00 9 80.00 10 95.00 ----------------------- Average score = 79.90 ANSWER PROGRAM Scores4(INPUT,OUTPUT); CONST NumberOfStudents = 10; Tab = ' '; { 18 spaces } Dash = '-'; NumberOfDashes = 46; VAR Score :ARRAY[1..NumberOfStudents] OF REAL; Average, SumOfScores :REAL; Index :INTEGER; BEGIN { Read the scores array } { --------------------- } FOR Index := 1 TO NumberOfStudents DO BEGIN WRITE('Enter Score of Student #', Index,': '); READLN(Score[Index]) END; { Calculate the average score } { --------------------------- } SumOfScores := 0; FOR Index := 1 TO NumberOfStudents DO SumOfScores :=SumOfScores + Score[Index]; Average :=SumOfScores / NumberOfStudents; { Display Results } { --------------- } WRITELN; WRITE(Tab, 'Student #'); WRITE(Tab, 'Score'); WRITELN; WRITE(Tab); FOR Index := 1 TO NumberOfDashes DO
  • 26. WRITE(Dash); WRITELN; FOR Index := 1 TO NumberOfStudents DO WRITELN(Tab,Index:3,tab,Score[Index]:10:2); WRITE(Tab); FOR Index := 1 TO NumberOfDashes DO WRITE(Dash); WRITELN; WRITELN(Tab,'Average score = ', Average:0:2); WRITELN; WRITELN('Press ENTER to continue..'); READLN END. QUESTION 10 Write the output of the program below for the following sample run: Enter element #1: 44 Enter element #2: 22 Enter element #3: 8 Enter element #4: 1 Enter element #5: 667 Enter element #6: 3 PROGRAM Sorting(INPUT,OUTPUT); CONST ArraySize = 6; TYPE Range = 1..ArraySize; NumbersArray = ARRAY[Range] OF INTEGER; VAR Numbers :NumbersArray; { ----------------- Read procedure --------------- } PROCEDURE ReadNumbers(L: INTEGER; VAR R :NumbersArray); VAR I :INTEGER; BEGIN FOR I := 1 TO L DO BEGIN WRITE('Enter element #', I,': '); READLN(R[I]) END END; { ----------------- Sort procedure --------------- } PROCEDURE SortNumbers(M: INTEGER; VAR S :NumbersArray); VAR I, J, Pot :INTEGER; BEGIN FOR I := 1 TO M-1 DO FOR J := I+1 TO M DO IF S[I] > S[J] THEN BEGIN { Swap contents }
  • 27. Pot := S[J]; S[J] := S[I]; S[I] := Pot END END; { ---------------- Print procedure --------------- } PROCEDURE PrintNumbers(N: INTEGER; T :NumbersArray); VAR I :INTEGER; BEGIN WRITELN; WRITE('The sorted array is: '); FOR I := 1 TO N DO WRITE(T[I],' '); WRITELN; END; { --------------- Main Program ------------------- } BEGIN ReadNumbers(ArraySize, Numbers); SortNumbers(ArraySize, Numbers); PrintNumbers(ArraySize, Numbers); WRITELN('Press ENTER to continue..'); READLN END. ANSWER Sample run: Enter element #1: 44 Enter element #2: 22 Enter element #3: 8 Enter element #4: 1 Enter element #5: 667 Enter element #6: 3 Output of the program The sorted array is: 1 38 22 44 667 Press ENTER to continue