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

Algo Bann

Here is pseudocode for a function that takes a number and returns "Fizz", "Buzz" or "FizzBuzz" based on the number being divisible by 3, 5 or both: Function FizzBuzz(number) If number is divisible by 3 and 5 Return "FizzBuzz" Else If number is divisible by 3 Return "Fizz" Else If number is divisible by 5 Return "Buzz" Else Return number as a string End If End Function To call it: result = FizzBuzz(15) Print result This would print "FizzBuzz" since 15 is divisible by both 3

Uploaded by

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

Algo Bann

Here is pseudocode for a function that takes a number and returns "Fizz", "Buzz" or "FizzBuzz" based on the number being divisible by 3, 5 or both: Function FizzBuzz(number) If number is divisible by 3 and 5 Return "FizzBuzz" Else If number is divisible by 3 Return "Fizz" Else If number is divisible by 5 Return "Buzz" Else Return number as a string End If End Function To call it: result = FizzBuzz(15) Print result This would print "FizzBuzz" since 15 is divisible by both 3

Uploaded by

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

Ques 1

function add_numbers(number1, number2)


sum = number1 + number2
return sum

# Call the function with parameters 5 and 7


result = add_numbers(5, 7)

# Output the result


print(result)
Ques 2
function guess_the_number()
// Generate a random number between 1 and 100
target_number = generate_random_number(1, 100)
// Initialize a variable to keep track of the user's guess
user_guess = 0
// Loop until the user guesses the correct number
while user_guess != target_number
// Ask the user for their guess
user_guess = input("Guess the number between 1 and 100: "
// Convert the user's input to an integer
user_guess = to_integer(user_guess)
// Check if the user's guess is too high or too low
if user_guess < target_number
print("Higher! Try again.")
else if user_guess > target_number
print("Lower! Try again.")
// Congratulate the user for guessing the correct number
print("Congratulations! You guessed the correct number:", target_number)
// Call the function to start the game
guess_the_number()
Adjust code
function guess_the_number()
// Generate a random number between 1 and 100
target_number = generate_random_number(1, 100)
// Initialize variables to keep track of the user's guess and attempts
user_guess = 0
attempts = 0
// Loop until the user guesses the correct number
while user_guess != target_number
// Ask the user for their guess
user_guess = input("Guess the number between 1 and 100: ")
// Convert the user's input to an integer
user_guess = to_integer(user_guess)
// Increment the attempts count
attempts = attempts + 1
// Check if the user's guess is too high or too low
if user_guess < target_number
print("Higher! Try again.")
else if user_guess > target_number
print("Lower! Try again.")
// Congratulate the user for guessing the correct number and display the number of attempts
print("Congratulations! You guessed the correct number:", target_number)
print("Number of attempts:", attempts)
// Call the function to start the game
guess_the_number()
Ques 3
function roll_dice()
// Roll two six-sided dice
die1 = random_integer(1, 6)
die2 = random_integer(1, 6)

// Calculate the sum of the two dice


sum = die1 + die2

return sum

// Call the function to roll the dice and get the sum
dice_sum = roll_dice()

// Output the sum of the two dice


print("Sum of two dice:", dice_sum)
Adjust
function roll_dice(roll1, roll2)
// Calculate the sum of the two dice rolls
sum = roll1 + roll2

// Return the sum


return sum

// Simulate rolling two six-sided dice


roll1 = random_integer(1, 6)
roll2 = random_integer(1, 6)

// Call the function to calculate the sum of the dice rolls


dice_sum = roll_dice(roll2, roll2)

// Output the sum of the two dice rolls


print("Sum of two dice:", dice_sum)
Ques 4
function coin_flip_game()
// Define the possible outcomes (head and tails) in an array
possible_outcomes = ["head", "tails"]

// Simulate the computer's coin flip by randomly selecting an outcome


computer_choice = random_choice(possible_outcomes)

// Ask the user for their guess (head or tails)


user_guess = input("Guess the coin flip outcome (head or tails): ")

// Check if the user's guess is correct and provide feedback


if user_guess == computer_choice
print("Congratulations! You guessed correctly.")
else
print("Sorry, you guessed wrong. The correct answer was:", computer_choice)

// Call the function to play the coin flip game


coin_flip_game()
Ques 5
function generate_lottery_numbers()
// Initialize an empty list to store the lottery numbers
lottery_numbers = []
// Loop to generate 6 unique random numbers
while length(lottery_numbers) < 6
// Generate a random number between 1 and 49
random_number = random_integer(1, 49)

// Check if the random number is not already in the list


if random_number not in lottery_numbers
// Add the unique random number to the list
add_to_list(lottery_numbers, random_number)

return lottery_numbers

// Call the function to generate lottery numbers


lottery_ticket = generate_lottery_numbers()

// Output the lottery numbers


print("Lottery numbers:", lottery_ticket)
Ques 6
// Define two global variables
global var dividend
global var divisor

// Function to perform division and print results


function divide_and_print()
// Check if the divisor is zero to avoid division by zero error
if divisor == 0
print("Error: Division by zero is not allowed.")
else
// Calculate the quotient and remainder
quotient = dividend / divisor
remainder = dividend % divisor

// Print the results


print("Quotient:", quotient)
print("Remainder:", remainder)

// Input the values of the global variables (dividend and divisor)


dividend = input("Enter the dividend: ")
divisor = input("Enter the divisor: ")

// Call the function to perform division and print results


divide_and_print()
Ques 7
// Define a global list of numbers
global list numbers
// Function to calculate and return the average
function calculate_average()
// Check if the list is empty to avoid division by zero error
if is_empty(numbers)
print("Error: The list is empty.")
else
// Calculate the sum of the numbers in the list
sum = 0
for each number in numbers
sum = sum + number
// Calculate the average
average = sum / length(numbers)
return average
// Input the list of numbers
numbers = input("Enter a list of numbers: ")

// Call the function to calculate the average


result = calculate_average()

// Check if there was an error or display the average


if result is not empty
print("Average:", result)
Ques 8
procedure timesTables(integerValue)
// Check if the inputValue is a positive integer
if integerValue <= 0
print("Please enter a positive integer.")
else
// Display the times tables for the entered integer
print("Times Tables for", integerValue)
for multiplier from 1 to 10
result = integerValue * multiplier
print(integerValue, "x", multiplier, "=", result)

// Prompt the user to enter an integer


inputValue = input("Enter a positive integer: ")

// Call the timesTables procedure with the user's input


timesTables(inputValue)
f
Exercise 1
-Solution-
Begin
variable: A,B,C : integers
print “Enter A”
read A
print “Enter B”
read B
CA
AB
BC
print(“The new values of A and B are A=“ + A+ “,B=“ + B
End

Dana Sobh
Exercise 1
-Output-
Enter A: 5
Enter B: 6
The new value of A and B are A= 6, B=5

Dana Sobh
Exercise 2
-Solution-
Begin
variable: A,B,C : integers
print “Enter A, B and C”
read A,B,C
BA
CB
AC
print(“The new values of A=“ + A+ “,B=“ + B + “C=“ + C
End
Dana Sobh
Exercise 2
-Output-
Enter A, B and C
5, 8 ,9
The new value of A=9 B=5 C=8

Dana Sobh
Exercise 3
-Solution-
Variable t, r : integer
d,h,m,s :integer
Begin
print(“ Enter the time in seconds”)
read t
d  t/(24*60*60)
r  t%(24*60*60)
h  r/(60*60)
r  r%(60*60)
m  r/60
s  r%60
print(“The number of days=“ +d+ “h=“+h+ “m=“ +m+ “s=“ +s
End

Dana Sobh Back to slide 40


Exercise 3
-Output-
Enter the time in second 123560
The number of days=1 h= 10 m=19 s=20

Dana Sobh
Exercise 3
-Flowchart-

Dana Sobh
Exercise 4
-Solution-
variable A,B,C : real
output d:real
Begin
print(“Enter A”)
read A
print(“Enter B”)
read B
print(“Enter C”)
read C
d  A*B*C
print(“The result is “ +d)
End

Dana Sobh
Exercise 4
-Flowchart-

Dana Sobh
Exercise 5
-Solution-
variable a,b,c,d,e : real
output f:real
Begin
print(“Enter 5 numbers”)
read a,b,c,d,e
f  (a+b+c+d+e)/5
print(“The result is:” +f)
End

Dana Sobh
Exercise 5
-Flowchart-

Dana Sobh
Exercise 6
-Solution-
variable x,y,A: real
Begin
print(“Enter x”)
read x
print(“Enter y”)
read y
A sqrt(x*x + y*y)
print(“The result is:” +A)
End
Dana Sobh
Exercise 6
-Flowchart-

Dana Sobh
Write an algorithm that asks the user to enter his country and then display his language

variable country: string


Begin
print(“Enter your country ”)
Read country
switch country do
case “USA”:
case “UK”:
print “English”;
break;
case “Lebanon”:
print “Arabic”;
break;
case “Paris”:
print “Francais”;
break;
otherwise
print “Not valid”
End switch
Write pseudocode to generate the first N
numbers in the Fibonacci sequence.
Function Fibonacci(N)
If N <= 0
Return Empty List
Else If N == 1
Return [0]
Else If N == 2
Return [0, 1]
Else
Initialize FibonacciList as a List with [0, 1]
For i from 3 to N (inclusive)
NextFib = FibonacciList[i-2] + FibonacciList[i-1]
Append NextFib to FibonacciList
End For
Return FibonacciList
End If
End Function
Write pseudocode for a function that takes a number as an argument and returns "Fizz", "Buzz"
or "FizzBuzz".

If the number is a multiple of 3 the output should be "Fizz".


If the number given is a multiple of 5, the output should be "Buzz".
If the number given is a multiple of both 3 and 5, the output should be "FizzBuzz".
If the number is not a multiple of either 3 or 5, the number should be output on its own as
shown in the examples below.

The output should always be a string even if it is not a multiple of 3 or 5. Examples


fizz_buzz(3) ➞ "Fizz" fizz_buzz(5) ➞ "Buzz"
fizz_buzz(15) ➞ "FizzBuzz" fizz_buzz(4) ➞ "4"
sln
FUNCTION fizz_buzz(n)
IF n MODULO 15 IS EQUAL TO 0 THEN
RETURN "FizzBuzz"
ELSE IF n MODULO 3 IS EQUAL TO 0 THEN
RETURN "Fizz"
ELSE IF n MODULO 5 IS EQUAL TO 0 THEN
RETURN "Buzz"
ELSE
RETURN STRING(n)
END IF
END FUNCTION
Example
-If statement-
• Question 11

Dana Sobh
Hint

Dana Sobh
Solution
• Solution of Question 11:

variable A: int
Begin
print(“Enter a number ”)
read A
fourthDigit  A%10
thirdDigit  (A/10)%10
secondDigit  (A/100)%10
fistDigit  (A/1000)%10
IF fistDigit + secondDigit == thirdDigit + fourthDigit then

print(“It is a lucky number”)


else

print(“It is not a lucky number”)


End IF
End Dana Sobh
Example
-While loop-
• Question
• Write a program that generates a random number and
asks the user to guess what the number is. If the user's
guess is higher than the random number, the program
should display "Too high, try again." If the user's guess is
lower than the random number, the program should
display "Too low, try again." The program should use a loop
that repeats until the user correctly guesses the random
number.

Dana Sobh
Example
-While loop-
• Solution of Question

variable num , guess , tries: int


Begin
tries = 0

do
print “Enter a guess between 1 and 100”r
read guess
if (guess > num)
print(“Too high! Try Again ”)
else
print(“Too low! Try Again”)
tries ++
while (guess != num)
print(“Correct! You got it in” + tries + “guesses”)
End
Dana Sobh
Question

Using For loop, make this output

Dana Sobh
Solution
Begin
Var i, j, n: int
Print(“Enter number of rows”)
Read n
For(i=1;i<=n ;i++){
for(j=1;j<=i; j++){
print(j)
}
print(“\n”)
}
End

Dana Sobh
Question

Using For loop, make this output

Dana Sobh
Solution
Begin
Var i, j, n: int
Print(“Enter number of rows”)
Read n
For(i=n ;i>=1;i--){
for(j=i ; j>=1;j--){
print(j)
}
print(“\n”)
}
End

Dana Sobh
Question
• Using nested while loop

Dana Sobh
Solution
Begin
Var i=0 : int
While( i <10){
int j=0
while(j<=i){
print(*)
j++
}
i++
}
Dana Sobh
Question
Using nested for loop

Dana Sobh
Solution
Begin
Var i, j, n: int
Print(“Enter number of rows”)
Read n
For(i=1;i<=n ;i++){
for(j=1;j<= n - i; j++){
print(“ ”)
for(j= 1; j<= i ; j++){
print(“*”)
}
}
print(“\n”)
}
End

Dana Sobh
Question

Dana Sobh
Solution
2 *i -1

Begin
Var i, j, n: int
Print(“Enter number of rows”)
Read n
For(i=1;i<=n ;i++){
for(j=1;j<= n - i; j++){
print( )
for(j= 1; j<= 2*i -1 ; j++){
print(“*”)
}
}
print(“\n”)
}
End

Dana Sobh
•Write a function that takes a list of numbers and returns a list with two elements:

•The first element should be the sum of all even numbers in the list.
•The second element should be the sum of all odd numbers in the list.

•Example
•sum_odd_and_even([1, 2, 3, 4, 5, 6]) ➞ [12, 9] # 2 + 4 + 6 = 12 and 1 + 3 + 5 = 9

•sum_odd_and_even([-1, -2, -3, -4, -5, -6]) ➞ [-12, -9])

•sum_odd_and_even([0, 0]) ➞ [0, 0])
FUNCTION sum_odd_and_even(numbers)
// Initialize sums
sum_even = 0
sum_odd = 0

// Iterate over the numbers


FOR EACH num IN numbers DO
// Check if the number is even or odd and update the appropriate sum
IF num MODULO 2 IS EQUAL TO 0 THEN
sum_even = sum_even + num
ELSE
sum_odd = sum_odd + num
END IF
END FOR

// Return a list with the sums


RETURN [sum_even, sum_odd]
END FUNCTION

// Test the function with your examples


PRINT sum_odd_and_even([1, 2, 3, 4, 5, 6]) // ➞ [12, 9]
PRINT sum_odd_and_even([-1, -2, -3, -4, -5, -6]) // ➞ [-12, -9]
PRINT sum_odd_and_even([0, 0]) // ➞ [0, 0]
•Write pseudocode for a program that will allow the user to enter the radius of a circle and the area of
a square. A function should then return True if the circumference of the circle is greater than the
square's perimeter and False if the square's perimeter is greater than the circumference of the circle.
•Examples
•circle_or_square(16, 625) ➞ True circle_or_square(5, 100) ➞ False
•circle_or_square(8, 144) ➞ True
FUNCTION circle_or_square(radius, area)
// Calculate the circumference of the circle
circumference = 2 * PI * radius

// Calculate the side length of the square


side_length = SQUARE_ROOT(area)

// Calculate the perimeter of the square


perimeter = 4 * side_length

// Compare the circumference and perimeter


IF circumference > perimeter THEN
RETURN True
ELSE
RETURN False
END IF
END FUNCTION

// Test the function with your examples


PRINT circle_or_square(16, 625) // ➞ True
PRINT circle_or_square(5, 100) // ➞ False
PRINT circle_or_square(8, 144) // ➞ True

You might also like