MCS 022 Solution (2019-2020)

Q1. a) What are the two criteria for classification of the advanced operating systems? Discuss any two operating systems in both the categories.
Answer : -
Advanced Operating Systems
  1. Architecture Driven System
    1. Network Operating System
    2. Distributed Operating System
    3. Multiprocessor Operating System
  2. Application Driven System
    1. Database Operating System
    2. Real-Time Operating System
    3. Multimedia Operating System

Network Operating System
A network operating system is a specialized operating system for a network device such as a router, switch or firewall.
Historically operating systems with networking capabilities were described as network operating system, because they allowed personal computers (PCs) to participate in computer networks and shared file and printer access within a local area network (LAN).
Network operating systems can be embedded in a router or hardware firewall that operates the functions in the network layer (layer 3).
Some important Network OS are listed below -
  • Cisco IOS - Cisco Internet work Operating System (IOS) is a family of network operating systems used on many Cisco Systems routers and current Cisco network switches. Earlier, Cisco switches ran Cat OS. IOS is a package of routing, switching, internet working and telecommunications functions integrated into a multitasking operating system.
  • Cisco NX-OS - NX-OS is a network operating system for the Nexus-series Ethernet switches and MDS-series  fibre Channel storage area network switches made by Cisco Systems.
  • AppleShare - Apple Share was a product from Apple Computer which implemented various network services. Its main purpose was to act as a file server, using the AFP protocol.
etc.
Distributed Operating System
A Distributed Operating System is an operating system that runs on a network of computers.
In a Distributed Operating System, each user thinks that running on a single large system with one operating system. The users don’t need to know where the files in the network.
Advantages
  • Failure of one system will not affect the other network communication, because all systems are independent from each other.
  • Since resources are being shared, computation is highly fast.
  • The data exchange speed is increased by using electronic mails.
  • Load on host computer reduces.
  • These systems are easily scalable as many systems can be easily added to the network.
  • Delay in data processing reduces.
Disadvantages
  • Failure of the main network will stop the entire communication.
  • To establish distributed systems the language which are used are not well defined yet.
  • They are very expensive.
  • The underlying software is highly complex.

Real-Time Operating System
Real time system means that the system is subjected to real time, i.e., response should be guaranteed within a specified timing constraint or system should meet the specified deadline. For example: missile systems, air traffic control systems, robots etc.
There are two types of Real-Time Operating System -
  • Hard Real-Time Systems - Hard Real-Time Systems are require for the applications where time constraints are very strict and even the shortest possible delay is not acceptable. These systems are built for saving life like automatic parachutes or air bags which are required to be readily available in case of any accident.
    In hard real-time systems, secondary storage is limited or missing and the data is stored in ROM. In these systems, virtual memory is almost never found.
  • Soft Real-Time Systems - Soft real-time systems are less restrictive. A critical real-time task gets priority over other tasks and retains the priority until it completes. Soft real-time systems have limited utility than hard real-time systems. For example, multimedia, virtual reality, Advanced Scientific Projects like undersea exploration and planetary rovers, etc.



Q1. b) Discuss the key characteristics of modern operating systems.
Answer : -
Multi-threading - Multi-threading is the ability of a program or an operating system process to manage its use by more than one user at a time and to even manage multiple requests by the same user without having to have multiple copies of the programming running in the computer. The process is divided into threads that can run simultaneously.
Symmetric Multi-processing - In Symmetric Multi-processing system a computer has more than one processor. These processors can share the same memory, data path, I/O facilities and also the same job for execution.
Advantages of Symmetric Multiprocessing -
  • The throughput of the system is increased in symmetric multiprocessing. As there are multiple processors, more processes are executed.
  • Symmetric multiprocessing systems are much more reliable than single processor systems. Even if a processor fails, the system still endures. Only its efficiency is decreased a little.
Distributed Operating System - A Distributed Operating System is an operating system that runs on a network of computers. The operating system, memory files shared by the number of users in the network from the server. In a Distributed Operating System, each user thinks that running on a single large system with one operating system. The users don’t need to know where the files in the network.
Micro-Kernel Architecture - Kernel is the core part of an operating system which manages system resources. It also acts like a bridge between application and hardware of the computer. It is one of the first programs loaded on start-up (after the Boot loader).
A Micro-Kernel is the minimum software that is required to correctly implement an operating system. This includes memory management, process scheduling mechanisms and basic inter-process communication.
Object-Oriented Design - It is used for adding modular extensions to a small kernel. It also enables programmers to customize an operating system without disrupting system integrity.



Q2. Discuss the objectives and primary functions of the following connecting devices :
  • Hubs
  • Routers
Answer : -
Hubs
If multiple incoming connections need to be connected with multiple outgoing connections, then a hub is required. In data communications, a hub is a place of convergence where data arrives from one or more directions and is forwarded out in one or more other directions. Hubs are multi-port repeaters, and as such they obey the same rules as repeaters. They operate at the OSI Model Physical Layer. Hubs are used to provide a physical Star Topology.
Routers
In an environment consisting of several network segments with different protocols and architecture, a bridge may not be adequate for ensuring fast communication among all of the segments. A complex network needs a device which not only knows the address of each segment, but also can determine the best path for sending data and filtering broadcast traffic to the local segment. Such a device is called a Router. Routers are both hardware and software devices. Router operates at the Network Layer of the OSI Model.



Q3. Explain virtual to physical address mapping concepts with the help of an abstract model.
Answer : - Your computer has two types of memory, Random Access Memory (RAM) and Virtual Memory. All programs use RAM, but when there isn't enough RAM for the program you're trying to run, Windows temporarily moves information that would normally be stored in RAM to a file on your hard disk called a Paging File. The amount of information temporarily stored in a paging file is also referred to as virtual memory. Using virtual memory, in other words, moving information to and from the paging file, frees up enough RAM for programs to run correctly.
A virtual address does not represent the actual physical location of an object in memory; instead, the system maintains a page table for each process, which is an internal data structure used to translate virtual addresses into their corresponding physical addresses. Each time a thread references an address, the system translates the virtual address to a physical address.
In this model, both virtual and physical memory are divided up into handy sized chunks called pages. These pages are all the same size. Each of these pages is given a unique number; the Page Frame Number (PFN). For every instruction in a program, for example to load a register with the contents of a location in memory, the CPU performs a mapping from a virtual address to a physical one. Also, if the instruction itself references memory then a translation is performed for that reference.
The address translation between virtual and physical memory is done by the CPU using page tables which contain all the information that the CPU needs. Typically there is a page table for every process in the system. Above figure shows a simple mapping between virtual addresses and physical addresses using page tables for Process X and Process Y. This shows that Process X’s virtual PFN 0 is mapped into memory in physical PFN 3 and that Process Y’s virtual PFN 2 is mapped into physical PFN 5. Each entry in the theoretical page table contains the following information :
  • The virtual PFN,
  • The physical PFN that it maps to,
  • Access control information for that page.



Q4. Describe important Linux directories and files.
Answer : -
  1. / – Root
    • Every single file and directory starts from the root directory.
    • Only root user has write privilege under this directory.
    • Please note that /root is root user’s home directory, which is not same as /.
  2. /bin – User Binaries
    • Contains binary executables.
    • Common linux commands you need to use in single-user modes are located under this directory.
    • Commands used by all the users of the system are located here. For example : ls, ping, grep, cp, etc.
  3. /boot – Boot Loader Files
    • Contains boot loader related files.
    • Kernel initrd, vmlinux, grub files are located under /boot. For example : initrd.img-2.6.32-24-generic, vmlinuz-2.6.32-24-generic.
  4. /dev – Device Files
    • Contains device files.
    • These include terminal devices, usb, or any device attached to the system. For example: /dev/tty1, /dev/usbmon0, etc.
  5. /etc – Configuration Files
    • Contains configuration files required by all programs.
    • This also contains startup and shutdown shell scripts used to start/stop individual programs. For example: /etc/resolv.conf, /etc/logrotate.conf, etc.
  6. /home – Home Directories
    • Home directories for all users to store their personal files. For example: /home/debabrata, /home/amit, etc.
  7. /lib – System Libraries
    • Contains library files that supports the binaries located under /bin and /sbin
    • Library filenames are either ld* or lib*.so.*, for example: ld-2.11.1.so, libncurses.so.5.7, etc.
  8. /media – Removable Media Devices
    • Temporary mount directory for removable devices. For examples, /media/cdrom for CD-ROM, /media/floppy for floppy drives, /media/cdrecorder for CD writer, etc.
  9. /mnt – Mount Directory
    • Temporary mount directory where sysadmins can mount filesystems.
  10. /opt – Optional add-on Applications
    • opt stands for optional.
    • Contains add-on applications from individual vendors.
    • add-on applications should be installed under either /opt/ or /opt/ sub-directory.
  11. /proc
    • Contains information about system process.
    • This is a pseudo filesystem contains information about running process. For example : /proc/{pid} directory contains information about the process with that particular pid.
    • This is a virtual filesystem with text information about system resources. For example : /proc/uptime
  12. /sbin – System Binaries
    • Just like /bin, /sbin also contains binary executables.
    • Linux commands located under this directory are used typically by system aministrator, for system maintenance purpose. For example : reboot, fdisk, ifconfig, etc.
  13. /srv – Service Data
    • srv stands for service.
    • Contains server specific services related data. For example, /srv/cvs contains CVS related data.
  14. /tmp – Temporary Files
    • Directory that contains temporary files created by system and users.
    • Files under this directory are deleted when system is rebooted.
  15. /usr – User Programs
    • Contains binaries, libraries, documentation, and source-code for second level programs.
    • /usr/bin contains binary files for user programs. If you can’t find a user binary under /bin, look under /usr/bin. For example : at, awk, less, etc.
    • /usr/sbin contains binary files for system administrators. If you can’t find a system binary under /sbin, look under /usr/sbin. For example: sshd, useradd, userdel, etc.
    • /usr/lib contains libraries for /usr/bin and /usr/sbin
    • /usr/local contains users programs that you install from source. For example, when you install apache from source, it goes under /usr/local/apache2
    • /usr/src holds the Linux kernel sources, header-files and documentation.
  16. /var – Variable Files
    • Content of the files that are expected to grow can be found under this directory.
    • This includes — system log files (/var/log); packages and database files (/var/lib), emails (/var/mail); print queues (/var/spool), lock files (/var/lock), temp files needed across reboots (/var/tmp), etc.



Q5. a) What will be the output of followings?
Answer : - Consider that the "myfile.text" contains the following lines -
Motherboard
Processor
RAM
Monitor
Hard Disk
DVD Writer
Graphic Card
RAM
Motherboard
Hard Disk
mohan play football

$ cat myfile.text | head -7 | tail -5
Answer : - Print the last 5 lines from the first 7 lines of the "myfile.text" file
root@UBUNTU-PC:/MyDirectory# cat myfile.text | head -7 | tail -5
RAM
Monitor
Hard Disk
DVD Writer
Graphic Card
root@UBUNTU-PC:/MyDirectory#

$ cat filename | more ls -l > temp
Answer : -

$ sort myfile.text | unique
Answer : - Wrong Command
Right command is - sort myfile.text | uniq
First sort the file contents alphabetically, then remove the duplicate lines.
root@UBUNTU-PC:/MyDirectory# sort myfile.text | uniq
DVD Writer
Graphic Card
Hard Disk
mohan play football
Monitor
Motherboard
Processor
RAM
root@UBUNTU-PC:/MyDirectory#

$ cat myfile.text | grep “mohan” | wc -l
Answer : - Count the number of lines present in the "myfile.text" file which contains the particular pattern "mohan".
root@UBUNTU-PC:/MyDirectory# cat myfile.text | grep “mohan” | wc -l
1
root@UBUNTU-PC:/MyDirectory#

$ ls -l | grep “jan”
Answer : - Display the detailed list of all the files and directories which name is contain the pattern "jan"



Q5. b) What options can be used with grep command?
Answer : - Option which can be used with grep command
Options Description
-c : This prints only a count of the lines that match a pattern
-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-e exp : Specifies expression with this option. Can use multiple times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,
 with each such part on a separate output line.


Q6. Briefly describe the features of followings and how are they configured in Linux?
  • Apache web server
  • DNS
  • NFS server
Answer : -
(i) Apache Web Server
Apache is the most widely used Web Server application in UNIX-like operating systems but can be used on almost all platforms such as Windows, OS X, etc.
The reasons behind its popularity are :
  • It is free to download and install.
  • It is open source - the source code is visible to anyone and everyone, which basically enables anyone to adjust the code, optimize it, and fix errors and security holes. People can add new features and write new modules.
  • It can be used for small websites of one or two pages, or huge websites of hundreds and thousands of pages, serving millions of regular visitors each month. It can serve both static and dynamic content.

(ii) DNS
Domain Name System is an Internet service that translates domain names into IP addresses. Since domain names are alphabetic, they are easier to remember. The Internet however, is really based on IP addresses. Every time you use a domain name, therefore, a DNS service must translate the name into the corresponding IP address. For example, the domain name www.------.com might translate to 198.60.136.3
A domain name is divided into three part -
  • Top Level Domain - A top-level domain recognizes a certain element regarding the associated website, such as its objective (business, government, education), its owner, or the geographical area from which it originated.
    Generic Top Level Domains
    TDLDescription
    .comCommercial
    .eduEducation
    .govU.S. national and state government agencies
    .intInternational Organizations
    .milU.S. military
    .netNetwork
    .orgOrganization
    Country-Code Top Level Domains
    TDLDescription
    .inIndia
    .ruRussia
    .deGermany
    .auAustralia
    .ukUnited Kingdom
    .cnChina
    .brBrazil
    .frFrance
    etc.
    Sponsored Top Level Domains
    TDLDescription
    .aeroMembers of the air-transport industry
    .coopCooperative associations
    .jobsHuman resource managers
    .museumMuseums
    .postPostal services
    .telFor businesses and individuals to publish contact data
    .travelTravel agents, airlines, tourism bureaus, etc.
    .mobiProviders and consumers of mobile products and services
    .catCatalan linguistic and cultural community
    .xxxPornographic sites


(iii) NFS Server
A network file system (NFS) is a type of file system mechanism that enables the storage and retrieval of data from multiple disks and directories across a shared network. It enables local users to access remote data and files in the same way they are accessed locally. NFS was initially developed by Sun Microsystems.



Q7. What are the purposes of dynamic addressing and directory services in Windows 2000? How are they configured?
Answer : -
Windows 2000 runs on TCP/IP, and to utilize AD, you must forsake the older Windows Internet Naming Service (WINS) technology in favor of DNS. WINS can still be useful on Windows 2000 networks, especially if you have non-Windows 2000 or XP clients. However, Active Directory will not use WINS for name resolution.The biggest downside to DNS has been that although distributed, it was still designed as a system that requires manual updates. Whenever a new host is added to a domain, an administrator needs to manually update the zone database on the primary DNS server to reference the new host. If there are secondary name servers on the network, the changes are replicated in a zone transfer.
However, a dynamic updating feature proposed in RFC 2136 provides the means for updating a zone's primary server automatically. Windows 2000 supports this new dynamic DNS, or simply DDNS. The caveat is that it works only with Windows 2000 clients, and older Windows NT, Windows 9X, and non-Windows clients still require manual updates, or at minimum, a Windows 2000 Dynamic Host Configuration Protocol (DHCP) proxy to act on their behalf during the dynamic registration process. When DDNS is enabled and Windows 2000 boots up and contacts a DHCP proxy for IP addressing information, it automatically sends an update to the name server it has been configured to use, adding its Address (A) resource record. This greatly simplifies the administration of DNS on a Windows 2000 network. In addition, DDNS simplifies the administration of AD by allowing domain controllers (DCs) to automatically register their Service (SRV) resource records into DNS without administrator intervention. It is important to note that, by default, DHCP will not automatically update DNS; you have to configure DHCP explicitly to update DNS by editing its properties and checking the box labeled Enable Updates for Clients That Do Not Support Dynamic Updates.


Q8. What is the purpose of VPN and name VPN technologies supported by Windows 2000?
Answer : - A virtual private network, or VPN, is an encrypted connection over the Internet from a device to a network. The encrypted connection helps ensure that sensitive data is safely transmitted. It prevents unauthorized people from eavesdropping on the traffic and allows the user to conduct work remotely. VPN technology is widely used in corporate environments.
A VPN extends a corporate network through encrypted connections made over the Internet. Because the traffic is encrypted between the device and the network, traffic remains private as it travels. An employee can work outside the office and still securely connect to the corporate network. Even smartphones and tablets can connect through a VPN.
Types of VPNs
  • Remote access - A remote access VPN securely connects a device outside the corporate office. These devices are known as endpoints and may be laptops, tablets, or smartphones. Advances in VPN technology have allowed security checks to be conducted on endpoints to make sure they meet a certain posture before connecting. Think of remote access as computer to network.
  • Site-to-Site - A Site-to-Site VPN connects the corporate office to branch offices over the Internet. Site-to-Site VPNs are used when distance makes it impractical to have direct network connections between these offices. Dedicated equipment is used to establish and maintain a connection. Think of Site-to-Site access as network to network.
Virtual Private Network Protocols
  • PPTP - Point to Point Tunneling Protocol (PPTP) is one of the oldest protocol by Microsoft. It is the fastest of all VPN protocols. It is ideal for applications where speed is important such as streaming and gaming. But, PPTP is not as secure because of its weak encryption. PPTP uses the TCP port 1723 for communication.
  • L2TP/IPsec - L2TP over IPsec is more secure than PPTP and offers more features. L2TP/IPsec is a way of implementing two protocols together in order to gain the best features of each.
    The data transmitted via the L2TP/IPSec protocol is usually authenticated twice. Each data packet transmitted via the tunnel includes L2TP headers. As a result, the data is de-multiplexed by the server. The double authentication of the data slows down performance, but it does provide the highest security.



Q9. What are Intrusion Detection Systems(IDS)? What IDS can do?
Answer : - An Intrusion Detection System (IDS) is a type of security software designed to automatically alert administrators when someone or something is trying to compromise information system through malicious activities or through security policy violations.
IDS is basically classified into two types :
  • Network Intrusion Detection System (NIDS)
    Network intrusion detection systems (NIDS) are set up at a planned point within the network to examine traffic from all devices on the network. It performs an observation of passing traffic on the entire  subnet and matches the traffic that is passed on the subnets to the collection of known attacks. Once an attack is identified or abnormal behavior is observed, the alert can be sent to the administrator. An example of an NIDS is installing it on the subnet where firewalls are located in order to see if someone is trying crack the firewall.
  • Host Intrusion Detection System (HIDS)
    Host intrusion detection systems (HIDS) run on independent hosts or devices on the network. A HIDS monitors the incoming and outgoing packets from the device only and will alert the administrator if suspicious or malicious activity is detected. It takes a snapshot of existing system files and compares it with the previous snapshot. If the analytical system files were edited or deleted, an alert is sent to the administrator to investigate.
Detection Method of IDS -
  • Signature-based Method - Signature-based IDS detects the attacks on the basis of the specific patterns such as number of bytes or number of 1’s or number of 0’s in the network traffic. It also detects on the basis of the already known malicious instruction sequence that is used by the malware. The detected patterns in the IDS are known as signatures.
    Signature-based IDS can easily detect the attacks whose pattern (signature) already exists in system but it is quite difficult to detect the new malware attacks as their pattern (signature) is not known.
  • Anomaly-based Method - Anomaly-based IDS was introduced to detect the unknown malware attacks as new malware are developed rapidly. In anomaly-based IDS there is use of machine learning to create a trustful activity model and anything coming is compared with that model and it is declared suspicious if it is not found in model. Machine learning based method has a better generalized property in comparison to signature-based IDS as these models can be trained according to the applications and hardware configurations.



Q10. Elaborate the primary aspects of firewall? What are the limitations of firewall?
Answer : - A firewall is a network security system designed to prevent unauthorized access to or from a private network. Firewalls can be implemented as both hardware and software, or a combination of both. Network firewalls are frequently used to prevent unauthorized Internet users from accessing private networks connected to the Internet, especially intranets. All messages entering or leaving the intranet pass through the firewall, which examines each message and blocks those that do not meet the specified security criteria.
Firewalls can be either hardware or software but the ideal configuration will consist of both. In addition to limiting access to your computer and network, a firewall is also useful for allowing remote access to a private network through secure authentication certificates and logins.

Firewall Filtering Techniques
Firewalls are used to protect both home and corporate networks. A typical firewall program or hardware device filters all information coming through the Internet to your network or computer system. There are several types of firewall techniques that will prevent potentially harmful information from getting through :
  • Packet Filter - Looks at each packet entering or leaving the network and accepts or rejects it based on user-defined rules. Packet filtering is fairly effective and transparent to users, but it is difficult to configure. In addition, it is susceptible to IP spoofing.
  • Application Gateway - Applies security mechanisms to specific applications, such as FTP and Telnet servers. This is very effective, but can impose a performance degradation.
  • Circuit-level Gateway - Applies security mechanisms when a TCP or UDP connection is established. Once the connection has been made, packets can flow between the hosts without further checking.
  • Proxy Server - Intercepts all messages entering and leaving the network. The proxy server effectively hides the true network addresses.
In practice, many firewalls use two or more of these techniques in concert. A firewall is considered a first line of defense in protecting private information. For greater security, data can be encrypted.

Limitations of Firewall
  • Firewalls cannot protect against what has been authorized.
  • It cannot stop attacks if the traffic does not pass through them.
  • They are only as effective as the rules they are configured to enforce.
  • The firewall cannot protect against the transfer of virus-infected programs or files. Because of the variety of operating systems and applications supported inside the perimeter, it would be impractical and perhaps impossible for the firewall to scan all incoming files, e-mail, and messages for viruses.
  • The firewall does not protect against internal threats, such as a disgruntled employee or an employee who unwittingly cooperates with an external attacker.



Q11. How does RAID support fault tolerance systems? How is it implemented in Windows 2000?
Answer : - Fault-tolerance is the ability to survive of one or several disk failures.
RAID is a technology that is used to increase the performance and/or reliability of data storage. RAID stands for Redundant Array of Independent Disks. A RAID system consists of two or more drives working in parallel. There are different RAID levels, each optimized for a specific situation.
  • RAID 0 – striping
  • RAID 1 – mirroring
  • RAID 5 – striping with parity
  • RAID 6 – striping with double parity
  • RAID 10 – combining mirroring and striping

RAID 0 – striping
In a RAID 0 system data are split up into blocks that get written across all the drives in the array. By using multiple disks (at least 2) at the same time, this offers superior I/O performance. This performance can be enhanced further by using multiple controllers, ideally one controller per disk.
Advantages
  • RAID 0 offers great performance, both in read and write operations. There is no overhead caused by parity controls.
  • All storage capacity is used, there is no overhead.
Disadvantages
  • RAID 0 is not fault-tolerant. If one drive fails, all data in the RAID 0 array are lost. It should not be used for mission-critical systems.

RAID 1 – mirroring
Data are stored twice by writing them to both the data drive (or set of data drives) and a mirror drive (or set of mirror drives). If a drive fails, the controller uses either the data drive or the mirror drive for data recovery and continues operation. You need at least 2 drives for a RAID 1 array.
Advantages
  • RAID 1 offers excellent read speed and a write-speed that is comparable to that of a single drive.
  • In case a drive fails, data do not have to be rebuild, they just have to be copied to the replacement drive.
Disadvantages
  • The main disadvantage is that the effective storage capacity is only half of the total drive capacity because all data get written twice.
  • Software RAID 1 solutions do not always allow a hot swap of a failed drive. That means the failed drive can only be replaced after powering down the computer it is attached to. For servers that are used simultaneously by many people, this may not be acceptable. Such systems typically use hardware controllers that do support hot swapping.

RAID 5 – striping with parity
RAID 5 is the most common secure RAID level. It requires at least 3 drives but can work with up to 16 drives. Data blocks are striped across the drives and on one drive a parity checksum of all the block data is written. The parity data are not written to a fixed drive, they are spread across all drives. Using the parity data, the computer can recalculate the data of one of the other data blocks, should those data no longer be available. That means a RAID 5 array can withstand a single drive failure without losing data or access to data.
Advantages
  • Read data transactions are very fast while write data transactions are somewhat slower (due to the parity that has to be calculated).
  • If a drive fails, you still have access to all data, even while the failed drive is being replaced and the storage controller rebuilds the data on the new drive.
Disadvantages
  • Drive failures have an effect on throughput, although this is still acceptable.
  • This is complex technology. If one of the disks in an array using 4TB disks fails and is replaced, restoring the data (the rebuild time) may take a day or longer, depending on the load on the array and the speed of the controller. If another disk goes bad during that time, data are lost forever.

RAID 6 – striping with double parity
RAID 6 is like RAID 5, but the parity data are written to two drives. That means it requires at least 4 drives and can withstand 2 drives dying simultaneously. The chances that two drives break down at exactly the same moment are of course very small. However, if a drive in a RAID 5 systems dies and is replaced by a new drive, it takes hours or even more than a day to rebuild the swapped drive. If another drive dies during that time, you still lose all of your data. With RAID 6, the RAID array will even survive that second failure.
Advantages
  • Like with RAID 5, read data transactions are very fast.
  • If two drives fail, you still have access to all data, even while the failed drives are being replaced. So RAID 6 is more secure than RAID 5.
Disadvantages
  • Write data transactions are slower than RAID 5 due to the additional parity data that have to be calculated.
  • Drive failures have an effect on throughput, although this is still acceptable.
  • This is complex technology. Rebuilding an array in which one drive failed can take a long time.

RAID 10 – combining mirroring and striping
It is possible to combine the advantages (and disadvantages) of RAID 0 and RAID 1 in one single system. This is a nested or hybrid RAID configuration. It provides security by mirroring all data on secondary drives while using striping across each set of drives to speed up data transfers.
Advantages
  • If something goes wrong with one of the disks in a RAID 10 configuration, the rebuild time is very fast since all that is needed is copying all the data from the surviving mirror to a new drive.
Disadvantages
  • Half of the storage capacity goes to mirroring, so compared to large RAID 5 or RAID 6 arrays, this is an expensive way to have redundancy.



Q12. List the different types of malicious code and compare the virus protection tools.
Answer : - Malicious software is any software that the user did not authorize to be loaded or software that collects data about a user without their permission.
Different Types of Malicious Software
  • Spyware - Spyware is any technology that aids in gathering information about a person or organization without their knowledge. They can monitor and log the activity performed on a target system, like log key strokes, or gather credit card and other information.
  • Virus - A computer virus is a piece of software that can 'infect' a computer, install itself and copy itself to other computers, without the users knowledge or permission. It usually attaches itself to other computer programs, data files, or the boot sector of a Hard drive.
  • Worm - Unlike a virus, a worm, is a standalone piece of malicious software that replicates itself in order to spread to other computers. It often uses a computer network to spread itself, relying on security flaws on the target system to allow access.
  • Trojan (Trojan Horse) - A type of malware that uses malicious code to install software that seems ok, but is hidden to create back doors into a system typically causing loss or theft of data from an external source.
  • Adware - Adware is software which can automatically causes pop-up and banner adverts to be displayed in order to generate revenue for its author or publisher. A lot of freeware will use Adware but not always in a malicious way, if it was malicious, it would then be classed as spyware or malware.
  • Rootkit - Rootkit Virus assists a hacker in remotely accessing or controlling a computing device or network without being exposed. They are hard to detect due to the reason that they become active even before the system’s OS is booted up.



Q13. What is Kerberos? Describe Kerberos management in Windows operating system.
Answer : - Kerberos is a ticketing-based authentication system, based on the use of symmetric keys. Kerberos uses tickets to provide authentication to resources instead of passwords. This eliminates the threat of password stealing via network sniffing. One of the biggest benefits of Kerberos is its ability to provide single sign-on (SSO). Once you log into your Kerberos environment, you will be automatically logged into other applications in the environment.
To help provide a secure environment, Kerberos makes use of Mutual Authentication. In Mutual Authentication, both the server and the client must be authenticated. The client knows that the server can be trusted, and the server knows that the client can be trusted. This authentication helps prevent man-in-the-middle attacks and spoofing. Kerberos is also time sensitive. The tickets in a Kerberos environment must be renewed periodically or they will expire.
When a user needs to access a service protected by Kerberos, the Kerberos protocol process can be divided into two phases - User Identity Authentication and Service Access.
User Identity Authentication - User authentication is a process of checking validity of identity information provided by users in the Kerberos authentication service. Identity information can be user names and passwords or information that can provide real identities in other forms. If user information passes the validity check, the Kerberos authentication service returns a valid Ticket-Granting Ticket (TGT) token, proving that the user has passed identity authentication. The user uses the TGT in the subsequent Service Access process.
Service Access - When the user needs to access a service, the user requests the Ticket-Granting Service (TGS) from the Kerberos server based on the TGT obtained in the first phase, providing the name of the service to be accessed. TGS checks the TGT and information about the service to be accessed. After the information passes the check, TGS returns a Service-Granting Ticket (SGT) token to the user. The user requests the component service based on the SGT and related user authentication information. The component service decrypts the SGT information in a symmetrical way and finishes user authentication. If the user passes the authentication process, the user can successfully access related resources of the service.

Kerberos in Windows Systems
Kerberos is very prevalent in the Windows environment. In fact, Windows 2000 and later use Kerberos as the default method of authentication. When you install your Active Directory domain, the domain controller is also the Key Distribution Center. In order to use Kerberos in a Windows environment, your client system must be a part of the Windows domain. Kerberos is used when accessing file servers, Web servers, and other network resources. When you attempt to access a Web server, Windows will try to sign you in using Kerberos. If Kerberos authentication does not work, then the system will fall back to NTLM authentication.



Q14. Define IPSec? What are its features? Discuss its implementation in Windows 2000.
Answer : - Exchanging sensitive information across a network, especially a public network, requires a security method that will protect the data in transit. That’s where Internet Protocol Security (IPSec) comes in. IPSec is a set of protocols that allows you to sign and encrypt data to be sent across an IP network, and authenticate and decrypt the protected packets on the receiving end. Windows 2000 Professional and Server include IPSec.

What is IPSec ?
IPSec is a set of protocols and cryptography-based services that work together to protect data from unauthorized access or tampering when it is sent across an IP network. IPSec provides three basic services :
  • Authentication - Confirmation of the origin of the IP packet; verification that the purported sender actually sent it.
  • Integrity - “Signing” of the packet to ensure that the data has not been changed in any way between the time it left the sender and the time it was received at the authorized destination.
  • Confidentiality - Encryption of the data to render is unreadable without the correct key.

Implementation of IPSec in Windows 2000
Windows 2000’s implementation of IPSec provides a high level of security, using a combination of algorithms and keys to encrypt the data so that it will be unreadable if intercepted along its route. IPSec uses two protocols to accomplish these tasks :
  • Authentication Header (AH) - This protocol provides authentication services for IPsec. It allows the recipient of a message to verify the identity of the sender. It also allows the recipient to verify that intermediate devices haven’t changed any of the data in the datagram. It also provides protection against so-called replay attacks, whereby a message is captured by an unauthorized user and resent.
  • Encapsulating Security Payload (ESP) - AH provides integrity authentication services to IPsec-capable devices so that they can verify that messages are received intact from other devices. For many applications, however, this is only one piece of the puzzle. We want to not only protect against intermediate devices changing the data grams, but also to protect against them examining their contents as well. For this level of private communication, AH is not enough; we need to use the ESP protocol.
    The main job of ESP is to provide the privacy we seek for IP data grams by encrypting them. An encryption algorithm combines the data in the datagram with a key to transform it into an encrypted form. This is then repackaged using a special format, and then transmitted to the destination, which decrypts it using the same algorithm.

Mcs 021 ,(Data and Files structures )Assignment solution 2020





Course Code : MCS-021

Course Title : Data and file Structures

Last Date of Submission : 15th October, 2019 (For July 2019 Session)

15th April, 2020 (For January 2020 Session)


Q1.Write an algorithm that accept binary tree as input and print the number of leaf nodes  to standard output.




Ans:

#include <iostream.h>
using namespace std;

/* A binary tree node has data,
pointer to left child and
a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;

/* Function to get the count
of leaf nodes in a binary tree*/
unsigned int getLeafCount(struct node* node)
{
if(node == NULL)
return 0;
if(node->Ieft == NULL && node->right == NULL)
return 1;
else
return getLeafCount(node->left)+
getLeafCount(node->right);

/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);

}

int main()

{
/*create a tree*/
struct node *root = newNode(l);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);

/*get leaf count of the above created tree*/
printf( "%d Leaf count of the tree is\n");
getLeafCount(root);
return 0;

}


Q2.Write an algorithm for implementation of a AVL tree.
Ans:


#include <stdio.h>

#include <stdlib.h>

struct avl_node_s {

struct avl_node_s *left;

struct avl_node_s *right;

int value;

};

typedef struct avl_node_s avl_node_t;
struct avl_tree_s {

struct avl_node_s *root;

};

typedef struct avl_tree_s avl_tree_t;
/* Create a new AVL tree. */
avl_tree_t *avl_create() {

avl_tree_t *tree = NULL;

if( ( tree = malloc( sizeof( avl_tree_t )
return NULL;

}

tree—>root = NULL;

return tree;

}

/* Initialize a new node. */
avl node t *avl create node() {
avl_node_t *node = NULL;

if( ( node = malloc( sizeof( avl node t )))==NULL){
return NULL;

}

node—>left = NULL;

node—>right = NULL;

node—>value =0;

return node;

}

/* Insert a new node. */

void avl_insert( avl_tree_t *tree, int value ) {
avl_node_t *node = NULL;

avl_node_t *next = NULL;

avl_node_t *last = NULL;

/* Well, there must be a first case */
if( tree—>root == NULL ) {

node = avl_create_node();

node—>value = value;

tree—>root = node;

/* Okay. We have a root already. Where do we put this? */
} else {

next = tree—>root;

last = NULL;

while( next != NULL )

 last = next;

if( value < next—>value ) {

next = next—>left;

} else if( value > next—>value ) {

next = next—>right;

/* Have we already inserted this node? */

} else if( value == next—>value ) {

/* This shouldn't happen. */

}

}

node = avl_create_node();

node—>value = value;

if( value < last—>Value ) last—>left = node;
if( value > last—>Value ) last—>right = node;
}

}

/* Find the height of an AVL node recursively */

int avl_node_height( avl_node t *node ) {

int height_left = 0;

int height_right = 0;

if( node—>left ) height_left = avl_node_height( node—>left );
if( node—>right ) height_right = avl_node_height( node—>right );
return height_right > height_left ? ++height_right
++height_left;

}

/* Find the balance of an AVL node */

int avl_node_balance( avl_node_t *node ) {

int balance = 0;

if( node—>left ) balance += avl node height( node—>left );

if( node—>right ) balance —= avlinodeiheight( node—>right );
return balance;

}

/* Do a depth first traverse of a node. */

void avl_traverse_node_dfs( avl_node_t *node, int depth ) {

int i = 0;

if( node—>left ) avl_traverse_node_dfs( node—>left, depth + 2 );
for( i = 0; i < depth; i++ ) putchar( ' ' );

printf( "%d: %d\n", node—>value, avl_node_balance( node ) );
if( node—>right ) avl_traverse_node_dfs( node—>right, depth + 2
);

}

/* Do a depth first traverse of a tree. */

void avl traverse dfs( avl tree t *tree ) {11
avl_traverse_node_dfs( tree—>root, O );

}

void main()
{

avl_tree_t *tree = NULL;
clrscr();

tree = avl_create();
avl_insert( tree, 30)
avl_insert (tree, 20)
avl_insert (tree, 40)
avl_insert (tree, 10)
avl_insert( tree, 50)
avl_traverse_dfs( tree);
getch();

}

Q3.Write a note of not more than 5 pages summarizing the latest research in the area  of "Trees" .Refer of various  journals and other online resources .Indicate them in your assignment.

Ans: In computer science, a tree is a widely used abstract data type (ADT)—or data structure implementing this ADT—that simulates a hierarchical tree structure, with a root value and subtrees of children with a parent node, represented as a set of linked nodes.

A tree data structure can be defined recursively as a collection of nodes (starting at a root(node), where each node is a data structure consisting of a value, together with a list of references to nodes (the "children"), with the constraints that no reference is duplicated, and none points to the root.

Alternatively, a tree can be defined abstractly as a whole (globally) as an ordered tree, with a value assigned to each node. Both these perspectives are useful: while a tree can be analyzed
mathematically as a whole, when actually represented as a data structure it is
usually represented and worked with separately by node (rather than as a set of nodes and an adjacency list of edges between nodes, as one may represent a digraph, for instance). For example, looking at a tree as a whole, one can talk about "the parent node" of a given node, but in general as a data structure a given node only contains the list of its children, but does not
contain a reference to its parent (if any).

Unordered tree

Mathematically, an unordered tree[1] (or "algebraic tree"[2]) can be defined as an algebraic structure {\displaystyle (X,parent)} {\displaystyle (X,parent)} where X is the non-empty carrier set of nodes and parent is a function on X which assigns each node x its "parent" node, parent(x). The structure is subject to the condition that every non-empty subalgebra must have the same fixed point. That is, there must be a unique I'root" node r, such that parent(r) = r and
for every node x, some iterative application parent(parent(...parent(x)...)) equals r.

There are several equivalent definitions. As the closest alternative, one can define unordered trees as partial algebras (X, parent) which are obtained from the total algebras described above by letting parent(r) be undefined. That is, the root r is the only node on which the parent function is not defined and for every node x, the root is reachable from x in the directed graph (X, parent). This definition is in fact coincident with that of an anti-arborescence. The TAoCP
book uses the term oriented tree.[3]

Another equivalent definition is that of a set-theoretic tree that is sineg-rooted and whose height is at most   (omega sign) (a finite-ish tree[4]). That is, the algebraic structures (X, parent) are equivalent to partial orders {\displaystyle (X,\|eq )} (X, \Ie) that have a top element r and whose every principal upset (aka principal filter) is a finite chain. To be precise, we should speak about
an inverse set-theoretic tree since the set-theoretic definition usually employs opposite ordering. The correspondence between (X, parent) and (X, S) is established via reflexive transitive closure / reduction, with the reduction resulting in the "partial" version without the root cycle.

The definition of trees in descriptive set theory (DST) utilizes the representation of partial orders (X, 2) as prefix orders between finite sequences. In turns out that up to isomorphism, there is a one-to-one correspondence between the (inverse of) DST trees and the tree structures defined so far.

We can refer to the four equivalent characterizations as to tree as an algebra, tree as a partial algebra, tree as a partial order, and tree as a prefix order. There is also a fifth equivalent definition — that of a graph-theoretic rooted tree which is just a connected acyclic rooted graph.

Terminology

A node is a structure which may contain a value or condition, or represent a separate data structure (which could be a tree of its own). Each node in a tree has zero or more child nodes, which are below it in the tree (by convention, trees are drawn growing downwards). A node that has a child is called the child's parent node (or ancestor node, or superior). A node has at most one parent.An internal node (also known as an inner node, inode for short, or branch node) is any node of a tree that has child nodes. Similarly, an external node (also known as an outer node, leaf node, or terminal node) is any node that does not have child nodes.The topmost node in a tree is called the root node. Depending on definition, a tree may be required to have a root node (in which case all trees are non-empty), or may be allowed to be empty, in which case it does not necessarily have a root node. Being the topmost node, the root node will not have a parent. It is the node at which algorithms on the tree begin, since as a data structure, one can only pass from parents to children. Note that some algorithms (such as post-order depth-first search) begin at the root, but first visit leaf nodes (access the value of
leaf nodes), on|y visit the root last (i.e., they first access the children of the root, but only access the value of the root last). All other nodes can be reached from it by following edges or links. (In the formal definition, each such path is also unique.) In diagrams, the root node is conventionally drawn at the top. In some trees, such as heaps, the root node has special properties. Every node in a tree can be seen as the root node of the subtree rooted at that
node.

The height of a node is the length of the longest downward path to a leaf from that node. The height of the root is the height of the tree. The depth of a node is the length of the path to its root (i.e., its root path). This is commonly needed in the manipulation of the various self- balancing trees, AVL Trees in particular. The root node has depth zero, leaf nodes have height zero, and a tree with only a single node (hence both a root and leaf) has depth and height zero.
Conventionally, an empty tree (tree with no nodes, if such are allowed) has height —1.

A subtree of a tree T is a tree consisting of a node in T and all of its descendants in T.[f][21]Nodes thus correspond to subtrees (each node corresponds to the subtree of itself and all itsdescendants) — the subtree corresponding to the root node is the entire tree, and each node is the root node of the subtree it determines; the subtree corresponding to any other node is called a proper subtree (by analogy to a proper subset).

Drawing trees

Trees are often drawn in the plane. Ordered trees can be represented essentially uniquely in the plane, and are hence called plane trees, as follows: if one fixes a conventional order (say, counterclockwise), and arranges the child nodes in that order (first incoming parent edge, then first child edge, etc.), this yields an embedding of the tree in the plane, unique up to ambient isotopy. Conversely, such an embedding determines an ordering of the child nodes.

If one places the root at the top (parents above children, as in a family tree) and places all nodes that are a given distance from the root (in terms of number of edges: the "level" of atree) on a given horizontal line, one obtains a standard drawing of the tree. Given a binary tree,
the first child is on the left (the "Left node"), and the second child is on the right (the "right node").


Representations

There are many different ways to represent trees; common representations represent the nodes as dynamically allocated records with pointers to their children, their parents, or both, or as items in an array, with relationships between them determined by their positions in the array (e.g., binary heap).

Indeed, a binary tree can be implemented as a list of lists (a list where the values are lists): the head of a list (the value of the first term) is the left child (subtree), while the tail (the list of second and subsequent terms) is the right child (subtree). This can be modified to allow values as well, as in Lisp S-expressions, where the head (value of first term) is the value of the node, the head of the tail (value of second term) is the left child, and the tail of the tail (list of third and subsequent terms) is the right child.

In general a node in a tree will not have pointers to its parents, but this information can be included (expanding the data structure to also include a pointer to the parent) or stored separately. Alternatively, upward links can be included in the child node data, as in a threaded binary tree.

Generalizations

Digraphs

If edges (to child nodes) are thought of as references, then a tree is a special case of a digraph, and the tree data structure can be generalized to represent directed graphs by removing the constraints that a node may have at most one parent, and that no cycles are allowed. Edges are still abstractly considered as pairs of nodes, however, the terms parent and child are usually replaced by different terminology (for example, source and target). Different implementation
strategies exist: a digraph can be represented by the same local data structure as a tree (node with value and list of children), assuming that I'list of children" is a list of references, or globally by such structures as adjacency lists.

|n graph theory, a tree is a connected acyclic graph; unless stated otherwise, in graph theory trees and graphs are assumed undirected. There is no one-to-one correspondence between such trees and trees as data structure. We can take an arbitrary undirected tree, arbitrarily pick one of its vertices as the root, make all its edges directed by making them point away from the root node — producing an arborescence — and assign an order to all the nodes. The resultcorresponds to a tree data structure. Picking a different root or different ordering produces a
different one.

Traversal methods

Stepping through the items of a tree, by means of the connections between parents and children, is called walking the tree, and the action is a 'walk' of the tree. Often, an operation might be performed when a pointer arrives at a particular node. A walk in which each parent node is traversed before its children is called a pre-order walk; a walk in which the children are traversed before their respective parents are traversed is called a post-order walk; a walk in which a node's left subtree, then the node itself, and finally its right subtree are traversed is called an in-order traversal. (This last scenario, referring to exactly two subtrees, a left subtree and a right subtree, assumes specifically a binary tree.) A level-order walk effectively performs a breadth-first search over the entirety of a tree; nodes are traversed level by level, where the root node is visited first, followed by its direct child nodes and their siblings, followed by its
grandchild nodes and their siblings, etc., until all nodes in the tree have been traversed.


 Q4.Write an algorithm for implementation for stack.

Ans:
// C program for array implementation of stack

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

// A structure to represent a stack
struct Stack{

int top;

unsigned capacity;

int* array;

// function to create a stack of given capacity. It initializes size of
// stack as O

struct Stack* createStack(unsigned capacity)

{
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(stack->capacity * sizeof(int));
return stack;
}
// Stack is full when top is equal to the last index
int isFull(struct Stack* stack)
{

return stack->top == stack->capacity - 1;
}
// Stack is empty when top is equal to -1
int isEmpty(struct Stack* stack)
{

return stack->to == -1;
}
// Function to add an item to stack. It increases top by 1
void push(struct Stack* stack, int item)
{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
printf("%d pushed to stack\n", item);
}
// Function to remove an item from stack. It decreases top by 1
int pop(struct Stack* stack)
{
if (isEmpty(stack))
return |NT_M|N;
return stack->array[stack->top--1;
}
 // Function to return the top from stack without removing it
int peek(struct Stack* stack)

{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top];
}
// Driver program to test above functions
int main()

{
struct Stack* stack = createStack(100);
push(stack, 10);
push(stack, 20);
push(stack, 30);
printf("%d popped from stack\n", pop(stack));

return 0;

}

































TYPES OF FUNCTION INVOKING

We categorize a function's invoking (calling) depending on arguments or parameters and their returning a value. In simple words we can divide a function's invoking into four types depending on whether parameters are passed to a function or not and whether a function returns some value or not.

The various types of invoking functions are:

• With no arguments and with no return value.
• With no arguments and with return value
• With arguments and with no return value
• With arguments and with return value.

 Let us discuss each category with some examples:

TYPE 1: With no arguments and have no return value

As the name suggests, any function which has no arguments and does not return any values to the calling function, falls in this category. These type of functions are confined to themselves i.e. neither do they receive any data from the calling function nor do they transfer any data to the calling function. So there is no data communication between the calling and the called function are only program control will be transferred.

Example

 /* Program for illustration of the function with no arguments and no return value*/

#include <stdio.h>
 main(){
 void message();
 printf("Control is in main\n");
 message();
 printf("Control is again in main\n");
}
void message()
{
printf("Control is in message function\n"); /* does not return anything */
}
OUTPUT
Control is in main
Control is in message function
Control is again in  main

TYPE 2:With no arguments and with return value
 suppose if a function does not receive any data from calling function but does send , some value to the calling function, then it falls in this category. 


Example

write a program to find the sum of the first ten natural numbers.

/* Program to find sum of first ten natural numbers */
#include <stdio.h>
int cal_sum(){ int i, s=0;
 for (i=0; i<=10 1++)
 return(s);
}

main()
{
 int sum;
sum=cal_sum();
printf("sum of first ten natural number is % d\n"sum);
}

OUTPUT

Sum o first ten natural number is 55
TYPE 3:With Arguments and have no return value
If a function includes arguments but does not return anything, it falls in this category. One way communication takes place between the calling and the called function.

Before proceeding further, first we discuss the type of arguments or parameters here. There are two types of arguments:

• Actual arguments
• Formal arguments

Let us take art example to make this concept clear:

Example


 Write a program to calculate sum of any three given numbers.



#include <stdio.h>
main(){
int al, a2, a3;
void sum(int, int, int);
printf("Enter three numbers: ");
scanf ("%d%d%d",&al ,&a2,&a3);
sum (al ,a2,a3);
}
 void sum(intf1,intf2,intf3)
{
int s;
s=f1+f2+f3;
printf("\n The sum of three numbers is %d\n",s);
}

OUTPUT

Enter three numbers : 25 34 49
The sum of three numbers is 108

TYPE 4: With arguments function and with return value.
In this category two-way communication takes place between the calling and called function i.e. a function returns a value and also arguments are passed to it. We modify above Example according to this category.

 Example
 Write a program to calculate sum of three numbers.
/*Program to calculate the sum of three numbers.*/
#include <stdio main ( )
{ int a I , a2, a3, result;
int sum(int, int, int);
 printf("Please enter any 3 numbers.");
scanf %d %d", & at &a2, &a3);
 result = sum (al ,a2,a3);
 printf ("Sum of the given numbers is : %d\n,result);
}
int sum (int fl, 12, int f3){
retum(fl +f2 + f3);
}
OUTPUT 
please enter any 3 numbers:
 3  4 5
Sum of the given numbers is: 12

TYPES OF VARIABLES AND STORAGE CLASSES IN C

In a program consisting of a number of functions a number of different types of variables can be found

Global vs static variable-Global variables are recognized  through out the program whereas local variables are recognized only inside the function. 


Static vs Dynamic variables- Retention of value by a local variable means that in ,static retention of the variable value Is lost once the function is completely  executed whereas in certain conditions the value of the variable has to be retained from the earlier execution and the execution retained .


The Variables can be characterized by their data type and their storage classes .One way to classify a variable is according to its data type and the other can be through its storage class. Data type refers to the type of value represented by a variable whereas storage class refers to the permanence of a variable and its scope with in  the program .

Storage Classes

There are four different storage classes specified in C:
I. Auto (mark)
2. Extern tall
3. Static
4. Register

The storage class associated  with a variable can sometimes be established by the location of the variable declaration within the program.

For example - auto int a, b;
                      static int a,b;

Automatic Variables

The variables local to a function are automatic i.e.. declared within the function The scope of lies within the function itself. The automatic defined in different functions,even if they have same name, are treated as different .It is the default storage class f. variables declared in a function.

• The auto is optional therefore there is no need to write it.
• All the formal arguments also have the auto storage class.
• The initialization of the auto-variables can be done:
         • in declarations
         • using assignment expression in a function
• If not initialized the unpredictable value is defined.
• The value is not retained after exit from the program.

EXAMPLE
#include<stdio.h>
main(int argc,char*argv[])
{
int a,b ;
double d;
printf("%d",argc);
a=10;
b=5;
d=(b*b)-(a/2);
 printf("%d,%d%f,a,b,d");
}
All variable a,b,d argc and argv[] have automatic storage classes.


 External (Global) Variables

 These  are not confined to a single function. Their scope ranges from the point  of declaration to the entire remaining program. Therefore, their scope,may be the entire program or more functions depending upon where they are declared.

•These are global and can be accessed by any function within its scope.Therefore value may be assigned in one and can be written in another.
• There is difference in external variable definition and declaration.
• External Definition is the same as any variable declaration:
            • Usually lies outside or before the function accessing it.
• It allocates storage space required .
•Initial value can be assigned.
•The external specifier is not required in external variable definition.
• A declaration is required if the external variable definition comes after the function definition.
•A declaration begins with an external specifier.
• Only when external variable is defined is the storage spate allocated.
• External variables can be assigned initial values as a part of variable definitions, but the values must be constants rather than expressions.
• If initial value is not included then it is automatically assigned a value of zero.

EXAMPLE
/*Program to illustrate the use of global variables.*/
# include <stdio.h>
int gv;    // gv is a global variable
  main(){ void function ();
 gv= 10; 1
printf ("%d is the value of gv before function call\n", gv);
 function I( );
 print(" %d is the value  of gv after function call\n", gv);
}
void function()
{
gv=15;
}

 OUTPUT
 10 is the value gv before function calling
 15 is the value gv after function calling

Static Variables
  In case of single file program  static variables are defined within functions and individually  have the same scope as automatic variables. But static variables retain their values throughout the execution of program within their previous values.

 • Th. specifier precedes the declaration. Static and the value cannot be  accessed  outside of their defining function.
 • The static variables may  have same name as that of external variables but the local variables take precedence in the function. Therefore external variables maintain their independence with locally defined auto and static variables.
•Initial value Is expressed as the constant and not expression.
•Zeros are  assigned to all variables whose declarations do not Include explicit initial values. Hence they always have assigned values.
•Initialization Is done only is the first execution.

 Example
/* Program to illustrate the use of static variable*/

include<stdio.h>
main()
{
int call-static();
int i,j;
i=j=0;
j=call_static();
printf("%d\n",j);
j=call_static();
printf("%d\n",j);
 j=call_static();
printf("%d\n",j);
 }

int call_static(){
static int i=1;

int j;
j=i;
i++;
return(j);
 }
OUTPUT
1
2
3

 Register Variables

Besides three storage class specifications namely, Automatic, External and Static there is a register storage class. Registers are special  storage areas with in a computer's CPU. All the arithmetic and logical operators are carried out with these   registers.

For the same program, the execution time can be reduced if certain values can be stored in registers rather than memory. These programs are smaller in size  and few data transfers are required. The reduction is there machine code and not in source code. They are declared by the proceeding declaration by register reserved word as follows:
register int m;

  • These variables are stored in registers of computers. If the registers are not available they are put in memory.
  •  Usually 2 or 3 register variables are there in the program.
  •   Scope is same as automatic variable, local to a function in which they are declared. 
  • Address operator '&' cannot be applied to a register variable.
  •  If the register is not available the variable is though to be like the automatic variable.
  •  Usually associated integer variable but with other types it is allowed having same size (short or unsigned). 
  • Can be formal arguments in functions.
  •  Pointers to register variables are not allowed.
  •  These variables can be used for loop indices also to increase efficiency.

Redmi Note 8 (Neptune Blue, 4GB RAM, 64GB Storage)


  •  
  • Redmi Note 8 (Neptune Blue, 4GB RAM, 64GB Storage)
  • 48MP AI Quad camera with portrait, ultra-wide lens, macro lens, LED flash, AI support, beautify support | 13MP front camera with AI portrait mode
  • 16.002 centimeters (6.3-inch) IPS LCD multi-touch capacitive touchscreen with 2280 x 1080 pixels resolution, 403 ppi pixel density and 19.5:9 aspect ratio | 2.5D curved glass
  • Memory, Storage & SIM: 4GB RAM | 64GB internal memory expandable up to 512GB | Dual SIM (nano+nano) dual-standby (4G+4G)
  • Android Pie v9 operating system with 2.0GHz Qualcomm Snapdragon 665 octa core processor
  • 4000mAH lithium-polymer battery providing talk-time of 32 hours and standby time of 540 hours | 18W fast charger. Built-in rechargeable battery. USB Type-C connector port
  • 1 year manufacturer warranty for device and 6 months manufacturer warranty for in-box accessories including batteries from the date of purchase
  • Box also includes: Power adapter, USB cable, SIM eject tool, warranty card, user guide and clear soft case