Company’s board member requested admin to provide MIS report of all employees with total, average, min, max, minimum salaried employees, maximum salaried employees and department wise salary.
You need to create a program for the same using following concepts of c++ programming language
Encapsulation
Abstraction
Inheritance
MVPs
P0
Create a class Person with datamembers: name, age, city
Create a class Employee which will inherit features of Person class with it’s own datamembers: empid, department, salary
P1
Create array of 10 employees and print its data using for loop
P2
Find and Print Total Salary, Average Salary, Max Salary, Min Salary
P3
Create function getMaxSalEmps() to print employees having highest salary
Create function getMinSalEmps() to print all employees having minimum salary
P4
Create function getDeptWiseSalary() to print department wise total salary
Session 2 (3 hours): Data types, variables, and basic input/output.
Explanation: Learn about different data types, how to declare variables, and use the scanf function to read user input. Perform basic arithmetic calculations.
Syntax Example:
#include <stdio.h>
int main() {
int num1, num2, sum;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
sum = num1 + num2;
printf("Sum: %d\n", sum);
return 0;
}
Assignment 1: Write a program that takes user input for two numbers, adds them, and displays the result. Output (example):
Enter two numbers: 3 5
Sum: 8
Assignment 2: Develop a program that converts temperature from Fahrenheit to Celsius.
“`c #include
int main() {
float fahrenheit, celsius;
printf("Enter temperature in Fahrenheit: ");
scanf("%f", &fahrenheit);
celsius = (fahrenheit - 32) * 5 / 9;
printf("Temperature in Celsius: %.2f\n", celsius);
return 0;
}
Output (example):
Enter temperature in Fahrenheit: 68
Temperature in Celsius: 20.00
Explanation: Learn about conditional statements to make decisions in your program based on conditions. Use logical operators to combine conditions.
Syntax Example:
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num > 0) {
printf("Positive\n");
} else if (num < 0) {
printf("Negative\n");
} else {
printf("Zero\n");
}
return 0;
}
Assignment 1: Write a program that checks if a given number is positive, negative, or zero. Output (example):
Enter a number: -7
Negative
Assignment 2: Create a program that determines the largest of three user-provided numbers.
```c
#include <stdio.h>
int main() {
int num1, num2, num3, largest;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
if (num1 >= num2 && num1 >= num3) {
largest = num1;
} else if (num2 >= num1 && num2 >= num3) {
largest = num2;
} else {
largest = num3;
}
printf("Largest: %d\n", largest);
return 0;
}
```
Output (example):
Enter three numbers: 15 9 12
Largest: 15
Session 2 (3 hours): Loops (while, for) and switch statements.
Explanation: Learn how to create loops for repetitive tasks using while and for. Use the switch statement for multiple choices.
Syntax Example:
#include <stdio.h>
int main() {
int num, i;
printf("Enter a number: ");
scanf("%d", &num);
for (i = 1; i <= 10; i++) {
printf("%d * %d = %d\n", num, i, num * i);
}
return 0;
}
Assignment 1: Implement a program that prints a multiplication table for a given number. Output (example):
Enter a number: 7
7 * 1 = 7
7 * 2 = 14
...
7 * 10 = 70
Assignment 2: Write a program that calculates the sum of all even numbers between 1 and a user-provided limit using a loop.
#include <stdio.h>
int main() {
int limit, sum = 0, i;
printf("Enter a limit: ");
scanf("%d", &limit);
for (i = 2; i <= limit; i += 2) {
sum += i;
}
printf("Sum of even numbers: %d\n", sum);
return 0;
}
Output (example):
Enter a limit: 10
Sum of even numbers: 30
Day 3: Arrays and Strings
Session 1 (3 hours): Introduction to arrays, declaring and initializing arrays.
Explanation: Learn about arrays, how to declare them, and access their elements. Understand the concept of indexing and looping through arrays.
Syntax Example:
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
printf("Third element: %d\n", numbers[2]);
return 0;
}
Assignment 1: Write a program to find the sum of all elements in an array. Output (example):
Sum of array elements: 150
Assignment 2: Develop a program that finds the smallest element in an array of integers.
#include <stdio.h>
int main() {
int array[5] = {25, 10, 15, 20, 5};
int smallest = array[0], i;
for (i = 1; i < 5; i++) {
if (array[i] < smallest) {
smallest = array[i];
}
}
printf("Smallest element: %d\n", smallest);
return 0;
}
Explanation: Understand dynamic memory allocation using malloc, and how to free allocated memory using free. Learn to prevent memory leaks.
Syntax Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int n, i, sum = 0;
printf("Enter the number of elements: ");
scanf("%d", &n);
arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
for (i = 0; i < n; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", &arr[i]);
sum += arr[i];
}
printf("Average: %.2f\n", (float)sum / n);
free(arr);
return 0;
}
Assignment 1: Implement a program that dynamically creates an array, populates it with user input, and calculates the average. Output (example):
Enter the number of elements: 4
Enter element 1: 12
Enter element 2: 15
Enter element 3: 20
Enter element 4: 10
Average: 14.25
Assignment 2: Write a program that removes duplicates from an array using dynamic memory allocation.
#include <stdio.h>
#include <stdlib.h>
int* removeDuplicates(int *arr, int *size) {
int *temp = (int *)malloc(*size * sizeof(int));
if (temp == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
// ... code to remove duplicates ...
return temp;
}
int main() {
// ... code to input array ...
int *result = removeDuplicates(array, &size);
// ... code to display result ...
free(result);
return 0;
}
Output (example):
Original array: 5 10 15 10 20 25 15 30
Array after removing duplicates: 5 10 15 20 25 30
Day 5: Functions, Structures, and File I/O
Session 1 (3 hours): Functions, function prototypes, and header files.
Explanation: Learn about functions, how to declare and define them. Understand the concept of recursion for solving problems.
Syntax Example:
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
Assignment 1: Write a program that calculates the factorial of a given number using a recursive function. Output (example):
Enter a positive integer: 5
Factorial of 5 is 120
Assignment 2: Create a program that calculates the nth term of the Fibonacci sequence using a recursive function.
#include <stdio.h>
int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
printf("Fibonacci(%d) = %d\n", num, fibonacci(num));
return 0;
}
Output (example):
Enter a positive integer: 7
Fibonacci(7) = 13
Session 2 (3 hours): Introduction to structures and file I/O.
Explanation: Learn about structures, how to define them, and how to use them to group related data. Explore file input/output operations.
Syntax Example:
#include <stdio.h>
struct Student {
char name[50];
int marks[3];
};
int main() {
struct Student student1;
printf("Enter student name: ");
scanf("%s", student1.name);
printf("Enter marks for three subjects: ");
scanf("%d %d %d", &student1.marks[0], &student1.marks[1], &student1.marks[2]);
// ... code to calculate grade ...
return 0;
}
Assignment 1: Develop a program that reads data from a text file, calculates the sum and average, and writes the results to another file. Output (example):
Sum: 85
Average: 17.00
Assignment 2: Write a program that reads student data from a file, calculates their grades, and outputs the result to another file.
#include <stdio.h>
struct Student {
char name[50];
int marks[3];
};
char calculateGrade(int marks) {
// ... code to calculate grade ...
}
int main() {
FILE *inputFile = fopen("students.txt", "r");
Linux operating system Explanation: Learn about the Linux operating system, its features, and its popularity among developers and system administrators.
Basic Linux commands Explanation: Understand essential Linux commands such as ls (list files and directories), cd (change directory), pwd (print working directory), and mkdir (make directory).
File and directory management Explanation: Learn how to create, delete, move, and rename files and directories using commands like touch, rm, mv, and cp.
File permissions and ownership Explanation: Understand the concept of file permissions and how to set permissions using chmod, as well as changing file ownership using chown.
File manipulation and text editing Explanation: Explore commands like cat (concatenate and display file contents), less (view file contents page by page), and nano (a basic text editor).
Assignments:
Create a directory named “my_files” and navigate into it. Answer: mkdir my_files (to create the directory) and cd my_files (to navigate into it).
Create a file named “my_text.txt” and write some text into it. Answer: touch my_text.txt (to create the file) and nano my_text.txt (to open the file in the nano text editor and write the text).
List all the files and directories in the current directory. Answer: ls (to list files and directories).
Rename the file “my_text.txt” to “new_text.txt”. Answer: mv my_text.txt new_text.txt (to rename the file).
Delete the directory “my_files” and all its contents. Answer: rm -r my_files (to remove the directory and its contents).
Day 2: Working with Files and Permissions
Topics:
File manipulation commands Explanation: Explore more file manipulation commands such as head (display the beginning of a file), tail (display the end of a file), and wc (word count).
File permissions and access modes Explanation: Understand the three levels of file permissions (owner, group, others) and how to set permissions using symbolic notation (rwx) and numeric notation (777).
Changing file ownership and group Explanation: Learn how to change the owner and group of a file using the chown and chgrp commands.
File compression and archiving Explanation: Discover commands like tar (archive files) and gzip (compress files) to manage large file collections efficiently.
File searching and filtering Explanation: Learn about commands like find (search for files and directories) and grep (search for text patterns in files).
Assignments:
Create a file named “sample.txt” and write some content into it. Answer: touch sample.txt (to create the file) and nano sample.txt (to open the file in the nano text editor and write the content).
Display the first 5 lines of the file “sample.txt”. Answer: head -n 5 sample.txt (to display the first 5 lines).
Set the file permissions of “sample.txt” to read and write for the owner only. Answer: chmod 600 sample.txt (to set the permissions).
Change the owner of “sample.txt
” to a different user. Answer: chown username sample.txt (to change the owner to the specified username).
Archive the file “sample.txt” and compress it into a single file. Answer: tar -czvf sample.tar.gz sample.txt (to create the archive and compress it).
Day 3: Introduction to Vim Editor
Topics:
Introduction to Vim Explanation: Understand the basics of the Vim editor, including its modes (Normal, Insert, Visual), navigation, and command execution.
Opening and saving files Explanation: Learn how to open files in Vim, make changes, and save them using commands like :e (open), :w (save), and :q (quit).
Moving and navigating within files Explanation: Explore various movement commands like h (left), j (down), k (up), l (right), and using line numbers to jump to specific locations.
Editing and modifying text Explanation: Understand text editing commands like i (insert), o (open a new line), x (delete a character), and yy (copy a line).
Undo and redo operations Explanation: Learn how to undo and redo changes made in Vim using the u (undo) and Ctrl+R (redo) commands.
Assignments:
Open the file “my_file.txt” in Vim and navigate to the end of the file. Answer: vim my_file.txt (to open the file) and G (to move to the end of the file).
Insert a new line after the current line and write some text into it. Answer: Press o (to open a new line) and start typing the desired text.
Delete the current line in Vim. Answer: Press dd (to delete the current line).
Copy the current line in Vim and paste it below the current line. Answer: Press yy (to copy the current line) and then p (to paste it below).
Save the changes made to the file and exit Vim. Answer: Press :wq (to save and quit).
Day 4: Advanced Vim Editing
Topics:
Visual mode in Vim Explanation: Learn how to select and manipulate blocks of text using Visual mode, including commands like v (characterwise), V (linewise), and Ctrl+V (blockwise).
Searching and replacing text Explanation: Discover how to search for specific text patterns using / (forward search) and ? (backward search), as well as replacing text using :s (substitute).
Advanced editing commands Explanation: Explore advanced editing commands like x (delete a character), r (replace a character), J (join lines), and . (repeat the last command).
Advanced movement and navigation Explanation: Learn advanced movement commands like w (jump to the beginning of the next word), b (jump to the beginning of the previous word), and gg (jump to the first line).
Split windows and tabs in Vim Explanation: Understand how to split the Vim editor window vertically and horizontally using commands like :split and :vsplit, and navigate between tabs.
Assignments:
Open the file “my_notes.txt” in Vim and search for the word “important”. Answer: vim my_notes.txt (to open the file) and /important (to search for the word “important”).
Replace all occurrences of the word “old” with “new” in the current line. Answer: :s/old/new/ (to perform the substitution).
Join the current line with the line below it. Answer: Press J (to join the lines).
Split the Vim editor window vertically. Answer: :vsplit (to split the window vertically).
Move the cursor to the beginning of the next word in Vim. Answer: Press w (to jump to the beginning of the next word).
Day 5: Vim Customization and Advanced Topics
Topics:
Vim configuration files Explanation: Understand the .vimrc file and how to customize Vim settings, key mappings, and plugins.
Customizing Vim colorschemes Explanation: Learn how to change the colorscheme in Vim to enhance the visual appearance and readability of your code.
Advanced Vim features and plugins Explanation: Explore advanced Vim features like macros, multiple cursors (using plugins), and code completion (using plugins).
Vim navigation shortcuts Explanation: Discover useful navigation shortcuts like Ctrl+U (scroll half a page up), Ctrl+D (scroll half a page down), and gg (jump to the first line).
Vim documentation and help Explanation: Learn how to access Vim documentation and help resources, including built-in help pages and online resources.
Assignments:
Customize the Vim settings by adding the following lines to your .vimrc file:
Set the tab width to 4 spaces.
Enable line numbers. Answer: Open the .vimrc file in Vim (vim ~/.vimrc) and add the desired configurations.
Change the colorscheme in Vim to a different one. Answer: In Vim, type :colorscheme <colorscheme_name> to change the colorscheme.
Create a macro in Vim that inserts a specific code snippet. Answer: Record the macro using q<register> and replay it using @<register>.
Install a plugin in Vim for code completion or any other desired functionality. Answer: Install the desired plugin using a plugin manager like Vundle or Pathogen.
Access the Vim built-in help and find information on a specific Vim command or feature. Answer: In Vim, type :help <command_or_feature> to access the built-in help pages.
Shell Scripting
Apologies for the oversight. Here are the shell scripting assignments along with sample answers for each day:
Day 1:
Write a shell script that takes two numbers as input and prints their sum.
#!/bin/bash
echo "Enter the first number: "
read num1
echo "Enter the second number: "
read num2
sum=$((num1 + num2))
echo "The sum is: $sum"
Create a shell script that reads a filename from the user and checks if it exists in the current directory. If the file exists, display a message confirming its existence; otherwise, display an error message.
#!/bin/bash
echo "Enter a filename: "
read filename
if [ -e "$filename" ]; then
echo "The file '$filename' exists in the current directory."
else
echo "Error: The file '$filename' does not exist in the current directory."
fi
Write a shell script that reads a string from the user and prints it in reverse order.
Create a script that takes a directory name as input and lists all the files in that directory.
#!/bin/bash
echo "Enter a directory name: "
read directory
if [ -d "$directory" ]; then
echo "Files in $directory:"
ls "$directory"
else
echo "Error: '$directory' is not a valid directory."
fi
Write a shell script that generates a random number between 1 and 100 and asks the user to guess the number. Provide appropriate feedback based on the user’s guess.
#!/bin/bash
random_number=$((RANDOM % 100 + 1))
echo "Guess the number between 1 and 100: "
read user_guess
if [ "$user_guess" -eq "$random_number" ]; then
echo "Congratulations! You guessed the correct number."
elif [ "$user_guess" -lt "$random_number" ]; then
echo "Try again. The number is higher than your guess."
else
echo "Try again. The number is lower than your guess."
fi
Day 2:
Write a shell script that takes a filename as input and checks if it is a regular file or a directory.
#!/bin/bash
echo "Enter a filename: "
read filename
if [ -f "$filename" ]; then
echo "'$filename' is a regular file."
elif [ -d "$filename" ]; then
echo "'$filename' is a directory."
else
echo "Error: '$filename' is neither a regular file nor a directory."
fi
Create a script that takes a file containing a list of numbers and calculates their sum.
#!/bin/bash
sum=0
while read -r num; do
sum=$((sum + num))
done < "$1"
echo "Sum of numbers in the file: $sum"
Write a shell script that renames all files in a directory with a specific extension to have a prefix “backup_” followed by the original filename.
#!/bin/bash
echo "Enter the directory name: "
read directory
echo "Enter the file extension to rename: "
read ext
for file in "$directory"/*."$ext"; do
filename=$(basename "$file")
mv "$file" "$directory/backup_$filename"
done
Create a script that reads a file and counts the number of lines, words, and characters in it.
#!/bin/bash
echo "Enter a filename: "
read filename
if [ -f "$filename" ]; then
line_count=$(wc -l < "$filename")
word_count=$(wc -w < "$filename")
char_count=$(wc -c < "$filename")
echo "Number of lines: $line_count"
echo "Number of words: $word_count"
echo "Number of characters: $char_count"
else
echo "Error: '$filename' is not a valid file."
fi
Write a shell script that takes a number as input and prints all the prime numbers less than or equal to that number.
#!/bin/bash
echo "Enter a number: "
read num
if [ "$num" -lt 2 ]; then
echo "There are no prime numbers less than 2."
else
echo "Prime numbers less than or equal to $num:"
for ((i = 2; i <= num; i++)); do
is_prime=1
for ((j = 2; j <= i / 2; j++)); do
if ((i % j == 0)); then
is_prime=0
break
fi
done
if [ "$is_prime" -eq 1 ]; then
echo "$i"
fi
done
fi
Day 3:
Create a shell script that takes a directory name as input and finds all the subdirectories within it.
#!/bin/bash
echo "Enter a directory name: "
read directory
if [ -d "$directory" ]; then
echo "Subdirectories in '$directory':"
find "$directory" -type d
else
echo "Error: '$directory' is not a valid directory."
fi
Write a script that reads a file and removes all the empty lines from it.
#!/bin/bash
echo "Enter a filename: "
read filename
if [ -f "$filename" ]; then
sed -i '/^[[:space:]]*$/d' "$filename"
echo "Empty lines removed from '$filename'."
else
echo "Error: '$filename' is not a valid file."
fi
Create a shell script that takes a string as input and checks if it is a palindrome.
#!/bin/bash
echo "Enter a string: "
read input_string
reverse_string=$(echo "$input_string" | rev)
if [ "$input_string" = "$reverse_string" ]; then
echo "The string is a palindrome."
else
echo "The string is not a palindrome."
fi
Write a shell script that reads a number as input and checks if it is even or odd.
#!/bin/bash
echo "Enter a number: "
read num
if ((num % 2 == 0)); then
echo "$num is an even number."
else
echo "$num is an odd number."
fi
Create a shell script that prints the current date and time.
Write a shell script that takes a directory name as input and deletes all the files in that directory with a “.tmp” extension.
#!/bin/bash
echo "Enter a directory name: "
read directory
if [ -d "$directory" ]; then
find "$directory" -type f -name "*.tmp" -delete
echo "All '.tmp' files in '$directory' deleted."
else
echo "Error: '$directory' is not a valid directory."
fi
Create a script that reads a file and replaces all occurrences of a word with another word.
#!/bin/bash
echo "Enter a filename: "
read filename
if [ -f "$filename" ]; then
echo "Enter the word to replace: "
read old_word
echo "Enter the new word: "
read new_word
sed -i "s/$old_word/$new_word/g" "$filename"
echo "Occurrences of '$old_word' replaced with '$new_word' in '$filename'."
else
echo "Error: '$filename' is not a valid file."
fi
Write a shell script that reads a number as input and checks if it is prime.
#!/bin/bash
echo "Enter a number: "
read num
if [ "$num" -lt 2 ]; then
echo "The number must be greater than or equal to 2 to check for primality."
else
is_prime=1
for ((i = 2; i <= num / 2; i++)); do
if ((num % i == 0)); then
is_prime=0
break
fi
done
if [ "$is_prime" -eq 1 ]; then
echo "$num is a prime number."
else
echo "$num is not a prime number."
fi
fi
Create a shell script that takes a directory name as input and counts the number of files and subdirectories in it.
#!/bin/bash
echo "Enter a directory name: "
read directory
if [ -d "$directory" ]; then
file_count=$(find "$directory" -type f | wc -l)
dir_count=$(find "$directory" -type d | wc -l)
echo "Number of files: $file_count"
echo "Number of subdirectories: $dir_count"
else
echo "Error: '$directory' is not a valid directory."
fi
Write a shell script that reads a string as input and converts it to uppercase.
Create a shell script that takes two numbers as input and swaps their values.
#!/bin/bash
echo "Enter the first number: "
read num1
echo "Enter the second number: "
read num2
echo "Before swapping: num1 = $num1, num2 = $num2"
# Swapping using a temporary variable
temp=$num1
num1=$num2
num2=$temp
echo "After swapping: num1 = $num1, num2 = $num2"
Write a script that takes a file and sorts its lines in ascending order.
#!/bin/bash
echo "Enter a filename: "
read filename
if [ -f "$filename" ]; then
sort "$filename" > sorted_"$filename"
echo "Lines in '$filename' sorted in ascending order and saved to 'sorted_$filename'."
else
echo "Error: '$filename' is not a valid file."
fi
Create a shell script that reads a directory name as input and prints the names of the 10 largest files in it.
#!/bin/bash
echo "Enter a directory name: "
read directory
if [ -d "$directory" ]; then
echo "The 10 largest files in '$directory':"
du -ah "$directory" | sort -rh | head -n 10
else
echo "Error: '$directory' is not a valid directory."
fi
Write a shell script that takes a list of filenames as arguments and checks if all of them exist in the current directory.
#!/bin/bash
for filename in "$@"; do
if [ ! -e "$filename" ]; then
echo "Error: '$filename' does not exist in the current directory."
else
echo "'$filename' exists in the current directory."
fi
done
Create a shell script that calculates the factorial of a given number.
#!/bin/bash
echo "Enter a number: "
read num
factorial=1
for ((i = 1; i <= num; i++)); do
factorial=$((factorial * i))
done
echo "Factorial of $num is: $factorial"
Retrieve the names of users whose age is greater than 30.
SELECT name FROM users WHERE age > 30;
Day 2: Data Manipulation
Topics:
Updating records with UPDATE statement
Deleting records with DELETE statement
Limiting and pagination with LIMIT and OFFSET
Aggregation functions: COUNT, SUM, AVG, MIN, MAX
Grouping data with GROUP BY
Assignments:
Update the age of the user with id 2 to 35.
UPDATE users SET age = 35 WHERE id = 2;
Delete the user with id 4 from the “users” table.
DELETE FROM users WHERE id = 4;
Retrieve the first 3 records from the “users” table.
SELECT * FROM users LIMIT 3;
Retrieve the total number of users in the “users” table.
SELECT COUNT(*) FROM users;
Retrieve the average age of users.
SELECT AVG(age) FROM users;
Day 3: Filtering and Sorting
Topics:
Using WHERE clause for conditional filtering
Using comparison operators: =, <>, <, >, <=, >=
Using logical operators: AND, OR, NOT
Sorting data with ORDER BY clause
Sorting in ascending and descending order
Assignments:
Retrieve the names of users whose city is ‘Mumbai’.
SELECT name FROM users WHERE city = 'Mumbai';
Retrieve the names of users whose age is between 25 and 35.
SELECT name FROM users WHERE age BETWEEN 25 AND 35;
Retrieve the names of users whose city is not ‘Delhi’.
SELECT name FROM users WHERE city <> 'Delhi';
Retrieve all records from the “users” table sorted by age in ascending order.
SELECT * FROM users ORDER BY age ASC;
Retrieve all records from the “users” table sorted by name in descending order.
SELECT * FROM users ORDER BY name DESC;
Day 4: Data Aggregation and Functions
Topics:
Using aggregate functions: COUNT, SUM, AVG, MIN, MAX
Working with NULL values: IS NULL, IS NOT NULL
Using mathematical functions: ROUND, CEILING, FLOOR
String functions: CONCAT, UPPER, LOWER, LENGTH
Date functions: NOW, DATE_FORMAT, DATE_ADD, DATE_SUB
Assignments:
Retrieve the total number of users in the “users” table.
SELECT COUNT(*) FROM users;
Retrieve the sum of ages of all users.
SELECT SUM(age) FROM users;
Retrieve the average age of users excluding NULL values.
SELECT AVG(age) FROM users WHERE age IS NOT NULL;
Retrieve the concatenated names and cities of all users.
SELECT CONCAT(name, ', ', city) AS info FROM users;
Retrieve the current date and time.
SELECT NOW();
Day 5: Grouping and Filtering with HAVING Clause
Topics:
Grouping data with GROUP BY clause
Filtering grouped data with HAVING clause
Using aggregate functions with GROUP BY
Using multiple columns in GROUP BY
Combining GROUP BY, HAVING, and ORDER BY
Assignments:
Retrieve the names and ages of users grouped by city.
SELECT city, GROUP_CONCAT(name) AS names, GROUP_CONCAT(age) AS ages FROM users GROUP BY city;
Retrieve the cities with more than 2 users.
SELECT city FROM users GROUP BY city HAVING COUNT(*) > 2;
Retrieve the average age of users in each city.
SELECT city, AVG(age) AS average_age FROM users GROUP BY city;
Retrieve the cities with the highest and lowest average age of users.
SELECT city, AVG(age) AS average_age FROM users GROUP BY city HAVING AVG(age) = (SELECT MAX(avg_age) FROM (SELECT AVG(age) AS avg_age FROM users GROUP BY city) AS temp) OR AVG(age) = (SELECT MIN(avg_age) FROM (SELECT AVG(age) AS avg_age FROM users GROUP BY city) AS temp);
Retrieve the cities with at least 1 user whose age is greater than 30, sorted by city name.
SELECT city FROM users WHERE age > 30 GROUP BY city ORDER BY city ASC;
Create a basic HTML document structure with a title and heading.
<!DOCTYPE html>
<html>
<head>
<title>My First Webpage</title>
</head>
<body>
<h1>Welcome to My Webpage</h1>
</body>
</html>
Write a paragraph describing your favorite hobby using appropriate HTML tags.
<!DOCTYPE html>
<html>
<head>
<title>My Hobbies</title>
</head>
<body>
<h2>My Favorite Hobby</h2>
<p>I enjoy playing the guitar in my free time. It's a great way to relax and express my creativity.</p>
</body>
</html>
Create an ordered list of your top 5 favorite movies.
Linking to external websites and internal sections
Inserting images in HTML
Image attributes and alternative text
Assignments:
Create a hyperlink that opens a new tab and leads to your favorite website.
<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<h1>Welcome to My Webpage</h1>
<a href="https://www.example.com" target="_blank">Visit Example.com</a>
</body>
</html>
Link an internal section within the same webpage using anchor tags.
<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<h1>Welcome to My Webpage</h1>
<a href="#about">Jump to About Section</a>
<h2 id="about">About</h2>
<p>This is the About section of my webpage.</p>
</body>
</html>
Insert an image of your favorite animal with appropriate alt text.
<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<h1>Welcome to My Webpage</h1>
<img src="animal.jpg" alt="A picture of my favorite animal">
</body>
</html>
Create a gallery of three images using HTML and appropriate attributes.
<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
<style>
h1 {
color: blue;
font-size: 24px;
}
h2 {
color: green;
font-size: 20px;
}
</style>
</head>
<body>
<h1>Welcome to My Webpage</h1>
<h2>About Me</h2>
<!-- Rest of the content -->
</body>
</html>
Add a background color and padding to the paragraphs in your webpage using CSS.
<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
<style>
p {
background-color: lightgray;
padding: 10px;
}
</style>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<!-- Rest of the content -->
</body>
</html>
Create a navigation bar using an unordered list and style it with CSS.
define("PI", 3.14);
echo "The value of PI is: " . PI;
Example 3: Variable scope (local and global):
$globalVariable = "I am a global variable";
function myFunction() {
$localVariable = "I am a local variable";
echo $localVariable;
echo $GLOBALS['globalVariable'];
}
myFunction();
$num1 = 10;
$num2 = 5;
var_dump($num1 == $num2); // Equal to
var_dump($num1 != $num2); // Not equal to
var_dump($num1 > $num2); // Greater than
var_dump($num1 < $num2); // Less than
var_dump($num1 >= $num2); // Greater than or equal to
var_dump($num1 <= $num
2); // Less than or equal to
$num = 10;
if ($num > 0) {
echo "The number is positive";
} else {
echo "The number is not positive";
}
Example 2: Switch case statement:
$day = "Monday";
switch ($day) {
case "Monday":
echo "Today is Monday";
break;
case "Tuesday":
echo "Today is Tuesday";
break;
default:
echo "Today is not Monday or Tuesday";
}
class Person {
public $name;
public $age;
public function sayHello() {
echo "Hello, my name is " . $this->name . " and I am " . $this->age . " years old.";
}
}
$person = new Person();
$person->name = "John";
$person->age = 25;
$person->sayHello();
Example 2: Constructors and property accessors:
class Person {
private $name;
private $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function getName() {
return $this->name;
}
public function getAge() {
return $this->age;
}
}
$person = new Person("John", 25);
echo $person->getName(); // Output: John
echo $person->getAge(); // Output: 25
Example 3: Inheritance:
class Animal {
public function makeSound() {
echo "The animal makes a sound.";
}
}
class Dog extends Animal {
public function makeSound() {
echo "The dog barks.";
}
}
$dog = new Dog();
$dog->makeSound(); // Output: The dog barks.
Example
4: Static properties and methods:
class MathUtils {
public static $pi = 3.14159;
public static function square($num) {
return $num * $num;
}
}
echo MathUtils::$pi; // Output: 3.14159
echo MathUtils::square(5); // Output: 25
Example 5: Abstract classes and interfaces:
abstract class Animal {
abstract public function makeSound();
}
interface CanFly {
public function fly();
}
class Bird extends Animal implements CanFly {
public function makeSound() {
echo "The bird chirps.";
}
public function fly() {
echo "The bird is flying.";
}
}
$bird = new Bird();
$bird->makeSound(); // Output: The bird chirps.
$bird->fly(); // Output: The bird is flying.
Remember to replace “your_username”, “your_password”, and “your_database” with your actual MySQL credentials and database name. Additionally, ensure that PDO extension is enabled in your PHP configuration.
package main
import "fmt"
func main() {
var message string = "Hello, Go!"
fmt.Println(message)
const pi = 3.14159
fmt.Println(pi)
}
Data Types and Type Conversion:
package main
import "fmt"
func main() {
var age int = 25
fmt.Println(age)
var price float64 = 9.99
fmt.Println(price)
var isTrue bool = true
fmt.Println(isTrue)
var name string = "John"
fmt.Println(name)
// Type conversion
var num int = 42
var result float64 = float64(num)
fmt.Println(result)
}
Operators
package main
import "fmt"
func main() {
var a = 10
var b = 5
fmt.Println(a + b)
fmt.Println(a - b)
fmt.Println(a * b)
fmt.Println(a / b)
fmt.Println(a % b)
var isTrue = true
fmt.Println(!isTrue)
}
Control Structures: if-else and switch:
package main
import "fmt"
func main() {
var num = 5
if num > 0 {
fmt.Println("Number is positive")
} else if num < 0 {
fmt.Println("Number is negative")
} else {
fmt.Println("Number is zero")
}
var day = "Monday"
switch day {
case "Monday":
fmt.Println("It's Monday")
case "Tuesday":
fmt.Println("It's Tuesday")
default:
fmt.Println("It's another day")
}
}
Loops: for and range
package main
import "fmt"
func main() {
// For loop
for i := 1; i <= 5; i++ {
fmt.Println(i)
}
// Range loop
nums := []int{1, 2, 3, 4, 5}
for index, value := range nums {
fmt.Println(index, value)
}
}
Functions in Go
Simple Function:
package main
import "fmt"
func add(a, b int) int {
return a + b
}
func main() {
result := add(3, 5)
fmt.Println(result)
}
Function with Multiple Return Values:
package main
import "fmt"
func divide(a, b int) (int, int) {
quotient := a / b
remainder := a % b
return quotient, remainder
}
func main() {
q, r := divide(10, 3)
fmt.Println("Quotient:", q)
fmt.Println("Remainder:", r)
}
Variadic Function:
package main
import "fmt"
func sum(numbers ...int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
func main() {
result := sum(1, 2, 3, 4, 5)
fmt.Println(result)
}
Anonymous Functions and Closures:
package main
import "fmt"
func main() {
add := func(a, b int) int {
return a + b
}
result := add(3, 5)
fmt.Println(result)
}
Recursion:
package main
import "fmt"
func factorial(n int) int {
if n == 0 {
return 1
}
return n * factorial(n-1)
}
func main() {
result := factorial(5)
fmt.Println(result)
}
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5}
fmt.Println(numbers)
fmt.Println(numbers[1:4]) // Slicing a slice
numbers = append(numbers, 6) // Appending an element
fmt.Println(numbers)
numbers = append(numbers[:2], numbers[3:]...) // Removing an element
fmt.Println(numbers)
}
Maps:
package main
import "fmt"
func main() {
person := map[string]string{
"name": "John",
"age": "30",
"email": "john@example.com",
}
fmt.Println(person)
fmt.Println(person["name"])
person["city"] = "New York" // Adding a new key-value pair
fmt.Println(person)
delete(person, "age") // Removing a key-value pair
fmt.Println(person)
}
Iterating over Slices and Maps:
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Println(index, value)
}
person := map[string]string{
"name": "John",
"age": "30",
"email": "john@example.com",
}
for key, value := range person {
fmt.Println(key, ":", value)
}
}
Structs and Methods in Go
Structs:
package main
import "fmt"
type Person struct {
name string
age int
address string
}
func main() {
person := Person{"John", 30, "New York"}
fmt.Println(person)
fmt.Println(person.name)
fmt.Println(person.age)
fmt.Println(person.address)
}
Certainly! Here are ten examples for each of the topics you mentioned:
BASICS
Basics: Example 1: Printing a message
print("Hello, World!")
Example 2: Arithmetic operations
a = 10
b = 5
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Modulo:", a % b)
Example 3: String concatenation
name = "Alice"
age = 25
print("My name is " + name + " and I am " + str(age) + " years old.")
Example 4: Using the input function
name = input("Enter your name: ")
print("Hello, " + name + "!")
Example 5: Conditional statements
num = int(input("Enter a number: "))
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
text = "Hello, World!"
print("Length:", len(text))
Example 9: Using the str() function
num = 42
text = "The answer is: " + str(num)
print(text)
Example 10: Importing and using modules
import math
radius = 5
area = math.pi * radius ** 2
print("Area of the circle:", area)
CONDITIONAL STATEMENTS IF ELSE
If-Else Statements: Example 1: Checking if a number is even or odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Example 2: Checking if a year is a leap year
year = int(input("Enter a year: "))
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print("The year is a leap year.")
else:
print("The year is not a leap year.")
Example 3: Determining the maximum of three numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
max_num = max(num1, num2, num3)
print("The maximum number is:", max_num)
Example 4: Checking if a student passed or failed
score = float(input("Enter the student's score: "))
if score >= 60:
print("The student passed.")
else:
print("The student failed.")
Example 5
: Categorizing a number into different ranges
num = float(input("Enter a number: "))
if num < 0:
print("The number is negative.")
elif num >= 0 and num <= 10:
print("The number is between 0 and 10.")
elif num > 10 and num <= 20:
print("The number is between 10 and 20.")
else:
print("The number is greater than 20.")
Example 6: Checking if a person is eligible to vote
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")
Example 7: Checking if a number is positive, negative, or zero (alternative approach)
num = float(input("Enter a number: "))
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
Example 8: Checking if a character is a vowel or consonant
char = input("Enter a character: ").lower()
if char in ['a', 'e', 'i', 'o', 'u']:
print("The character is a vowel.")
else:
print("The character is a consonant.")
Example 9: Checking if a number is a multiple of another number
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
if num1 % num2 == 0:
print(num1, "is a multiple of", num2)
else:
print(num1, "is not a multiple of", num2)
Example 10: Checking if a year is a leap year (alternative approach)
year = int(input("Enter a year: "))
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print("The year is a leap year.")
else:
print("The year is not a leap year.")
For loop with range
Printing numbers from 0 to 9:
for i in range(10):
print(i)
Printing even numbers from 2 to 10:
for i in range(2, 11, 2):
print(i)
Calculating the sum of numbers from 1 to 100:
total = 0
for i in range(1, 101):
total += i
print("Sum:", total)
Printing numbers in reverse order from 9 to 0:
for i in range(9, -1, -1):
print(i)
Multiplying each number in the range by 2 and printing the result:
for i in range(10):
result = i * 2
print(result)
Printing the square of each number in the range from 1 to 5:
for i in range(1, 6):
square = i ** 2
print(square)
Printing numbers in increments of 5 from 0 to 50:
for i in range(0, 51, 5):
print(i)
Checking if a number is divisible by 3 in the range from 1 to 20:
for i in range(1, 21):
if i % 3 == 0:
print(i, "is divisible by 3")
Printing the ASCII value of each character in a string:
text = "Hello"
for char in text:
ascii_value = ord(char)
print(char, ":", ascii_value)
Repeating a specific action a certain number of times using range: