SlideShare a Scribd company logo
1 of 27
Download to read offline
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

Similar to BASICS OF COMPUTER PROGRAMMING-TAKE HOME ASSIGNMENT 2018

Answers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And EngineersAnswers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And EngineersSheila Sinclair
 
2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_setskinan keshkeh
 
2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_setskinan keshkeh
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2Abdul Haseeb
 
Csci101 lect02 selection_andlooping
Csci101 lect02 selection_andloopingCsci101 lect02 selection_andlooping
Csci101 lect02 selection_andloopingElsayed Hemayed
 
Fuzail_File_C.docx
Fuzail_File_C.docxFuzail_File_C.docx
Fuzail_File_C.docxSyedFuzail14
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa Thapa
 
Functions Practice Sheet.docx
Functions Practice Sheet.docxFunctions Practice Sheet.docx
Functions Practice Sheet.docxSwatiMishra364461
 
RSA SIGNATURE: BEHIND THE SCENES
RSA SIGNATURE: BEHIND THE SCENESRSA SIGNATURE: BEHIND THE SCENES
RSA SIGNATURE: BEHIND THE SCENESacijjournal
 
List Processing in ABAP
List Processing in ABAPList Processing in ABAP
List Processing in ABAPsapdocs. info
 
PROGRAMMING IN C EXAMPLE PROGRAMS FOR NEW LEARNERS - SARASWATHI RAMALINGAM
PROGRAMMING IN C EXAMPLE PROGRAMS FOR NEW LEARNERS  - SARASWATHI RAMALINGAMPROGRAMMING IN C EXAMPLE PROGRAMS FOR NEW LEARNERS  - SARASWATHI RAMALINGAM
PROGRAMMING IN C EXAMPLE PROGRAMS FOR NEW LEARNERS - SARASWATHI RAMALINGAMSaraswathiRamalingam
 
Review questions and answers
Review questions and answersReview questions and answers
Review questions and answersIIUM
 
Rsa Signature: Behind The Scenes
Rsa Signature: Behind The Scenes Rsa Signature: Behind The Scenes
Rsa Signature: Behind The Scenes acijjournal
 

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

Answers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And EngineersAnswers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
 
2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets
 
2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets2Bytesprog2 course_2014_c1_sets
2Bytesprog2 course_2014_c1_sets
 
Python programming workshop session 2
Python programming workshop session 2Python programming workshop session 2
Python programming workshop session 2
 
C++ in 10 Hours.pdf.pdf
C++ in 10 Hours.pdf.pdfC++ in 10 Hours.pdf.pdf
C++ in 10 Hours.pdf.pdf
 
Csci101 lect02 selection_andlooping
Csci101 lect02 selection_andloopingCsci101 lect02 selection_andlooping
Csci101 lect02 selection_andlooping
 
Pseudocode By ZAK
Pseudocode By ZAKPseudocode By ZAK
Pseudocode By ZAK
 
Fuzail_File_C.docx
Fuzail_File_C.docxFuzail_File_C.docx
Fuzail_File_C.docx
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
 
C tutorial
C tutorialC tutorial
C tutorial
 
Functions Practice Sheet.docx
Functions Practice Sheet.docxFunctions Practice Sheet.docx
Functions Practice Sheet.docx
 
RSA SIGNATURE: BEHIND THE SCENES
RSA SIGNATURE: BEHIND THE SCENESRSA SIGNATURE: BEHIND THE SCENES
RSA SIGNATURE: BEHIND THE SCENES
 
Verilogforlab
VerilogforlabVerilogforlab
Verilogforlab
 
Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
 
List Processing in ABAP
List Processing in ABAPList Processing in ABAP
List Processing in ABAP
 
PROGRAMMING IN C EXAMPLE PROGRAMS FOR NEW LEARNERS - SARASWATHI RAMALINGAM
PROGRAMMING IN C EXAMPLE PROGRAMS FOR NEW LEARNERS  - SARASWATHI RAMALINGAMPROGRAMMING IN C EXAMPLE PROGRAMS FOR NEW LEARNERS  - SARASWATHI RAMALINGAM
PROGRAMMING IN C EXAMPLE PROGRAMS FOR NEW LEARNERS - SARASWATHI RAMALINGAM
 
Ansi c
Ansi cAnsi c
Ansi c
 
Plsql programs
Plsql programsPlsql programs
Plsql programs
 
Review questions and answers
Review questions and answersReview questions and answers
Review questions and answers
 
Rsa Signature: Behind The Scenes
Rsa Signature: Behind The Scenes Rsa Signature: Behind The Scenes
Rsa Signature: Behind The Scenes
 

More from musadoto

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

More from musadoto (20)

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

Recently uploaded

GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 

Recently uploaded (20)

GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 

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