UNIT 1
Computer Basics
Definition
Being a modern-day kid, you must have used, seen, or read about computers. This is because they are an integral part of our everyday existence. Be it school, banks, shops, railway stations, hospital or your own home, computers are present everywhere, making our work easier and faster for us. As they are such integral parts of our lives, we must know what they are and how they function. Let us start with defining the term computer formally.
The literal meaning of computer is a device that can calculate. However, modern computers can do a lot more than calculate. Computer is an electronic device that receives input, stores or processes the input as per user instructions and provides output in desired format.
Input-Process-Output Model
Computer input is called data and the output obtained after processing it, based on user’s instructions is called information. Raw facts and figures which can be processed using arithmetic and logical operations to obtain information are called data.
The processes that can be applied to data are of two types −
- Arithmetic operations − Examples include calculations like addition, subtraction, differentials, square root, etc.
- Logical operations − Examples include comparison operations like greater than, less than, equal to, opposite, etc.
The corresponding figure for an actual computer looks something like this −
The basic parts of a computer are as follows −
- Input Unit − Devices like keyboard and mouse that are used to input data and instructions to the computer are called input unit.
- Output Unit − Devices like printer and visual display unit that are used to provide information to the user in desired format are called output unit.
- Control Unit − As the name suggests, this unit controls all the functions of the computer. All devices or parts of computer interact through the control unit.
- Arithmetic Logic Unit − This is the brain of the computer where all arithmetic operations and logical operations take place.
- Memory − All input data, instructions and data interim to the processes are stored in the memory. Memory is of two types – primary memory and secondary memory. Primary memory resides within the CPU whereas secondary memory is external to it.
Control unit, arithmetic logic unit and memory are together called the central processing unit or CPU. Computer devices like keyboard, mouse, printer, etc. that we can see and touch are the hardware components of a computer. The set of instructions or programs that make the computer function using these hardware parts are called software. We cannot see or touch software. Both hardware and software are necessary for working of a computer.
Advantages of Using Computer
Now that we know the characteristics of computers, we can see the advantages that computers offer−
- Computers can do the same task repetitively with same accuracy.
- Computers do not get tired or bored.
- Computers can take up routine tasks while releasing human resource for more intelligent functions.
Disadvantages of Using Computer
Despite so many advantages, computers have some disadvantages of their own −
- Computers have no intelligence; they follow the instructions blindly without considering the outcome.
- Regular electric supply is necessary to make computers work, which could prove difficult everywhere especially in developing nations.
Booting
Starting a computer or a computer-embedded device is called booting. Booting takes place in two steps −
- Switching on power supply
- Loading operating system into computer’s main memory
- Keeping all applications in a state of readiness in case needed by the user
The first program or set of instructions that run when the computer is switched on is called BIOS or Basic Input Output System. BIOS is a firmware, i.e. a piece of software permanently programmed into the hardware.
If a system is already running but needs to be restarted, it is called rebooting. Rebooting may be required if a software or hardware has been installed or system is unusually slow.
There are two types of booting −
- Cold Booting − When the system is started by switching on the power supply it is called cold booting. The next step in cold booting is loading of BIOS.
- Warm Booting − When the system is already running and needs to be restarted or rebooted, it is called warm booting. Warm booting is faster than cold booting because BIOS is not reloaded.
Generation in computer terminology is a change in technology a computer is/was being used. Initially, the generation term was used to distinguish between varying hardware technologies. Nowadays, generation includes both hardware and software, which together make up an entire computer system.
There are five computer generations known till date. Each generation has been discussed in detail along with their time period and characteristics. In the following table, approximate dates against each generation have been mentioned, which are normally accepted.
Following are the main five generations of computers.
First Generation
The period of first generation was from 1946-1959. The computers of first generation used vacuum tubes as the basic components for memory and circuitry for CPU (Central Processing Unit). These tubes, like electric bulbs, produced a lot of heat and the installations used to fuse frequently. Therefore, they were very expensive and only large organizations were able to afford it.
In this generation, mainly batch processing operating system was used. Punch cards, paper tape, and magnetic tape was used as input and output devices. The computers in this generation used machine code as the programming language.
The main features of the first generation are −
- Vacuum tube technology
- Unreliable
- Supported machine language only
- Very costly
- Generated a lot of heat
- Slow input and output devices
- Huge size
- Need of AC
- Non-portable
- Consumed a lot of electricity
Some computers of this generation were −
- ENIAC
- EDVAC
- UNIVAC
- IBM-701
- IBM-650
Second Generation
The period of second generation was from 1959-1965. In this generation, transistors were used that were cheaper, consumed less power, more compact in size, more reliable and faster than the first generation machines made of vacuum tubes. In this generation, magnetic cores were used as the primary memory and magnetic tape and magnetic disks as secondary storage devices.
In this generation, assembly language and high-level programming languages like FORTRAN, COBOL were used. The computers used batch processing and multiprogramming operating system.
The main features of second generation are −
- Use of transistors
- Reliable in comparison to first generation computers
- Smaller size as compared to first generation computers
- Generated less heat as compared to first generation computers
- Consumed less electricity as compared to first generation computers
- Faster than first generation computers
- Still very costly
- AC required
- Supported machine and assembly languages
Some computers of this generation were −
- IBM 1620
- IBM 7094
- CDC 1604
- CDC 3600
- UNIVAC 1108
Third Generation
The period of third generation was from 1965-1971. The computers of third generation used Integrated Circuits (ICs) in place of transistors. A single IC has many transistors, resistors, and capacitors along with the associated circuitry.
The IC was invented by Jack Kilby. This development made computers smaller in size, reliable, and efficient. In this generation remote processing, time-sharing, multiprogramming operating system were used. High-level languages (FORTRAN-II TO IV, COBOL, PASCAL PL/1, BASIC, ALGOL-68 etc.) were used during this generation.
The main features of third generation are −
- IC used
- More reliable in comparison to previous two generations
- Smaller size
- Generated less heat
- Faster
- Lesser maintenance
- Costly
- AC required
- Consumed lesser electricity
- Supported high-level language
Some computers of this generation were −
- IBM-360 series
- Honeywell-6000 series
- PDP (Personal Data Processor)
- IBM-370/168
- TDC-316
Fourth Generation
The period of fourth generation was from 1971-1980. Computers of fourth generation used Very Large Scale Integrated (VLSI) circuits. VLSI circuits having about 5000 transistors and other circuit elements with their associated circuits on a single chip made it possible to have microcomputers of fourth generation.
Fourth generation computers became more powerful, compact, reliable, and affordable. As a result, it gave rise to Personal Computer (PC) revolution. In this generation, time sharing, real time networks, distributed operating system were used. All the high-level languages like C, C++, DBASE etc., were used in this generation.
The main features of fourth generation are −
- VLSI technology used
- Very cheap
- Portable and reliable
- Use of PCs
- Very small size
- Pipeline processing
- No AC required
- Concept of internet was introduced
- Great developments in the fields of networks
- Computers became easily available
Some computers of this generation were −
- DEC 10
- STAR 1000
- PDP 11
- CRAY-1(Super Computer)
- CRAY-X-MP(Super Computer)
Fifth Generation
The period of fifth generation is 1980-till date. In the fifth generation, VLSI technology became ULSI (Ultra Large Scale Integration) technology, resulting in the production of microprocessor chips having ten million electronic components.
This generation is based on parallel processing hardware and AI (Artificial Intelligence) software. AI is an emerging branch in computer science, which interprets the means and method of making computers think like human beings. All the high-level languages like C and C++, Java, .Net etc., are used in this generation.
AI includes −
- Robotics
- Neural Networks
- Game Playing
- Development of expert systems to make decisions in real-life situations
- Natural language understanding and generation
The main features of fifth generation are −
- ULSI technology
- Development of true artificial intelligence
- Development of Natural language processing
- Advancement in Parallel Processing
- Advancement in Superconductor technology
- More user-friendly interfaces with multimedia features
- Availability of very powerful and compact computers at cheaper rates
Some computer types of this generation are −
- Desktop
- Laptop
- Notebook
- Ultrabook
- Chromebook
Computer scan is broadly classified by their speed and computing power.
Sr.No. | Type | Specifications |
1 | PC (Personal Computer) or Micro-Computers | It is a single user computer system having a moderately powerful microprocessor. It is termed as a computer that is equipped microprocessor as its CPU. |
2 | Workstation | It is also a single user computer system, similar to the personal computer, however, has a more powerful microprocessor. |
3 | Mini-Computer | It is a multi-user computer system, capable of supporting hundreds of users simultaneously. |
4 | Main Frame | It is a multi-user computer system, capable of supporting hundreds of users simultaneously. Software technology is different from minicomputer. |
5 | Super-Computer | It is an extremely fast computer, which can execute hundreds of millions of instructions per second. |
PC (Personal Computer)
A PC can be defined as a small, relatively inexpensive computer designed for an individual user. PCs are based on the microprocessor technology that enables manufacturers to put an entire CPU on one chip. Businesses use personal computers for word processing, accounting, desktop publishing, and for running spreadsheet and database management applications. At home, the most popular use for personal computers is playing games and surfing the Internet.
Although personal computers are designed as single-user systems, these systems are normally linked together to form a network. In terms of power, nowadays high-end models of the Macintosh and PC offer the same computing power and graphics capability as low-end workstations by Sun Microsystems, Hewlett-Packard, and Dell.
Workstation
The workstation is a computer used for engineering applications (CAD/CAM), desktop publishing, software development, and other such types of applications which require a moderate amount of computing power and relatively high-quality graphics capabilities.
Workstations generally come with a large, high-resolution graphics screen, a large amount of RAM, inbuilt network support, and a graphical user interface. Most workstations also have mass storage device such as a disk drive, but a special type of workstation, called diskless workstations, comes without a disk drive.
Common operating systems for workstations are UNIX and Windows NT. Like PC, workstations are also single-user computers like PC but are typically linked together to form a local area network, although they can also be used as stand-alone systems.
Minicomputer
It is a midsize multi-processing system capable of supporting up to 250 users simultaneously.
Mainframe
The mainframe is very large in size and is an expensive computer capable of supporting hundreds or even thousands of users simultaneously. Mainframe executes many programs concurrently and supports much simultaneous execution of programs.
Supercomputer
Supercomputers are one of the fastest computers currently available. Supercomputers are very expensive and are employed for specialized applications that require an immense amount of mathematical calculations (number-crunching).
For example, weather forecasting, scientific simulations, (animated)graphics, fluid dynamic calculations, nuclear energy research, electronic design, and analysis of geological data (e.g. In petrochemical prospecting).
Computer Block Diagram
Mainly computer system consists of three parts that are central processing unit (CPU), Input Devices, and Output Devices. The Central Processing Unit (CPU) is divided into two parts again: arithmetic logic unit (ALU) and the control unit (CU). The set of instruction is in the form of raw data.
A large amount of data is stored in the computer memory with the help of primary and secondary storage devices. The CPU is like the heart/brain of the computer. The user does not get the desired output, without the necessary option taken by the CPU. The Central processing unit (CPU) is responsible for the processing of all the instructions which are given by the user to the computer system.
Fig: Block Diagram of the computer.
The data is entered through input devices such as the keyboard, mouse, etc. This set of instruction is processed by the CPU after getting the input by the user, and then the computer system produces the output. The computer can show the output with the help of output devices to the user, such as monitor, printer, etc.
- CPU (Central Processing Unit)
- Storage Unit
- ALU(Arithmetic Logic Unit)
- Control Unit
Central Processing Unit (CPU)
The computer system is nothing without the Central processing Unit so, it is also known as the brain or heat of computer. The CPU is an electronic hardware device which can perform different types of operations such as arithmetic and logical operation.
The CPU contains two parts: the arithmetic logic unit and control unit. We have discussed briefly the arithmetic unit, logical unit, and control unit which are given below:
Control Unit
The control unit (CU) controls all the activities or operations which are performed inside the computer system. It receives instructions or information directly from the main memory of the computer.
When the control unit receives an instruction set or information, it converts the instruction set to control signals then; these signals are sent to the central processor for further processing. The control unit understands which operation to execute, accurately, and in which order.
Arithmetic and Logical Unit
The arithmetic and logical unit is the combinational digital electronic circuit that can perform arithmetic operations on integer binary numbers. It presents the arithmetic and logical operation. The outputs of ALU will change asynchronously in response to the input. The basic arithmetic and bitwise logic functions are supported by ALU.
Storage Unit
The information or set of guidelines are stored in the storage unit of the computer system. The storage unit provides the space to store the data or instruction of processed data. The information or data is saved or hold in computer memory or storage device. The data storage is the core function and fundamental of the computer components.
Components of Computer System
The hardware and software exist on the computer. The information which is stored through the device is known as computer software. The hardware components of the computer system are related to electronic and mechanical parts, and the software component is related to data and computer programs. Many elements are connected to the main circuit board of the computer system called a “motherboard.”
- Processor.
- Main Memory.
- Secondary Memory.
- Input Devices.
- Output Devices.
These are mainly five components of the computer system. The computer hardware, computer software, and liveware exist in the element of the computer system.
Processor
The processor is an electric circuitry within the computer system. The Central processing unit is the central processor or main processor of the computer system. The processor carries out the instructions of the computer program with the help of basic arithmetic and logic, input/output operations.
Main Memory
The Random Access Memory is the main memory of the computer system, which is known as RAM. The main memory can store the operating system software, application software, and other information. The Ram is one of the fastest memory, and it allows the data to be readable and writeable.
Secondary memory
We can store the data and programs on a long-term basis in the secondary memory. The hard disks and the optical disks are the common secondary devices. It is slow and cheap memory as compare to primary memory. This memory is not connected to the processor directly.
It has a large capacity to store the data. The hard disk has a capacity of 500 gigabytes. The data and programs on the hard disk are organized into files, and the file is the collection of data on the disk. The secondary storage is direct access by the CPU; that’s why it is different from the primary storage.
The hard disk is about 100 times the capacity of the main memory. The main difference between primary and secondary storage is speed and capacity. There are several large blocks of data which are copied from the hard disk into the main memory.
Input Devices
The user provides the set of instruction or information to the computer system with the help of input devices such as the keyboard, mouse, scanner, etc. The data representation to the computer system is in the form of binary language after that the processor processes the converted data. The input unit implements the data which is instructed by the user to the system.
We can enter the data from the outside world into the primary storage as the input through input devices. The input devices are the medium of communication between the outside world and the computer system. There are some important features of input devices which are given below:
- The input devices receive or accept the data or instruction from the user, who exist in the outside world.
- These devices convert the data or instruction into the machine-readable form for further processing.
- The input device performs like the connection between the outside world and our computer system.
- The keyboard and mouse are common examples of input devices.
- When the whole procedure is finished, we get the desired output from the output devices such as monitor, printer, etc.
Output Devices
The output devices produce or generate the desired result according to our input, such as a printer, monitor, etc. These devices convert the data into a human-readable form from binary code.
The computer system is linked or connected to the outside world with the help of output devices. The primary examples of output devices are a printer, projector, etc. These devices have various features which are given below:
- These devices receive or accept the data in the binary form.
- The output devices convert the binary code into the human-readable form.
- These devices produce the converted result and show to the user.
Motherboard
The motherboard is the computer's main circuit board. It's a thin plate that holds the CPU, memory, connectors for the hard drive and optical drives, expansion cards to control the video and audio, and connections to your computer's ports (such as USB ports). The motherboard connects directly or indirectly to every part of the computer.
CPU/processor
The central processing unit (CPU), also called a processor, is located inside the computer case on the motherboard. It is sometimes called the brain of the computer, and its job is to carry out commands. Whenever you press a key, click the mouse, or start an application, you're sending instructions to the CPU.
The CPU is usually a two-inch ceramic square with a silicon chip located inside. The chip is usually about the size of a thumbnail. The CPU fits into the motherboard's CPU socket, which is covered by the heat sink, an object that absorbs heat from the CPU.
A processor's speed is measured in megahertz (MHz), or millions of instructions per second; and gigahertz (GHz), or billions of instructions per second. A faster processor can execute instructions more quickly. However, the actual speed of the computer depends on the speed of many different components—not just the processor.
RAM (random access memory)
RAM is your system's short-term memory. Whenever your computer performs calculations, it temporarily stores the data in the RAM until it is needed.
This short-term memory disappears when the computer is turned off. If you're working on a document, spreadsheet, or other type of file, you'll need to save it to avoid losing it. When you save a file, the data is written to the hard drive, which acts as long-term storage.
RAM is measured in megabytes (MB) or gigabytes (GB). The more RAM you have, the more things your computer can do at the same time. If you don't have enough RAM, you may notice that your computer is sluggish when you have several programs open. Because of this, many people add extra RAM to their computers to improve performance.
Hard drive
The hard drive is where your software, documents, and other files are stored. The hard drive is long-term storage, which means the data is still saved even if you turn the computer off or unplug it.
When you run a program or open a file, the computer copies some of the data from the hard drive onto the RAM. When you save a file, the data is copied back to the hard drive. The faster the hard drive, the faster your computer can start up and load programs.
Power supply unit
The power supply unit in a computer converts the power from the wall outlet to the type of power needed by the computer. It sends power through cables to the motherboard and other components.
If you decide to open the computer case and take a look, make sure to unplug the computer first. Before touching the inside of the computer, you should touch a grounded metal object—or a metal part of the computer casing—to discharge any static build-up. Static electricity can be transmitted through the computer circuits, which can seriously damage your machine.
Expansion cards
Most computers have expansion slots on the motherboard that allow you to add various types of expansion cards. These are sometimes called PCI (peripheral component interconnect) cards. You may never need to add any PCI cards because most motherboards have built-in video, sound, network, and other capabilities.
However, if you want to boost the performance of your computer or update the capabilities of an older computer, you can always add one or more cards. Below are some of the most common types of expansion cards.
Video card
The video card is responsible for what you see on the monitor. Most computers have a GPU (graphics processing unit) built into the motherboard instead of having a separate video card. If you like playing graphics-intensive games, you can add a faster video card to one of the expansion slots to get better performance.
Sound card
The sound card—also called an audio card—is responsible for what you hear in the speakers or headphones. Most motherboards have integrated sound, but you can upgrade to a dedicated sound card for higher-quality sound.
Network card
The network card allows your computer to communicate over a network and access the Internet. It can either connect with an Ethernet cable or through a wireless connection (often called Wi-Fi). Many motherboards have built-in network connections, and a network card can also be added to an expansion slot.
Bluetooth card (or adapter)
Bluetooth is a technology for wireless communication over short distances. It's often used in computers to communicate with wireless keyboards, mice, and printers. It's commonly built into the motherboard or included in a wireless network card. For computers that don't have Bluetooth, you can purchase a USB adapter, often called a dongle.
The computer memory holds the data and instructions needed to process raw data and produce output. The computer memory is divided into large number of small parts known as cells. Each cell has a unique address which varies from 0 to memory size minus one.
Computer memory is of two types: Volatile (RAM) and Non-volatile (ROM). The secondary memory (hard disk) is referred as storage not memory.
But, if we categorize memory on behalf of space or location, it is of four types:
- Register memory
- Cache memory
- Primary memory
- Secondary memory
Register Memory
Register memory is the smallest and fastest memory in a computer. It is not a part of the main memory and is located in the CPU in the form of registers, which are the smallest data holding elements. A register temporarily holds frequently used data, instructions, and memory address that are to be used by CPU. They hold instructions that are currently processed by the CPU. All data is required to pass through registers before it can be processed. So, they are used by CPU to process the data entered by the users.
Registers hold a small amount of data around 32 bits to 64 bits. The speed of a CPU depends on the number and size (no. Of bits) of registers that are built into the CPU. Registers can be of different types based on their uses. Some of the widely used Registers include Accumulator or AC, Data Register or DR, the Address Register or AR, Program Counter (PC), I/O Address Register, and more.
Types and Functions of Computer Registers:
- Data Register: It is a 16-bit register, which is used to store operands (variables) to be operated by the processor. It temporarily stores data, which is being transmitted to or received from a peripheral device.
- Program Counter (PC): It holds the address of the memory location of the next instruction, which is to be fetched after the current instruction is completed. So, it is used to maintain the path of execution of the different programs and thus executes the programs one by one, when the previous instruction gets completed.
- Instructor Register: It is a 16-bit register. It stores the instruction which is fetched from the main memory. So, it is used to hold instruction codes, which are to be executed. The Control Unit takes instruction from Instructor Register, then decodes and executes it.
- Accumulator Register: It is a 16-bit register, which is used to store the results produced by the system. For example, the results generated by CPU after the processing are stored in the AC register.
- Address Register: It is a 12-bit register that stores the address of a memory location where instructions or data is stored in the memory.
- I/O Address Register: Its job is to specify the address of a particular I/O device.
- I/O Buffer Register: Its job is to exchange the data between an I/O module and the CPU.
Cache Memory
Cache memory is a high-speed memory, which is small in size but faster than the main memory (RAM). The CPU can access it more quickly than the primary memory. So, it is used to synchronize with high-speed CPU and to improve its performance.
Cache memory can only be accessed by CPU. It can be a reserved part of the main memory or a storage device outside the CPU. It holds the data and programs which are frequently used by the CPU. So, it makes sure that the data is instantly available for CPU whenever the CPU needs this data. In other words, if the CPU finds the required data or instructions in the cache memory, it doesn't need to access the primary memory (RAM). Thus, by acting as a buffer between RAM and CPU, it speeds up the system performance.
Types of Cache Memory:
L1: It is the first level of cache memory, which is called Level 1 cache or L1 cache. In this type of cache memory, a small amount of memory is present inside the CPU itself. If a CPU has four cores (quad core CPU), then each core will have its own level 1 cache. As this memory is present in the CPU, it can work at the same speed as of the CPU. The size of this memory ranges from 2KB to 64 KB. The L1 cache further has two types of caches: Instruction cache, which stores instructions required by the CPU, and the data cache that stores the data required by the CPU.
L2: This cache is known as Level 2 cache or L2 cache. This level 2 cache may be inside the CPU or outside the CPU. All the cores of a CPU can have their own separate level 2 cache, or they can share one L2 cache among themselves. In case it is outside the CPU, it is connected with the CPU with a very high-speed bus. The memory size of this cache is in the range of 256 KB to the 512 KB. In terms of speed, they are slower than the L1 cache.
L3: It is known as Level 3 cache or L3 cache. This cache is not present in all the processors; some high-end processors may have this type of cache. This cache is used to enhance the performance of Level 1 and Level 2 cache. It is located outside the CPU and is shared by all the cores of a CPU. Its memory size ranges from 1 MB to 8 MB. Although it is slower than L1 and L2 cache, it is faster than Random Access Memory (RAM).
How does cache memory work with CPU?
When CPU needs the data, first of all, it looks inside the L1 cache. If it does not find anything in L1, it looks inside the L2 cache. If again, it does not find the data in L2 cache, it looks into the L3 cache. If data is found in the cache memory, then it is known as a cache hit. On the contrary, if data is not found inside the cache, it is called a cache miss.
If data is not available in any of the cache memories, it looks inside the Random Access Memory (RAM). If RAM also does not have the data, then it will get that data from the Hard Disk Drive.
So, when a computer is started for the first time, or an application is opened for the first time, data is not available in cache memory or in RAM. In this case, the CPU gets the data directly from the hard disk drive. Thereafter, when you start your computer or open an application, CPU can get that data from cache memory or RAM.
Primary Memory
Primary Memory is of two types: RAM and ROM.
RAM (Volatile Memory)
It is a volatile memory. It means it does not store data or instructions permanently. When you switch on the computer the data and instructions from the hard disk are stored in RAM.
CPU utilizes this data to perform the required tasks. As soon as you shut down the computer the RAM loses all the data.
ROM (Non-volatile Memory)
It is a non-volatile memory. It means it does not lose its data or programs that are written on it at the time of manufacture. So, it is a permanent memory that contains all important data and instructions needed to perform important tasks like the boot process.
Secondary Memory
The secondary storage devices which are built into the computer or connected to the computer are known as a secondary memory of the computer. It is also known as external memory or auxiliary storage.
The secondary memory is accessed indirectly via input/output operations. It is non-volatile, so permanently stores the data even when the computer is turned off or until this data is overwritten or deleted. The CPU can't directly access the secondary memory. First, the secondary memory data is transferred to primary memory then the CPU can access it.
Some of the secondary memory or storage devices are described below:
1) Hard Disk:
It is a rigid magnetic disc that is used to store data. It permanently stores data and is located within a drive unit.
The hard disk is also known as a hard drive. It is a rigid magnetic disc that stores data permanently, as it is a non-volatile storage device. The hard disk is located within a drive unit on the computer's motherboard and comprises one or more platters packed in an air-sealed casing. The data is written on the platters by moving a magnetic head over the platters as they spin. The data stored on a computer's hard drive generally includes the operating system, installed software, and the user's files and programs, including pictures, music, videos, text documents, etc.
Components of Hard Drive:
The main components of a hard drive include a head actuator, read/write actuator arm, read/write head, platter, and spindle. A circuit board, which is called the disk controller or interface board, is present on the back of a hard drive. It allows the hard drive to communicate with the computer.
2) Solid-state Drive:
SSD (Solid State Drive) is also a non-volatile storage medium that is used to hold and access data. Unlike a hard drive, it does not have moving components, so it offers many advantages over SSD, such as faster access time, noiseless operation, less power consumption, and more.
As the cost of SSD has come down, it has become an ideal replacement for a standard hard drive in desktop and laptop computers. It is also suitable for notebooks, and tablets that don't require lots of storage.
3) Pen drive:
Pen drive is a compact secondary storage device. It is also known as a USB flash drive, thumb drive or a jump drive. It connects to a computer via a USB port. It is commonly used to store and transfer data between computers. For example, you can write a report using a computer and then copy or transfer it in the pen drive. Later, you can connect this pen drive to a computer to see or edit your report. You can also store your important documents and pictures, music, videos in the pen drive and keep it at a safe place.
Pen drive does not have movable parts; it comprises an integrated circuit memory chip that stores the data. This chip is housed inside a plastic or aluminium casing. The data storage capacity of the pen drive generally ranges from 2 GB to 128 GB. Furthermore, it is a plug and play device as you don't need additional drives, software, or hardware to use it.
4) SD Card:
SD Card stands for Secure Digital Card. It is most often used in portable and mobile devices such as smartphones and digital cameras. You can remove it from your device and see the things stored in it using a computer with a card reader.
There are many memory chips inside the SD card that store the data; it does not have moving parts. SD cards are not created equal, so they may differ from each other in terms of speed, physical sizes, and capacity. For example, standard SD cards, mini SD cards, and micro SD cards.
5) Compact Disk (CD):
Compact Disk is a portable secondary storage device in the shape of a round medium disk. It is made of polycarbonate plastic. The concept of CD was co-developed by Philips and Sony in 1982. The first CD was created on 17 August 1982 at the workshop of Philips in Germany.
In the beginning, it was used for storing and playing sound recordings, later it was used for various purposes such as for storing documents, audio files, videos, and other data like software programs in a CD.
Physical characteristics of a CD/ Structure of CD:
A standard CD is around 5 inches in diameter and 0.05 inches in thickness. It is made of a clear polycarbonate plastic substrate, a reflective metallic layer, and a clear coating of acrylic plastic. These thin circular layers are attached one on top of another as described below:
- A polycarbonate disc layer at the bottom has the data encoded by creating lands and pits.
- The polycarbonate disc layer is coated with a thin aluminium layer that reflects the laser.
- The reflective aluminium layer is coated with a lacquer layer to prevent oxidation in order to protect the below layers. It is generally spin coated directly on the top of the reflective layer.
- The label print is applied on the lacquer layer, or artwork is screen printed on the top of the disc on the lacquer layer by offset printing or screen printing.
How Does a CD Work?
The data or information is stored or recorded or encoded in CD digitally using a laser beam that etches tiny indentations or bumps on its surface. The bump is called a pit, which represents the number 0. Space, where the bump is not created, is called land, and it represents the number 1. Thus, the data is encoded into a compact disc by creating pits (0) and lands (1). The CD players use laser technology to read the optically recorded data.
6) DVD:
DVD is short for digital versatile disc or digital video disc. It is a type of optical media used for storing optical data. Although it has the same size as a CD, its storage capacity is much more than a CD. So, it is widely used for storing and viewing movies and to distribute software programs as they are too large to fit on a CD. DVD was co-developed by Sony, Panasonic, Philips, and Toshiba in 1995.
Types of DVDs:
DVDs can be divided into three main categories which are as follows:
- DVD-ROM (Read-Only): These types of DVDs come with media already recorded on them, such as movie DVDs. As the name suggests, data on these discs cannot be erased or added, so these discs are known as a read-only or non-writable DVD.
- DVD-R (Writable): It allows you to record or write information to the DVD. However, you can write information only once as it becomes a read-only DVD once it is full.
- DVD-RW (Rewritable or Erasable): This type of discs can be erased, written, or recorded multiple times.
A port is a physical docking point using which an external device can be connected to the computer. It can also be programmatic docking point through which information flows from a program to the computer or over the Internet.
Characteristics of Ports
A port has the following characteristics −
- External devices are connected to a computer using cables and ports.
- Ports are slots on the motherboard into which a cable of external device is plugged in.
- Examples of external devices attached via ports are the mouse, keyboard, monitor, microphone, speakers, etc.
Let us now discuss a few important types of ports −
Serial Port
- Used for external modems and older computer mouse
- Two versions: 9 pin, 25 pin model
- Data travels at 115 kilobits per second
Parallel Port
- Used for scanners and printers
- Also called printer port
- 25 pin model
- IEEE 1284-compliant Centronics port
PS/2 Port
- Used for old computer keyboard and mouse
- Also called mouse port
- Most of the old computers provide two PS/2 port, each for the mouse and keyboard
- IEEE 1284-compliant Centronics port
Universal Serial Bus (or USB) Port
- It can connect all kinds of external USB devices such as external hard disk, printer, scanner, mouse, keyboard, etc.
- It was introduced in 1997.
- Most of the computers provide two USB ports as minimum.
- Data travels at 12 megabits per seconds.
- USB compliant devices can get power from a USB port.
VGA Port
- Connects monitor to a computer's video card.
- It has 15 holes.
- Similar to the serial port connector. However, serial port connector has pins, VGA port has holes.
Power Connector
- Three-pronged plug.
- Connects to the computer's power cable that plugs into a power bar or wall socket.
Firewire Port
- Transfers large amount of data at very fast speed.
- Connects camcorders and video equipment to the computer.
- Data travels at 400 to 800 megabits per seconds.
- Invented by Apple.
- It has three variants: 4-Pin FireWire 400 connector, 6-Pin FireWire 400 connector, and 9-Pin FireWire 800 connector.
Modem Port
- Connects a PC's modem to the telephone network.
Ethernet Port
- Connects to a network and high speed Internet.
- Connects the network cable to a computer.
- This port resides on an Ethernet Card.
- Data travels at 10 megabits to 1000 megabits per seconds depending upon the network bandwidth.
Game Port
- Connect a joystick to a PC
- Now replaced by USB
Digital Video Interface, DVI port
- Connects Flat panel LCD monitor to the computer's high-end video graphic cards.
- Very popular among video card manufacturers.
Sockets
- Sockets connect the microphone and speakers to the sound card of the computer.
PCI stands for Peripheral Component Interconnect.
It could be a standard information transport that was common in computers from 1993 to 2007 or so. It was for a long time the standard transport for extension cards in computers, like sound cards, network cards, etc. It was a parallel transport, that, in its most common shape, had a clock speed of 66 MHz, and can either be 32 or 64 bits wide. It has since been replaced by PCI Express, which could be a serial transport as contradicted to PCI. A PCI port, or, more precisely, PCI opening, is essentially the connector that’s utilized to put through the card to the transport. When purge, it basically sits there and does nothing.
Types of PCI :
These are various types of PCI:
- PCI 32 bits have a transport speed of 33 MHz and work at 132 MBps.
- PCI 64 bits have a transport speed of 33 MHz and work at 264 MBps.
- PCI 64 bits have a transport speed of 66 MHz and work at 512 MBps.
- PCI 64 bits have a transport speed of 66 MHz and work at 1 GBps.
Function of PCI :
PCI slots are utilized to install sound cards, Ethernet and remote cards and presently strong state drives utilizing NVMe innovation to supply SSD drive speeds that are numerous times speedier than SATA SSD speeds. PCI openings too permit discrete design cards to be included to a computer as well.
PCI openings (and their variations) permit you to include expansion cards to a motherboard. The extension cards increment the machines capabilities past what the motherboard may create alone, such as: upgraded illustrations, extended sound, expanded USB and difficult drive controller, and extra arrange interface options, to title a couple of.
Advantage of PCI :
- You’ll interface a greatest of five components to the PCI and you’ll be able moreover supplant each of them by settled gadgets on the motherboard.
- You have different PCI buses on the same computer.
- The PCI transport will improve the speed of the exchanges from 33MHz to 133 MHz with a transfer rate of 1 gigabyte per second.
- The PCI can handle gadgets employing a greatest of 5 volts and the pins utilized can exchange more than one flag through one stick.
Disadvantage of PCI :
- PCI Graphics Card cannot get to system memory.
- PCI does not support pipeline.
Disk formatting is the process of preparing a hard disk drive or flexible disk medium for data storage. In some cases, the formatting operation may also create one or more new file systems. The formatting process that performs basic medium preparation is often referred to as “low-level formatting.” The term “high-level formatting” most often refers to the process of generating a new file system. In certain operation systems (e.g., Microsoft Windows), the two processes are combined and the term “format” is understood to mean an operation in which a new disk medium is fully prepared to store files. Illustrated to the right are the prompts and diagnostics printed by MS-DOS’s FORMAT.COM utility as a hard drive is being formatted.
Formatting a disk for use by an operating system and its applications involves three different steps.
Low-level formatting (i.e., closest to the hardware) marks the surfaces of the disks with markers indicating the start of a recording block (typically today called sector markers) and other information like block CRC to be used later, in normal operations, by the disk controller to read or write data. This is intended to be the permanent foundation of the disk, and is often completed at the factory.
Partitioning creates data structures needed by the operating system. This level of formatting often includes checking for defective tracks or defective sectors.
High-level formatting creates the file system format within the structure of the intermediate-level formatting. This formatting includes the data structures used by the OS to identify the logical drive or partition’s contents). This may occur during operating system installation, or when adding a new disk. Disk and distributed file system may specify an optional boot block, and/or various volume and directory information for the operating system.
Partitioning
Partitioning is the process of writing information into blocks of a storage device or medium that allows access by an operating system. Some operating systems allow the device (or its medium) to appear as multiple devices; i.e. partitioned into multiple devices.
On MS-DOS, Windows, and UNIX-based operating systems (such as BSD, Linux/GNU, OS X) this is normally done with a partition editor, such as fdisk, parted, and Disk Utility. These operating systems support multiple partitions.
In current IBM mainframe OSs derived from OS/360 and DOS/360, such as z/OS and z/VSE, this is done by the INIT command of the ICKDSF utility. These OSs support only a single partition per device, called a volume. The ICKDSF functions include creating a volume label and writing a Record 0 on every track.
Floppy disks are not partitioned; however, depending upon the OS they may require volume information in order to be accessed by the OS.
Partition editors and ICKDSF today do not handle low level functions for HDDs and optical disk drives such as writing timing marks, and they cannot reinitialize a modern disk that has been degaussed or otherwise lost the factory formatting.
Formatting Disk Drive
Step 1: Partition the hard disk
- Insert the Windows XP CD into your CD or DVD drive, or insert the first Windows XP Setup disk into the floppy disk drive, and then restart the computer to start the Windows XP Setup program. Note If you are using the Windows XP Setup disks, insert each additional disk when you are prompted, and then press ENTER to continue after you insert each disk.
- If you are prompted, select any options that are required to start the computer from the CD or DVD drive.
- If your hard disk controller requires a third-party original equipment manufacturer (OEM) driver, press F6 to specify the driver.
- At the Welcome to Setup page, press ENTER.
- Press F8 to accept the Windows XP Licensing Agreement.
- If an existing Windows XP installation is detected, you are prompted to repair it. To bypass the repair, press ESC.
- All existing partitions and non-partitioned spaces are listed for each physical hard disk. Use the ARROW keys to select an existing partition, or create a new partition by selecting the non-partitioned space where you want to create a new partition. You can also press C to create a new partition using non-partitioned space.
- To create the partition with the maximum size, press ENTER. To specify the partition size, type the size in megabytes (MB) for the new partition, and then press ENTER.
- If you want to create additional partitions, repeat steps g. And h.
- To format the partition and install Windows XP.
Step 2: Format the hard disk and install Windows XP
- Use the ARROW keys to select the partition where you want to install Windows XP, and then press ENTER.
- Select the format option that you want to use to format the partition. You can select from the following options: Notes
- Format the partition by using the NTFS file system (Quick)
- Format the partition by using the FAT file system (Quick)
- Format the partition by using the NTFS file system
- Format the partition by using the FAT file system
- Leave the current file system intact (no changes)
- If the selected partition is a new partition, the option to leave the current file system intact is not available.
- If the selected partition is larger than 32 gigabytes (GB), the FAT file system option is not available.
- If the selected partition is larger than 2 GB, the Windows Setup program uses the FAT32 file system (you must press ENTER to confirm).
- If the partition is smaller than 2 GB, the Windows Setup program uses the FAT16 file system.
- If you deleted and created a new System partition, but you are installing Windows XP on a different partition, you are prompted to select a file system for both the System and Start up partitions.
- Press ENTER.
- After the Windows Setup program formats the partition, follow the instructions that appear on the screen to install Windows XP.
BIOS (basic input/output system) is the program a computer's microprocessor uses to start the computer system after it is powered on. It also manages data flow between the computer's operating system (OS) and attached devices, such as the hard disk, video adapter, keyboard, mouse and printer.
History of BIOS
The term BIOS was first coined in 1975 by American computer scientist Gary Kildall. It was incorporated into IBM's first personal computer in 1981 and, in the years to come, gained popularity within other PCs, becoming an integral part of computers for some time. However, BIOS' popularity has waned in favour of a newer technology: Unified Extensible Firmware Interface (UEFI). Intel announced a plan in 2017 to retire support for legacy BIOS systems by 2020, replacing them with UEFI.
Uses of BIOS
The main use of BIOS is to act as a middleman between OSes and the hardware they run on. BIOS is theoretically always the intermediary between the microprocessor and I/O device control information and data flow. Although, in some cases, BIOS can arrange for data to flow directly to memory from devices, such as video cards, that require faster data flow to be effective.
How does BIOS work?
BIOS comes included with computers, as firmware on a chip on the motherboard. In contrast, an OS like Windows or iOS can either be pre-installed by the manufacturer or vendor or installed by the user. BIOS is a program that is made accessible to the microprocessor on an erasable programmable read-only memory (EPROM) chip. When users turn on their computer, the microprocessor passes control to the BIOS program, which is always located at the same place on EPROM.
When BIOS boots up a computer, it first determines whether all of the necessary attachments are in place and operational. Any piece of hardware containing files the computer needs to start is called a boot device. After testing and ensuring boot devices are functioning, BIOS loads the OS -- or key parts of it -- into the computer's random access memory (RAM) from a hard disk or diskette drive (the boot device).
The 4 functions of BIOS
BIOS identifies, configures, tests and connects computer hardware to the OS immediately after a computer is turned on. The combination of these steps is called the boot process.
These tasks are each carried out by BIOS' four main functions:
- Power-on self-test (POST). This tests the hardware of the computer before loading the OS.
- Bootstrap loader. This locates the OS.
- Software/drivers. This locates the software and drivers that interface with the OS once running.
- Complementary metal-oxide semiconductor (CMOS) setup. This is a configuration program that enable users to alter hardware and system settings. CMOS is the name of BIOS' non-volatile memory.
Accessing BIOS
With BIOS, the OS and its applications are freed from having to understand exact details, such as computer hardware addresses, about the attached I/O devices. When device details change, only the BIOS program needs to be changed. Sometimes, this change can be made during system setup.
Users can access BIOS and configure it through BIOS Setup Utility. Accessing BIOS Setup Utility varies somewhat depending on the computer being used. However, the following steps generally enable users to access and configure BIOS through Setup Utility:
- Reset or power off the computer.
- When the computer turns back on, look for a message that says "entering setup" or something similar. Accompanying that message will be a key that the user should press to enter system configuration. Here's an example message a user might see: "Press [key] to enter BIOS setup." Some keys often used as prompts are Del, Tab, Esc and any of the function keys (F1-F12).
- Upon seeing the prompt, quickly press the key specified.
Once in BIOS Setup Utility, users can change hardware settings, manage memory settings, change the boot order or boot device, and reset the BIOS password, among other configuration tasks.
BIOS security
BIOS security is a somewhat overlooked component of cybersecurity; however, it should still be managed to prevent hackers from executing malicious code on the OS. Security group Cylance, in 2017, showed how modern BIOS security flaws could enable ransomware programs inside a motherboard's UEFI and exploit other PC BIOS vulnerabilities.
Another unique exploit involving the manipulation of BIOS was Plundervolt. Plundervolt could be used to mess with a computer's power supply at the time data was being written to memory, causing errors that lead to security gaps. Intel released a BIOS patch to defend against it.
BIOS manufacturers
BIOS, in its beginnings, was originally owned by IBM. However, some companies, such as Phoenix Technologies, have reverse-engineered IBM's original version to create their own. Phoenix, in doing this, allowed other companies to create clones of the IBM PC and, more importantly, create non-IBM computers that work with BIOS. One company that did this was Compaq.
Today, many manufacturers produce motherboards with BIOS chips in them. Some examples are the following:
- AMI
- Asus
- Foxconn
- Hewlett Packard (HP)
- Ricoh
Knowing the motherboard manufacturer is important because users may want to update their BIOS and chipset drivers -- the drivers that enable the OS to work with other devices in the computer, such as a video card -- to the most recent versions. Driver updates may improve computer performance or patch recent BIOS-level security vulnerabilities. Each manufacturer has a unique way of updating these drivers.
View BIOS information at POST
The first way is by restarting your computer. When the initial load (also called POST) screen is displayed, the BIOS Type and version is also displayed.
Tip
If the load screen is displayed for only a few seconds, you can try pressing the Pause/Break key on your keyboard to pause the loading process. Pausing the screen should make it easier to find and read the BIOS information. When you're ready to resume the boot process, press Pause/Break again.
The BIOS information is often found at or near the top of the POST screen.
Also, you will see information on what hard drive(s) and CD/DVD drives are installed in your computer.
Tip
On the boot screen, you can also access the CMOS setup for more hardware.
- How to enter the BIOS or CMOS setup.
To help with load times, or display a company logo, this screen may not be viewable. If this is the case, try the below alternate resolutions.
Through Windows System Information
The BIOS information is also shown in the Windows System Information utility. To open this utility, click Start, Programs, Accessories, System Tools, and then System Information. If you're running Windows Vista or Windows 7, or Windows 10 type System Information in the Start search box.
The System Information window displays information about your computer, including the type of BIOS you have and the version, under the System Summary section. As seen in the picture below, this computer has a DELL BIOS version 1.0.0 with a BIOS Version/Date of 11/5/2008.
Using the systeminfo command line command
You can also use the systeminfo command from the command line to view the BIOS version and other system information by following the following steps.
- Open the Windows command line.
- Type systeminfo and press Enter to get a screen similar to the example shown below.
Note
You may need to scroll up to see the BIOS version.
In the Windows registry
You can also find BIOS information in the Windows registry. While in the registry, realize that improperly changing a setting can affect how Windows operates. So be careful if you choose to use this option to view your BIOS information.
To access the registry, click Start and in the Run or Search box, type regedit in the text field and press Enter. In the Registry Editor, navigate to the below registry directory.
HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System
Find the subkeys SystemBiosDate and SystemBiosVersion to see the BIOS and version for your motherboard. As seen in the picture below, the BIOS date and version are shown in these two keys.
Finding BIOS date through debug routine
Earlier computers without access to the above tools can also use the MS-DOS and Windows command line debug command to view the BIOS date, as shown below.
At the C:\> prompt, type the following commands.
Debug
- d FFFF:5 L 8
After typing the above command, a string similar to the example below is shown.
FFFF:0000 30 34 2F-33 30 2F 39 38 4/30/98
The 4/30/98 would be the date of your computer BIOS.
What is an Algorithm?
An algorithm is a process or a set of rules required to perform calculations or some other problem-solving operations especially by a computer. The formal definition of an algorithm is that it contains the finite set of instructions which are being carried in a specific order to perform the specific task. It is not the complete program or code; it is just a solution (logic) of a problem, which can be represented either as an informal description using a Flowchart or Pseudocode.
Characteristics of an Algorithm
The following are the characteristics of an algorithm:
- Input: An algorithm has some input values. We can pass 0 or some input value to an algorithm.
- Output: We will get 1 or more output at the end of an algorithm.
- Unambiguity: An algorithm should be unambiguous which means that the instructions in an algorithm should be clear and simple.
- Finiteness: An algorithm should have finiteness. Here, finiteness means that the algorithm should contain a limited number of instructions, i.e., the instructions should be countable.
- Effectiveness: An algorithm should be effective as each instruction in an algorithm affects the overall process.
- Language independent: An algorithm must be language-independent so that the instructions in an algorithm can be implemented in any of the languages with the same output.
Dataflow of an Algorithm
- Problem: A problem can be a real-world problem or any instance from the real-world problem for which we need to create a program or the set of instructions. The set of instructions is known as an algorithm.
- Algorithm: An algorithm will be designed for a problem which is a step by step procedure.
- Input: After designing an algorithm, the required and the desired inputs are provided to the algorithm.
- Processing unit: The input will be given to the processing unit, and the processing unit will produce the desired output.
- Output: The output is the outcome or the result of the program.
Why do we need Algorithms?
We need algorithms because of the following reasons:
- Scalability: It helps us to understand the scalability. When we have a big real-world problem, we need to scale it down into small-small steps to easily analyse the problem.
- Performance: The real-world is not easily broken down into smaller steps. If the problem can be easily broken into smaller steps means that the problem is feasible.
Let's understand the algorithm through a real-world example. Suppose we want to make a lemon juice, so following are the steps required to make a lemon juice:
Step 1: First, we will cut the lemon into half.
Step 2: Squeeze the lemon as much you can and take out its juice in a container.
Step 3: Add two tablespoon sugar in it.
Step 4: Stir the container until the sugar gets dissolved.
Step 5: When sugar gets dissolved, add some water and ice in it.
Step 6: Store the juice in a fridge for 5 to minutes.
Step 7: Now, it's ready to drink.
The above real-world can be directly compared to the definition of the algorithm. We cannot perform the step 3 before the step 2, we need to follow the specific order to make lemon juice. An algorithm also says that each and every instruction should be followed in a specific order to perform a specific task.
Now we will look an example of an algorithm in programming.
We will write an algorithm to add two numbers entered by the user.
The following are the steps required to add two numbers entered by the user:
Step 1: Start
Step 2: Declare three variables a, b, and sum.
Step 3: Enter the values of a and b.
Step 4: Add the values of a and b and store the result in the sum variable, i.e., sum=a+b.
Step 5: Print sum
Step 6: Stop
Factors of an Algorithm
The following are the factors that we need to consider for designing an algorithm:
- Modularity: If any problem is given and we can break that problem into small-small modules or small-small steps, which is a basic definition of an algorithm, it means that this feature has been perfectly designed for the algorithm.
- Correctness: The correctness of an algorithm is defined as when the given inputs produce the desired output, which means that the algorithm has been designed algorithm. The analysis of an algorithm has been done correctly.
- Maintainability: Here, maintainability means that the algorithm should be designed in a very simple structured way so that when we redefine the algorithm, no major change will be done in the algorithm.
- Functionality: It considers various logical steps to solve the real-world problem.
- Robustness: Robustness means that how an algorithm can clearly define our problem.
- User-friendly: If the algorithm is not user-friendly, then the designer will not be able to explain it to the programmer.
- Simplicity: If the algorithm is simple then it is easy to understand.
- Extensibility: If any other algorithm designer or programmer wants to use your algorithm then it should be extensible.
Importance of Algorithms
- Theoretical importance: When any real-world problem is given to us and we break the problem into small-small modules. To break down the problem, we should know all the theoretical aspects.
- Practical importance: As we know that theory cannot be completed without the practical implementation. So, the importance of algorithm can be considered as both theoretical and practical.
Issues of Algorithms
The following are the issues that come while designing an algorithm:
- How to design algorithms: As we know that an algorithm is a step-by-step procedure so we must follow some steps to design an algorithm.
- How to analyse algorithm efficiency
Approaches of Algorithm
The following are the approaches used after considering both the theoretical and practical importance of designing an algorithm:
- Brute force algorithm: The general logic structure is applied to design an algorithm. It is also known as an exhaustive search algorithm that searches all the possibilities to provide the required solution. Such algorithms are of two types:
- Optimizing: Finding all the solutions of a problem and then take out the best solution or if the value of the best solution is known then it will terminate if the best solution is known.
- Sacrificing: As soon as the best solution is found, then it will stop.
- Divide and conquer: It is a very implementation of an algorithm. It allows you to design an algorithm in a step-by-step variation. It breaks down the algorithm to solve the problem in different methods. It allows you to break down the problem into different methods, and valid output is produced for the valid input. This valid output is passed to some other function.
- Greedy algorithm: It is an algorithm paradigm that makes an optimal choice on each iteration with the hope of getting the best solution. It is easy to implement and has a faster execution time. But, there are very rare cases in which it provides the optimal solution.
- Dynamic programming: It makes the algorithm more efficient by storing the intermediate results. It follows five different steps to find the optimal solution for the problem:
- It breaks down the problem into a subproblem to find the optimal solution.
- After breaking down the problem, it finds the optimal solution out of these subproblems.
- Stores the result of the subproblems is known as memorization.
- Reuse the result so that it cannot be recomputed for the same subproblems.
- Finally, it computes the result of the complex program.
- Branch and Bound Algorithm: The branch and bound algorithm can be applied to only integer programming problems. This approach divides all the sets of feasible solutions into smaller subsets. These subsets are further evaluated to find the best solution.
- Randomized Algorithm: As we have seen in a regular algorithm, we have predefined input and required output. Those algorithms that have some defined set of inputs and required output, and follow some described steps are known as deterministic algorithms. What happens that when the random variable is introduced in the randomized algorithm?. In a randomized algorithm, some random bits are introduced by the algorithm and added in the input to produce the output, which is random in nature. Randomized algorithms are simpler and efficient than the deterministic algorithm.
- Backtracking: Backtracking is an algorithmic technique that solves the problem recursively and removes the solution if it does not satisfy the constraints of a problem.
The major categories of algorithms are given below:
- Sort: Algorithm developed for sorting the items in a certain order.
- Search: Algorithm developed for searching the items inside a data structure.
- Delete: Algorithm developed for deleting the existing element from the data structure.
- Insert: Algorithm developed for inserting an item inside a data structure.
- Update: Algorithm developed for updating the existing element inside a data structure.
Algorithm Analysis
The algorithm can be analysed in two levels, i.e., first is before creating the algorithm, and second is after creating the algorithm. The following are the two analysis of an algorithm:
- Priori Analysis: Here, priori analysis is the theoretical analysis of an algorithm which is done before implementing the algorithm. Various factors can be considered before implementing the algorithm like processor speed, which has no effect on the implementation part.
- Posterior Analysis: Here, posterior analysis is a practical analysis of an algorithm. The practical analysis is achieved by implementing the algorithm using any programming language. This analysis basically evaluates that how much running time and space taken by the algorithm.
Algorithm Complexity
The performance of the algorithm can be measured in two factors:
- Time complexity: The time complexity of an algorithm is the amount of time required to complete the execution. The time complexity of an algorithm is denoted by the big O notation. Here, big O notation is the asymptotic notation to represent the time complexity. The time complexity is mainly calculated by counting the number of steps to finish the execution. Let's understand the time complexity through an example.
- Sum=0;
- // Suppose we have to calculate the sum of n numbers.
- For i=1 to n
- Sum=sum+i;
- // when the loop ends then sum holds the sum of the n numbers
- Return sum;
In the above code, the time complexity of the loop statement will be atleast n, and if the value of n increases, then the time complexity also increases. While the complexity of the code, i.e., return sum will be constant as its value is not dependent on the value of n and will provide the result in one step only. We generally consider the worst-time complexity as it is the maximum time taken for any given input size.
- Space complexity: An algorithm's space complexity is the amount of space required to solve a problem and produce an output. Similar to the time complexity, space complexity is also expressed in big O notation.
For an algorithm, the space is required for the following purposes:
- To store program instructions
- To store constant values
- To store variable values
- To track the function calls, jumping statements, etc.
Auxiliary space: The extra space required by the algorithm, excluding the input size, is known as an auxiliary space. The space complexity considers both the spaces, i.e., auxiliary space, and space used by the input.
So,
Space complexity = Auxiliary space + Input size.
Types of Algorithms
The following are the types of algorithm:
- Search Algorithm
- Sort Algorithm
Search Algorithm
On each day, we search for something in our day to day life. Similarly, with the case of computer, huge data is stored in a computer that whenever the user asks for any data then the computer searches for that data in the memory and provides that data to the user. There are mainly two techniques available to search the data in an array:
- Linear search
- Binary search
Linear Search
Linear search is a very simple algorithm that starts searching for an element or a value from the beginning of an array until the required element is not found. It compares the element to be searched with all the elements in an array, if the match is found, then it returns the index of the element else it returns -1. This algorithm can be implemented on the unsorted list.
Binary Search
A Binary algorithm is the simplest algorithm that searches the element very quickly. It is used to search the element from the sorted list. The elements must be stored in sequential order or the sorted manner to implement the binary algorithm. Binary search cannot be implemented if the elements are stored in a random manner. It is used to find the middle element of the list.
Sorting Algorithms
Sorting algorithms are used to rearrange the elements in an array or a given data structure either in an ascending or descending order. The comparison operator decides the new order of the elements.
Why do we need a sorting algorithm?
- An efficient sorting algorithm is required for optimizing the efficiency of other algorithms like binary search algorithm as a binary search algorithm requires an array to be sorted in a particular order, mainly in ascending order.
- It produces information in a sorted order, which is a human-readable format.
- Searching a particular element in a sorted list is faster than the unsorted list.
Flowchart is a diagrammatic representation of sequence of logical steps of a program. Flowcharts use simple geometric shapes to depict processes and arrows to show relationships and process/data flow.
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
Symbol | Symbol Name | Purpose |
Start/Stop | Used at the beginning and end of the algorithm to show start and end of the program. | |
Process | Indicates processes like mathematical operations. | |
Input/ Output | Used for denoting program inputs and outputs. | |
Decision | Stands for decision statements in a program, where answer is usually Yes or No. | |
Arrow | Shows relationships between different shapes. | |
On-page Connector | Connects two or more parts of a flowchart, which are on the same page. | |
Off-page Connector | Connects two parts of a flowchart which are spread over different pages. |
Guidelines for Developing Flowcharts
These are some points to keep in mind while developing a flowchart −
- Flowchart can have only one start and one stop symbol
- On-page connectors are referenced using numbers
- Off-page connectors are referenced using alphabets
- General flow of processes is top to bottom or left to right
- Arrows should not cross each other
Example Flowcharts
Here is the flowchart for going to the market to purchase a pen.
Here is a flowchart to calculate the average of two numbers.
Paradigm can also be termed as method to solve some problem or do some task. Programming paradigm is an approach to solve problem using some programming language or also we can say it is a method to solve a problem using tools and techniques that are available to us following some approach. There are lots for programming language that are known but all of them need to follow some strategy when they are implemented and this methodology/strategy is paradigms. Apart from varieties of programming language there are lots of paradigms to fulfil each and every demand. They are discussed below:
1. Imperative programming paradigm:
It is one of the oldest programming paradigm. It features close relation to machine architecture. It is based on Von Neumann architecture. It works by changing the program state through assignment statements. It performs step by step task by changing state. The main focus is on how to achieve the goal. The paradigm consists of several statements and after execution of all the result is stored.
Advantage:
- Very simple to implement
- It contains loops, variables etc.
Disadvantage:
- Complex problem cannot be solved
- Less efficient and less productive
- Parallel programming is not possible
Examples of Imperative programming paradigm:
C : developed by Dennis Ritchie and Ken Thompson
Fortan : developed by John Backus for IBM
Basic : developed by John G Kemeny and Thomas E Kurtz
// average of five number in C
Int marks[5] = { 12, 32, 45, 13, 19 } int sum = 0; Float average = 0.0; For (int i = 0; i < 5; i++) { Sum = sum + marks[i]; } Average = sum / 5; |
Imperative programming is divided into three broad categories: Procedural, OOP and parallel processing. These paradigms are as follows:
- Procedural programming paradigm –
This paradigm emphasizes on procedure in terms of under lying machine model. There is no difference in between procedural and imperative approach. It has the ability to reuse the code and it was boon at that time when it was in use because of its reusability. - Examples of Procedural programming paradigm:
- C : developed by Dennis Ritchie and Ken Thompson
- C++ : developed by Bjarne Stroustrup
- Java : developed by James Gosling at Sun Microsystems
- ColdFusion : developed by J Allaire
Pascal : developed by Niklaus Wirth
#include <iostream> Using namespace std; Int main() { Int i, fact = 1, num; Cout << "Enter any Number: "; Cin >> number; For (i = 1; i <= num; i++) { Fact = fact * i; } Cout << "Factorial of " << num << " is: " << fact << endl; Return 0; } |
Then comes OOP,
8. Object oriented programming –
The program is written as a collection of classes and object which are meant for communication. The smallest and basic entity is object and all kind of computation is performed on the objects only. More emphasis is on data rather procedure. It can handle almost all kind of real life problems which are today in scenario.
Advantages:
- Data security
- Inheritance
- Code reusability
- Flexible and abstraction is also present
Examples of Object Oriented programming paradigm:
Simula : first OOP language
Java : developed by James Gosling at Sun Microsystems
C++ : developed by Bjarne Stroustrup
Objective-C : designed by Brad Cox
Visual Basic .NET : developed by Microsoft
Python : developed by Guido van Rossum
Ruby : developed by Yukihiro Matsumoto
Smalltalk : developed by Alan Kay, Dan Ingalls, Adele Goldberg
Import java.io.*;
Class GFG { Public static void main(String[] args) { System.out.println("GfG!"); Signup s1 = new Signup(); s1.create(22, "riya", "riya2@gmail.com", 'F', 89002); } }
Class Signup { Int userid; String name; String emailid; Char sex; Long mob;
Public void creates(int userid, String name, String emailid, char sex, long mob) { System.out.println("Welcome to GeeksforGeeks\nLets create your account\n"); This.userid = 132; This.name = "Radha"; This.emailid = "radha.89@gmail.com"; This.sex = 'F'; This.mob = 900558981; System.out.println("your account has been created"); } } |
9. Parallel processing approach –
Parallel processing is the processing of program instructions by dividing them among multiple processors. A parallel processing system possess many numbers of processor with the objective of running a program in less time by dividing them. This approach seems to be like divide and conquer. Examples are NESL (one of the oldest one) and C/C++ also supports because of some library function.
2. Declarative programming paradigm:
It is divided as Logic, Functional, Database. In computer science the declarative programming is a style of building programs that expresses logic of computation without talking about its control flow. It often considers programs as theories of some logic. It may simplify writing parallel programs. The focus is on what needs to be done rather how it should be done basically emphasize on what code is actually doing. It just declares the result we want rather how it has be produced. This is the only difference between imperative (how to do) and declarative (what to do) programming paradigms. Getting into deeper we would see logic, functional and database.
- Logic programming paradigms –
It can be termed as abstract model of computation. It would solve logical problems like puzzles, series etc. In logic programming we have a knowledge base which we know before and along with the question and knowledge base which is given to machine, it produces result. In normal programming languages, such concept of knowledge base is not available but while using the concept of artificial intelligence, machine learning we have some models like Perception model which is using the same mechanism.
In logical programming the main emphasize is on knowledge base and the problem. The execution of the program is very much like proof of mathematical statement, e.g., Prolog - Sum of two number in prolog:
- Predicates
- Sumoftwonumber(integer, integer)
- Clauses
- Sum(0, 0).
- Sum(n, r):-
- n1=n-1,
- Sum(n1, r1),
r=r1+n
12. Functional programming paradigms –
The functional programming paradigms has its roots in mathematics and it is language independent. The key principal of this paradigms is the execution of series of mathematical functions. The central model for the abstraction is the function which are meant for some specific computation and not the data structure. Data are loosely coupled to functions.The function hide their implementation. Function can be replaced with their values without changing the meaning of the program. Some of the languages like perl, javascript mostly uses this paradigm.
13. Examples of Functional programming paradigm:
14.
15. JavaScript : developed by Brendan Eich
16. Haskwell : developed by Lennart Augustsson, Dave Barton
17. Scala : developed by Martin Odersky
18. Erlang : developed by Joe Armstrong, Robert Virding
19. Lisp : developed by John Mccarthy
20. ML : developed by Robin Milner
Clojure : developed by Rich Hickey
The next kind of approach is of Database.
21. Database/Data driven programming approach –
This programming methodology is based on data and its movement. Program statements are defined by data rather than hard-coding a series of steps. A database program is the heart of a business information system and provides file creation, data entry, update, query and reporting functions. There are several programming languages that are developed mostly for database application. For example, SQL. It is applied to streams of structured data, for filtering, transforming, aggregating (such as computing statistics), or calling other programs. So, it has its own wide application.
22. CREATE DATABASE databaseAddress;
23. CREATE TABLE Addr (
24. PersonID int,
25. LastName varchar(200),
26. FirstName varchar(200),
27. Address varchar(200),
28. City varchar(200),
29. State varchar(200)
);
Character Set
The character set are set of words, digits, symbols and operators that are valid in C.
There are four types of Character Set:-
Character Set | ||
1. | Letters | Uppercase A-Z |
2. | Digits | All digits 0-9 |
3. | Special Characters | All Symbols: , . : ; ? ' " ! | \ / ~ _$ % # & ^ * - + < > ( ) { } [ ] |
4. | White Spaces | Blank space, Horizintal tab, Carriage return, New line, Form feed |
Tokens
Tokens are the smallest unit of the program meaningful to the compiler.
Tokens are classified as – Keywords, Identifiers, Contestants, Strings, Operators.
Data Types
A data type specifies the type of data that a variable can store such as integer, floating, character, etc.
There are the following data types in C language.
Types | Data Types |
Basic Data Type | Int, char, float, double |
Derived Data Type | Array, pointer, structure, union |
Enumeration Data Type | Enum |
Void Data Type | Void |
Basic Data Types
The basic data types are integer-based and floating-point based. C language supports both signed and unsigned literals.
The memory size of the basic data types may change according to 32 or 64-bit operating system.
Let's see the basic data types. Its size is given according to 32-bit architecture.
Data Types | Memory Size | Range |
Char | 1 byte | −128 to 127 |
Signed char | 1 byte | −128 to 127 |
Unsigned char | 1 byte | 0 to 255 |
Short | 2 byte | −32,768 to 32,767 |
Signed short | 2 byte | −32,768 to 32,767 |
Unsigned short | 2 byte | 0 to 65,535 |
Int | 2 byte | −32,768 to 32,767 |
Signed int | 2 byte | −32,768 to 32,767 |
Unsigned int | 2 byte | 0 to 65,535 |
Short int | 2 byte | −32,768 to 32,767 |
Signed short int | 2 byte | −32,768 to 32,767 |
Unsigned short int | 2 byte | 0 to 65,535 |
Long int | 4 byte | -2,147,483,648 to 2,147,483,647 |
Signed long int | 4 byte | -2,147,483,648 to 2,147,483,647 |
Unsigned long int | 4 byte | 0 to 4,294,967,295 |
Float | 4 byte |
|
Double | 8 byte |
|
Long double | 10 byte |
|
Constants
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming" etc.
There are different types of constants in C programming.
List of Constants in C
Constant | Example |
Decimal Constant | 10, 20, 450 etc. |
Real or Floating-point Constant | 10.3, 20.2, 450.6 etc. |
Octal Constant | 021, 033, 046 etc. |
Hexadecimal Constant | 0x2a, 0x7b, 0xaa etc. |
Character Constant | 'a', 'b', 'x' etc. |
String Constant | "c", "c program", "c in javatpoint" etc. |
2 ways to define constant in C
There are two ways to define constant
Const keyword
- #define preprocessor
1) C const keyword
The const keyword is used to define constant in C programming.
- Const float PI=3.14;
Now, the value of PI variable can't be changed.
- #include<stdio.h>
- Int main(){
- Const float PI=3.14;
- Printf("The value of PI is: %f",PI);
- Return 0;
- }
Output:
The value of PI is: 3.140000
If you try to change the value of PI, it will render compile time error.
- #include<stdio.h>
- Int main(){
- Const float PI=3.14;
- PI=4.5;
- Printf("The value of PI is: %f",PI);
- Return 0;
- }
Output:
Compile Time Error: Cannot modify a const object
2) C #define preprocessor
The #define preprocessor is also used to define constant.
An expression is a formula in which operands are linked to each other by the use of operators to compute a value. An operand can be a function reference, a variable, an array element or a constant.
Let's see an example:
- a-b;
In the above expression, minus character (-) is an operator, and a, and b are the two operands.
There are four types of expressions exist in C:
- Arithmetic expressions
- Relational expressions
- Logical expressions
- Conditional expressions
Each type of expression takes certain types of operands and uses a specific set of operators. Evaluation of a particular expression produces a specific value.
For example:
- x = 9/2 + a-b;
The entire above line is a statement, not an expression. The portion after the equal is an expression.
Arithmetic Expressions
An arithmetic expression is an expression that consists of operands and arithmetic operators. An arithmetic expression computes a value of type int, float or double.
When an expression contains only integral operands, then it is known as pure integer expression when it contains only real operands, it is known as pure real expression, and when it contains both integral and real operands, it is known as mixed mode expression.
Evaluation of Arithmetic Expressions
The expressions are evaluated by performing one operation at a time. The precedence and associativity of operators decide the order of the evaluation of individual operations.
When individual operations are performed, the following cases can be happened:
- When both the operands are of type integer, then arithmetic will be performed, and the result of the operation would be an integer value. For example, 3/2 will yield 1 not 1.5 as the fractional part is ignored.
- When both the operands are of type float, then arithmetic will be performed, and the result of the operation would be a real value. For example, 2.0/2.0 will yield 1.0, not 1.
- If one operand is of type integer and another operand is of type real, then the mixed arithmetic will be performed. In this case, the first operand is converted into a real operand, and then arithmetic is performed to produce the real value. For example, 6/2.0 will yield 3.0 as the first value of 6 is converted into 6.0 and then arithmetic is performed to produce 3.0.
Let's understand through an example.
6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)
Evaluation of expression | Description of each operation |
6*2/( 2+1 * 2/3 +6) +8 * (8/4) | An expression is given. |
6*2/(2+2/3 + 6) + 8 * (8/4) | 2 is multiplied by 1, giving value 2. |
6*2/(2+0+6) + 8 * (8/4) | 2 is divided by 3, giving value 0. |
6*2/ 8+ 8 * (8/4) | 2 is added to 6, giving value 8. |
6*2/8 + 8 * 2 | 8 is divided by 4, giving value 2. |
12/8 +8 * 2 | 6 is multiplied by 2, giving value 12. |
1 + 8 * 2 | 12 is divided by 8, giving value 1. |
1 + 16 | 8 is multiplied by 2, giving value 16. |
17 | 1 is added to 16, giving value 17. |
Relational Expressions
- A relational expression is an expression used to compare two operands.
- It is a condition which is used to decide whether the action should be taken or not.
- In relational expressions, a numeric value cannot be compared with the string value.
- The result of the relational expression can be either zero or non-zero value. Here, the zero value is equivalent to a false and non-zero value is equivalent to true.
Relational Expression | Description |
x%2 = = 0 | This condition is used to check whether the x is an even number or not. The relational expression results in value 1 if x is an even number otherwise results in value 0. |
a!=b | It is used to check whether a is not equal to b. This relational expression results in 1 if a is not equal to b otherwise 0. |
a+b = = x+y | It is used to check whether the expression "a+b" is equal to the expression "x+y". |
a>=9 | It is used to check whether the value of a is greater than or equal to 9. |
Let's see a simple example:
- #include <stdio.h>
- Int main()
- {
- Int x=4;
- If(x%2==0)
- {
- Printf("The number x is even");
- }
- Else
- Printf("The number x is not even");
- Return 0;
- }
Output
Logical Expressions
- A logical expression is an expression that computes either a zero or non-zero value.
- It is a complex test condition to take a decision.
Let's see some example of the logical expressions.
Logical Expressions | Description |
( x > 4 ) && ( x < 6 ) | It is a test condition to check whether the x is greater than 4 and x is less than 6. The result of the condition is true only when both the conditions are true. |
x > 10 || y <11 | It is a test condition used to check whether x is greater than 10 or y is less than 11. The result of the test condition is true if either of the conditions holds true value. |
! ( x > 10 ) && ( y = = 2 ) | It is a test condition used to check whether x is not greater than 10 and y is equal to 2. The result of the condition is true if both the conditions are true. |
Let's see a simple program of "&&" operator.
- #include <stdio.h>
- Int main()
- {
- Int x = 4;
- Int y = 10;
- If ( (x <10) && (y>5))
- {
- Printf("Condition is true");
- }
- Else
- Printf("Condition is false");
- Return 0;
- }
Output
Let's see a simple example of "| |" operator
- #include <stdio.h>
- Int main()
- {
- Int x = 4;
- Int y = 9;
- If ( (x <6) || (y>10))
- {
- Printf("Condition is true");
- }
- Else
- Printf("Condition is false");
- Return 0;
- }
Output
Conditional Expressions
- A conditional expression is an expression that returns 1 if the condition is true otherwise 0.
- A conditional operator is also known as a ternary operator.
The Syntax of Conditional operator
Suppose exp1, exp2 and exp3 are three expressions.
Exp1 ? exp2 : exp3
The above expression is a conditional expression which is evaluated on the basis of the value of the exp1 expression. If the condition of the expression exp1 holds true, then the final conditional expression is represented by exp2 otherwise represented by exp3.
Let's understand through a simple example.
- #include<stdio.h>
- #include<string.h>
- Int main()
- {
- Int age = 25;
- Char status;
- Status = (age>22) ? 'M': 'U';
- If(status == 'M')
- Printf("Married");
- Else
- Printf("Unmarried");
- Return 0;
- }
Output
Before we study the basic building blocks of the C programming language, let us look at a bare minimum C program structure so that we can take it as a reference in the upcoming chapters.
Hello World Example
A C program basically consists of the following parts −
- Preprocessor Commands
- Functions
- Variables
- Statements & Expressions
- Comments
Let us look at a simple code that would print the words "Hello World" −
#include <stdio.h>
Int main() {
/* my first program in C */
Printf("Hello, World! \n");
Return 0;
}
Let us take a look at the various parts of the above program −
- The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler to include stdio.h file before going to actual compilation.
- The next line int main() is the main function where the program execution begins.
- The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So, such lines are called comments in the program.
- The next line printf(...) is another function available in C which causes the message "Hello, World!" to be displayed on the screen.
- The next line return 0; terminates the main() function and returns the value 0.
Compile and Execute C Program
Let us see how to save the source code in a file, and how to compile and run it. Following are the simple steps −
- Open a text editor and add the above-mentioned code.
- Save the file as hello.c
- Open a command prompt and go to the directory where you have saved the file.
- Type gcc hello.c and press enter to compile your code.
- If there are no errors in your code, the command prompt will take you to the next line and would generate a.out executable file.
- Now, type a.out to execute your program.
- You will see the output "Hello World" printed on the screen.
$ gcc hello.c
$ ./a.out
Hello, World!
Make sure the gcc compiler is in your path and that you are running it in the directory containing the source file hello.c.
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language is rich in built-in operators and provides the following types of operators −
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Misc Operators
We will, in this chapter, look into the way each operator works.
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume variable A holds 10 and variable B holds 20 then −
Operator | Description | Example |
+ | Adds two operands. | A + B = 30 |
− | Subtracts second operand from the first. | A − B = -10 |
* | Multiplies both operands. | A * B = 200 |
/ | Divides numerator by de-numerator. | B / A = 2 |
% | Modulus Operator and remainder of after an integer division. | B % A = 0 |
++ | Increment operator increases the integer value by one. | A++ = 11 |
-- | Decrement operator decreases the integer value by one. | A-- = 9 |
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10 and variable B holds 20 then −
Operator | Description | Example |
== | Checks if the values of two operands are equal or not. If yes, then the condition becomes true. | (A == B) is not true. |
!= | Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. | (A != B) is true. |
> | Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. | (A > B) is not true. |
< | Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. | (A < B) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. | (A >= B) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. | (A <= B) is true. |
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then −
Operator | Description | Example |
&& | Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. | (A && B) is false. |
|| | Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. | (A || B) is true. |
! | Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. | !(A && B) is true. |
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows −
p | q | p & q | p | q | p ^ q |
0 | 0 | 0 | 0 | 0 |
0 | 1 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 |
1 | 0 | 0 | 1 | 1 |
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and variable 'B' holds 13, then −
Operator | Description | Example |
& | Binary AND Operator copies a bit to the result if it exists in both operands. | (A & B) = 12, i.e., 0000 1100 |
| | Binary OR Operator copies a bit if it exists in either operand. | (A | B) = 61, i.e., 0011 1101 |
^ | Binary XOR Operator copies the bit if it is set in one operand but not both. | (A ^ B) = 49, i.e., 0011 0001 |
~ | Binary One's Complement Operator is unary and has the effect of 'flipping' bits. | (~A ) = ~(60), i.e,. -0111101 |
<< | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. | A << 2 = 240 i.e., 1111 0000 |
>> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. | A >> 2 = 15 i.e., 0000 1111 |
Assignment Operators
The following table lists the assignment operators supported by the C language −
Operator | Description | Example |
= | Simple assignment operator. Assigns values from right side operands to left side operand | C = A + B will assign the value of A + B to C |
+= | Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. | C += A is equivalent to C = C + A |
-= | Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. | C -= A is equivalent to C = C - A |
*= | Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. | C *= A is equivalent to C = C * A |
/= | Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. | C /= A is equivalent to C = C / A |
%= | Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. | C %= A is equivalent to C = C % A |
<<= | Left shift AND assignment operator. | C <<= 2 is same as C = C << 2 |
>>= | Right shift AND assignment operator. | C >>= 2 is same as C = C >> 2 |
&= | Bitwise AND assignment operator. | C &= 2 is same as C = C & 2 |
^= | Bitwise exclusive OR and assignment operator. | C ^= 2 is same as C = C ^ 2 |
|= | Bitwise inclusive OR and assignment operator. | C |= 2 is same as C = C | 2 |
Misc Operators ↦ sizeof & ternary
Besides the operators discussed above, there are a few other important operators including sizeof and ? : supported by the C Language.
Operator | Description | Example |
Sizeof() | Returns the size of a variable. | Sizeof(a), where a is integer, will return 4. |
& | Returns the address of a variable. | &a; returns the actual address of the variable. |
* | Pointer to a variable. | *a; |
? : | Conditional Expression. | If Condition is true ? then value X : otherwise value Y |
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category | Operator | Associativity |
Postfix | () [] -> . ++ - - | Left to right |
Unary | + - ! ~ ++ - - (type)* & sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | << >> | Left to right |
Relational | < <= > >= | Left to right |
Equality | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %=>>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
Operator Precedence and Associativity
Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category | Operator | Associativity |
Postfix | () [] -> . ++ - - | Left to right |
Unary | + - ! ~ ++ - - (type)* & sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | << >> | Left to right |
Relational | < <= > >= | Left to right |
Equality | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %=>>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
Example Code
#include <stdio.h>
Main() {
Int a = 20;
Int b = 10;
Int c = 15;
Int d = 5;
Int e;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
Printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
Printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = (a + b) * (c / d); // (30) * (15/5)
Printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a + (b * c) / d; // 20 + (150/5)
Printf("Value of a + (b * c) / d is : %d\n" , e );
Return 0;
}
Output
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition.
C has a wide range of operators to perform various operations.
C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables).
Operator | Meaning of Operator |
+ | Addition or unary plus |
- | Subtraction or unary minus |
* | Multiplication |
/ | Division |
% | Remainder after division (modulo division) |
Example 1: Arithmetic Operators
// Working of arithmetic operators
Int main()
{
Int a = 9,b = 4, c;
c = a+b;
Printf("a+b = %d \n",c);
c = a-b;
Printf("a-b = %d \n",c);
c = a*b;
Printf("a*b = %d \n",c);
c = a/b;
Printf("a/b = %d \n",c);
c = a%b;
Printf("Remainder when a divided by b = %d \n",c);
Return 0;
}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
The operators +, - and * computes addition, subtraction, and multiplication respectively as you might have expected.
In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.
It is because both the variables a and b are integers. Hence, the output is also an integer. The compiler neglects the term after the decimal point and shows answer 2 instead of 2.25.
The modulo operator % computes the remainder. When a=9 is divided by b=4, the remainder is 1. The % operator can only be used with integers.
Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,
// Either one of the operands is a floating-point number
a/b = 2.5
a/d = 2.5
c/b = 2.5
// Both operands are integers
c/d = 2
C Increment and Decrement Operators
C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.
Example 2: Increment and Decrement Operators
// Working of increment and decrement operators
Int main()
{
Int a = 10, b = 100;
Float c = 10.5, d = 100.5;
Printf("++a = %d \n", ++a);
Printf("--b = %d \n", --b);
Printf("++c = %f \n", ++c);
Printf("--d = %f \n", --d);
Return 0;
}
Output
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000
Here, the operators ++ and -- are used as prefixes. These two operators can also be used as postfixes like a++ and a--.
C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most common assignment operator is =
Operator | Example | Same as |
= | a = b | a = b |
+= | a += b | a = a+b |
-= | a -= b | a = a-b |
*= | a *= b | a = a*b |
/= | a /= b | a = a/b |
%= | a %= b | a = a%b |
Example 3: Assignment Operators
// Working of assignment operators
Int main()
{
Int a = 5, c;
c = a; // c is 5
Printf("c = %d\n", c);
c += a; // c is 10
Printf("c = %d\n", c);
c -= a; // c is 5
Printf("c = %d\n", c);
c *= a; // c is 25
Printf("c = %d\n", c);
c /= a; // c is 5
Printf("c = %d\n", c);
c %= a; // c = 0
Printf("c = %d\n", c);
Return 0;
}
Output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
C Relational Operators
A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.
Operator | Meaning of Operator | Example |
== | Equal to | 5 == 3 is evaluated to 0 |
> | Greater than | 5 > 3 is evaluated to 1 |
< | Less than | 5 < 3 is evaluated to 0 |
!= | Not equal to | 5 != 3 is evaluated to 1 |
>= | Greater than or equal to | 5 >= 3 is evaluated to 1 |
<= | Less than or equal to | 5 <= 3 is evaluated to 0 |
Example 4: Relational Operators
// Working of relational operators
Int main()
{
Int a = 5, b = 5, c = 10;
Printf("%d == %d is %d \n", a, b, a == b);
Printf("%d == %d is %d \n", a, c, a == c);
Printf("%d > %d is %d \n", a, b, a > b);
Printf("%d > %d is %d \n", a, c, a > c);
Printf("%d < %d is %d \n", a, b, a < b);
Printf("%d < %d is %d \n", a, c, a < c);
Printf("%d != %d is %d \n", a, b, a != b);
Printf("%d != %d is %d \n", a, c, a != c);
Printf("%d >= %d is %d \n", a, b, a >= b);
Printf("%d >= %d is %d \n", a, c, a >= c);
Printf("%d <= %d is %d \n", a, b, a <= b);
Printf("%d <= %d is %d \n", a, c, a <= c);
Return 0;
}
Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
C Logical Operators
An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming.
Operator | Meaning | Example |
&& | Logical AND. True only if all operands are true | If c = 5 and d = 2 then, expression ((c==5) && (d>5)) equals to 0. |
|| | Logical OR. True only if either one operand is true | If c = 5 and d = 2 then, expression ((c==5) || (d>5)) equals to 1. |
! | Logical NOT. True only if the operand is 0 | If c = 5 then, expression !(c==5) equals to 0. |
Example 5: Logical Operators
// Working of logical operators
Int main()
{
Int a = 5, b = 5, c = 10, result;
Result = (a == b) && (c > b);
Printf("(a == b) && (c > b) is %d \n", result);
Result = (a == b) && (c < b);
Printf("(a == b) && (c < b) is %d \n", result);
Result = (a == b) || (c < b);
Printf("(a == b) || (c < b) is %d \n", result);
Result = (a != b) || (c < b);
Printf("(a != b) || (c < b) is %d \n", result);
Result = !(a != b);
Printf("!(a != b) is %d \n", result);
Result = !(a == b);
Printf("!(a == b) is %d \n", result);
Return 0;
}
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
Explanation of logical operator program
- (a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1 (true).
- (a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
- (a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
- (a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false).
- !(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true).
- !(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).
C Bitwise Operators
During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-level which makes processing faster and saves power.
Bitwise operators are used in C programming to perform bit-level operations.
Operators | Meaning of operators |
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise exclusive OR |
~ | Bitwise complement |
<< | Shift left |
>> | Shift right |
Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
Int a, c = 5, d;
The sizeof operator
The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).
Example 6: sizeof Operator
Int main()
{
Int a;
Float b;
Double c;
Char d;
Printf("Size of int=%lu bytes\n",sizeof(a));
Printf("Size of float=%lu bytes\n",sizeof(b));
Printf("Size of double=%lu bytes\n",sizeof(c));
Printf("Size of char=%lu byte\n",sizeof(d));
Return 0;
}
Output
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
What is Typecasting in C?
Typecasting is converting one data type into another one. It is also called as data conversion or type conversion. It is one of the important concepts introduced in 'C' programming.
'C' programming provides two types of type casting operations:
- Implicit type casting
- Explicit type casting
Implicit type casting
Implicit type casting means conversion of data types without losing its original meaning. This type of typecasting is essential when you want to change data types without changing the significance of the values stored inside the variable.
Implicit type conversion happens automatically when a value is copied to its compatible data type. During conversion, strict rules for type conversion are applied. If the operands are of two different data types, then an operand having lower data type is automatically converted into a higher data type. This type of type conversion can be seen in the following example.
#include<stdio.h>
Int main(){
Short a=10; //initializing variable of short data type
Int b; //declaring int variable
b=a; //implicit type casting
Printf("%d\n",a);
Printf("%d\n",b);
}
Output
10
10
- In the given example, we have declared a variable of short data type with value initialized as 10.
- On the second line, we have declared a variable of an int data type.
- On the third line, we have assigned the value of variable s to the variable a. On third line implicit type conversion is performed as the value from variable s which is of short data type is copied into the variable a which is of an int data type.
Converting Character to Int
Consider the example of adding a character decoded in ASCII with an integer:
#include <stdio.h>
Main() {
Int number = 1;
Char character = 'k'; /*ASCII value is 107 */
Int sum;
Sum = number + character;
Printf("Value of sum : %d\n", sum );
}
Output:
Value of sum : 108
Here, compiler has done an integer promotion by converting the value of 'k' to ASCII before performing the actual addition operation.
Arithmetic Conversion Hierarchy
The compiler first proceeds with promoting a character to an integer. If the operands still have different data types, then they are converted to the highest data type that appears in the following hierarchy chart:
Consider the following example to understand the concept:
#include <stdio.h>
Main() {
Int num = 13;
Char c = 'k'; /* ASCII value is 107 */
Float sum;
Sum = num + c;
Printf("sum = %f\n", sum );}
Output:
Sum = 120.000000
First of all, the c variable gets converted to integer, but the compiler converts num and c into "float" and adds them to produce a 'float' result.
Important Points about Implicit Conversions
- Implicit type of type conversion is also called as standard type conversion. We do not require any keyword or special statements in implicit type casting.
- Converting from smaller data type into larger data type is also called as type promotion. In the above example, we can also say that the value of s is promoted to type integer.
- The implicit type conversion always happens with the compatible data types.
We cannot perform implicit type casting on the data types which are not compatible with each other such as:
- Converting float to an int will truncate the fraction part hence losing the meaning of the value.
- Converting double to float will round up the digits.
- Converting long int to int will cause dropping of excess high order bits.
In all the above cases, when we convert the data types, the value will lose its meaning. Generally, the loss of meaning of the value is warned by the compiler.
'C' programming provides another way of typecasting which is explicit type casting.
Explicit type casting
In implicit type conversion, the data type is converted automatically. There are some scenarios in which we may have to force type conversion. Suppose we have a variable div that stores the division of two operands which are declared as an int data type.
Int result, var1=10, var2=3;
Result=var1/var2;
In this case, after the division performed on variables var1 and var2 the result stored in the variable "result" will be in an integer format. Whenever this happens, the value stored in the variable "result" loses its meaning because it does not consider the fraction part which is normally obtained in the division of two numbers.
To force the type conversion in such situations, we use explicit type casting.
It requires a type casting operator. The general syntax for type casting operations is as follows:
(type-name) expression
Here,
- The type name is the standard 'C' language data type.
- An expression can be a constant, a variable or an actual expression.
Let us write a program to demonstrate implementation of explicit type-casting in 'C'.
#include<stdio.h>
Int main()
{
Float a = 1.2;
//int b = a; //Compiler will throw an error for this
Int b = (int)a + 1;
Printf("Value of a is %f\n", a);
Printf("Value of b is %d\n",b);
Return 0;
}
Output:
Value of a is 1.200000
Value of b is 2
- We have initialized a variable 'a' of type float.
- Next, we have another variable 'b' of integer data type. Since the variable 'a' and 'b' are of different data types, 'C' won't allow the use of such expression and it will raise an error. In some versions of 'C,' the expression will be evaluated but the result will not be desired.
- To avoid such situations, we have typecast the variable 'a' of type float. By using explicit type casting methods, we have successfully converted float into data type integer.
- We have printed value of 'a' which is still a float
- After typecasting, the result will always be an integer 'b.'
In this way, we can implement explicit type casting in 'C' programming.
Summary
- Typecasting is also called as type conversion
- It means converting one data type into another.
- Converting smaller data type into a larger one is also called as type promotion.
- 'C' provides an implicit and explicit way of type conversion.
- Implicit type conversion operates automatically when the compatible data type is found.
- Explicit type conversion requires a type casting operator.
Keep in mind the following rules for programming practice when dealing with different data type to prevent from data loss :
- Integers types should be converted to float.
- Float types should be converted to double.
- Character types should be converted to integer.
Type coercion
Type coercion is the automatic conversion of a datum from one data type to another within an expression. Coercion occurs because the datum is stored as one data type but its context requires a different data type.
Text Books:
1. Programming with C-Gottfried-Schaums Outline Series-TMH
2. C Programming – Anitha Goel/Ajay Mittal/E.Sreenivasa Reddy-Pearson India
References:
1. Problem Solving with C- Somasekharan-PHI.
2. C Programming- Behrouz A forouzan – CENGAGE Learning
3. Test your c skills-Yaswanth kanithker
4. Let us C- Yaswanth kanithker