"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Wednesday, September 4, 2024

Assignment :Control Structures

Class 4: Control Structures - Part 1

(Conditional Statements: if, else if, else, switch)

Assignment 1: Check if a Number is Positive, Negative, or Zero

Code:

<?php

$number = 10;

if ($number > 0) {

    echo "The number is positive.";

} elseif ($number < 0) {

    echo "The number is negative.";

} else {

    echo "The number is zero.";

}

?>

 

 Explanation: This script checks if a given number is positive, negative, or zero using if, else if, and else statements.


Assignment 2: Grade Assignment Based on Score

Code:

<?php

$score = 85;

if ($score >= 90) {

    echo "Grade: A";

} elseif ($score >= 80) {

    echo "Grade: B";

} elseif ($score >= 70) {

    echo "Grade: C";

} else {

    echo "Grade: D";

}

?>

 

 Explanation: This script assigns a grade based on a student's score using conditional statements.


Assignment 3: Day of the Week Using switch

Code:

<?php


$dayNumber = 3;

switch ($dayNumber) {

    case 1:

        echo "Monday";

        break;

    case 2:

        echo "Tuesday";

        break;

    case 3:

        echo "Wednesday";

        break;

    case 4:

        echo "Thursday";

        break;

    case 5:

        echo "Friday";

        break;

    case 6:

        echo "Saturday";

        break;

    case 7:

        echo "Sunday";

        break;

    default:

        echo "Invalid day number.";

}

?>

 

 Explanation: This script uses a switch statement to display the name of the day based on the number provided.


Assignment 4: Check if a Year is a Leap Year

Code:

<?php

$year = 2024;

 if (($year % 4 == 0 && $year % 100 != 0) || ($year % 400 == 0)) {

    echo "$year is a leap year.";

} else {

    echo "$year is not a leap year.";

}

?>

 

 Explanation: This script checks if a given year is a leap year using conditional statements.


Assignment 5: Check if a Number is Even or Odd

Code:

<?php

$number = 7;

 if ($number % 2 == 0) {

    echo "The number is even.";

} else {

    echo "The number is odd.";

}

?>

 

 Explanation: This script checks if a number is even or odd using an if-else statement.

Assignment 6: Categorize Age Group

Code:

<?php


$age = 25;

 if ($age < 13) {

    echo "Child";

} elseif ($age >= 13 && $age < 20) {

    echo "Teenager";

} elseif ($age >= 20 && $age < 60) {

    echo "Adult";

} else {

    echo "Senior";

}

?>

 

 Explanation: This script categorizes a person into different age groups based on their age using if, else if, and else statements.


Assignment 7: Check the Largest of Three Numbers

Code:


<?php

$a = 10;

$b = 20;

$c = 15;

 if ($a > $b && $a > $c) {

    echo "$a is the largest.";

} elseif ($b > $a && $b > $c) {

    echo "$b is the largest.";

} else {

    echo "$c is the largest.";

}

?>

 

 Explanation: This script determines the largest of three numbers using conditional statements.


Assignment 8: Check Vowel or Consonant Using switch

Code:

<?php

$letter = 'e';

 switch ($letter) {

    case 'a':

    case 'e':

    case 'i':

    case 'o':

    case 'u':

        echo "$letter is a vowel.";

        break;

    default:

        echo "$letter is a consonant.";

}

?>

 

Step by step Explanation:

1. Variable Assignment:

$letter = 'e';

The variable $letter is assigned the value 'e', which is the letter to be checked.

2. switch Statement:

switch ($letter) {

    case 'a':

    case 'e':

    case 'i':

    case 'o':

    case 'u':

        echo "$letter is a vowel.";

        break;

    default:

        echo "$letter is a consonant.";

}

The switch statement evaluates the value of $letter and executes the appropriate block of code based on its value.

a. case Blocks:

Each case represents a possible value for $letter. If $letter matches one of these values, the corresponding block of code will be executed.

case 'a':

case 'e':

case 'i':

case 'o':

case 'u':

    echo "$letter is a vowel.";

    break;

The case 'a':, case 'e':, case 'i':, case 'o':, and case 'u': represent the vowels.

If $letter matches any of these cases (i.e., if $letter is 'a', 'e', 'i', 'o', or 'u'), the message "$letter is a vowel." will be printed.

break; ensures that the program exits the switch statement after a match is found, preventing it from continuing to the next cases.

In this example, $letter is 'e', so this block will execute, printing "e is a vowel.".

b. default Block:

default:

    echo "$letter is a consonant.";

The default block is executed if none of the case values match. It acts as a fallback for all other letters that are not vowels.

If $letter is a consonant (i.e., not 'a', 'e', 'i', 'o', or 'u'), the message "$letter is a consonant." will be printed.

In this case, since $letter is 'e' (a vowel), the default block will not execute.

3. Output:

Since $letter = 'e', and 'e' is a vowel, the output will be:

e is a vowel.

Summary:

The script checks whether $letter is a vowel (a, e, i, o, u) using a switch statement.

If the letter is a vowel, it prints "$letter is a vowel.".

If the letter is not a vowel (i.e., a consonant), it prints "$letter is a consonant.".

In this case, since $letter = 'e', the output is "e is a vowel.".

Assignment 9:

 Determine Season Based on Month

Write a PHP program that takes a numeric value representing a month (1 for January, 2 for February, etc.) and outputs the corresponding season based on the following conditions:

March (3) to May (5) is Spring.

June (6) to August (8) is Summer.

September (9) to November (11) is Autumn.

December (12) to February (2) is Winter.

Test your program by setting the month variable to 4. What season is displayed?


Code:

<?php

$month = 4;

if ($month >= 3 && $month <= 5) {

    echo "Spring";

} elseif ($month >= 6 && $month <= 8) {

    echo "Summer";

} elseif ($month >= 9 && $month <= 11) {

    echo "Autumn";

} else {

    echo "Winter";

}

?>

 

Step by step Explanation:

1. Variable Assignment:

$month = 4;

The variable $month is assigned the value 4, which represents the month of April.

2. Conditional Statements (if-elseif-else):

The program uses a series of if, elseif, and else statements to check the value of $month and output the appropriate season.

a. First Condition: Spring

if ($month >= 3 && $month <= 5) {

    echo "Spring";

}

This condition checks if $month is between 3 (March) and 5 (May), inclusive.

If the month is within this range, it means it's Spring.

Since $month = 4 (April), which falls within this range, the condition is true, so the program prints:

Spring

b. Second Condition: Summer

elseif ($month >= 6 && $month <= 8) {

    echo "Summer";

}

This condition checks if $month is between 6 (June) and 8 (August).

If true, the program will print "Summer". However, since $month = 4, this condition is false, and the program does not execute this block.

c. Third Condition: Autumn

elseif ($month >= 9 && $month <= 11) {

    echo "Autumn";

}

This condition checks if $month is between 9 (September) and 11 (November).

If true, it prints "Autumn". In this case, since $month = 4, this condition is also false, and the program skips this block.

d. Default Condition: Winter

else {

    echo "Winter";

}

This else block handles all cases where the month is either in December (12), January (1), or February (2).

Since none of the previous conditions matched, this block would be executed if $month was outside the specified ranges.

However, since $month = 4 (which satisfied the Spring condition), this block is not executed.

3. Output:

Since $month = 4 (April), the first condition is satisfied, and the program outputs:

Spring

Summary:

  1. The program checks the value of $month to determine the corresponding season.
  2. If the month is between March (3) and May (5), it outputs "Spring".
  3. If it's between June (6) and August (8), it outputs "Summer".
  4. If it's between September (9) and November (11), it outputs "Autumn".
  5. For all other months (December, January, and February), it outputs "Winter".
  6. Since $month = 4 (April), the output is "Spring".

Assignment 10: Check if a Character is a Digit

Write a PHP program that checks whether a given character is a digit. Use the ctype_digit() function to determine if the character is a numeric digit (0–9). Test your program with the character '7'. What will be the output of the program?

Code:

<?php

$char = '7';

 if (ctype_digit($char)) {

    echo "$char is a digit.";

} else {

    echo "$char is not a digit.";

}

?>

 

Explanation of the Code:

1. Variable Assignment:

$char = '7';

The variable $char is assigned the value '7', which is a string containing a single character.
2. Conditional Statement:
if (ctype_digit($char)) {
    echo "$char is a digit.";
} else {
    echo "$char is not a digit.";
}
a. Function ctype_digit($char):
The ctype_digit() function checks whether the given character or string consists of only numeric digits (0–9).
In this case, $char = '7', which is a numeric character, so ctype_digit($char) will return true.
b. if Block:
Since ctype_digit($char) returns true, the code inside the if block will execute:
echo "$char is a digit.";
This outputs:
7 is a digit.
c. else Block:
The else block would only execute if the ctype_digit($char) condition were false, meaning the character is not a numeric digit. In this case, it is not executed because $char = '7' is a digit.
3. Output:
Since '7' is a digit, the output of this program will be:
7 is a digit.
Summary:

  1. The program checks if the variable $char contains a numeric digit using the ctype_digit() function.
  2. If $char is a digit, it prints "$char is a digit.".
  3. Otherwise, it prints "$char is not a digit.".
  4. Since $char = '7', which is a digit, the output is "7 is a digit.".


Class 5: Control Structures - Part 2

(Loops: for, while, do...while, Loop Control: break, continue)


Assignment 11: Print the First 10 Natural Numbers Using a for Loop

Code:

<?php

for ($i = 1; $i <= 10; $i++) {

    echo $i . " ";

}

?>

 

 Explanation: This script prints the first 10 natural numbers using a for loop.


Assignment 12: Print Even Numbers Between 1 and 20 Using a while Loop

Code:

<?php

$i = 2;

while ($i <= 20) {

    echo $i . " ";

    $i += 2;

}

?>

 

 Explanation: This script prints all even numbers between 1 and 20 using a while loop.


Assignment 13: Prompt Until Negative Number Using do...while Loop

Write a PHP program that repeatedly asks the user to enter a number until they enter a negative number. The program should use a do-while loop to keep asking for input, and once a negative number is entered, it should display a message saying "You entered a negative number." What will be the output when the user enters 5, 2, and -1 sequentially?

Code:

<?php


do {

    $number = readline("Enter a number: ");

} while ($number >= 0);

 echo "You entered a negative number.";

?>

 

Explanation of the Code:

1. do-while Loop:

a. do Block:

The do block contains the code that will be executed at least once, regardless of the condition.

The program prompts the user for input using the readline() function and stores the value in the $number variable:

$number = readline("Enter a number: ");

readline() displays the message "Enter a number: " and waits for user input.

After the user inputs a number, it is stored in the $number variable.

b. while Condition:

After the do block is executed, the program checks the condition in the while statement:

while ($number >= 0);

If the user enters a non-negative number ($number >= 0), the loop repeats, and the program asks for another number.

If the user enters a negative number, the condition becomes false, and the loop terminates.

2. After the Loop:

Once the loop ends (i.e., the user enters a negative number), the following statement is executed:

echo "You entered a negative number.";

This prints the message "You entered a negative number." to the screen.

Example Input and Output:

Let's walk through an example where the user enters 5, 2, and then -1.

The program starts and asks for a number:

Enter a number: 5

5 is entered, which is non-negative (5 >= 0), so the loop continues.

The program asks for another number:

Enter a number: 2

2 is entered, which is also non-negative (2 >= 0), so the loop continues.

The program asks for another number:

Enter a number: -1

-1 is entered, which is a negative number, so the condition $number >= 0 becomes false, and the loop stops.

The program then prints:

You entered a negative number.

Summary:

  1. The program uses a do-while loop to keep prompting the user to enter a number until they input a negative number.
  2. The do block ensures that the prompt appears at least once.
  3. Once a negative number is entered, the loop exits, and the program prints "You entered a negative number.".

Assignment 14: Skip the Number 13 in a for Loop

Write a PHP program that uses a for loop to print the numbers from 1 to 20, except for the number 13. Use the continue statement to skip the number 13 in the loop. What will be the output of the program?

Code:

<?php


for ($i = 1; $i <= 20; $i++) {

    if ($i == 13) {

        continue;

    }

    echo $i . " ";

}

?>

 

Explanation of the Code:

1. for Loop:

The for loop is used to iterate from 1 to 20. It has three parts:

for ($i = 1; $i <= 20; $i++) {

Initialization: $i = 1 sets the starting value of the loop control variable $i to 1.

Condition: $i <= 20 ensures the loop runs as long as $i is less than or equal to 20.

Increment: $i++ increases the value of $i by 1 in each iteration.

2. if Statement with continue:

if ($i == 13) {

    continue;

}

The if statement checks if $i is equal to 13.

If $i equals 13, the continue statement is triggered.

What does continue do? The continue statement skips the rest of the code in the loop for the current iteration and jumps to the next iteration, meaning the program does not execute the echo $i . " " for $i = 13.

3. echo Statement:

echo $i . " ";

If $i is not 13, the program prints the value of $i followed by a space (" ").

This prints numbers from 1 to 20, but skips 13 due to the continue statement.

Output:

The program prints numbers from 1 to 20, except for 13. So, the output will be:

1 2 3 4 5 6 7 8 9 10 11 12 14 15 16 17 18 19 20 

Summary:

  1. The program uses a for loop to iterate from 1 to 20.
  2. The if ($i == 13) block checks for the value 13, and when $i equals 13, the continue statement skips the current iteration, meaning 13 is not printed.
  3. All other numbers from 1 to 20 are printed except for 13, resulting in the output:      1 2 3 4 5 6 7 8 9 10 11 12 14 15 16 17 18 19 20

Assignment 15: Find the Sum of Numbers from 1 to 50 Using a for Loop

Code:

<?php

$sum = 0;

 for ($i = 1; $i <= 50; $i++) {

    $sum += $i;

}

echo "Sum of numbers from 1 to 50 is: $sum";

?>

 

 Explanation: This script calculates the sum of numbers from 1 to 50 using a for loop.


Assignment 16: Reverse Digits of a Number Using a while Loop

Code:

<?php

$number = 12345;

$reverse = 0;

while ($number > 0) {

    $remainder = $number % 10;

    $reverse = ($reverse * 10) + $remainder;

    $number = (int)($number / 10);

}

 echo "Reversed Number: $reverse";

?>

 

Step by step Explanation:

1. Variable Initialization:

$number = 12345;

$reverse = 0;

$number is initialized to 12345, which is the number to be reversed.

$reverse is initialized to 0. This variable will hold the reversed number as the loop processes each digit.

2. while Loop:

while ($number > 0) {

    $remainder = $number % 10;

    $reverse = ($reverse * 10) + $remainder;

    $number = (int)($number / 10);

}

The while loop continues as long as $number is greater than 0.

a. Extract the Last Digit:

$remainder = $number % 10;

% 10 calculates the remainder when $number is divided by 10. This gives the last digit of $number.

For example, if $number is 12345, 12345 % 10 results in 5. So, $remainder becomes 5.

b. Build the Reversed Number:

$reverse = ($reverse * 10) + $remainder;

($reverse * 10) shifts the current digits in $reverse one place to the left (e.g., from 0 to 0, from 5 to 50).

+ $remainder adds the last digit of $number to the end of $reverse.

Initially, $reverse is 0. After processing the first digit (5), $reverse becomes 5.

c. Remove the Last Digit:

$number = (int)($number / 10);

/ 10 performs integer division, effectively removing the last digit of $number.

(int) casts the result to an integer, removing any fractional part.

For example, 12345 / 10 results in 1234.5. Casting to integer gives 1234, so $number becomes 1234.

3. Repeat the Loop:

The loop continues, extracting the next last digit, building up the reversed number, and reducing $number until $number is 0.

After the loop completes, $reverse holds the reversed number.

4. Output:

echo "Reversed Number: $reverse";

This line outputs the reversed number.

Example Walkthrough:

Let's illustrate how the reversal happens step-by-step for $number = 12345:

First Iteration:

$remainder = 12345 % 10 = 5

$reverse = (0 * 10) + 5 = 5

$number = (int)(12345 / 10) = 1234

Second Iteration:

$remainder = 1234 % 10 = 4

$reverse = (5 * 10) + 4 = 54

$number = (int)(1234 / 10) = 123

Third Iteration:

$remainder = 123 % 10 = 3

$reverse = (54 * 10) + 3 = 543

$number = (int)(123 / 10) = 12

Fourth Iteration:

$remainder = 12 % 10 = 2

$reverse = (543 * 10) + 2 = 5432

$number = (int)(12 / 10) = 1

Fifth Iteration:

$remainder = 1 % 10 = 1

$reverse = (5432 * 10) + 1 = 54321

$number = (int)(1 / 10) = 0

Loop Ends:

$number is now 0, so the loop terminates.

Final Output:

The final value of $reverse is 54321.

The program prints:

Reversed Number: 54321

Summary:

The program reverses the digits of a given number by repeatedly extracting the last digit, building up the reversed number, and removing the last digit from the original number.

After the loop completes, it outputs the reversed number.

Assignment 17: Print Multiplication Table of a Number Using a for Loop

Code:

<?php


$number = 5;

 for ($i = 1; $i <= 10; $i++) {

    echo "$number x $i = " . ($number * $i) . "\n";

}

?>

 

 Explanation: This script prints the multiplication table of a given number using a for loop.


Assignment 18: Calculate Factorial of a Number Using a while Loop

Code:

<?php

$number = 5;

$factorial = 1;

 while ($number > 0) {

    $factorial *= $number;

    $number--;

} 

echo "Factorial is: $factorial";

?>

 

Step by step Explanation:

1. Variable Initialization:

$number = 5;

$factorial = 1;

$number is initialized to 5, which is the number for which we want to calculate the factorial.

$factorial is initialized to 1. This variable will hold the result of the factorial calculation.

2. while Loop:

while ($number > 0) {

    $factorial *= $number;

    $number--;

}

The while loop runs as long as $number is greater than 0.

a. Multiplying $factorial:

$factorial *= $number;

This line updates $factorial by multiplying it with the current value of $number.

The *= operator is shorthand for $factorial = $factorial * $number.

b. Decrementing $number:

$number--;

The -- operator decreases the value of $number by 1 after each iteration.

3. Output:

echo "Factorial is: $factorial";

After the loop completes, this line prints the calculated factorial.

Example Walkthrough:

Let's calculate the factorial of 5 step by step:

Initialization:

$number = 5

$factorial = 1

First Iteration:

$factorial = 1 * 5 = 5

$number is decremented to 4.

Second Iteration:

$factorial = 5 * 4 = 20

$number is decremented to 3.

Third Iteration:

$factorial = 20 * 3 = 60

$number is decremented to 2.

Fourth Iteration:

$factorial = 60 * 2 = 120

$number is decremented to 1.

Fifth Iteration:

$factorial = 120 * 1 = 120

$number is decremented to 0.

Loop Ends:

The condition $number > 0 is now false because $number is 0, so the loop terminates.

Final Output:

After exiting the loop, $factorial holds the value 120.

The program prints:

Factorial is: 120

Summary:

  1. The program calculates the factorial of a given number by repeatedly multiplying the current value of $factorial with $number and then decrementing $number.
  2. The loop continues until $number becomes 0.
  3. The result is then printed out. For the input of 5, the factorial calculated is 120.


Assignment 19: Find the Sum of Digits of a Number Using a while Loop

Code:


<?php


$number = 1234;

$sum = 0;

 while ($number > 0) {

    $sum += $number % 10;

    $number = (int)($number / 10);

}

 

echo "Sum of digits: $sum";

?>

 

 Explanation: This script calculates the sum of the digits of a given number using a while loop.


Assignment 20: Print Fibonacci Series up to n Terms Using a for Loop

Code:

<?php

$n = 10;

$first = 0;

$second = 1;

 echo "$first $second ";

 for ($i = 3; $i <= $n; $i++) {

    $next = $first + $second;

    echo "$next ";

    $first = $second;

    $second = $next;

}

?>

 

Step by step Explanation.

1. Variable Initialization:

$n = 10;

$first = 0;

$second = 1;

$n is set to 10, which indicates the total number of Fibonacci terms to generate.

$first is initialized to 0, representing the first term in the Fibonacci sequence.

$second is initialized to 1, representing the second term in the Fibonacci sequence.

2. Initial Output:

echo "$first $second ";

This line prints the first two terms of the Fibonacci sequence, 0 and 1, followed by a space.

3. for Loop:

for ($i = 3; $i <= $n; $i++) {

    $next = $first + $second;

    echo "$next ";

    $first = $second;

    $second = $next;

}

Initialization: The loop starts with $i = 3 because the first two terms (0 and 1) are already printed. The loop continues as long as $i is less than or equal to $n.

a. Calculate the Next Term:

$next = $first + $second;

This line calculates the next term in the Fibonacci sequence by summing the previous two terms ($first and $second).

b. Print the Next Term:

echo "$next ";

This line prints the newly calculated term.

c. Update Terms:

$first = $second;

$second = $next;

first is updated to the value of second, and second is updated to the value of next. This shifts the window to the next two terms in the sequence.

4. Final Output:

After the loop completes, all terms up to $n have been printed.

Example Walkthrough:

For $n = 10, the program will print the first 10 Fibonacci numbers. Here's how the loop operates:

Initial Values:

$first = 0

$second = 1

Initial Output:

Prints: 0 1

First Iteration ($i = 3):

$next = $first + $second = 0 + 1 = 1

Prints: 1

Updates: $first = 1, $second = 1

Second Iteration ($i = 4):


$next = $first + $second = 1 + 1 = 2

Prints: 2

Updates: $first = 1, $second = 2

Third Iteration ($i = 5):


$next = $first + $second = 1 + 2 = 3

Prints: 3

Updates: $first = 2, $second = 3

Fourth Iteration ($i = 6):


$next = $first + $second = 2 + 3 = 5

Prints: 5

Updates: $first = 3, $second = 5

Fifth Iteration ($i = 7):


$next = $first + $second = 3 + 5 = 8

Prints: 8

Updates: $first = 5, $second = 8

Sixth Iteration ($i = 8):


$next = $first + $second = 5 + 8 = 13

Prints: 13

Updates: $first = 8, $second = 13

Seventh Iteration ($i = 9):


$next = $first + $second = 8 + 13 = 21

Prints: 21

Updates: $first = 13, $second = 21

Eighth Iteration ($i = 10):


$next = $first + $second = 13 + 21 = 34

Prints: 34

Updates: $first = 21, $second = 34

Final Output:

The complete output will be:

0 1 1 2 3 5 8 13 21 34

Summary:

  1. The program prints the Fibonacci sequence up to the n-th term.
  2. It starts with the first two terms and uses a for loop to calculate and print subsequent terms.
  3. Each iteration calculates the next term by summing the previous two terms, updates the variables, and prints the result.

Assignment 21: Find the Largest Number in an Array Using a for Loop

Code:

<?php

$numbers = array(10, 20, 50, 30, 40);

$largest = $numbers[0];

 for ($i = 1; $i < count($numbers); $i++) {

    if ($numbers[$i] > $largest) {

        $largest = $numbers[$i];

    }

}

 echo "Largest number is: $largest";

?>

 

 Explanation: This script finds the largest number in an array using a for loop.


Assignment 22: Print All Prime Numbers Between 1 and 50 Using Nested Loops

Code:

<?php


for ($num = 2; $num <= 50; $num++) {

    $isPrime = true;

  for ($i = 2; $i <= sqrt($num); $i++) {

        if ($num % $i == 0) {

            $isPrime = false;

            break;

        }

    }

       if ($isPrime) {

        echo $num . " ";

    }

}

?>

 

 Explanation: This script prints all prime numbers between 1 and 50 using nested for loops. A prime number is a number greater than 1 that has no divisors other than 1 and itself.


Assignment 23: Implement break in a Loop

Code:

<?php


for ($i = 1; $i <= 10; $i++) {

    if ($i == 5) {

        break;

    }

    echo $i . " ";

}

 

echo "Loop ended at 5.";

?>

 

 Explanation: This script demonstrates the use of the break statement to exit a loop prematurely when a certain condition is met (in this case, when $i equals 5).


Assignment 24: Implement continue in a Loop

Code:


<?php

for ($i = 1; $i <= 10; $i++) {

    if ($i % 2 == 0) {

        continue;

    }

    echo $i . " ";

}

?>

 

Explanation: This script uses the continue statement to skip the current iteration of the loop when a certain condition is met (in this case, when $i is an even number).


Assignment 25: Find the First Number Greater Than 100 in an Array Using foreach and break

Code:


<?php

$numbers = array(25, 50, 75, 150, 200);

 foreach ($numbers as $number) {

    if ($number > 100) {

        echo "First number greater than 100 is: $number";

        break;

    }

}

?>

 

 Explanation: This script iterates over an array using foreach and uses the break statement to stop the loop when the first number greater than 100 is found.



No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template