ProgramminginC_I

 UNIT-1

Computer Fundamentals

Introduction of Computers:

The term computer is derived from the Latin word compute, which means to calculate. A Computer is an electronic device that processes data and converts it into information that is useful to people.

A computer is a data processor. It can accept input [data + instructions]. The computer stores the input in memory cells. It then processes the stored input. It gives out the result as output information.

The computer accepts input and outputs data in an alphanumeric form. Internally it converts the input data [English] to meaningful binary digits [Machine Language], performs the given operations and transforms the data from binary format to English.

Classification of Computers

Based on their configuration, Computers can be classified into 4 types:

1. Super Computers

2. Mainframe Computers

3. Mini Computers

4. Micro Computers

Super-computers:

Super-computers are very fast and powerful machines. They are very large in size. They can perform quadrillions of calculations per second. They are very Expensive. Super Computers can be used in weather forecasting, nuclear energy research, etc.

Example:

1. CRAY super computer [ USA]

2 .Sunway TaihuLight [China]

3. Aaditya

4. Param Yuva-II [ INDIA]

Mainframe computers:

A mainframe computer supports a vast number of users. It can process large amounts of data at very high speeds. These computers are very large in size, and expensive.

The main difference between a supercomputer and a mainframe is that:

A supercomputer can execute a single program faster than a mainframe. A Mainframe uses its power to execute many programs concurrently.

Example: The IBM 370 and IBM 3090.

Minicomputers 

A minicomputer can be used by multiple users (between10 to 100). It is smaller in size. They are less expensive. Minicomputers are used for scientific and engineering tasks. They are also used as small servers.

Example: The IBM AS/400.

Microcomputers:

The microcomputer can be used by a single user at a time. It contains a microprocessor chip, a memory system, interface units and I/O units, etc.

There are many types of microcomputers:

Desktop computer: It is a microcomputer that can fit on a desk.

Laptop computer: It is a microcomputer that can fit on your lap.

Palmtop computer/PDAs: It is a hand-sized microcomputer. Its screen serves both as an input and output device.

Anatomy of a Computer

A computer system can be divided into two components:

I. Hardware

II. Software

Hardware: The physical components of a computer is known as the Hardware. It includes:

· Input and output devices

· Central processing unit (CPU)

· Memory unit and storage devices

· Interface unit

Input Devices

The devices, which are used to enter the data and instructions into the computer are known as the input devices. The most common input devices are:

Keyboard: A Keyboard is like a type-writer. Normally it contains of 104 keys. Keyboard follows QWERTY layout. It includes Character keys, Function keys, Control keys, Navigation keys, Toggle keys, miscellaneous keys, etc.

Mouse A mouse is the pointing device. It is used to move the cursor around the screen and to point to an object. It has two or three buttons for clicking. It tracks the motion of the mouse pointer. It senses the clicks and sends them to the computer. So that it can respond appropriately.

Scanner A scanner is a device that scans pictures or documents. So that we can store them, seen, modify and print on a printer.

Output devices

The devices, which can show or display the output/ result information are known as the output devices. It includes

Monitor: Computer display devices are known as a monitor or Visual Display Unit (VDU). Monitor of different sizes and technology. CRT (Cathode-ray tube) and LCD (liquid crystal display) monitors are the two common types of Monitors.

Printer The printer is a device that prints any data, report, document, etc. Printers can produce hard copies of the data. They are of 2 types: An impact printer: It is a printer in which the print head will be in physical contact with the paper. 

Example: Dot matrix printer.

A non–impact printer: It is a printer in which the print head does not have any physical contact with the paper. 

Example: Laser printer.

Central processing unit (CPU)

Central Processing Unit (CPU) acts as the brain of the computer. It contains the following functional units:

Registers These are high-speed storage devices. The Instruction Register (IR) holds the current instructions. The Program Counter (PC) holds the address of the next instruction. It also contains a set of general-purpose registers for temporary storage of data values.

Arithmetic logic unit (ALU): It can perform arithmetic operations, such as addition and subtraction and the logical operations, such as comparing two numbers.

Control unit (CU) The control unit coordinates all the devices. It controls the transfer of data and instructions between main memory and the registers in the CPU.

Memory Unit

An electronic storage area of a computer is known as Memory. It is mainly of two types:

primary memory and the secondary memory.

Primary memory 

Primary memory stores the currently executing data and. Primary memory is also  known as main memory. This memory is accessed directly by the processor. It includes RAM, Cache memory.

Secondary Memory 

Secondary memory provides large storage. It is permanent memory and inexpensive. It is slower than primary memory. It is also known as auxiliary memory. It includes Storage devices such as hard disks, floppy disks, CDROMs, and magnetic tapes.

Unit of memory

The unit of memory is a byte. The memory’s capacity is expressed in number of bytes. The following are some units used to express the memory capacity:

· Kilobyte (KB) = 1024 bytes

· Megabyte (MB) = 1024 Kilobytes

· Gigabyte (GB) = 1024 Megabytes

· Terabyte (TB) = 1024 Gigabytes

· Petabyte (PB) = 1024 Terabytes

· Exabyte (EB) = 1024 Petabytes

· Zettabyte (ZB) = 1024 Exabytes

· Yottabyte (YB) = 1024 Zettabytes

Memory hierarchy

A computer system uses various types of memory. These memory differ in speed, cost, size, and volatility. They can be organized in a hierarchy, as shown below:

It shows that from top to bottom, the speed decreases but the capacity increases and the prices become much lower. The registers, Cache, RAM are volatile but the secondary memory are non-volatile.

Interface unit

A set of parallel lines that interconnects the CPU with memory and I/O devices are known as the interface unit.

It can be classified into three types:

Data bus: It can carry the actual data.

Address bus memory or Input/output device: It can transport the Addresses.

Control bus: It can carry the control information between the CPU and other devices.

The following figure shows an interface unit:

Motherboard It is an electronic circuit board. It holds all the components in the computer system. The motherboard provides physical connections among them. It consists of the following:

§ CPU Socket: It holds the central processor.

§ Memory Sockets: These sockets hold the RAM.

§ Interface module: It is for the hard disk, floppy disk, and CD-ROM drives.

§ ROM integrated chip: It contains the BIOS programs.

§ Ports and expansion slots: It is used to connect a device with the bus.

§ PCI slots: It connects the I/O devices.

§ Advanced graphics port (AGP): It holds the Video card.

§ Parallel port: It is used as the printer port, or LPT1.

§ Serial ports: These are used as communication ports or COM ports.

§ USB (universal serial bus): This is a serial port. USB can connect the devices, such as mouse, keyboards, hard disk drives, pendrives, cameras, modems and printers.

§ CMOS: The CMOS stands for Complementary Metal Oxide semiconductor memory. It is a type of RAM that stores information about the size of the hard disk, the amount of RAM, etc.

System unit

The System Unit holds all the system components in it. It is sometimes called cabinet. It holds the main components like motherboard, hard disk, SMPS, etc.

Cabinets are of two types.

i) AT cabinets (or mini-tower)

ii) ATX cabinets

· AT cabinets are smaller and cheaper. They are popularly called mini-tower cabinets. They are used for older processors and smaller motherboards.

· ATX cabinets are larger in size than AT cabinets. They are more expensive and have more features.

Software

Software provides the instructions that tell the hardware what to do. 

A set of instructions is known as a Program. A set of related programs are known as a software. It can provide desired functions and performance.

Comparison between computer program and software 

Program 

  • A single developer is involved.
  • Small in size  
  • Have limited functionality
  • The user interface may not be very important.

Software

  • A large number of developers are involved.
  • Extremely large in size
  • Have enormous functionality.
  • User interface must be carefully designed for the users

Software is generally 2 types: 

System software

Application software.

System software

System software is designed to run the computer. The software such as language translator, operating system, loader, linker, etc are the system software.

Application software

Application software is designed to perform specific tasks of the users. Microsoft Word, Microsoft Excel, Microsoft Power Point, Microsoft Access, etc. are some of the examples of application software.

Application software is of 2 types: 

custom software and pre-written software packages.

Custom Software:

Software that is developed for a specific user is known as custom software.

A pre-written software package 

It is a software that is developed for general needs of all the users.

The most important software are :

§ Database management software, e.g.

Oracle, DB2, Microsoft SQL server, etc.

§ Spreadsheet software, e.g. Microsoft Excel.

§ Word processing, e.g. Microsoft Word,Corel Wordperfect

§ Desktop publishing (DTP), e.g. Pagemaker.

§ Graphics software, e.g. Corel Draw.

§ Statistical, e.g. SPSS,Tora.

Memory

RAM:

RAM stands for Random Access Memory. Any location in a RAM can be accessed directly. RAM is volatile in nature. Its contents can be erased when the power is off. So that it is also known as Temporary Memory. They are limited in size.

TYPES OF RAM:

There are two types of RAM. Dynamic RAM and Static RAM.

Dynamic RAM (DRAM): 

It refreshes its data after every few milliseconds. It has higher storage capacity and is cheaper than Static RAM.

It does not require refreshing.

It is more expensive 

It is lower in bit density

It is faster than dynamic RAM.

Static RAM (SRAM): 

It need not be refreshed. It remains stable as long as power is supplied to it.

SRAM is costlier but has higher speed than DRAM.

It requires‘‘refresheing’’

It is less expensive

It holds more bits of storage

It is slower than SRAM.

Cache Memory

It is a high-speed memory. It stores the data currently in use by the processor. It acts as a high speed buffer between CPU and main memory. It increases the processing speed. The cache memory is very expensive and is limited in capacity.

There are two levels of cache:

Level 1 (Primary) cache

This type of cache memory is placed on the processor itself. This cache is very fast and its size varies generally from 8 KB to 64 KB.

Level 2 (Secondary) cache 

It is slower than L1 cache.

It is usually 64 KB to 2 MB in size. Level 2 cache is also called external cache.

ROM

ROM stand for Read Only Memory. ROM is used in personal computers for storing start-up instructions. It is used for BIOS test or POST. ROMs can be written only at the time of manufacture.

PROM:

A Programmable ROM (PROM), is also non-volatile and can be programmed only once.

EPROM: 

Erasable Programmable Read Only

Memories can be written electrically. Its data can be erased by using ultraviolet light.

EEPROM: 

Electrically Erasable Programmable Read Only Memory (EEPROM can be written onto by electrical signals. Its data can be erased by electrical signals.

Secondary Memory

There are four main types of secondary storage devices:

· Disk drives

· CD drives (CD-R, CD-RW, and DVD)

· Tape drives

· USB flash drives

Floppy Disk:

The floppy disk is a thin, round piece of plastic material, coated with a magnetic medium. The floppy disk is enclosed by a plastic shell. Its size is 3½ inches and can store 1.44 MB of data.

Hard Disk:

A hard disk is a permanent memory device found inside the system unit. A hard disk consists of metal platters. Each platter is divided into tracks and sectors. Read/write heads are used to read/write the data. The storage capacity of a hard disk is very large and expressed in terms of gigabytes (GB). It stores the data permanently.

CD’s

A CD is a portable secondary storage medium. Various types of CDs are available: CD-R and CD-RW. Once created Data stored on CD-R (CD Recordable) disc can’t be changed. A CD Rewritable (CD-RW) disc can be erased and reused.  CD-RW drives are used to create and read both CD-R and CD-RW discs.

Tape drive

A tape drive is a data storage device that reads and writes data on a magnetic tape. Magnetic tapes are generally used for backup. Magnetic tapes are cheap but has a long stability.

USB Flash drive:

It is a small, portable flash memory card. It can be plugged into a computers USB port. It is easy to carry and more durable. Because it cannot contain any internal moving parts. It is also are called pen drive.


Operating System

An operating system is a system software that acts as

an intermediary between the user and the Hardware.

Mac, MS Windows, Linux, Solaris, Android etc are

some of the operating systems.

The common functions of an operating system:

§ Process(or) management

A process is a program in execution. The operating

system decides which process to run. It also assigns

priority to the processes.

§ Memory management Operating system is

responsible to allocate and de-allocate

memory.

§ Device management The operating system

controls accesses to the I/O devices among the

processes.

§ File management: The file system in an

operating system allows users to create,

delete, modify, open, close, and apply other

operations to various types of files.

Booting

Booting is the initial set of operations that the

computer performs when it is switched on.

When a computer is switched on, it performs

BIOS/POST and loads the Operating system files into

memory.

Booting is of 2 types:

Cold booting: The process of starting the computer

and loading its operating system by turning the power

on.

Warm booting: The process of restarting the

computer and loading its operating system again is

known as warm booting.

Operational overview of a CPU

The processing required for a single instruction is

called an instruction cycle. The CPU performs four

steps for each instruction: fetch, decode, execute, and

store.

· First, the instruction is fetched from main

memory and loaded into Instruction

Register (IR), Its address is specified by PC

register.

· Then it increments the PC to the next

instruction in the program.

· In IR, the instruction is decoded to

determine the actions needed for its

execution.

· The control unit enables execution of the

instruction.

· The result of the instruction is stored

(written) to either a register or a memory

location.

· The next instruction of a program will

follow the same steps.

· This will continue until there is no more

instruction in the program or the computer

is turned off.

Generation and Classification of Programming

Languages:

A programming language is an artificial

formalism in which algorithms can be expressed. It

is the communication bridge between a

programmer and computer. It is useful to create

programs that the computer can understand.

The programming languages are broadly classified

into 5 generations:

First Generation Language:

Computer is an electronic machine. It knows only

machine (electronic) codes.

ON and OFF are known as the Machine codes.

ON can be indicated with 1 and OFF can be indicated

with 0.

A language which contains only 1’s and 0’s in it is

known as Machine Language. It is also known as the

First Generation Language(1GL).

A Machine language is directly understood by the

computer. It has the following format:

Example:

Second Generation Language:

The Language that use mnemonics for computer

operations and memory locations is known as

Assembly language. It was created in early 1950’s. It

is known as the Second Generation Language (2GL).

Assembly language uses an Assembler. An

Assembler is a translator. It translates the assembly

language instructions into machine understandable

form.

Example:

Third Generation Language:

The language that contains English like statements

and mathematical symbols is known

as a High Level Language. It is known as the Third

Generation Language (3GL).

Example:

There are many high level languages like

FORTRAN, ALGOL, COBOL, C, C++, JAVA,

C#, etc.

High level languages uses different types of

translators to convert the instructions into machine

understandable form.

For example: C language uses a Compiler.

Fourth Generation Language:

Fourth Generation Languages are more English like

languages. They are especially useful for accessing

the databases. 4GL’S can reduce programming

effort and time to coding.

SQL, SAS, COGNOS, PHP, etc. are some

examples of 4GL’s.

Fifth Generation Language:

The software that automatically generate 3GL code

based on the arrangement of the graphical symbols

or icons [by the programmer] is known as a Fifth

Generation Language. These are the natural

languages.

CASE tools are the examples of Fifth generation

languages.

Classification of Programming Languages:

Programming languages can be classified into lowlevel

or high-level languages. Both assembly

language and machine language are considered as

low-level languages. Low-level languages are the

native language of the computer.

Based on the programming paradigm, the High level

languages are of three types:

1. Procedural languages

2. Non-procedural languages

3. Problem oriented languages.

1. Procedural programming languages:

In procedural programming, each program can be

divided into small procedures (subroutines or

functions). This style is easier for programmers.

There are mainly three types:

· Algorithmic languages: In this style, the

programmer must specify the steps, which the

computer has to follow. It uses top-down

approach. Languages like C, COBOL,

PASCAL and FORTRAN fall into this

category.

[Top-down approach: It is a technique of

programming that first defines the overall outlines of

the program and then fills in the details.]

· Object Oriented languages: Object-oriented

programming depends on software objects.

Data and associated operations are combined

into objects. This approach provides reuse of

code and design. C++, JAVA, SMALLTALK,

etc. are some examples of object-oriented

languages

· Scripting languages:

A scripting language is a language that is

designed for integrating and

communicating with other languages.

UNIX shell is one of the earliest scripting

languages. Some of the most widely used

scripting languages are JavaScript,

VBScript, PHP, Perl, Python, Ruby, ASP.

These languages are the interpreted

languages.

2. Non-procedural languages:

These are the functional languages. A

functional language program consists of

built-in functions with arguments. LISP,

ML, Scheme, etc. are examples of

functional languages.

3. Problem-oriented languages:

These languages provide pre-programmed

functions. The user need to write those

functions. MATLAB is an example of this

category. MATLAB is very popular

language among scientists and engineers.

***

Translator, Loader, Linker

· A Translator is a program that translates

the source program into machine

understandable form.

· A Linker is a program that combines the

machine language program with other

programs in the library.

· A Loader is a program that loads the

executable program’s from secondary

memory into primary memory and prepares

them for execution and starts the execution.

Compilers – Interpreters

There are two ways to translate a program from high

level language into the machine language. They are:

COMPILING and INTERPRETING.

Compiling: When you compile a program, the entire

program is translated into machine language before

it is executed.

· A COMPILER is a translator program that

performs Compilation.

· C and C++ languages uses Compilers for their

translation.

Interpreting: When you interpret a program, the

program is translated line by line, as it is executed.

· An Interpreter is a translator program that

performs interpretation.

· JavaScript language uses Interpreter for its

translation.

· JAVA language uses Compilers as well as

Interpreters.

Differences:

1. A Compiler takes the entire program as its

input.

2. An Interpreter takes Instruction by instruction

as its input.

3. A Compiler generates Object Code

4. An Interpreter does not generate any object

code.

5. A Compiler requires more memory

6. An Interpreter requires less memory.

***

Compiling, Linking and Loading a Program

A Compiler translates a program written in a source

language into target language. The compilation

process can be divided into the following phases:

1. Lexical Analysis

2. Syntax Analysis

3. Semantic Analysis

4. Intermediate code generation

5. Code Generation

1. Lexical analysis:

In this phase, the source program is scanned

for lexical units (identifiers, operators, etc.).

It creates a table called symbol table. The

Symbol Table is used to record information

about the user-defined names in the program.

2. Syntax analysis: In this phase, tokens are

combined into expressions or statements.

This process is known as parsing. This

parsing process can produce a Parse Tree.

Syntax rules can be described by using a

technique called as BNF (Backus Naur

Form) grammar.

3. Semantic analysis: The semantic analysis

phase further analyses the parsed

statements.

4. Intermediate code generation and

optimization: Many compilers produce an

intermediate form of code for optimization.

The intermediate code may be is in

assembly language.Developing a Program

There are seven important steps in developing a

program:

1. Definition

2. Design

3. Coding

4. Testing

5. Documentation

6. Implementation

7. Maintenance.

1. Definition: This is the first step in developing

a program. The definition must include the

needed output, the available input, and etc.

2. Design: This is the second step in developing

a program. It should design the problem

solution (algorithm).

3. Coding: This is the third step in developing a

program. It writes the program instructions in

a programing language. The instructions must

follow the syntax.

4. Testing: This is the fourth step in developing

a problem. It tests the program for the errors.

Errors in a program are called bugs. The

process of finding the bugs and correcting

them is called Debugging.

5. Documentation: This is the fifth step in

developing a program. It completes the

documentation of the program.

Documentation is extremely important.

Documentation should contain user

instructions, an explanation of the logic of the

program, and expected I/O.

6. Implementation: This is the sixth step in

developing a program. After completing the

program, it needs to be installed on a

computer.

7. Maintenance: A completed program requires

attention. It needs to be maintained and

evaluated for possible changes.

***

Software Development

Software development is more than programming.

It involves a large number of people. Programming

is one of the activities in software development. A

software is built according to client’s requirements.

It is driven by cost, schedule and quality. That is,

software should be developed at reasonable cost,

handed over in reasonable time.

Software development involves the following

steps:

1.Feasibility study:

Feasibility study is an assessment of the proposed

project. It verifies the feasibility of the software

development. Feasibility study is of three types:

· Economic feasibility

· Technical feasibility

· Operational feasibility

Economic feasibility: It verifies whether the

development of new software will be financially

beneficial or not.

Technical feasibility: It verifies various factors

such as the performance of the technologies, their

interoperability with other technologies, etc.

Operational feasibility: It verifies the (a) Type of

tools needed (b) Skills required (c) Documentation

d) other support required for operating the software.

2. Requirement analysis:

In this phase, the requirements related to the

software are understood. This is an important step

in developing software. If the requirements of the

user are not properly understood, then the

developing software becomes a failure.

3. Design:

The Design phase creates the architecture and

design of the new software. It has two stages:

· System design

· Detailed software design.

System design: It designs the overall system

architecture. It prepares an abstract

representation of that system.

· Detailed design: It designs the software

system functions. It prepares the specification

of the software to be written.

4. Implementation:

In this phase, the code of the new software is

developed. The programmers in the software

development team use development tools for this

purpose.

5. Testing:

The Testing phase detects errors in the new software

and rectify those errors. The testing phase performs

verification and validation.

· Verification is the process of checking the

software based on some specifications.

· Validation involves testing the product to

verify whether it meets the user requirements.

6. Deployment:

The newly developed software need to be installed in

its target environment. It hand overs the software

documentation to the users. It also gives training to

the users.

7. Maintenance:

In this phase, developed software becomes

operational. It requires a continuous support.

Algorithms

To solve any problem a plan is needed. An algorithm

is a part of the plan for the computer program.

What is an Algorithm?

Computer scientist Niklaus Wirth stated that:

Program = Algorithms + Data.

An algorithm is ‘an effective procedure for solving a

problem in a finite number of steps’.

“Effective” means that an answer is found and it has

a finite number of steps. A well-designed algorithm

should give an answer and also it must be terminated.

Definition:

An Algorithm is a finite set of instructions for

solving a problem.

Different Ways of Stating Algorithms:

Algorithms can be represented in four ways:

1. Step-form

2. Pseudo-code

3. Flowchart

4. Nassi-Schneiderman

Step-form representation:

· The step-form uses normal language.

· It states the algorithm with written

statements.

· Every statement is logically related to the

preceding statement.

· Each statement solves a part of the problem

and all the statements together complete the

solution.

Example:

Write an algorithm for finding the sum of any two

numbers.

Step 1. START

Step 2. PRINT “ENTER TWO NUMBERS”

Step 3. INPUT A, B

Step 4. C ßA + B

Step 5. PRINT C

Step 6. STOP

Pseudo-code

· It is a written form representation of the

algorithm.

· It is in the human language.

· It uses a limited vocabulary to define its

actions.

Example:

If student's grade is greater than or equal to 60

Print "passed"

else

Print "failed"

Endif

Flowchart and Nassi-Schneiderman

· These are a graphical representation of the

algorithm.

· They use symbols and language to

represent sequence, decision, and

repetition actions.

Example:

Draw a flowchart to find largest of three

numbers?

Solution:

Strategy for Designing Algorithms

The strategy for designing algorithms involves 3

steps:

1. Investigation step

2. Top-Down development step

3. Step-wise refinement

Investigation step:

The investigation phase determines the requirements

for the problem solution. Here you need to:

I. Identify the outputs.

II. Identify the input variables.

III. Identify the decisions and conditions.

IV. Identify the processes.

V. Identify the environment.

Top–down development:

It plans the solution by breaking it into smaller

modules.

· Devise the overall problem solution: Divide

the problem solution into small modules.

· Verify the feasibility of solution: Check that

the modules together form the whole solution

to the Problem.

Stepwise refinement:

It further decomposes the modules, defines the

procedures and also verifies their correctness.

· Work out all the details for each module.

· Decompose any module into further

meaningful smaller pieces.

· Group common processes together

· Group common variables together.

· Test each small procedure for its correctness

Example:

Write an algorithm for finding the sum of any two

numbers.

Solution:

Let the two numbers be A and B and let their sum be

equal to C. Then, the desired algorithm is given as

follows:

Step 1. START

Step 2. PRINT “ENTER TWO NUMBERS”

Step 3. INPUT A, B

Step 4. C ßA + B

Step 5. PRINT C

Step 6. STOP ***

Spaghetti code

A Non-modular code is known as Spaghetti code.

It produces a disorganized computer program. It

may also contain many GOTO statements in it.

That makes the program more complex.

***

Structured programming

Structured programming is a style of programming

that includes the following characteristics:

1. Block structure:

The statements in the program must be organized

into functional groups.

2. Avoidance of jumps:

A lot of GOTO statements makes the programs

more error-prone. Structured programming uses

less number of goto statements. Therefore it is also

known as ‘GOTO less programming’.

3. Modularity: Structuring the program makes it

easier to understand.

Advantages of structured programming:

· Structured programming can develop wellorganized

codes.

· Many developers can work simultaneously

on the same program.

· It reduces complexity.

· It also saves time

· It encourages stepwise refinement.

Disadvantages of structured programming:

· Error control may be harder to manage.

· Managing modifications may also be

difficult.

· Debugging efforts can be delayed.

Overview of C

Ø C is a general purpose programming

language.

Ø C was designed by Dennis Ritchie in 1972 at

AT&T Bell labs of USA on a DEC PDP-11

that used the UNIX operating system.

Ø C is a structured programming language. The

use of goto is either prohibited or discouraged.

Ø In C, functions are the building blocks. Thus

It allows the programs to be modular.

Ø C is also known as a middle-level language

because it combines the best elements of highlevel

languages with the features of assembly

language.

Ø C code is also portable. It can run on any

computer

Ø C is well suited for system-level

programming.

Ø C has only a few keywords. For example, C89

defines only 32 keywords.

Ø C is suitable to develop almost any type of

software. It can be best suited to develop

system software and also to develop

application software.

***

Developing programs in C

There are mainly three steps in developing a program

in C:

1. Writing the C program

2. Compiling the program

3. Executing the program

Writing the program:

A C program can be written by using any text

editor (vi / edlin). Turbo C++ provides an

Integrated Development Environment for

developing a C and C++ programs. An IDE has

an environment for writing, modifying, testing, and

debugging the programs. After creating the

program (Source Code), it should be saved with file

extension “.c”.

Compiling & Linking the program:

Compiling includes pre-processing, compilation,

assembly, and linking. For compiling the C

program use the COMPILE command (or

ALT+F9) from the Turbo C++ IDE. If your

program has any errors then the COMPILER will

list out the compile time errors.

Executing the program:

After successful compilation, use the RUN

command (or Ctrl+F9) from the Turbo C++ IDE to

execute the program. If your program has any

errors then it will list out the runtime errors.

Otherwise it will display the result.

Errors

Errors in a program are called bugs. The process of

finding the bugs and correcting them is called

Debugging.

Errors are of Three types:

§ Compile errors: These are the errors

that are given by the compiler.

Compile errors prevent the program

from running.

§ Linking errors: These are the errors

that are given by the linker and ends

the program. The linker can also

detect and report errors at the time of

linking.

§ Run-time errors: These are the errors

that are given by the operating system.

***

Parts of a Simple C Program

Let us consider a simple program named first.c:

/* A Simple C Program */

#include<stdio.h>

int main(void)

{

printf(“C is Sea\n”);

return 0;

}

Let us see line by line:

1. /* A Simple C Program */

This is known as a Comment line. We can put

comments in a program. Comments will

provide information about the program and its

instructions. Comment lines starts with /* and

ends with */. The C compiler considers them

as non-executable statements.

A comment line can also begin with //. It

extends up to the next line break. So the above

statement can also be written as follows:

//A Simple C Program

2. #include<stdio.h>

This is known as Pre-Processor directive.

· In C all the lines that begin with #

are known as pre-processor

directives. A Pre-Processor is a

program that processes the

directives before the compilation

process.

· #include directive includes the

contents of a file during

compilation. Here, <stdio.h> is a

header file that contains

information about I/O functions.

3. int main(void)

A C program may contain one or more

functions. Every C program must contain a

main() function. Every C program starts its

execution at main() statement.

4. { }

This is a brace. Braces are useful to group a

set of statements. Such a group of a program

is called a block.

5. printf(“C is Sea\n”);

printf() is a ‘library function’. It is a

formatted output function. Printf() can be

used to print the given contents on the

screen.

In C, The character combination that

consists of a backslash ( \) followed by a

letter or digits is known as Escape

Sequences. The \n is an escape sequence. It

is used to print the new line character.

The following are different escape sequence characters:

Code Meaning

\a Bell

\? Question Mark

\b backspace

\r Carriage return

\t Horizontal tab

\v Vertical tab

\\ Backslash

\” Double quote

\’ Single quote

\n New Line

6. return 0;

This statement indicates that the main() function

returns a value 0 to the operating system.

The return statement is not mandatory.

7. ; (Semicolon)

In C a semicolon can be used as a statement

terminator.The semicolon is required to

indicate the compiler that the statement is

completed.

8. All program instructions/statements have to be

written in lower-case characters.

Header files

A header file is a file that has C declarations and

macro definitions. It provides the required

information for the pre-processor and compiler to

process the program.

The ISO C contains the following header files:

assert.h signal.h errno.h stddef.h

complex.h stdarg.h fenv.h stdint.h

ctype.h stdbool.h float.h stdio.h

inttypes.h stdlib.h locale.h time.h

iso646.h string.h math.h wchar.h

limits.h tgmath.h setjmp.h wctype.h

There are two ways of including files in C program:

1. #include<filename>

This method tells the preprocessor to look for

the file in the default location. This method is

used to include standard headers such as

stdio.h or stdlib.h.

2. #include “file name”

This method tells the preprocessor to look for

the file in the current directory first, then

in the predefined locations. This method is

used to include programmer created files.

***

Structure of a C Program

A C program may contain the following structure:

Preprocessor directives:

In C all the lines that begin with # are known as preprocessor

directives. A Pre-Processor is a program

that processes the directives before the compilation

process.

Global declarations:

The global declaration contain the global variables.

The variables that are available for all the functions

in the program are known as global variables.

Main program section:

All the functions in a c program can be divided

into two sections:

§ Local definition

§ Statements.

Local definitions:

Local definitions are at the beginning of the

functions. Local definitions are available within

that function only.

Statements:

Statement section consists of the executable

instructions.

C Tokens

The smallest individual units in a c program are called

tokens or lexical units. C tokens can be classified as

follows:

1. Keywords

2. Identifiers

3. Constants

4. Separators

5. Operators

Keywords

keywords are the reserved words. Keywords have a

fixed meaning. These meanings cannot be changed.

The keywords cannot be used as variable names.

ANSI C defines the following 32 keywords:

auto break case char const

continue default do double else

enum extern float for goto

if int long register return

short signed sizeof static struct

switch typedef union unsigned void

volatile while

Identifiers

Identifiers are the names given to the variables,

constants, data types, arrays, functions, structs,

unions and classes.

Identifiers has the following rules:

I. An identifier must start with an alphabet (

or underscore).

II. It may contain a sequence of letters and

digits

III. Identifiers are case sensitive. “count” is

different from “Count”.

IV. Keywords cannot be used as identifiers

IV. White spaces are not allowed.

V. An identifier may contain any number of

characters.

Some of the valid identifiers:

total_marks

number1

_count

Some of the invalid identifiers:

1number

struct

student name

C Constants

Constants are the fixed values that do not change

during the program execution. They are also known

as literals. In C, the keyword “const” can be used to

declare constants. It has the following syntax:

const datatype identifier = value;

Example: const int i = 30;

const float pi = 3.14;

Constants are of different types

1. Integer Constants

2. Real Constants

3. Character Constants

4. String Constants

1. Integer Constants

Integer constants are the whole numbers without

any fractional part. There are three types of integer

constants:

1.1. Decimal Integer Constants

The integer constants that contains a set of digits, 0

through 9 are known as Decimal integer constants

Example:

124, -121, 0, 5678

1.2. Octal Integer Constants

Integer constants that contains a set of digits from

the set 0 through 7 are known as Octal integer

constants. An Octal integer starts with 0.

Example:

010, 0123, 0, 0560

1.3. Hexadecimal Integer Constants

The integer constants that contain a set of digits 0

to 9 and A to F are known as hexadecimal integer

constatns. A hexaemcal constant starts with 0x or

0X.

Example:

Example:

0xB, 0X9d, 0X123F

2. Real Constants

The constants that have fractional parts are called real

or floating point constants. These may be represented

in fractional form or the exponent form.

Example:

0.08, -0.901, 132.03

3. Character Constants

A single character that is enclosed within single

quotes is known as a character constant.

Examples:

‘a’ , ‘S’, ‘4’

4.String constants:

A group of characters enclosed within double quotes

is known as a String constant

Example:

“Dennis Ritchie”

“Ravi”

"C 99"

***

Separators

There are some special symbols used in C.

[] () {} , ; :

Braces{}: These opening and ending curly braces

marks the start and end of a block.

Parentheses(): These special symbols are used to

indicate function calls and function parameters.

Brackets[]: Opening and closing brackets are used as

array element reference.

***

Operators

Operators are the symbols that performs some

mathematical or logical operations.

Depending on the number of operands, the operators

can be classified into:

· Unary Operators: The operators that require

only single operand are known as unary

operators.

· Binary Operators: The operators that require

two operands are known as binary operators.

· Ternary Operators: The operators that

require three operands are known as Ternary

operators.

Data types

A data type is a characteristic that defines what type

of data a variable can hold and the set of operations

that can be applied.

In C the data types are broadly classified into the

following types:

1.Primary Data types:

The standard and basic data types of C are known

as the primary data types. C has five basic data

types:

1. Char: A char type represents character data type.

It occupies 1 byte of memory. It uses the keyword

“char”. Character constants and literals can be

represented within single quotes.

2.Int: Integers are the numbers without any decimal

point (period/exponent). An int type can be

classified into three types:

· short: A short type can represent smallest

integers. It occupies 2 bytes of memory.

· int: An int data type occupies 2 bytes / 4

bytes of storage. Its range is -32,768 to

32767 or or -2,147,483,648 to

2,147,483,647.

· long: A long type can represent long

integers. It occupies 4 bytes of storage.

3. Float: The numbers with decimal point

(exponent) are known as floating point

numbers or real numbers. They can use the

keyword “float”. Float types are classified

into three types:

· float: A float type can represent 6 digits of

precision. It occupies 4 bytes of storage. Its

range is -3.4e38 to +3.4e38.

· double: A double type can represent double

precision floating point numbers. It occupies

8 bytes of storage. Its range is -1.7e308 to

+1.7e308.

· long double: A double type can represent

large range of values. It occupies 10 bytes of

storage.

4. Void type: A void type can represent

“valueless”. It specifies an empty set of

values.

Variables:

Variables are the names given to the memory

locations. Variables can store data. A variable can

change its value during the program execution.

Variables will follow the rules of identifiers.

Variables can be declared by using the following

syntax:

example: int x = 10;

float f =2.3;

C variables are of four types:

Integer Variables: The identifiers that are used to

store integer data are known as integer variables. It

uses the keyword “int”. It has the following syntax:

int id1, id2 ;

Example: int a=10, b=20;

Real/Floating Point Variables: The identifiers

that are used to store floating point data are known

as real variables. The keywords “float”, “double”,

“long double” can be used to declare real group of

variables. It has the following syntax:

float id1, id2 ;

Example: float x=5.3, y=2.4;

Character variables: The identifiers that are used

to store a single character is known as character

variables. It uses the keyword “char”. It has the

following syntax:

char id1, id2 ;

Example: char a= ‘S’, b=’M’;

Boolean variables: The variables, which are used

to store either TRUE of FALSE are known as

Boolean variables. It uses the keyword “bool”.

Example: bool counter=TRUE;

Program Statements

A statement is a syntactic construction that

performs an action. In C, Program statements can

be classified into the following types:

Declaration statements:

Declaration statements declares the variables.

They have the following general form:

data type variable_name_1,

variable_name_2, ..., variable_name_n;

Example: int a, b, c;

Variables can be declared at three basic places:

· Variables that are declared inside a

function are called local variables.

· The variables that are declared in the

definition of function parameters are called

formal parameters.

· The variables that are declared outside all

functions are called global variables

Expression statements:

Expression statement is a sequence of operators and

operands. It performs computation of a value. For

example:

x = 4; is a statement.

sum =a+b; is a statement

Compound statements:

Compound statement is a sequence of statements that

may be treated as a single statement.

Labeled statements:

A labelled statement can be used to mark any

statement. So that control may be transferred to that

statement by switch statement.

Control statements:

A control statement is a statement that determine the

‘flow of execution’ in a program. These are of 3 types:

· Selection statements:

Selection statements allow a program to select a

particular statements for execution.

Example: if..else statement

· Iteration statements:

Iteration statements are used to execute the

statements repeatedly.

Example: while, for, and do..while statements

· Jump statements:

Jump statements can cause an unconditional

jump to some other place in the program.

Example: goto statement

***

Operators

An operator is a symbol that performs the

mathematical, or logical operations. C has the

following types of operators:

Arithmetic Operators

Arithmetic operators can perform the arithmetic

operations. There are five main arithmetic

operators in ‘C’. They are:

‘+’ for additions, ‘-' for subtraction, ‘*’ for

multiplication, ‘/’ for division and ‘%’ for

remainder division.

The following table shows the arithmetic operators

in c:

The operators *, / and % have higher precedence

than + and -. Multiplication, division and remainder

operations will be carried out before addition and

subtraction.

Relational Operators:

Relational operators are symbols that are used to

test the relationship between two operands. If the

relation is true, it returns 1; if the relation is false, it

returns value 0.

C’ has six relational operators as follows:

Logical Operators

There are three logical operators in C language, they

are logical &&(and) , logical !!(or), logical !(not).

The result of a logical and operation will be true only

if both operands are true, whereas the result of a

logical or operation will be true if either operand is

true or if both operands are true.

Bitwise Operators

Bitwise operators perform manipulations of data

at bit level. Bitwise operators are not applied

to float or double.

Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise Exclusive OR

<< Left Shift

>> Right Shift

The following is the truth table of Bitwise operators:

a b a&b a|b a^b

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

The bitwise shift operators shifts the bit value. These

operators shifts the bits by the specified number of

positions.

Example:

a = 0001000

a << 2 = 0100000

a >> 2 = 0000010

These operators have lower precedence than the

arithmetic operators.

Increment and Decrement operators

The unary ‘++’ and ‘--’ operators are known as

increment and decrement operators. These

operators can increment or decrement the value of

a variable by 1.

These operators can be used in ‘prefix’ and

‘postfix’ formats:

· var++; post increment

· var-- ; // Post decrement

· ++var; // Pre increment

· --var; // Post decrement.

Difference between prefix and postfix formats:

In a prefix format, First the operand is

incremented/decremented. Second its value will be

assigned to the variable on its left.

In a postfix format, First the operand’s value will

be assigned to the variable on its left. Second the

operand is incremented/decremented.

Conditional Operator

The conditional operator has three expressions. It

takes the following form:

expression1 ? expression2 : expression3;

First, expression1 is evaluated. If it is true(1), then

expression2 will be taken as the final result.

Otherwise, expression3 is will be taken as the final

result.

For example:

int m = 1, n = 2, min;

min = (m < n ? m : n); /* min is assigned a value 1

*/

For example:

min = (m < n ? m++ : n++);

m is incremented because m++ is evaluated. But n

is not incremented because n++ is not evaluated.

Comma Operator

The comma operator allows the evaluation of

multiple expressions, separated by the comma. It

evaluates from left to right in order. It takes the

value of the rightmost expression as the final result.

It takes the following form:

expressionM = (expression1, expression2, …,

expressionN);

int i = 0;

int j;

Sizeof operator

Sizeof is a special operato. It calculates the size of any

data item. It takes a single operand that may be a type

name (e.g., int) and returns its size.

Example:

int n;

n=sizeof(char);

Assignment Operators

Assignment Operator is Used to assign value to an

variable. In C assignment Operator is denoted by

equal to sign(=). Assignment Operator is binary

operator. It operates on two operands.

It has the following format:

v=exp;

Example:

count = 9;

sum = a+b;

C Provides a short hand notation of assignment. It has

the following format:

v op=exp;

Example:

Operator

Name

Example

Equillent

expression

+= Addition

assignment

x += 4;

x = x + 4;

-= Subtraction

Assignement

x-=4 x=x-4

*= Multiplication

Assignment

x*=4 x=x*4

/= Divison

assignment

x/=4 x=x/4

%= Reminder

assignment

x%=4 x=x%4

***

Expression Evaluation–precedence and

associativity

C operators have two properties: Priority and

Associativity.

Priority determines the order in which different

operators are evaluated. Operators of higher

precedence are applied before the operators of lower

precedence.

j = (i += 1, i += 2, i + 3);

Here, j will be assigned the value 6.

Associativity determines the order in which

operators of equal priority are evaluated. It defines

the direction, L to R or right-to-left.

Rules of Operator Precedence:

C applies the following rules to its operators when

evaluating the arithmetic expressions:

1. The expressions contained within pairs of

parentheses are evaluated first. Parentheses are said

to be at the “highest level of precedence.”

2. Multiplication, division and remainder

operations are applied next.

3. Addition and subtraction operations are

evaluated next.

4. If an expression contains several same level of

operators then evaluation proceeds from left to

right.

5. The assignment operator (=) is evaluated last.

The following table shows the precedence of

operators:

Examples of expressions:

1. x = 5 * 4 + 6 * 5

= 20 + 6 * 5

= 20+30

=50

2. x= 3 * ( 5 +4 ) * 6

= 3 * 9 * 6

= 27 * 6

= 162

***

Type Conversion

The process of converting one predefined type into

another type is called type conversion.

Type conversion is two types:

Implicit Type Conversion:

A type conversion that is automatically performed by

the compiler is known as implicit type conversion or

type promotion.

It has the following rules:

· All short and char are automatically converted

to int.

· If either of the operand is of type long double,

then others will be converted to long double

and result will be long double.

· If either of the operand is double, then others

are converted to double.

· If either of the operand is float, then others

are converted to float.

Explicit Type Conversion:

A type conversion that is performed by the

programmer is known as explicit type conversion.

The explicit type conversion is also known as type

casting.

It takes the following form:

(data_type)expression;

where, data_type is any valid c data type, and

expression may be constant, variable or expression.

For example,

x=(int)a+b*d;

The following rules have to be followed while

converting the expression from one type to another

to avoid the loss of information:

· All integer types to be converted to float.

· All float types to be converted to double.

· All character types to be converted to

integer.

 

5. Code generation: This is the final phase

that converts the intermediate code into

target machine code. It also performs

linking and loading step to generate an

executable program.

 

No comments:

Post a Comment