0% found this document useful (0 votes)
3 views48 pages

Project (1) To Prolog

This project report explores three programming paradigms: procedural (Pascal), functional (Scheme), and logic programming (Prolog). It includes detailed comparisons of grammar, control structures, and example programs for each paradigm, demonstrating their syntax and functionality. The report concludes with comparisons and insights drawn from the analysis of the different programming languages.

Uploaded by

naif alhrbi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views48 pages

Project (1) To Prolog

This project report explores three programming paradigms: procedural (Pascal), functional (Scheme), and logic programming (Prolog). It includes detailed comparisons of grammar, control structures, and example programs for each paradigm, demonstrating their syntax and functionality. The report concludes with comparisons and insights drawn from the analysis of the different programming languages.

Uploaded by

naif alhrbi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Project Report

Concepts of Programming Languages

CS213 | 462

Supervisor : Prof. Dr. Mohammed A. Alhagery

Students & IDs :

Naif Suliman Alharbi 441108673

Nayil Fahhad ALharbi 441109857

Abdulmajeed Mohammed Alsharif

Bader Khalaf Almutairi

Mohammed Fahad Al-Motawa 441109093


Table of Contents

PART 1: PROCEDURAL PROGRAMMING, PASCAL...................................................2


DESCRIBE PASCAL GRAMMAR:...............................................................................................3

COMPARING PASCAL GRAMMAR WITH C GRAMMAR:..........................................................4

GENERAL SKELETON PROGRAM:............................................................................................5

EXPLANATION OF CONTROL STATEMENT: ............................................................................6

PROGRAMS:............................................................................................................................7

Naif Suliman alharbi …............................................................................................................7

Nayil Fahhad ALharbi……..........................................................................................10

Abdulmajeed Mohammed Alsharif........................................................................................13

Bader Khalaf Almutairi ..........................................................................................................17

Mohammed Fahad Al-Motawa ..............................................................................................20

PART 2: FUNCTIONAL PROGRAMMING, SCHEME. ................................................23


PROGRAMS:...........................................................................................................................24

Naif Suliman alharbi ...............................................................................................................24

Nayil Fahhad ALharbi…:.............................................................................................27

Abdulmajeed Mohammed Alsharif.........................................................................................29

Bader Khalaf Almutairi............................................................................................................32

Mohammed Fahad Al-Motawa:..............................................................................................34

PART 3: LOGIC PROGRAMMING, PROLOG............................................................37

PROGRAMS:............................................................................................................................38

Naif Suliman alharbi.................................................................................................38

Nayil Fahhad ALharbi:.................................................................................................41

Abdulmajeed Mohammed Alsharif:..................................................................................................42

Bader Khalaf Almutairi ...................................................................................................46

Mohammed Fahad Al-Motawa................................................................................................47

COMPARISONS AND CONCLUSIONS...................................................................49


REFERENCE:...........................................................................................................51
Introduction
Programming languages fall into different paradigms, each designed to solve problems in
unique ways. This report examines three different paradigms: procedural (Pascal),
functional (Scheme), and logic programming (Prolog). Through a series of programs, we
compare their syntax, structure, and efficiency.

Part 1: Procedural Programming (Pascal)


Pascal Grammar vs. C Grammar
Pascal and C have different grammar structures. Pascal is strongly typed and more
structured, while Callows more flexibility and direct memory manipulation. The main
differences include: • Variable Declaration: Pascal requires explicit declaration (var

x:

integer;), whereas C combines declaration and initialization (int x; ).


• Control Structures: Pascal uses begin ... end;, while C uses { l.
• Functions: Pascal functions must be declared before use.

General Program Skeleton in Pascal


program Example; begin
writeln('Hello, Pascal!'); end.
Control Statements in Pascal
Control statements in Pascal are used to control the flow of execution within a program. The main
types include:

• if...then...else: Used for decision-making.

if x > 0 then writeln('Positive')


else writeln
('Negative');

• for...do: Used for loops with a known number of


iterations.

for i := 1 to 10 do writeln(i);
• while...do: Used when the number of iterations is not
known in advance.

while x < 10 do begin writeln(x);


X := X + 1; end;

• repeat...until: Similar to while, but ensures the


loop runs at least once.

repeat
writeln(x);
X := X + 1; until x > 10;

• case...of: Used as an alternative to multiple if


statements.

• case choice of

• 1: writeln('Option 1');

• 2: writeln('Option 2');

• else

• writeln('Invalid choice'); end;

Example Programs in Pascal Naif suliman


alharbi
Code 1:Calculate the Perimeter of a Square

program PerimeterSquare;
var side, perimeter: integer; begin
write('Enter the side length of the square: ');
readln(side); perimeter := 4 * side; writeln('The perimeter
of the square is: perimeter); end.
,r
ff I If
ff the outpot is
f f
Code 2:Check if a Number is Even or Odd

program EvenOrOdd; var


num: integer; begin
write('Enter a number: '); readln(num);
if num mod 2 0
then
writeln('The number is even.')
else writeln('The number is odd.');
end.

\I I I I I I I I I I the outpot is

Code 3:Choose Coffee or Tea

program CoffeeOrTea; var


choice: char; begin
writeln('Do you want Coffee or Tea? (c/t)'); readln(choice);
case choice of
'c', 'C': writeln('Here is your Coffee!'); 't', 'T':
writeln('Here is your Tea!'); else writeln('Invalid
choice!');
end;
end.

,1 ff If ff I If the outpot is
Name : Nayil Fahhad ALharbi

Code 1: rock paper scissors game.


program RockPaperScissors;
uses crt, sysutils;

var
player1, player2: string;

begin
clrscr;

write('Player 1, enter Rock, Paper, or Scissors: ');


readln(player1);

write('Player 2, enter Rock, Paper, or Scissors: ');


readln(player2);

// Convert input to lowercase for comparison


player1 := LowerCase(player1);
player2 := LowerCase(player2);

// Validate input
if not ((player1 = 'rock') or (player1 = 'paper') or
(player1 = 'scissors')) or
not ((player2 = 'rock') or (player2 = 'paper') or
(player2 = 'scissors')) then
begin
writeln('Invalid input! Please enter only "Rock",
"Paper", or "Scissors".');
Halt;
end;

// Determine the winner


if player1 = player2 then
writeln('Draw!')
else if ((player1 = 'rock') and (player2 =
'scissors')) or
((player1 = 'scissors') and (player2 =
'paper')) or
((player1 = 'paper') and (player2 = 'rock'))
then
writeln('Player 1 won!')
else
writeln('Player 2 won!');
end.

Output:

Code 2: Multiplication table for number.

program MultiplicationTable; uses SysUtils;

var n, i: Integer; result: string;

begin Write('Enter a number (1 to 10): '); ReadLn(n);


if (n < 1) or (n > 10) then begin WriteLn('Invalid
input! Please enter a number between 1 and 10.'); Halt;
end;

result := '';

for i := 1 to 10 do begin result := result + IntToStr(i)


+ ' * ' + IntToStr(n) + ' = ' + IntToStr(i * n);

if i < 10 then
result := result + sLineBreak;

end;

WriteLn(result); end.

Output:

Code 3: Count of positives/ sum of Negatives.


program CountPositivesSumNegatives;
uses SysUtils;

var
n, i, value, count, sum: Integer;

begin
Write('Enter the number of elements: ');
ReadLn(n);
if n <= 0 then
begin
WriteLn('[]');
Exit;
end;

count := 0;
sum := 0;

for i := 1 to n do
begin
ReadLn(value);
if value > 0 then
Inc(count)
else if value < 0 then
sum := sum + value;
end;

WriteLn('[', count, ', ', sum, ']');


end.

Output

Name : Abdulmajeed Mohammed Alsharif

Code 1: Day of the Week Finder

program DayOfWeekFinder; uses crt; var day, month, year,


century, yearOfCentury, weekDay: integer; weekDays:
array[0..6] of string = ('Saturday', 'Sunday', 'Monday',
'Tuesday', 'Wednesday', 'Thursday', 'Friday'); begin
write(' Enter the day: '); readln(day); write(' Enter the
month: '); readln(month); write(' Enter the year: ');
readln(year);
if month < 3 then begin
month := month +
12; year := year -
1; end; century := year div 100;
yearOfCentury := year mod 100;
weekDay := (day + (13 * (month + 1)) div 5 + yearOfCentury
+
(yearOfCentury div 4) + (century div 4) - (2 * century)) mod 7;
if weekDay < 0 then weekDay := weekDay + 7;
writeln('✅ The day of the week is: ', weekDays[weekDay]);
end.

Output:

Enter the day: 5


Enter the month: 6
Enter the year: 2024
✅ The day of the week is: Wednesday

Code 2: Temperature Converter

program TemperatureConverter; uses crt; var celsius,


fahrenheit, kelvin: real; begin write(' Enter temperature
in Celsius: ');
readln(celsius);

fahrenheit := (celsius * 9/5) + 32; kelvin


:= celsius + 273.15;

writeln(' Temperature in Fahrenheit: ', fahrenheit:0:2, '


°F'); writeln(' Temperature in Kelvin: ', kelvin:0:2, ' K');
end.

Output:
Enter temperature in Celsius: 36
Temperature in Fahrenheit: 96.80 °F
Temperature in Kelvin: 309.15 K
Code 3: Guess the Number game
program GuessTheNumber; uses crt; var secret, guess: integer;
begin randomize; secret := random(100) + 1;
writeln(' Welcome to the Guessing Game!'); writeln(' Try to
guess the secret number between 1 and
100'); repeat

write('🤔 Enter your guess: '); readln(guess);


if guess < secret then writeln(' The secret
number is higher!') else if guess
> secret then writeln(' The secret number is
lower!'); until guess = secret;
writeln('🎉 Congratulations! You guessed the
correct number!'); end.

Output:
Welcome to the Guessing Game!
Try to guess the secret number between 1 and 100 Enter your
guess: 5
The secret number is higher!
Enter your guess: 99 The
secret number is lower!
Enter your guess: 95 The
secret number is lower! Enter
your guess: 94 The secret
number is lower! Enter your
guess: 92 The secret number
is higher! Enter your guess:
93

🎉 Congratulations! You guessed the correct number!

Name : Bader Khalaf Almutairi

Code 1: Number To Words program


NumberToWords; procedure
PrintNumberInWords(num: integer); begin case num
of 1: write('One'); 2:
write('Two');
3: write('Three');
4: write('Four');
5: write('Five');
6: write('Six');
7: write('Seven');
8: write('Eight');
9: write('Nine'); 10:
write('Ten'); else
write('Out of range');
end;

end; var number: integer; begin


writeln('Enter a number between 1 and 10:');
readln(number); write('The number in
words is: ');
PrintNumberInWords(number); writeln; end.

Output:

Code 2: Prime Number Checker


program PrimeNumberChecker; var number, i:
integer; isPrime: boolean; begin
writeln('Enter a number:'); readln(number);
if number <= 1 then begin
writeln(number, ' is not a prime number.');
exit; end;
isPrime := true; for i := 2 to
trunc(sqrt(number)) do begin if number
mod i = 0 then begin

isPrime := false; break; end;


end; if isPrime then writeln(number, '
is a prime number.') else

writeln(number, ' is not a prime number.'); end.


Output:

Code 2: Count Characters


program CountCharacters; var sentence:
string; count, i: integer; begin
writeln('Enter a sentence:');
readln(sentence); count := 0; for
i := 1 to length(sentence) do begin
if sentence[i] <> ' ' then
count := count + 1; end;
writeln('The number of characters

(excluding spaces) is: ', count); end.

Output:

Name : Mohammed Fahad Al-Motawa

Program 1: Shapes Calculator


program ShapesCalc; uses crt; var
ACircle , CCircle , ATriangle , PTriangle , ARectangle , PRectangle
: double ;
raduis , base , heghit , length , width , l1 , l2 , l3 : double ;
Chooese , Shape : char;
begin clrscr ;
TextColor(9);
writeln(' ________________________________________________');
writeln(' | |');
writeln(' | If you want to calculate area Enter (1) |');
writeln(' | If you want to calculate Perimeter Enter (2) |');
write(' |') ;TextColor(12); write(' If you want to exit
enter (0) '); TextColor(9); writeln('|') ;
TextColor(9);
writeln(' |________________________________________________|');
TextColor(15); readln(Chooese); if (Chooese = '0') then
begin
writeln('Thank you for using shape calculater');
exit; end ; TextColor(9); if (Chooese =
'1') then clrscr; begin
writeln(' |For area of triangle Enter (1)|');
writeln(' |For area of circle Enter (2)|');
writeln(' |For area of rectangle Enter (3)|');
readln(Shape); if (Shape = '1') then
begin
writeln(' Enter The Height ');
readln(heghit);
writeln(' Enter The base ');
readln(base);
ATriangle := 0.5 * (base * heghit);
TextColor(14);
writeln('The area of triangle is = ', ATriangle:0:2);
writeln; end;
if (Shape = '2') then
begin
writeln(' Enter The Raduis ');
readln(raduis);
ACircle := 3.14 * (raduis * raduis ) ;
TextColor(14);
writeln('The area of circle is = ', ACircle:0:2);
writeln; end;
if (Shape = '3') then
begin
writeln(' Enter The length ');
readln(length);
writeln(' Enter The width ');
readln(width);
ARectangle := length * width ;
TextColor(14);
writeln('The area of rectangle is = ', ARectangle:0:2);
writeln; end; end;
if (Chooese = '2') then
begin
TextColor(9);
writeln(' |For Perimeter of triangle Enter (1)|');
writeln(' |For Circumference of circle Enter (2)|');
writeln(' |For Perimeter of rectangle Enter (3)|');
readln(Shape); if (Shape = '1') then begin
writeln(' Enter The lengths of the three sides : ');
writeln('Enter the length of first side ');
readln(l1);
writeln('Enter the length of seconed side ');
readln(l2);
writeln('Enter the length of third side ');
readln(l3);
PTriangle := l1+l2+l3 ;
TextColor(14);
writeln('The Perimeter of triangle is = ', PTriangle:0:2);
writeln; end;
if (Shape = '2') then
begin clrscr;
writeln(' Enter The Raduis ');
readln(raduis);
CCircle := 2 * 3.14 * raduis ;
TextColor(14);
writeln('The Circumference of circle is = ', CCircle:0:2);
writeln; end;
if (Shape = '3') then
begin
writeln(' Enter The length ');
readln(length);
writeln(' Enter The width ');
readln(width);
PRectangle := 2 * (length + width) ;
TextColor(14);
writeln('The Perimeter of rectangle is = ', PRectangle:0:2);
writeln; end; end; end.

Output:
Program 2: Books Library
program BookLibrary; uses crt;
type Book = record
Title: string;
Author: string;
Date: string;
end; var
books: array[1..50] of Book;
bcount, i, select: integer;
index: integer; title,
author, date: string;
procedure Add; begin
if bcount < 50 then
begin
writeln('Enter the Title:');
readln(title);
writeln('Enter the Author name:');
readln(author);
writeln('Enter the Publication date:');
readln(date); bcount := bcount + 1;
books[bcount].Title := title;
books[bcount].Author := author;
books[bcount].Date := date;
writeln('Book added successfully.');
delay(2000) ; end else
writeln('The library is full.');
writeln('_'); writeln; end;
procedure Display; begin if
bcount = 0 then begin
writeln('The library is empty.');
delay(2000); end else begin
for i := 1 to bcount do
begin
writeln('Book ', i, ':'); writeln('Title
: ', books[i].Title); writeln('Author : ',
books[i].Author); writeln('Publication Date :
', books[i].Date);
TextColor(12);
writeln;
writeln('(Press any key to continue)');
TextColor(white);
writeln;
readln(); end; end;
writeln('_');
writeln; end;
procedure delete;
begin
writeln('Enter the index of the book to delete : ');
readln(index);
if (index > 0) and (index <= bcount) then
begin
for i := index to bcount - 1 do
books[i] := books[i + 1];
bcount := bcount - 1;
writeln('Book deleted successfully');
delay(2000); end else
writeln('Invalid index');
writeln('_');
delay(2000) ; writeln;
end; begin bcount := 0;
repeat writeln;
writeln('1. Add Book');
writeln('2. Display Books');
writeln('3. delete Book');
writeln('4. Exit');
writeln('_');
write('Enter your choice: ');
readln(select); writeln;
case select of 1: Add;
2: Display;
3: delete;
end; until
select = 4;
write('Thanks for using the program'); end.

Output:

Program 3: Parking Reservation


program ParkingReservation; uses crt;
var plate: string; hours:
integer; parkClass: string; rate:
real; invoiceBeforeTax: real;
totalAfterTax: real; tax: real;
begin clrscr;
writeln('Enter the car plate number: ');
readln(plate);

clrscr;
writeln('Parking Classes and Proximity:');
writeln('Gold: $5.00 per hour (10m~ close to the building)');
writeln('Silver: $3.00 per hour (50m~ from the building)');
writeln('Bronze: $2.00 per hour (100m~ from the building)');

writeln('Enter the number of hours: ');


readln(hours);
writeln('Enter the class of the park (Gold/Silver/Bronze): ');
readln(parkClass); case parkClass of 'Gold': rate := 5.0;
'Silver': rate := 3.0;
'Bronze': rate := 2.0; else
writeln('Invalid park class entered.');
exit; end;
invoiceBeforeTax := hours * rate;
tax := 0.15 * invoiceBeforeTax;
totalAfterTax := invoiceBeforeTax + tax;
writeln('---------------------------');
writeln('Invoice for Parking:');
writeln('Car Plate: ', plate);
writeln('Hours: ', hours);
writeln('Class: ', parkClass);
writeln('Invoice Before Tax: $', invoiceBeforeTax:0:2);
writeln('Tax (15%): $', tax:0:2);
writeln('Total After Tax: $', totalAfterTax:0:2);
writeln('---------------------------'); readln;
end.

Output:
Part 2: Functional Programming, Scheme.
programs:
Naif suliman alharbi:
Code 1: Calculate the Perimeter of a Square

(display "Enter the side length of the square: ")

(define side (read))

(define perimeter (* 4 side))

(display "The perimeter of the square is: ")

(display perimeter)

(newline)

Outpot:
Code 2: Check if a Number is Even or Odd

(display "Enter a number: ")


(define num (read))

(if (= (modulo num 2) 0)


(display "The number is even.")
(display "The number is odd."))

(newline)

The outpot:
Code 3: Choose Coffee or Tea

(display "Do you want Coffee or Tea? (c/t): ")


(define choice (read-char)) ; Read a single character
input

(cond
[(or (char=? choice #\c) (char=? choice #\C)) (display
"Here is your Coffee!")]
[(or (char=? choice #\t) (char=? choice #\T)) (display
"Here is your Tea!")]
[else (display "Invalid choice!")])

(newline)
The outpot:
Name : Nayil Fahhad Alharbi

Code 1: computing the sum of squares of numbers ( the previous examble “Code 1” has changed)

(define (get-number)
(begin
(display "Enter a number (1 to 10): ")
(let ((n (string->number (read-line))))
(if (and n (<= 1 n 10)) n
(begin (display "Invalid input! Try again.\n")
(get-number))))))

(define (sum-of-squares n)
(if (= n 0) 0 (+ (* n n) (sum-of-squares (- n 1)))))

(define (sum-of-squares-table n)
(for-each (lambda (i) (display (format "~a^2 = ~a\n" i
(* i i)))) (iota n 1)))

(define (main)
(let ((n (get-number)))
(display "\nSquares Table:\n")
(sum-of-squares-table n)
(display (format "\nSum of squares = ~a\n" (sum-of-
squares n)))))
(main)

Output:
Code 2: Multiplication table for number.

(define (get-number) (display "Enter a number (1 to 10):


") (let ((n (string->number (read-line)))) (if (and n (<=
1 n 10)) n (begin (display "Invalid input!\n") (get-
number)))))

(define (multiplication-table n) (for-each (lambda (i)


(display (format "~a * ~a = ~a\n" i n (* i n)))) (iota 10
1))) ; Generates numbers 1 to 10

(multiplication-table (get-number))

Output:
Code 3: Count of positives/ sum of Negatives.

(define (count-positives-sum-negatives n)
(if (<= n 0)
(display "[]")
(let loop ((i 1) (count 0) (sum 0))
(if (> i n)
(begin
(display "Count of positives: ") (display
count) (newline)
(display "Sum of negatives: ") (display sum)
(newline))
(let ((value (read)))
(loop (+ i 1)
(if (> value 0) (+ count 1) count)
(if (< value 0) (+ sum value)
sum)))))))

(display "Enter the number of elements: ")


(count-positives-sum-negatives (read))
Output:

Name : Abdulmajeed Mohammed Alsharif

Code 1: Day of the Week Finder


(define (day-of-week day month year)
(if (< month 3)
(begin
(set! month (+ month 12))
(set! year (- year 1))))
(let* ((century (quotient year 100))
(year-of-century (modulo year 100))
(week-day (modulo (+ day
(quotient (* 13 (+ month
1)) 5)
year-of-century
(quotient year-of-century
4)
(quotient century 4)
(* -2 century))
7))
(week-days '("Saturday" "Sunday" "Monday"
"Tuesday" "Wednesday" "Thursday" "Friday")))
(list-ref week-days (modulo week-day 7))))

(display "Enter the day: ") (define day (read))


(display "Enter the month: ") (define month (read))
(display "Enter the year: ") (define year (read))

(display "✅ The day of the week is: ")


(display (day-of-week day month year))
(newline)

Output:

Code 2: Temperature Converter

(define (celsius-to-fahrenheit celsius)


(+ (* celsius 9/5) 32))

(define (celsius-to-kelvin celsius)


(+ celsius 273.15))
(display "Enter temperature in Celsius: ") (define
celsius (read))

(display "Temperature in Fahrenheit: ")


(display (celsius-to-fahrenheit celsius))
(display " °F\n")

(display "Temperature in Kelvin: ")


(display (celsius-to-kelvin celsius))
(display " K\n")

Output:

Code 3: Guess the Number game

(define (guess-the-number)
(define secret (+ 1 (random 100)))
(define (game-loop)
(display "\n Enter your guess: ")
(flush-output)
(let ((guess (read)))
(cond
((< guess secret)
(display "The secret number is higher!")
(game-loop))
((> guess secret)
(display "The secret number is lower!")
(game-loop))
(else
(display "🎉 Congratulations! You guessed the
correct number!")))))
(display "Welcome to the Guessing Game!\n")
(display "Try to guess the secret number between 1 and
100\n")
(game-loop))

Output:

Name : Bader Khalaf Almutairi

Code 1: Number To Words program:

(define (print-number-in-words num)


(cond ((= num 1) (display "One"))
((= num 2) (display "Two"))
((= num 3) (display "Three"))
((= num 4) (display "Four"))
((= num 5) (display "Five"))
((= num 6) (display "Six"))
((= num 7) (display "Seven"))
((= num 8) (display "Eight"))
((= num 9) (display "Nine"))
((= num 10) (display "Ten"))
(else (display "Out of range"))))
(display "Enter a number between 1 and 10: ")
(let ((number (read)))
(display "The number in words is: ")
(print-number-in-words number)
(newline))
Output:

Code 2: Prime Number Checker:

(define (prime? number)


(cond ((<= number 1) #f)
((= number 2) #t)
((even? number) #f)
(else (let loop ((i 3))
(cond ((>= (* i i) number) #t)
((= (modulo number i) 0) #f)
(else (loop (+ i 2))))))))

(display "Enter a number: ")


(let ((number (read)))
(if (prime? number)
(display (string-append (number->string number) " is a prime
number."))
(display (string-append (number->string number) " is not a prime
number."))))

Output:
Code 3: Count Characters:

(define (count-characters sentence)


(define (count-char chars)
(if (null? chars)
0
(+ (if (char=? (car chars) #\space) 0 1) (count-char (cdr
chars)))))
(count-char (string->list sentence)))

(display "Enter a sentence: ")


(let ((sentence (read-line)))
(display (string-append "The number of characters (excluding spaces)
is: "
(number->string (count-characters
sentence)))))

Output:
Name : Mohammed Fahad Al-Motawa

Program 1: Shapes Calculator


#lang scheme
(define (main)
(display " | Shape Calculator Options |")
(newline)
(display " _____________________________________")
(newline)
(display " | 1: Calculate Area |")
(newline)
(display " | 2: Calculate Perimeter |")
(newline)
(display " | 0: Exit |")
(newline)
(display " _____________________________________")
(newline)

(let ((choice (read)))


(cond
((= choice 0)
(display "Thank you for using shape calculator")
(newline))

((= choice 1)
(area-calc))

((= choice 2)
(perimeter-calc))
(else
(display "Invalid choice. Please try again.")
(newline)))))
(define (area-calc)
(display " | Area Calculation Options |")
(newline)
(display " | 1: Triangle | (requires height and
base)")
(newline)
(display " | 2: Circle | (requires radius)")
(newline)
(display " | 3: Rectangle | (requires length and
width)")
(newline)

(let ((shape (read)))


(cond
((= shape 1)
(display "Enter Height: ")
(let ((height (read))
(base (begin
(display "Enter Base: ")
(read))))
(display "Triangle Area = ")
(display (* 0.5 base height))
(newline)))

((= shape 2)
(display "Enter Radius: ")
(let ((radius (read)))
(display "Circle Area = ")
(display (* 3.14 radius radius))
(newline)))

((= shape 3)
(display "Enter Length: ")
(let ((length (read))
(width (begin
(display "Enter Width: ")
(read))))
(display "Rectangle Area = ")
(display (* length width))
(newline)))
(else
(display "Invalid option for area calculation.")
(newline)))))

(define (perimeter-calc)
(display " | Perimeter Calculation Options |")
(newline)
(display " | 1: Triangle | (requires lengths of
three sides)")
(newline)
(display " | 2: Circle | (requires radius)")
(newline)
(display " | 3: Rectangle | (requires length and
width)")
(newline)

(let ((shape (read)))


(cond
((= shape 1)
(display "Enter Side Lengths (a b c): ")
(let ((N1 (read))
(N2 (read))
(N3 (read)))
(display "Triangle Perimeter = ")
(display (+ N1 N2 N3))
(newline)))

((= shape 2)
(display "Enter Radius: ")
(let ((radius (read)))
(display "Circle Circumference = ")
(display (* 2 3.14 radius))
(newline)))

((= shape 3)
(display "Enter Length: ")
(let ((length (read))
(width (begin
(display "Enter Width: ")
(read))))
(display "Rectangle Perimeter = ")
(display (* 2 (+ length width)))
(newline)))
(else
(display "Invalid option for perimeter calculation.")
(newline)))))

(main)

Output:

Program 2: Books Library


#lang scheme
(define books '())

(define (add-book)
(if (< (length books) 50)
(let* ((title (begin (display "Enter the Title: ") (read-line)))
(author (begin (display "Enter the Author name: ") (read-
line)))
(date (begin (display "Enter the Publication date: ")
(read-line))))
(set! books (append books (list (list title author date))))
(display "Book added successfully.") (newline))
(display "The library is full.")))
(define (display-books)
(if (null? books)
(begin
(display "The library is empty.") (newline))
(let loop ((bks books) (index 1))
(unless (null? bks)
(display "Book ") (display index) (display ":") (newline)
(display "Title: ") (display (car (car bks))) (newline)
(display "Author: ") (display (cadr (car bks))) (newline)
(display "Publication Date: ") (display (caddr (car bks)))
(newline)
(display "(Press Enter to continue)") (newline)
(read-line)
(loop (cdr bks) (+ index 1))))))

(define (delete-book)
(display "Enter the index of the book to delete: ") (newline)
(let ((index (read)))
(read-line) ;; Consume newline after read
(if (and (> index 0) (<= index (length books)))
(begin
(set! books (append (take books (- index 1)) (drop books
index)))
(display "Book deleted successfully.") (newline))
(display "Invalid index."))))

(define (library-menu)
;; Initialization before loop
(display "Welcome to the Book Library System!") (newline)
(display "Initializing library...") (newline)
(let loop ()
(display "\n1. Add Book\n2. Display Books\n3. Delete Book\n4.
Exit\n")
(display "Enter your choice: ")
(let ((choice (read)))
(read-line) ;; Consume newline after reading choice
(cond
((= choice 1) (add-book))
((= choice 2) (display-books))
((= choice 3) (delete-book))
((= choice 4) (begin
(display "Thanks for using the program.")
(newline)
(display "(Press Enter to continue)")
(newline)
(read-line)
(exit)))
(else (display "Invalid choice, try again."))))
(loop)))

(library-menu)
Output:

Program 3: Parking Reservation


#lang scheme

(define (trim-string str)


(string-trim str))

(define (parking-reservation)
(define plate "")
(define hours 0)
(define parkClass "")
(define rate 0.0)
(define invoiceBeforeTax 0.0)
(define tax 0.0)
(define totalAfterTax 0.0)

(display "Enter the car plate number: ")


(set! plate (read-line))
(display "Parking Classes and Proximity:\n")
(display "Gold: $5.00 per hour (10m~ close to the building)\n")
(display "Silver: $3.00 per hour (50m~ from the building)\n")
(display "Bronze: $2.00 per hour (100m~ from the building)\n\n")
(display "Enter the number of hours: ")
(set! hours (read))
(let loop ()
(display "Enter the class of the park (Gold/Silver/Bronze): ")
(set! parkClass (trim-string (read-line)))

(if (string=? parkClass "")


(begin
(loop))
(if (or (string-ci=? parkClass "Gold")
(string-ci=? parkClass "Silver")
(string-ci=? parkClass "Bronze"))
(begin
(cond
[(string-ci=? parkClass "Gold") (set! rate 5.0)]
[(string-ci=? parkClass "Silver") (set! rate 3.0)]
[(string-ci=? parkClass "Bronze") (set! rate 2.0)])
(begin
(set! invoiceBeforeTax (* hours rate))
(set! tax (* 0.15 invoiceBeforeTax))
(set! totalAfterTax (+ invoiceBeforeTax tax))

(display "---------------------------\n")
(display "Invoice for Parking:\n")
(display (string-append "Car Plate: " plate "\n"))
(display (string-append "Hours: " (number->string hours)
"\n"))
(display (string-append "Class: " parkClass "\n"))
(display (string-append "Invoice Before Tax: $" (number-
>string invoiceBeforeTax) "\n"))
(display (string-append "Tax (15%): $" (number->string
tax) "\n"))
(display (string-append "Total After Tax: $" (number-
>string totalAfterTax) "\n"))
(display "---------------------------\n")))
(begin
(display "Invalid park class entered. Please try again.\
n")
(loop))))))

(parking-reservation)

Output:
Part 3 : prolog .

Naif suliman alharbi

Code 1:Calculate the Perimeter of a Square

calculate_perimeter :-
write('Enter the side length of the square: '),
read(Side),
Perimeter is 4 * Side,
write('The perimeter of the square is: '),
write(Perimeter), nl.
Outpot :
Code 2:Check if a Number is Even or Odd

check_even_or_odd :-
write('Enter a number: '),
read(Num),
( Num mod 2 =:= 0
-> write('The number is even.')
; write('The number is odd.')
), nl.

Outpot:

Code 3:Choose Coffee or Tea


coffee_or_tea :-
writeln('Do you want Coffee or Tea? (c/t)'),
read(Choice),
(
(Choice = 'c'; Choice = 'C') -> writeln('Here is
your Coffee!');
(Choice = 't'; Choice = 'T') -> writeln('Here is
your Tea!');
writeln('Invalid choice!')
).
Outpot:
Name : Nayil Fahhad ALharbi

Code 1: rock paper scissors game.(Sum of Squares program not


Running so, the example has changed to rock paper scissors game.)

rock_paper_scissors :-

writeln('Player 1, enter Rock, Paper, or Scissors:'),


read_line_to_string(user_input, P1Input),

writeln('Player 2, enter Rock, Paper, or Scissors:'),


read_line_to_string(user_input, P2Input),

string_lower(P1Input, P1),

string_lower(P2Input, P2),

( (P1 = "rock"; P1 = "paper"; P1 = "scissors"),

(P2 = "rock"; P2 = "paper"; P2 = "scissors") ->

( P1 = P2 ->

writeln('Draw!')

; ( (P1 = "rock", P2 = "scissors")

; (P1 = "scissors", P2 = "paper")

; (P1 = "paper", P2 = "rock") ) ->

writeln('Player 1 won!')

; writeln('Player 2 won!') )

; writeln('Invalid input! Please enter only "Rock", "Paper", or


"Scissors".')

).

:- rock_paper_scissors.

Outpot:
Code 2: Multiplication table for number.

start :-

writeln('Enter a number (1 to 10):'),


read_line_to_string(user_input, Input),

number_string(N, Input),

( N < 1 ; N > 10 ->

writeln('Invalid input! Please enter a number between 1


and 10.')

print_table(1, N)

).

print_table(11, _) :- !.

print_table(I, N) :-

Product is I * N,

format('~w * ~w = ~w~n ', [I, N, Product]),

I1 is I + 1,

print_table(I1, N).

:- start.

Outpot:
Code 3: Count of positives/ sum of Negatives.

start :-

writeln('Enter the number of elements:'),


read_line_to_string(user_input, Input),

number_string(N, Input),

( N =< 0 ->

writeln('[]')

loop(N, 0, 0)

).

loop(0, Count, Sum) :-

format(' [~w, ~w]~n ', [Count, Sum]).

loop(N, Count, Sum) :-

N > 0,
read_line_to_string(user_input, Input),
number_string(Value, Input),

( Value > 0 ->

NewCount is Count + 1,

NewSum = Sum

; Value < 0 ->

NewCount = Count,

NewSum is Sum + Value

; % Value = 0

NewCount = Count,

NewSum = Sum

),

N1 is N - 1,

loop(N1, NewCount, NewSum).

:- start.

Outpot:

You might also like