Blog

Demo

Basic

  1. WAP to read 2 numbers and print addition
  2. WAP to read 2 numbers and print subtraction
  3. WAP to read 2 numbers and print multiplication
  4. WAP to read 2 numbers and print division
  5. WAP to read 2 numbers and print modulus (Remainder)
  6. WAP to read radius and print area and circumference of circle
  7. WAP to read length and breadth and print area and perimeter of rectangle

Conditional Statement (if else)

  1. WAP to read a number and check if its positive or negative
  2. WAP to read a number and check it is even or odd
  3. WAP to read 2 numbers and find greatest among them
  4. WAP to read 3 numbers and find greatest among them
  5. WAP to read marks of 5 subjects and check the student is pass or failed
    1. add validation for marks less than 0
    2. add validation for marks greater than 100

Loops

  1. WAP to print hello world 10 times with numbering
  2. WAP to print square of numbers from 1 to 10
  3. WAP to print numbers from 1 to given number
  4. WAP to print cube of numbers from 1 to given number
  5. WAP to read a number and print table of that number
  6. WAP to execute Fizz Buzz Problem / Print number 1 to 100
    1. if number is divisible by 3 then print Fizz
    2. if number is divisible by 5 then print Buzz
    3. if number is divisible by both 3 and 5 then print Fizz Buzz
  7. WAP to execute lift program of 20 floor
    1. print number with delay of 1 sec (use time module’s sleep method)
    2. skip 13 number
    3. break after printing 13
  8. WAP to create random jackpot number and take input from user to guess the number. Based on level the attempt to guess the number should change
    1. Easy – 20 attempts
    2. Medium – 10 attempts
    3. Difficult – 5 attempts

How to clear RAM – Clear Cache – Drop Cache

The “1, 2, 3” cache clear method in Linux refers to clearing different types of caches managed by the operating system. Each cache type is managed differently and cleared by writing a specific value to the file /proc/sys/vm/drop_caches.

Cache Types:

  1. PageCache (Value: 1):
    • PageCache stores file contents that are cached in memory to reduce disk I/O.
  2. Dentries and Inodes (Value: 2):
    • Dentry is a cache of directory entries, and inodes store file metadata.
  3. PageCache + Dentries + Inodes (Value: 3):
    • Clears both PageCache and Dentry/inode caches.

Steps to Clear Cache with Examples:

1. Check Current Memory Usage

Use the free -h command to view current memory and cached memory:

free -h

Look under the “buff/cache” column to see the cache usage.

2. Clear Cache

Use the following commands to clear caches. Root privileges are required, so prefix with sudo:

Clear PageCache:
sudo sh -c "echo 1 > /proc/sys/vm/drop_caches"
Clear Dentry and Inode Cache:
sudo sh -c "echo 2 > /proc/sys/vm/drop_caches"
Clear Both PageCache and Dentry/Inode Cache:
sudo sh -c "echo 3 > /proc/sys/vm/drop_caches"

3. Check Memory Usage Again

Run the free -h command again to verify that the cache has been cleared.

Example Workflow:

  1. Check Memory Before Clearing: free -h Output: total used free shared buff/cache available Mem: 15Gi 4.0Gi 2.0Gi 0.5Gi 9Gi 10Gi Swap: 2Gi 0B 2Gi
  2. Clear All Caches (PageCache, Dentries, and Inodes): sudo sh -c "echo 3 > /proc/sys/vm/drop_caches"
  3. Check Memory After Clearing: free -h Output: total used free shared buff/cache available Mem: 15Gi 4.0Gi 7.0Gi 0.5Gi 4Gi 11Gi Swap: 2Gi 0B 2Gi

Notice how the “buff/cache” column decreases.

Best Practices

  • Clearing caches isn’t typically necessary because Linux uses unused memory to cache files and automatically clears it when needed.
  • Use this method only for debugging or specific needs (e.g., testing performance under no cache conditions).

Would you like to try this on your system now? Let me know if you need additional help!

Let’s break down PageCache, Dentries, and Inodes with simple explanations and commands you can use on your Ubuntu system to see how they work.


1. PageCache

  • What it is:
    • PageCache stores file data read from disk in memory to speed up future reads.
    • If a file is accessed again, the system reads it from memory instead of the slower disk.
  • Example:
    1. Create a Large File: dd if=/dev/zero of=testfile bs=1M count=100 This creates a file testfile of 100 MB size.
    2. Clear Cache: sudo sh -c "echo 3 > /proc/sys/vm/drop_caches"
    3. Read the File (Populates PageCache): time cat testfile > /dev/null The first read is slow because it loads data from disk.
    4. Read the File Again (From PageCache): time cat testfile > /dev/null The second read is faster as it fetches data from memory (PageCache).
    5. Verify Cache Usage: Check memory usage using: free -h

2. Dentries

  • What it is:
    • A dentry (directory entry) cache stores metadata about directories, such as filenames and their locations in the filesystem.
    • This speeds up directory traversals and file lookups.
  • Example:
    1. Clear Cache: sudo sh -c "echo 3 > /proc/sys/vm/drop_caches"
    2. List a Large Directory (Populates Dentry Cache): ls -R /usr > /dev/null
    3. List the Directory Again (From Dentry Cache): time ls -R /usr > /dev/null The second run will be faster because the directory structure is cached in memory.

3. Inodes

  • What it is:
    • An inode is a data structure storing metadata about a file (e.g., permissions, owner, size).
    • Inode caching stores this metadata to reduce disk reads.
  • Example:
    1. Find Inodes Used by the System: df -i This shows the inode usage for each mounted filesystem.
    2. Create Many Files (Populates Inode Cache): mkdir testdir for i in {1..10000}; do touch testdir/file$i; done
    3. Clear Cache: sudo sh -c "echo 2 > /proc/sys/vm/drop_caches"
    4. List Files (Rebuilds Inode Cache): time ls testdir > /dev/null
    5. List Files Again (From Inode Cache): time ls testdir > /dev/null The second run will be faster due to inode caching.

Summary of Commands:

  • free -h: Check memory usage (PageCache in “buff/cache”).
  • df -i: Check inode usage for filesystems.
  • echo [1|2|3] > /proc/sys/vm/drop_caches: Clear caches.

The command dd if=/dev/zero of=testfile bs=1M count=100 is a Linux command used to create a file filled with zeros. Here’s a breakdown of each part:

Command Breakdown:

  1. dd:
    • A low-level command-line utility used for copying and converting data between files or devices.
  2. if=/dev/zero:
    • if stands for “input file.”
    • /dev/zero is a special file in Linux that produces a continuous stream of null bytes (zeros).
  3. of=testfile:
    • of stands for “output file.”
    • testfile is the name of the file where the data (zeros) will be written.
  4. bs=1M:
    • bs stands for “block size.”
    • This sets the size of each block of data to 1 Megabyte (MB).
  5. count=100:
    • Specifies the number of blocks to copy.
    • In this case, 100 blocks of 1 MB each.

What the Command Does:

  • It writes 100 MB (1 MB × 100 blocks) of zero-filled data to a file named testfile.

Example Output:

When you run the command, you’ll see something like this:

100+0 records in
100+0 records out
104857600 bytes (105 MB) copied, 0.123456 s, 847 MB/s

This means:

  • 100+0 records in: 100 blocks read from the input file (/dev/zero).
  • 100+0 records out: 100 blocks written to the output file (testfile).
  • 104857600 bytes: Total bytes written (100 MB).
  • 0.123456 s: Time taken to execute the command.
  • 847 MB/s: Write speed.

Verify the File:

  • Check the file size: ls -lh testfile You should see the size as 100 MB.
  • Inspect the file contents: hexdump -C testfile | head This will display the file’s contents in hexadecimal format, and you’ll see it filled with 00 (zeros).

Why clearing dentries does not affect memory a lot

The behavior you’re observing can be explained by how Linux handles PageCache and Dentries/Inodes caching.

Key Points:

  1. PageCache (Cleared with echo 1 > /proc/sys/vm/drop_caches):
    • Clearing PageCache removes cached file data but does not clear dentries and inodes.
    • If you only clear the PageCache, Linux has to read file contents from disk, but dentry and inode information might still be available in memory.
  2. Dentries and Inodes (Cleared with echo 2 > /proc/sys/vm/drop_caches):
    • Clearing dentry and inode caches removes directory structure and file metadata information from memory.
    • If dentry and inode caches are cleared, listing directories or performing file operations becomes slower because the system must rebuild this information by reading from disk.

Your Test Results:

  1. Before Cache Clear:
    • The first ls -R command runs quickly (0.343s) because both PageCache and dentry/inode caches are populated.
  2. After Clearing PageCache:
    • After running echo 1 > /proc/sys/vm/drop_caches, the second ls -R command takes significantly longer (2.756s) because:
      • PageCache is cleared, so file contents must be reloaded from disk.
      • However, dentries and inodes are not cleared, so some metadata is still available.

Why It Still Takes More Time:

The additional time comes from the fact that:

  1. After clearing the PageCache, the system has to read the file contents (or parts of the directory structure) from disk, which is slower than fetching them from memory.
  2. Even though dentries and inodes are still in memory, they depend on PageCache for efficient access to file content. So the system has to do extra work to populate the PageCache again.
  3. Directory traversal involves a combination of file metadata (dentries/inodes) and directory file contents (loaded via PageCache). Clearing just the PageCache impacts this process.

Solution to Test Dentry Cache Impact:

To focus solely on dentry and inode caches, you need to clear them explicitly with:

sh -c "echo 2 > /proc/sys/vm/drop_caches"

Then rerun:

time ls -R /usr > /dev/null

You’ll notice that this run will also take longer compared to when the dentry cache is intact, but the pattern will differ from clearing the PageCache.


Suggested Workflow to Understand All Cache Impacts:

  1. Baseline: time ls -R /usr > /dev/null
  2. Clear PageCache: sh -c "echo 1 > /proc/sys/vm/drop_caches" time ls -R /usr > /dev/null
  3. Clear Dentries and Inodes: sh -c "echo 2 > /proc/sys/vm/drop_caches" time ls -R /usr > /dev/null
  4. Clear Both PageCache and Dentries/Inodes: sh -c "echo 3 > /proc/sys/vm/drop_caches" time ls -R /usr > /dev/null

This should give you a clear understanding of how each type of cache contributes to performance.

inotify

You can watch realtime operations happing in directory using inotifywatch and inotifywait command

Install inotify tool

sudo apt install inotify-tools

Create directory

mkdir -p /tmp/test

Watch action

inotifywatch -v -e modify,create,delete /tmp/test

Ctrl + C

#Then check statistics

Real time watch action

inotifywait -m -e modify,create,delete /tmp/test/
inotifywait -m -r -e modify,create,delete /tmp/test/

Now try to create modify and delete the file

touch /tmp/test/file1.txt
echo "Hello" > /tmp/test/file1.txt
rm /tmp/test/file1.txt

Ctrl + C
Left terminal to watch activities and right one to run commands

To monitor multiple paths at a time run following commands

inotifywatch -e access,modify /home/user/myfolder /home/user/another_folder /home/user/myfile.txt
OR
inotifywait -m -e access,modify /home/user/myfolder /home/user/another_folder /home/user/myfile.txt

Elastic Search

To check health

curl -X GET "localhost:9200/_cat/health"

To list all index (tables)

curl -X GET "localhost:9200/_cat/indices"

To delete existing index

curl -X DELETE localhost:9200/logs

To delete multiple indices at a time

curl -X DELETE localhost:9200/index1,index2,index3

To create new index(table)

curl -X PUT localhost:9200/index1

To insert new document

curl -X POST localhost:9200/users/_doc -H 'Content-Type: application/json' -d '{"name":"Shailesh", "age": 35, "city": "Nagpur"}'

To list all documents

curl -X GET localhost:9200/users/_search?pretty

To limit / size

curl -X GET localhost:9200/users/_search -H 'Content-Type: application/json' -d '{"size":2}'

To add limit with offset

curl -X GET localhost:9200/users/_search -H 'Content-Type: application/json' -d '{"from":3, "size":2}'

To list with where clause and equal operator

curl -X GET localhost:9200/users/_search?pretty -H 'Content-Type: application/json' -d '{"query": {"match": {"name": "Shailesh"}}}'

With like query

curl -X GET localhost:9200/users/_search?pretty -H 'Content-Type: application/json' -d '{"query": {"wildcard":{"name.keyword":"Shail*"}}}'

With range

curl -X GET localhost:9200/users/_search -H 'Content-Type: application/json' -d '{"query": { "range" : {"salary": {"gt": 10000, "lt":30000}} } }'
curl -X GET localhost:9200/users/_search -H 'Content-Type: application/json' -d '{"query": { "range" : {"salary": {"gte": 10000, "lte":30000}} } }'

Select data from more than one index

curl -X GET localhost:9200/table1,table2/_search
curl -X GET localhost:9200/table1,table2/_search -H 'Content-Type: application/json' -d '{"query": {"range": {"salary": {"gt": "20000"}}}}'

This will search data from both the indices and will show all the documents whose salary is greater than 20000

Now the most important command, the full text search

curl -X GET "localhost:9200/users/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "match": {
      "name": {
        "query": "Amit Desai",
        "operator": "and"
      }
    }
  }
}'

This will search amit and desai matches in any order, you can use or operator also if wanted to match any of the word from amit and desai

How to create rpm package

Install required tools

rpm -qa | grep rpmdevtools
yum list | grep rpmdevtools
yum install rpmdevtools

Create directory structure required for rpm build if not exist

rpmdev-setuptree
rpmbuild/
├── BUILD
├── RPMS
├── SOURCES
├── SPECS
└── SRPMS

Create source package under SOURCES

mkdir hello-0.0.1
cd hello-0.0.1

hello.sh

#!/bin/sh
echo "Hello world"
tar -cvzf hello-0.0.1.tar.gz hello-0.0.1

Create spec file and make necessary changes

cd ~/rpmbuild/SPECS
rpmdev-newspec hello.spec
Name:           hello
Version:        0.0.1
Release:        1%{?dist}
Summary:        A simple hello world script
BuildArch:      noarch

License:        GPL
Source0:        %{name}-%{version}.tar.gz

Requires:       bash

%description
A demo RPM build

%prep
%setup -q

%install
rm -rf $RPM_BUILD_ROOT
mkdir -p $RPM_BUILD_ROOT/opt/hello
cp * $RPM_BUILD_ROOT/opt/hello

%clean
rm -rf $RPM_BUILD_ROOT

%files
/opt/hello/*

%postun
rm -vrf /opt/hello

%changelog
* Sun Feb 04 2024 
- First version being packaged

Now directory structure should look like this

/home/tux/rpmbuild/
├── BUILD
├── BUILDROOT
├── RPMS
├── SOURCES
│   └── hello-0.0.1.tar.gz
├── SPECS
│   └── hello.spec
└── SRPMS

Build rpm using following command

rpmbuild -ba SPECS/hello.spec

where -b is build a is for both source and binary
if you want only binary then put -bb flag
if you want only source then put -bs flag

Install the rpm using following command

sudo rpm -ivh ~/rpmbuild/RPMS/noarch/hello-0.0.1-1.el8.noarch.rpm

Verify rpm installed successfully using following command

rpm -qi hello
tree /opt/hello

The %changelog entry of a package can be viewed, too:

rpm -q hello –changelog

Uninstall or erase installed rpm

sudo rpm -q | grep hello
sudo rpm -ve hello

Troubleshoot

To extract files and directories from rpm

rpm2cpio hello-0.0.1-1.el8.noarch.rpm | cpio -idmv

XML

users.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE users>
<?xml-stylesheet type="text/xsl" href="users.xslt"?>
<users>
  <user>
    <name>John Doe</name>
    <age>26</age>
    <city>New York</city>
  </user>
  <user>
    <name>Alice Smith</name>
    <age>25</age>
    <city>Los Angeles</city>
  </user>
  <user>
    <name>Pintu</name>
    <age>23</age>
    <city>Mumbai</city>
  </user>
</users>

users.xslt

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="yes"/>

  <xsl:template match="/users">
    <html>
      <head>
        <title>User Information</title>
      </head>
      <body>
        <h2>User Information</h2>
        <table border="1">
          <tr>
            <th>Name</th>
            <th>Age</th>
            <th>City</th>
          </tr>
          <xsl:for-each select="user">
            <tr>
              <td><xsl:value-of select="name"/></td>
              <td><xsl:value-of select="age"/></td>
              <td><xsl:value-of select="city"/></td>
            </tr>
          </xsl:for-each>
        </table>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

POC

Run xml file on VSCode Live Server

Assignment

Remove city and use address with children city and state and then show same in html table

C++ Mini Project

Problem Statement

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
    1. Create a class Person with datamembers: name, age, city
    2. Create a class Employee which will inherit features of Person class with it’s own datamembers: empid, department, salary
  • P1
    1. Create array of 10 employees and print its data using for loop
  • P2
    1. Find and Print Total Salary, Average Salary, Max Salary, Min Salary
  • P3
    1. Create function getMaxSalEmps() to print employees having highest salary
    2. Create function getMinSalEmps() to print all employees having minimum salary
  • P4
    1. Create function getDeptWiseSalary() to print department wise total salary

Sample Output

How to deploy express app on netlify

Step 1: Login to netlify.com from browser (preferably from default browser using github account)

https://www.netlify.com/

Install netlify locally

npm install netlify-cli -g

Login to netlify from console

netlify init

Step 2: Create project locally with api file projectfolder/functions/api.js

const express = require('express');
const serverless = require('serverless-http');
const app = express();
const router = express.Router();

router.get('/', (req, res) => {
  res.send('App is running..');
});

app.use('/.netlify/functions/api', router);
module.exports.handler = serverless(app);

//const port = 8080;
//app.listen(process.env.PORT || port, () => {	
//	console.log(`Listening on port ${port}`);
//});

Step 3: As we are deploying using lambda function create projectfolder/netlify.toml in project root directory

[build]
    functions = "functions"

Step 4: Modify package.json file

{
    "scripts": {
      "build": "netlify deploy --prod"
    },
    "dependencies": {
      "express": "^4.18.2",
      "netlify-cli": "^12.7.2",
      "netlify-lambda": "^2.0.15",
      "serverless-http": "^3.2.0"
    }
}

Step 5: Install required packages/modules

npm i express

Step 6: Test application locally

netlify functions:serve

Step 7: Build the project and deploy on netlify

NOTE: If you are running it for 1st time then chose Create & configure a new site

npm run build

Access api from browser/postman

https://yourproject.netlify.app/.netlify/functions/api

You can check your functions api in netlify portal as well

https://app.netlify.com/sites/<your-project>/functions/api

CRUDL APP

api.js

const conn_str = "mongodb+srv://<username>:<password>@cluster0.<clusterid>.mongodb.net/<databasename>?retryWrites=true&w=majority";
const mongoose = require("mongoose");

mongoose.connect(conn_str)
.then(() => console.log("Connected successfully..."))
.catch( (error) => console.log(error) );


const express = require("express");
const serverless = require('serverless-http');
const app = express();
const router = express.Router();
var cors = require('cors')
app.use(express.json());
app.use(cors())

const empSchema = new mongoose.Schema(    {
    name: String,
    contact_number: String,
    address: String,
    salary: Number,
    employee_id: Number,
    role: String
});

const emp = mongoose.models.emps || new mongoose.model("emps", empSchema);

router.get('/', (req, res) => {
    res.send('App is running..');
});

router.get("/employees", async (req, res) => {
    // var data = [{name: "hari", salary: 25000}, {name: "sameer", salary: 23000}]
    let data = await emp.find();
    res.send(data)
})

//fetch single document by id
//http://localhost:8989/employees/657d397eea713389134d1ffa

router.get("/employees/:id", async (req, res) => {
    // console.log(req.params)
    let data = await emp.find({_id: req.params['id']});
    res.send(data[0])
})

//update document by id
router.put("/employees", async (req, res) => {

	let u_data = await emp.updateOne({"_id": req.body.id}, {
		"$set": {
			"name" : req.body.name,
			"salary" : req.body.salary,
		}
	});
	
	res.send(u_data);

})


//http://localhost:8989/employees?id=657d397eea713389134d1ffe
router.delete("/employees", async (req, res) => {
    let d_data = await emp.deleteOne({"_id": req.query['id']});
	res.send(d_data);
})

router.post("/employees", async (req, res) => {

    // doc = {
    //     "name":"harsha newly added",
    //     "contact_number":"9833910512",
    //     "address":"mumbai",
    //     "salary":20000,
    //     "employee_id":98829,
    //     "role":"operations"
    // }

    doc = req.body;

    let u = await emp(doc);
	let result = u.save();
	res.send(doc);

})

app.use('/.netlify/functions/api', router);
module.exports.handler = serverless(app);

C crash course

Day 1: Introduction to C Programming

  • Session 1 (3 hours): Introduction to C Programming.
  • Explanation: Learn about the basics of C programming, the structure of a C program, and how to use the printf function to display output.
  • Syntax Example:
#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

Assignment 1: Write a program that displays “Hello, World!” on the screen.

Output:

  Hello, World!

Assignment 2: Create a program that calculates the area of a rectangle using user-provided width and height.

#include <stdio.h>

int main() {
    float width, height, area;

    printf("Enter width: ");
    scanf("%f", &width);

    printf("Enter height: ");
    scanf("%f", &height);

    area = width * height;
    printf("Area: %.2f\n", area);

    return 0;
}

Output (example):

  Enter width: 4.5
  Enter height: 7.2
  Area: 32.40
  • 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

Day 2: Control Flow and Functions

  • Session 1 (3 hours): Conditional statements (if, else if, else), logical operators.
  • 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;
}

Output (example):

  Smallest element: 5
  • Session 2 (3 hours): Introduction to strings, string functions (strlen, strcpy, etc.).
  • Explanation: Learn about strings in C, which are arrays of characters. Explore various string functions for manipulation.
  • Syntax Example:
#include <stdio.h>

int main() {
    char name[20] = "John";
    printf("Hello, %s!\n", name);

    return 0;
}
  • Assignment 1: Create a program that checks if a given string is a palindrome. Output (example):
  Enter a string: radar
  Palindrome

Assignment 2: Write a program that counts the number of vowels in a user-provided string.

#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    int i, vowels = 0;

    printf("Enter a string: ");
    scanf("%s", str);

    for (i = 0; i < strlen(str); i++) {
        char ch = tolower(str[i]);
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            vowels++;
        }
    }

    printf("Number of vowels: %d\n", vowels);

    return 0;
}

Output (example):

  Enter a string: education
  Number of vowels: 5

Day 4: Pointers and Memory Management

  • Session 1 (3 hours): Pointers, pointer arithmetic, and references.
  • Explanation: Learn about pointers, memory addresses, and how to use pointers to manipulate variables and arrays.
  • Syntax Example:
#include <stdio.h>

int main() {
    int num = 5;
    int *ptr = &num;

    printf("Value of num: %d\n", num);
    printf("Value at ptr: %d\n", *ptr);

    return 0;
}
  • Assignment 1: Write a program that swaps the values of two variables using pointers. Output (example):
  Before swapping: num1 = 5, num2 = 10
  After swapping: num1 = 10, num2 = 5
  • Assignment 2: Develop a program that uses pointers to reverse an array of integers. Output (example):
  Original array: 5 10 15 20 25
  Reversed array: 25 20 15 10 5
  • Session 2 (3 hours): Dynamic memory allocation (malloc, free) and memory leaks.
  • 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");

FILE *outputFile = fopen(“grades.txt”, “w”);

    struct Student student;

    while (fscanf(inputFile, "%s %d %d %d", student.name, &student.marks[0], &student.marks[1], &student.marks[2]) != EOF) {
        // ... code to calculate grade ...

        fprintf(outputFile, "Student Name: %s\n", student.name);
        fprintf(outputFile, "Marks: %d %d %d\n", student.marks[0], student.marks[1], student.marks[2]);
        fprintf(outputFile, "Grade: %c\n", calculateGrade(totalMarks));
    }

    fclose(inputFile);
    fclose(outputFile);

    return 0;
}

Output (example):

  Student Name: John Doe
  Marks: 80 85 90
  Grade: A
#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");


    FILE *outputFile = fopen("grades.txt", "w");

    struct Student student;

    while (fscanf(inputFile, "%s %d %d %d", student.name, &student.marks[0], &student.marks[1], &student.marks[2]) != EOF) {
        // ... code to calculate grade ...

        fprintf(outputFile, "Student Name: %s\n", student.name);
        fprintf(outputFile, "Marks: %d %d %d\n", student.marks[0], student.marks[1], student.marks[2]);
        fprintf(outputFile, "Grade: %c\n", calculateGrade(totalMarks));
    }

    fclose(inputFile);
    fclose(outputFile);

    return 0;
}

Output (example):

  Student Name: John Doe
  Marks: 80 85 90
  Grade: A

Linux Crash Course

Day 1: Introduction to Linux

Topics:

  1. Linux operating system
    Explanation: Learn about the Linux operating system, its features, and its popularity among developers and system administrators.
  2. 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).
  3. File and directory management
    Explanation: Learn how to create, delete, move, and rename files and directories using commands like touch, rm, mv, and cp.
  4. 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.
  5. 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:

  1. 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).
  2. 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).
  3. List all the files and directories in the current directory.
    Answer: ls (to list files and directories).
  4. Rename the file “my_text.txt” to “new_text.txt”.
    Answer: mv my_text.txt new_text.txt (to rename the file).
  5. 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:

  1. 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).
  2. 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).
  3. Changing file ownership and group
    Explanation: Learn how to change the owner and group of a file using the chown and chgrp commands.
  4. File compression and archiving
    Explanation: Discover commands like tar (archive files) and gzip (compress files) to manage large file collections efficiently.
  5. File searching and filtering
    Explanation: Learn about commands like find (search for files and directories) and grep (search for text patterns in files).

Assignments:

  1. 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).
  2. Display the first 5 lines of the file “sample.txt”.
    Answer: head -n 5 sample.txt (to display the first 5 lines).
  3. Set the file permissions of “sample.txt” to read and write for the owner only.
    Answer: chmod 600 sample.txt (to set the permissions).
  4. Change the owner of “sample.txt

” to a different user.
Answer: chown username sample.txt (to change the owner to the specified username).

  1. 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:

  1. Introduction to Vim
    Explanation: Understand the basics of the Vim editor, including its modes (Normal, Insert, Visual), navigation, and command execution.
  2. 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).
  3. 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.
  4. 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).
  5. 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:

  1. 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).
  2. 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.
  3. Delete the current line in Vim.
    Answer: Press dd (to delete the current line).
  4. 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).
  5. Save the changes made to the file and exit Vim.
    Answer: Press :wq (to save and quit).

Day 4: Advanced Vim Editing

Topics:

  1. 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).
  2. 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).
  3. 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).
  4. 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).
  5. 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:

  1. 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”).
  2. Replace all occurrences of the word “old” with “new” in the current line.
    Answer: :s/old/new/ (to perform the substitution).
  3. Join the current line with the line below it.
    Answer: Press J (to join the lines).
  4. Split the Vim editor window vertically.
    Answer: :vsplit (to split the window vertically).
  5. 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:

  1. Vim configuration files
    Explanation: Understand the .vimrc file and how to customize Vim settings, key mappings, and plugins.
  2. Customizing Vim colorschemes
    Explanation: Learn how to change the colorscheme in Vim to enhance the visual appearance and readability of your code.
  3. Advanced Vim features and plugins
    Explanation: Explore advanced Vim features like macros, multiple cursors (using plugins), and code completion (using plugins).
  4. 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).
  5. Vim documentation and help
    Explanation: Learn how to access Vim documentation and help resources, including built-in help pages and online resources.

Assignments:

  1. 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.
  1. Change the colorscheme in Vim to a different one.
    Answer: In Vim, type :colorscheme <colorscheme_name> to change the colorscheme.
  2. Create a macro in Vim that inserts a specific code snippet.
    Answer: Record the macro using q<register> and replay it using @<register>.
  3. 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.
  4. 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:

  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"
  1. 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
  1. Write a shell script that reads a string from the user and prints it in reverse order.
#!/bin/bash

echo "Enter a string: "
read input_string

reversed_string=$(echo "$input_string" | rev)
echo "Reversed string: $reversed_string"
  1. 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
  1. 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:

  1. 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
  1. 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"
  1. 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
  1. 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
  1. 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:

  1. 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
  1. 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
  1. 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
  1. 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
  1. Create a shell script that prints the current date and time.
#!/bin/bash

current_date=$(date +"%Y-%m-%d")
current_time=$(date +"%H:%M:%S")

echo "Current date: $current_date"
echo "Current time: $current_time"

Day 4:

  1. 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
  1. 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
  1. 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
  1. 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
  1. Write a shell script that reads a string as input and converts it to uppercase.
#!/bin/bash

echo "Enter a string: "
read input_string

upper_case_string=$(echo "$input_string" | tr '[:lower:]' '[:upper:]')

echo "Uppercase string: $upper_case_string"

Day 5:

  1. 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"
  1. 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
  1. 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
  1. 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
  1. 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"

mysql crash course

Day 1: Basic SQL Queries

Topics:

  1. Introduction to SQL and relational databases
  2. Creating a database and tables
  3. Inserting data into tables
  4. Retrieving data with SELECT statement
  5. Filtering and sorting data

Assignments:

  1. Create a database named “mydb”.
   CREATE DATABASE mydb;
  1. Create a table named “users” with columns id, name, age, city, added_at, and updated_at.
   CREATE TABLE users (
     id INT PRIMARY KEY,
     name VARCHAR(50),
     age INT,
     city VARCHAR(50),
     added_at DATETIME,
     updated_at DATETIME
   );
  1. Insert 5 records into the “users” table.
   INSERT INTO users (id, name, age, city, added_at, updated_at)
   VALUES
     (1, 'John', 25, 'Mumbai', '2022-01-01', '2022-01-02'),
     (2, 'Jane', 30, 'Delhi', '2022-01-03', '2022-01-04'),
     (3, 'Mike', 35, 'Bangalore', '2022-01-05', '2022-01-06'),
     (4, 'Lisa', 28, 'Chennai', '2022-01-07', '2022-01-08'),
     (5, 'David', 32, 'Kolkata', '2022-01-09', '2022-01-10');
  1. Retrieve all records from the “users” table.
   SELECT * FROM users;
  1. Retrieve the names of users whose age is greater than 30.
   SELECT name FROM users WHERE age > 30;

Day 2: Data Manipulation

Topics:

  1. Updating records with UPDATE statement
  2. Deleting records with DELETE statement
  3. Limiting and pagination with LIMIT and OFFSET
  4. Aggregation functions: COUNT, SUM, AVG, MIN, MAX
  5. Grouping data with GROUP BY

Assignments:

  1. Update the age of the user with id 2 to 35.
   UPDATE users SET age = 35 WHERE id = 2;
  1. Delete the user with id 4 from the “users” table.
   DELETE FROM users WHERE id = 4;
  1. Retrieve the first 3 records from the “users” table.
   SELECT * FROM users LIMIT 3;
  1. Retrieve the total number of users in the “users” table.
   SELECT COUNT(*) FROM users;
  1. Retrieve the average age of users.
   SELECT AVG(age) FROM users;

Day 3: Filtering and Sorting

Topics:

  1. Using WHERE clause for conditional filtering
  2. Using comparison operators: =, <>, <, >, <=, >=
  3. Using logical operators: AND, OR, NOT
  4. Sorting data with ORDER BY clause
  5. Sorting in ascending and descending order

Assignments:

  1. Retrieve the names of users whose city is ‘Mumbai’.
 SELECT name FROM users WHERE city = 'Mumbai';
  1. Retrieve the names of users whose age is between 25 and 35.
   SELECT name FROM users WHERE age BETWEEN 25 AND 35;
  1. Retrieve the names of users whose city is not ‘Delhi’.
   SELECT name FROM users WHERE city <> 'Delhi';
  1. Retrieve all records from the “users” table sorted by age in ascending order.
   SELECT * FROM users ORDER BY age ASC;
  1. 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:

  1. Using aggregate functions: COUNT, SUM, AVG, MIN, MAX
  2. Working with NULL values: IS NULL, IS NOT NULL
  3. Using mathematical functions: ROUND, CEILING, FLOOR
  4. String functions: CONCAT, UPPER, LOWER, LENGTH
  5. Date functions: NOW, DATE_FORMAT, DATE_ADD, DATE_SUB

Assignments:

  1. Retrieve the total number of users in the “users” table.
   SELECT COUNT(*) FROM users;
  1. Retrieve the sum of ages of all users.
   SELECT SUM(age) FROM users;
  1. Retrieve the average age of users excluding NULL values.
   SELECT AVG(age) FROM users WHERE age IS NOT NULL;
  1. Retrieve the concatenated names and cities of all users.
   SELECT CONCAT(name, ', ', city) AS info FROM users;
  1. Retrieve the current date and time.
   SELECT NOW();

Day 5: Grouping and Filtering with HAVING Clause

Topics:

  1. Grouping data with GROUP BY clause
  2. Filtering grouped data with HAVING clause
  3. Using aggregate functions with GROUP BY
  4. Using multiple columns in GROUP BY
  5. Combining GROUP BY, HAVING, and ORDER BY

Assignments:

  1. 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;
  1. Retrieve the cities with more than 2 users.
   SELECT city FROM users GROUP BY city HAVING COUNT(*) > 2;
  1. Retrieve the average age of users in each city.
   SELECT city, AVG(age) AS average_age FROM users GROUP BY city;
  1. 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);
  1. 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;