unit – i · since the invention of the abacus, ... and it is the french mathematician and...

71
UNIT – I Syllabus: Introduction to Computers – Computer Systems, Computing Environments, Computer Languages, Creating and running programs, Program Development, algorithms and flowcharts , Number systems-Binary, Decimal, Hexadecimal and Conversions, storing integers and real numbers. Introduction to C Language – Background, C Programs, Identifiers, Types, Variables, Constants, Input / Output, Operators(Arithmetic, relational, logical, bitwise etc.), Expressions, Precedence and Associativity, Expression Evaluation, Type conversions, Statements- Selection Statements(making decisions) – if and switch statements, Repetition statements ( loops)-while, for, do-while statements, Loop examples, other statements related to looping – break, continue, goto, Simple C Program examples.

Upload: lekiet

Post on 10-Apr-2018

217 views

Category:

Documents


3 download

TRANSCRIPT

UNIT – I

Syllabus:Introduction to Computers – Computer Systems, Computing Environments, Computer Languages, Creating and running programs, Program Development, algorithms and flowcharts , Number systems-Binary, Decimal, Hexadecimal and Conversions, storing integers and real numbers. Introduction to C Language – Background, C Programs, Identifiers, Types, Variables, Constants, Input / Output, Operators(Arithmetic, relational, logical, bitwise etc.), Expressions, Precedence and Associativity, Expression Evaluation, Type conversions, Statements- Selection Statements(making decisions) – if and switch statements, Repetition statements ( loops)-while, for, do-while statements, Loop examples, other statements related to looping – break, continue, goto, Simple C Program examples.

Unit-1

INTRODUCTION

Computer systems

A Computer is an electronic device which performs operations such as accepts data as an input, store the data, manipulate or process the data and produce the result as an output.

An historical overview of computer:

The date of the use of the first computer is open to debate as it depends on how we define a computer. If we base this overview on the search for the first apparatus that was used within some form of calculation, we are taken back to at least the ancient Greeks and Romans who are said to have used the abacus to help them with additions and subtractions. However, the abacus is simply a memory support. The position of the beads merely helps the user to remember (or store) values used in the calculation.

Since the invention of the abacus, the work of the Scottish mathematician and philosopher John Napier is often viewed as a significant contribution towards the development of increasingly sophisticated calculation devices. John Napier invented the idea of logarithms and used this concept to develop a device (known

as Napier’s bones) that managed to reduce the complexity of multiplication and division into the more simple operations of addition and subtraction.

The first mechanical computing machinesThe development of the first mechanical computing machine is generally considered to be the next major step in the advancement of computing devices, and it is the French mathematician and philosopher Blaise Pascal who is credited with this invention. His calculator, also known as the Pascaline, was able to add or subtract two decimal numbers with the help of mechanical gears.

The English mathematician Charles Babbage is known for the development of his Difference Engine and the Analytical Engine. In his Difference Engine Babbage attempted to create a machine (the size of a small room!) that was able to perform calculations without having to attempt multiplication and division. Unfortunately, the project (funded by the British government) could not be completed before funding ran out. Still, plans and components of the Difference Engine have survived, and Babbage continued to explore his ideas in the development of the Analytical Engine. The Analytical Engine is the first machine that was able to receive instructions in the form of holes in paper cards (punch cards) and hence is considered as the first programmable machine. Also, theAnalytical Engine was the first machine to support conditional program execution.

A major milestone in the development of computers since the 1940s includes the development of the first desktop computers. Several (successful) attempts were made by computer companies and individuals. However, the most famous remains the development of the PC (personal computer), which was first developed by IBM in 1981

Block Diagram of Computer

Hardware: The physical components which are used to assemble computer system are known as hardware. Any computer device which we can touch including cables and wires is hardware.

Input Unit:

Computers need to receive data and instruction in order to solve any problem.

Therefore we need to input the data and instructions into the computers. The input unit consists of one or more input devices. Keyboard is the one of the most commonly used input device. Other

commonly used input devices are the mouse, floppy disk drive, magnetic tape, etc. All the input devices perform the followingfunctions.

• Accept the data and instructions from the outside world.

• Convert it to a form that the computer can understand.

• Supply the converted data to the computer system for further processing.

Storage Unit:

The storage unit of the computer holds data and instructions that are entered through the input unit, before they are processed. It preserves the intermediate and final results before these are sent to the output devices. It also saves the data for the later use. The various storage devices of a computer system are divided into two categories.

1. Primary Storage: Stores and provides very fast. This memory is generally used to hold the program being currently executed in the computer, the data being received from the input unit, the intermediate and final results of the program. The primary memory is temporary in nature. The data is lost, when the computer is switched off. In order to store the data permanently, the data has to be transferred to the secondary memory. The cost of the primary storage is more compared to the secondary storage. Therefore most computers have limited primary storage capacity.

2. Secondary Storage: Secondary storage is used like an archive. It stores several programs, documents, data bases etc. The programs that you run on the computer are first transferred to the primary memory before it is actually run. Whenever the results are saved, again they get stored in the secondary memory. The secondary memory is slower and cheaper than the primary memory. Some of the commonly used secondary memory devices are Hard disk, CD, etc.,

Output Unit:

The output unit of a computer provides the information and results of acomputation to outside world. Printers, Visual Display Unit (VDU) are the commonly used output devices. Other commonly used output devices are floppy disk drive, hard disk drive, and magnetic tape drive.

Arithmetic Logical Unit:

All calculations are performed in the Arithmetic Logic Unit (ALU) of thecomputer. It also does comparison and takes decision. The ALU can perform basic operations such as addition, subtraction, multiplication, division, etc and does logic operations viz, >, <, =, ‘etc. Whenever calculations are required, the control unit transfers the data from storage unit to ALU once the computations are done, the results are transferred to the storage unit by the control unit and then it is send to the output unit for displaying results.

Control Unit:

It controls all other units in the computer. The control unit instructs the input unit, where to store the data after receiving it from the user. It controls the flow of data and instructions from the storage unit to ALU.

It also controls the flow of results from the ALU to the storage unit. The control unit is generally referred as the central nervous system of the computer that control and synchronizes its working.

Central Processing Unit:

The control unit and ALU of the computer are together known as the Central Processing Unit (CPU). The CPU is like brain performs the following functions:

• It performs all calculations.

• It takes all decisions.

• It controls all units of the computer.

Memory Size:

All digital computers use the binary system, i.e. 0’s and 1’s. Each character or a number is represented by an 8 bit code. The set of 8 bits is called a byte. A character occupies 1 byte space. A numeric occupies 2 byte space.

Byte is the space occupied in the memory. The size of the primary storage is specified in KB (Kilobytes) or MB (Megabyte). One KB is equal to 1024 bytes and one MB is equal to 1024KB.

The size of the primary storage in a typical PC usually starts at 16MB. PCs having 32 MB, 48MB, 128 MB, 256MB memory are quite common.

Software

Software is a set of program or instructions given to the computer to carry out certain jobs or tasks. It is set of programs which actually makes the computer useful. The software can be classified into three categories

System Software: System software is responsible for managing a variety of independent hardware components, so that they can work together. Its purpose is to unburden the application software programmer from the often complex details of the particular computer being used, including such accessories as communications devices, printers, device readers, displays and keyboards, and also to partition the computer's resources such as memory and processor time in a safe and stable manner.

• Device drivers

• Operating systems

• Servers

• Utilities

• Window systems

Programming Software: Programming Software usually provides tools to assist a programmer in writing computer programs, and software using different programming languages in a more convenient way. The tools include:

• Compilers

• Debuggers

• Interpreters

• Linkers

• Text editors

Application Software:

Application software is developed to aid in any task that benefits from computation. It is a broad category, and encompasses Software ofmany kinds, including the internet browser being used to display this page. This category includes:

• Business software

• Computer Aided design

• Databases

• Educational software

• Image editing

• Industrial automation

• Mathematical software

• Medical software

• Simulation

• Telecommunications

• Video game

Computing Environments:

Computing Environment is a collection of computers / machines, software, and networks that support the processing and exchange of electronic information meant to support various types of computing solutions.

Personal computing Environment:

A personal computer (PC) is a computer whose original sales price, size, and capabilities make it useful for individuals, and intended to be operated directly by an end user, with no intervening computer operator. Personal computers generally run on Windows, Mac or some version of Linux operating system.

Time-Sharing Environment

In the time-sharing environment, all computing must be done by the central computer. The central computer the shared resources, it manage the shared data and printing. Employees in large companies often work in what is known as time- sharing environment. In the time sharing environment, many users are connected to one or more computers. These computers may be mini computers and central mainframes. In this environment the output devices, auxiliary storage devices are shared by all the users.

Client/Server Environment

Client/Server computing environment splits the computing function between a central computer and user’s computers. The users are given personal computers or work stations so that some of the computation responsibility can be moved from the central computer and assigned to the workstations. In the client/server environment the user’s micro

computers or work stations are called the client. The central computer

which may be a powerful micro computer, minicomputer or central mainframe system is known as server.

Distributed Computing Environment

A distributed computing environment provides a seamless integration of computing functions between different servers and clients. The internet provides connectivity to different servers throughout the world. This environment provides reliable, scalable and highly available network.

Decimal, Binary and Hexadecimal Number System and Conversion• Numeral Systems1. Decimal System2. Binary Numeral System3. Octal Numeral System4. Decimal Numeral System5. Hex Numeral System• These number systems refer to the number of symbols used to

represent numbers.Decimal System• In the decimal system, we use ten different symbols: 0, 1, 2, 3, 4,

5, 6, 7, 8, and 9. With these ten symbols, we can represent any quantity.

• Therefore, decimal is said to be Base Ten.• When we count in Base Ten, we count starting with zero and

going up to nine in order.• 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,• Once we reach the last symbol, we create a new placement in

front of the first and count that up.• 8, 9, 10, 11, 12, … , 19, 20, …• This continues when we run out of symbols for that placement.

So, after 99, we go to 100.• Each additional placement is an additional power of 10, as

stated above. Consider this chart.

103 102 101 100

1000 100 10 1

• This is applicable for Base 10 as well as to other bases.

• Knowing this will help you understand the other bases better.

Binary• Binary is another number system having Base Two. • In a binary number system, there are only two symbols used to

represent numbers: • 0 and 1. • When we count up from zero in binary, we run out of symbols

much more frequently.• 0, 1, …

Binary 0 1 10 11 100 101 110 111 1000

Decimal 0 1 2 3 4 5 6 7 8

• In Binary we can create a chart of 2 raised to the power of ZERO to n

26 25 24 23 22 21 20

1 0 0 1 1 0 1

64 + 0 + 0 + 8 + 4 + 0 + 1

=77 (Decimal)

• Hexadecimal• The hexadecimal system is Base Sixteen. • As its base implies:• This number system uses sixteen symbols to represent numbers. • Unlike binary and octal, hexadecimal has SIX additional symbols

that it uses beyond the conventional ones found in decimal. • But what comes after 0,1,2……, 9?

• Hexadecimal symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F.

• In a digital display, the numbers B and D are lowercase.• When counting in hexadecimal, after 9, you go directly to A. • Then, you count B, C, D, E, and F. • What after F? • After F is 10, 11,12…..,19. • After 19, the next number is 1A. • This goes on forever.

163 162 161 160

4096 256 16 1

0 1 2 3 4 5 6 7 8 9 A B C D E F

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

• Decimal equivalent of Hexadecimal 2DB7

163 162 161 160

2 D B 7

(4096*2) +(256*13) +(16*11) +(1*7)8192 +3328 +176 +7

11703

Binary Numbers

8 4 2 1HexVal

DeciVal

0 0 0 0 0 0

0 0 0 1 1 1

0 0 1 0 2 2

0 0 1 1 3 3

0 1 0 0 4 4

0 1 0 1 5 5

0 1 1 0 6 6

0 1 1 1 7 7

1 0 0 0 8 8

1 0 0 1 9 9

1 0 1 0 A 10

1 0 1 1 B 11

1 1 0 0 C 12

1 1 0 1 D 13

1 1 1 0 E 14

1 1 1 1 F 15

Storage of Integer and Real number

1 x 101 + 3 x 100 = 1310 = 11012 = 1 x 23 + 1 x 22 + 0 x 21 + 1 x 20

1 x 10 + 3 x 1 = 1310 = 11012 = 1 x 8 + 1 x 4 + 0 x 2 + 1 x 1

6 x 10-1 + 2 x 10-2 + 5 x 10-3 = 0.62510 = 0.1012 = 1 x 2-1 + 0 x 2-2 + 1 x 2-3

6 x 1/10 + 2 x 1/100 + 5 x 1/1000 = 0.62510 = 0.1012 = 1 x 1/2 + 0 x 1/4 + 1 x 1/8

• The two most common floating-point binary storage formats used by Intel processors were created for Intel and later standardized by the IEEE organization:

• Real: 32 bits1 bit for the sign, 8 bits for the exponent, and 23 bits for the mantissa.

• Long Real: 64 bits1 bit for the sign, 11 bits for the exponent, and 52 bits for the mantissa. Also called double precision.

• The Sign• The sign of a binary floating-point number is represented by a

single bit. A 1 bit indicates a negative number, and a 0 bit indicates a positive number.

• The Mantissa• Using -3.154 x 105 as an example, the sign is negative,

the mantissa is 3.154, and the exponent is 5.• Exponent is 8 bit

Software Development Life Cycle (SDLC)

SDLC stands for Software Development Life Cycle. SDLC is the process consisting of a series of planned activities to develop software.

Water Fall Model

The waterfall model is a sequential software development model in which development is seen as flowing steadily downwards (like a waterfall) through several phases. It is also referred to as a linear-sequential life cycle model. It is very simple to understand and use. In a waterfall model, each phase must be completed fully before the next phase can begin

1. Specifying and analyzing the problem statement.2. Designing

3. Coding and Implementation4. Debugging5. Testing and validating6. Documentation and maintenance

Specifying and analyzing the problem statement: The problem which has to be implemented into a program must be thoroughly understood before the program is written. Problem must be analyzed to determine the input and output requirements of the program. A problem statement is created with these specifications.

Designing: With the problem statement obtained in the previous step, various methods available for obtaining the required solution are analyzed and the best method is designed into algorithm/pseudocode/flowchart.

Coding and implementation: the actual problem is written in the required programming language with the help of information depicted in flow charts and algorithms.

Implementation: With inputs from system design, the system is first developed in small programs called units, which are integrated in the next phase.

Debugging: There is a possibility of occurrence of errors in programs. These errors must be removed to ensure proper working of programs. Hence solving the program without errors is known as debugging.Types of errors that may occur in the program are:

a) Syntactic Errors (Compilation Errors): These errors occur due to the usage of wrong syntax for the statements.b) Runtime Errors: These errors are determined at the execution time of the program.c) Logical Errors: These errors occur due to incorrect usage of the instructions in the program.

Testing: Testing is performed to check whether the program is producing correct results or not for different values according to user requirement.

Documentation and Maintenance: Documentation is the process of collecting, organizing and maintaining, in written the complete information of the program for future references. Maintenance is the process of upgrading the program according to the changing requirements.

Advantages of waterfall model:

∑ This model is simple and easy to understand and use.∑ In this model phases are processed and completed one at a time.

Phases do not overlap.∑ Waterfall model works well for smaller projects where

requirements are very well understood.

Disadvantages of waterfall model:

∑ Once an application is in the testing stage, it is very difficult to go back and change something that was not well-thought out in the concept stage.

∑ No working software is produced until late during the life cycle.∑ High amounts of risk and uncertainty.∑ Not a good model for complex and object-oriented projects.∑ Poor model for long and ongoing projects.

Algorithm

An Algorithm is a finite step-by-step procedure to solve a well-defined computational problem and achieve a required result.

We use algorithms every day. For example, a recipe for baking a cake is an algorithm, Steps to make a tea is an algorithm, etc.

In computer system, an algorithm is basically an instant of logic written in software by software developer to be effective for the intended target computer in order for the software on the target machine to do something.

Algorithms can be expressed in any language, from natural languages like English or Hindi to programming languages like C.

Example: Algorithm/pseudo code to add two numbers

Step 1: Start

Step 2: Read the two numbers in to a,b

Step 3: c=a+b

Step 4: write/print c

Step 5: Stop.

Characteristics of Algorithms:

While designing an algorithm as a solution to a given problem, we must take care of the following five important characteristics of an algorithm

Inputs:

An algorithm has zero or more inputs that are externally supplied.

Output:

An algorithm has one or more outputs.

In our simple definition of an algorithm, we stated that an algorithm is a set of instructions for solving a problem. Unless an algorithm produces some result, we can never be certain whether our solution is correct.

Definiteness:

Each steps of an algorithm must be precisely defined; the action to be carried out must be unambiguously specified.

Let us try to present the scenario of making a tea

Make a Cup of Tea

Get Milk, Sugar and Powder

Fill Kettle with Water

Wait until Kettle Boils

Put Milk, Sugar and powder

Give Cup of Tea/coffee to User

If one goes through these steps without aware of the statement of the problem. He /she could possibly feel that this is the algorithm for making coffee or something else not tea. The step1 may imply tea powder, coffee powder etc. such an ambiguity doesn’t an instruction of an algorithmic step. Thus every step should be made unambiguous. An unambiguous step is called definite instruction when that step is clearly defined.

Effectiveness:

An algorithm should be effective. This means that each of the instruction of an algorithm should be feasible. In other words, every step of an algorithm should be such that it can be carried out.

Explanation: Each operation in an algorithm must be doable, that is the operation must be something that is possible to do. Suppose you were given an algorithm for planting a garden, where the very first step instructed you to remove all rocks from the garden. This instruction may not be doable if there is a four ton rock buried just below ground level. Similarly for computer many mathematical operations such as division by zero or finding the square root of negative number are also impossible. These operations are not effective computable so they cannot be used in writing algorithm.

Finiteness:

An algorithm must terminate after a finite number of steps and further each step must be executable in finite amount of time.

Explanation: Algorithm should be composed of finite number of operations and they should complete their execution in a finite amount of time. Suppose we wanted to write an algorithm to print all integers greater than one. Our steps might look like

Print 1Print 2::While our algorithm seems to be pretty clear, we have two problems first; the algorithm must have an infinite number of steps. Because there are an infinite number of integers greater than one. Second the algorithm will run forever trying to count to infinity. These problems violate our definition that an algorithm must halt in a finite amount of time. Every algorithm must reach some operation that tells it to stop.

Flow Chart

The pictorial representation of an algorithm using some shapes and symbols is known as flow chart. (or)

The diagrammatic representation of way to solve the given problem is called flow chart.

Start or end of the program

Computational steps or processing function of a program

Input or output operation

Decision making and branching

Connector or joining of two parts of program

Off-page connector

Flow line

Display

Example Flow Char to print the sum of two numbers

Example Flow Char to print the number is even or odd

A BRIEF HISTORY OF ‘C ’:

C is a programming language. Developed by Dennis Ritchie in the early 1970’s (1972) at Bell laboratory. It shares a number of similarities with other programming languages. First we may need to clarify what a programming language is; a programming language is a language that provides a bridge between the computer and human beings. Basically there are two types of languages. They are low level languages and High level languages. A “low-level” language is one that is closer to a computer’s thinking than to a human language. A prime example would be Assembly language. A “high-level” language is one that is closer to human language. COBOL and BASIC are prime examples of high-level language. Many people consider C to be high-level languages, but actually C is both some what of a bridge between the low-level languages and high-level languages. You might think of them as mid-

level languages. Since it shares a number of similarities with other programming languages. We will take a look at those languages. Each programming language has various strengths and weaknesses. Some, like BASIC, are easy to use but are neither flexible nor powerful. Others, such as Assembly, are powerful, but difficult to use. Some languages are also written with specific purposes in mind. FORTRAN was written specifically for mathematical programming, BASIC was designed simply for teaching programming, and COBOL was designed for business applications. ‘C’ was designed as a general purpose language. It is used in business applications, telecommunications programming, artificial intelligence programming, games programming, and much more. This is one reason why the ‘C’ language is created. Another reason for creating a ‘c’ language is when Dennis Ritchie of Bell Laboratories was working on a project to develop the UNIX operating system. For this work Ritchie needed a language that was concise, that produced compact, fast programs, and that could control hardware efficiently. Traditionally, programmers met these needs by using assembly language, which is closely tied to a computer's internal machine language. However, assembly language is a low-level language, that is, it is specific to a particular computer processor. So if you want to move an assembly program to a different kind of computer, you may have to completely rewrite the program using a different assembly language. But UNIX was intended to work on a variety of computer types (or platforms). That suggested using a high-level language. A high-level language is oriented towards problem-solving instead of towards specific hardware. Ritchie wanted a language

that combined low-level efficiency and hardware access with high-level generality and portability. So, building from older languages, he created ‘C’. Dennis Ritchie used ALGOL, BCPL and B as the basic reference language from which he created C. In 1983, the American National Standards Institute (ANSI) began the definition of a standard of a C. The resulting standard is known as ANSI C.

STRUCTURE OF A C PROGRAM

1. The preprocessor commands are special instructions to the preprocessor that specifies how to prepare the program for compilation. One of the most important preprocessor commands we use commonly is include. The include command tells the preprocessor that we need information from selected libraries known as header files.

2. The global declaration section comes at the beginning of the program. The global variables are declared here.

3. The execution of the program starts from the function called main(). All functions in a program, including main, are divided into threesections.

a) Declaration section: it is at the beginning of the function. It describes the data that you will be using in the function.

b) Initialization Section: Here variable are initialized

c) Executable Section: It contains the instructions to the computer thatperform specific task.

Creating and Running Programs

There are four steps in this process.

1. Writing and editing the program using Text editor (source code).

2. Compile the program using any C compiler.(.bak file)

3. Linking the program with the required library modules(object file)

4. Executing the program. (.Exe file)

Creating and Editing a C Program in C Programming Language compiler:

Writing or creating and editing source program is a first step in c language. Source code is written in c programming language according to the type of problem or requirement, in any text editor.

Saving C Program in C Programming Language: Source code is saved on the secondary storage. Source code is saved as text file. The extension of file must be ".c". Example the file name is "learn c programming language.c"

Compiling C program in C Programming Language: Computer does notunderstand c programming language. It understands only 0 and 1 means machine language. So c programming language code is converted into machine language.

The process of converting source code in to machine code is called compiling.

Compiler is a program that compiles source code. Compiler also detects errors in source program. If compiling is successful source program is converted into object program. Object program is saved on disk. The extension of file is ".obj"

Linking in C programming Language: There are many built in functions available in c programming language. These functions are also called library functions. These functions are stored in different header files.

Loading program: The process of transferring a program from secondary storage to main memory for execution is called loading a program. A program called loader does loading.

Executing program: Execution is the last step. In this step program starts execution. Its instructions start working and output of the program display on the screen.

Let's begin with a simple ‘C’ program that displays a message.

#include<stdio.h>main() { /*printing begins*/ Printf(“WELCOME TO C PROGRAMMING”); }

C's input/output scheme involves several definitions found in the stdiofile. The above program needs these definitions to use the printf facility to display a message. The #include directive causes the contents of the file to be sent along with the contents of your file to the compiler. Original file is not altered, but a composite file formed from the file and goes on to the next stage of compilation. Generally files are included with the extension .h, this extension stands for 'header file'. The second line state that you have a function called main().When you run a C program, execution always begins at the beginning of the main() function. Therefore, if you don't have main(), you don't have a complete program, and the compiler points out that you haven't defined a main() function. note: you normally don't call main() from other parts of your program. Typically, however, main() is called by startup code that your compiler adds to your program to mediate between the program and the operating system. The opening braces ‘{‘ in the third line marks the beginning of the function main and closing braces ‘}’ in the fifth line indicates the end of the function. All the

statement between these two braces form function body. The function body contains a set of instruction to perform the given task. In the above program the function body contains two statements out of which only the printf line is an executable statement .printf is a predefine, (predefine means that it is a function that has already been written and compiled and linked together with our program at the time of linking) standard C function for printing output. printf function prints everything between the starting and the ending of quotation marks.

The another one is called comments. A comment is a remark from the programmer to the reader that usually identifies a section of a program or explains some aspect of the code. it is enclosed between /* and */symbols called delimiters. The compiler ignores the comments. Note: You should use comments to document your programs. The more complex the program, the more valuable comments become. Not only do they help others to understand what you have done, but also they help you understand what you've done, especially if you haven't looked at the program for a while.

Standard Headers you should know about:

stdio.h – Standard IO: printf, scanf, getchar, putchar read, write, etc.

stdlib.h - common utility functions: malloc, calloc, strtol, atoi, etc

string.h - string and byte manipulation: strlen, strcpy, strcat, etc.

ctype.h – character types: isalnum, isupport, tolower, etc.

math.h – math functions: ceil, exp, floor, sqrt, pow etc.

signal.h – signal handling facility: raise, signal, etc

time.h – time related facility: asctime, clock, time_t, etc

Advantages (or) features of C Language:

Portability:C Programs are portable i.e. we can compile or execute C program in any operating system(unix,dos,windows)..Compiler and Preprocessor make it possible for C Programs to run it on Different Platforms.

Modular Programming:Modular programming is a software design technique that increases the extent to which software is composed of separate parts, called Modules.C Program consist of different modules that are integrated together to form complete program.

SPEED:C compiler produces machine code very fast compared to other language compiler. C compiler can compile around 1000 lines of code in a seconds or two. One more benefit of the C Compiler is that it also optimize the code for faster execution.

General purpose: C can be used to implement any kind of applications such as math’s oriented, graphics, business oriented applications.

Middle level language: As a middle level language C combines both the advantages of low level and high level languages. (arrays,pointers etc).

C Tokens:

In any passage of text, Individual word and punctuation marks are called tokens. Similarly in C program the smallest individual unit is known as C Tokens. C has six (6) types of tokens they are:

Keywords: keywords serve as basic building blocks for the program statements. These are system defined names. All keywords have fixed meanings and it can’t be changed. Note: All keywords must be written in lower case. There are 32+5(ANSI) keywords in C language

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while

_Bool _Imaginary restrict _Complex

inline

Identifiers: Identifiers refers to the name of the variables, functions and arrays. These are user-defined names consists of a sequence of letters and digits, with a letter as a first character. Ex’s: amount, sum, arr etc.The identifiers must conform to the following rules.

1. First character must be an alphabet (or underscore)

2. Identifier names must consist of only letters, digits and underscoreno other symbols are allowed.

3. Any standard C language keyword cannot be used as a variable name.

4. An identifier should not contain a space.

Constants: Constants in C refer to the fixed values that do not changed during the execution of a program. Generally there are two types of constant they are 1.Numeric constants: C predefines a set of numeric data types, which allow the representation of integers, floating point numbers: (i)integer constants: Integer constant is a set of digits, preceded by an optional –or + sign. Ex.’s: 123, -456, 0 , etc. (ii)Real constants: integer constant are inadequate to represent quantities that vary continuosly,such as height, percentage, temp and so on. These quantities are represented by the number containing fractional parts. Such numbers are called real or floating point constant.Ex.’s: 0.02, -456.8,+247.1 2.Character constant: There are two types of

character constant they are: (i)Single character constant: A Single character constant contains a single character enclosed within a pair of single quote marks. EX’s:’A’,’5’,’ ‘ etc. (ii)String Constant: A string constant is a sequence of character enclosed in double quotes. The character may be a letter, number, special character and a blank space. Ex’s: “Hello”, “1947”, “X” etc.

Strings: A string is a series of characters stored in consecutive bytes of memory. The idea of a series of characters stored in consecutive bytes implies that you can store a string in an array of char, with each character kept in its own array element. Strings provide a convenient way to store text information, such as messages to the user ("Please tell me your secret Swiss bank account number: ") or responses from the user ("You must be joking"). C-style strings have a special feature: The last character of every string is the null character. This character, written \0, is the character with ASCII code 0, and it serves to mark the string's end.

Special Symbol’s: C also provide some symbols like ‘{}’,’()’,’[]’ etc.

Operators:

Operators is a symbol that tells the computer to perform certain mathematical or logical manipulations. C operators can be classified into a number of categories. They are as follows:

1. Arithematic Operators: Perhaps you have warm memories of doing arithmetic drills in grade school. You can give that same pleasure to your computer. C uses operators to do arithmetic. It provides operators for five basic arithmetic : addition(+), subtraction(-), multiplication(*),

division(/), and taking the modulus(%). Each of these operators uses two values (called operands) to calculate a final answer. Together, the operator and its operands constitute an expression.

Integer Arithmetic

When an arithmetic operation is performed on two whole numbers or integers than such an operation is called as integer arithmetic. It always gives an integer as the result. Let x = 27 and y = 5 be 2 integer numbers. Then the integer operation leads to the following results.

x + y = 32 , x – y = 22 , x * y = 115 , x % y = 2 , x / y = 5

In integer division the fractional part is truncated.

Real arithmetic

When an arithmetic operation is preformed on two real numbers or fraction numbers such an operation is called floating point arithmetic. The floating point results can be truncated according to the properties requirement. The remainder operator is not applicable for floating point arithmetic operands.

Let x = 14.0 and y = 4.0 then

x + y = 18.0 , x – y = 10.0 , x * y = 56.0 , x / y = 3.50

Mixed mode arithmetic

When one of the operand is real and other is an integer and if the arithmetic operation is carried out on these 2 operands then it is called as mixed mode arithmetic. If any one operand is of real type then the result will always be real thus

15/10.0 = 1.5

2. Relational Operators:

In programming we requires the ability to make comparisons between variables, constants, and the values of expressions and depending on there relation, take certain decisions. C provides you with six relational operators for comparing two data values. They are less then(<), Greater then(>), Less then or equal to(<=),Greater then or equal to(>=), Equal to(==) and Not equal to(!=).each operator produces either the value true, or the value false, and so is eminently suited to the business of making decisions.

3. Logical Operators:

You will often want to combine number of conditions so that you execute a particular course. This can be done by using logical operators that combines several expressions that have a value true or false. C has the following three logical operators &&(logical AND), ||(logical OR), !(logical NOT). The logical AND (&&) operator evaluates to true only if both its operands evaluate to true. The logical OR (||) operator evaluates to true if either of its operands evaluates to true. The operands are guaranteed to be evaluated from left to right. Evaluation stops as soon as the truth or falsity of the expression is determined.

Example: a > b && x = = 10

The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both expressions are true i.e., if a is greater than b and x is equal to 10.

4. Assignment Operator:

The = operator is the basic binary assignment operator. The value of the right-hand operand is assigned to the left-hand operand. The other operators are shorthand operators that combine an assignment with an arithmetic or bitwise operation. For example, a += b is equivalent to a = a + b.

5. Increment/Decrement Operators: The unary operators are used to increment or decrement the value of their operands. The operator can perform the increment (++) or decrement (- -) in either a prefix or postfix manner. With a prefix operation, the operator is placed before the operand (++variable). The increment or decrement occurs before any other operations are performed. When the operand is placed after the variable (variable++), the increment or decrement is performed in a postfix manner, meaning it is done after any other operations take place. ++variable and variable++ mean the same thing when they form statements independently, they behave differently when they are used inexpression on the right hand side of an assignment statement.

Consider the followingm = 5;y = ++m; (prefix)

In this case the value of y and m would be 6Suppose if we rewrite the above statement asm = 5;y = m++; (post fix)Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left. On the other hand, a postfix operator first assigns the value to the variable on the left and then increments the operand.

6. Special Operators

C supports some special operators of interest such as comma operator, size of operator, pointer operators (& and *) and member selection operators (. and ->).

The Comma Operator

The comma operator can be used to link related expressions together. A comma linked list of expressions are evaluated left to right and value of right most expression is the value of the combined expression.

For example the statement

value = (x = 10, y = 5, x + y);

First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowest precedence in operators the parenthesis is necessary.

The size of Operator

The operator size of gives the size of the data type or variable in terms of bytes occupied in the memory. The operand may be a variable, a constant or a data type qualifier.

Example

m = sizeof (sum);

n = sizeof (long int);

7. Bitwise Operators

C has a distinction of supporting special operators known as bitwise operators for manipulation data at bit level. A bitwise operator operates on each bit of data.

Those operators are used for testing, complementing or shifting bits to the right on left.

Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise Exclusive

<< Shift left

>> Shift right

~ One’s Compliment

The shift operators move bits to the right or left. When applied to unsigned numbers, these operators are implementation independent. Therefore they must be used with caution with signed numbers.

Bitwise Left Shift Operator (<<)

It is a binary operator that requires two integral operands. The first operand is the value to be shifted. The second operand specifies the number of bits to be shifted.

Shifting binary numbers are like shifting decimal numbers. If we have an eight digit decimal number, and we shift it three places to the left, then the leftmost three digits are lost and three zero digits are added to the right.

Bitwise Right Shift Operator (>>)

It is a binary operator that requires two integral operands. The first operand is the value to be shifted. The second operand specifies the number of bits to be shifted.

Shifting binary numbers are like shifting decimal numbers. When bits are shifted right, the bits at right most end are deleted.

8. Conditinol Operator: The conditional operator is sometimes called a ternary operator because it involves three operands.

The conditional operator can be written generally as:

logical_expression ? expression1: expression2

If the logical_expression evaluates as true, the result of the operation is the value of expression1, and if logical_expression evaluates to false, the result is the value of expression2.

Note that if expression1 is evaluated because logical_expression is true, then expression2 will not be, and vice versa.

For example:

a = 10;

b = 15;

x = (a > b) ? a : b

Here x will be assigned to the value of b. The condition follows that the expression is false therefore b is assigned to x.

Variables: A variable is a storage location. A variable always has a type associated with it. A variable of primitive type holds the value of a primitive type. You do have to follow a few simple C naming rules:

1. The first character in a name cannot be a digit. 2. Uppercase characters are considered distinct from lowercase

characters3. You can't use a C keyword for a name

note: you should use meaningful names for variables, so it could make some sense.

Example:

int sum,number, salary;

double average, mean;

EXPRESSIONS

An expression is a combination of variables constants and operators written according to the syntax of C language. In C every expression evaluates to a value i.e., every expression results in some value of a certain type that can be assigned to a variable.

Evaluation of Expressions

Expressions are evaluated using OPERATOR PRECEDENCE AND ASSOCIATIVITY

OPERATOR PRECEDENCE AND ASSOCIATIVITY

Each operator in C has a precedence associated with it. The precedence is used to determine how an expression involving more than one operator is evaluated. There are distinct levels of precedence and an operator may belong to one of these levels. The operators of higher precedence are evaluated first. The operators of same precedence are evaluated from right to left or from left to right depending on the level. This is known as Associativity property of an operator.

Precedence in Arithmetic Operators

An arithmetic expression without parenthesis will be evaluated from left to right using the rules of precedence of operators. There are two distinct priority levels of arithmetic operators in C.

High priority * / %

Low priority + -

Example

x = a * b – c

here * will be evaluated first than -

y = b / c * a

here / will be evaluated first than *

Precdence Group Operators Associativity

(Highest to Lowest )

(param) subscript etc., ( ) [ ] –>. L ‡ R

Unary operators - + ! ~ ++ – – (type) * & sizeof R ‡ L

Multiplicative * / % L ‡ R

Additive + – L ‡ R

Bitwise shift << >> L ‡ R

Relational < <= > >= L ‡ R

Equality = = != L ‡ R

Bitwise AND & L ‡ R

Bitwise exclusive OR ^ L ‡ R

Bitwise OR | L ‡ R

Logical AND && L ‡ R

Logical OR | | L ‡ R

Conditional ?: R ‡ L

Assignment = += –= *= /= %= &= ^= R ‡ L

Comma , L ‡ R

Data Types: As we mentioned above, each variable that you declare can store values of a type determined by the data type of that variable. The varieties of data type available allow the programmer to select the type appropriate to the need of the application as well as the computer. There are two categories of data types:

1.primary (or fundamental) data type: All C compiler support four fundamental data type they are as follows Character Type (char): The type char is typically used to represent individual characters and small integers. It is represented in a single machine byte. The qualifier signed or unsigned may be explicitly applied to char. While unsigned char have values between 0 to 255,signed char have values from -128 to 127. Integer type( int) : The type int is used to represent integer values. Generally integer occupy 2 bytes of storage. In order to provide some control over the range of numbers and storage space, C has three classes of integer storage namely short int, int, and long int. Represent integer values of different sizes. Typically, short int are represented in

half a machine word, int in a machine word, and long int in either one or two machine words. Floating point type: The types float, double, and long double represent floating point single, double, and extended precision values. Typically, floats are represented in 4 bytes; doubles in 8 bytes, and long double in 10 bytes.

Size and Range of Data Types on 16 bit machine.type SIZE (Bits) Range

char or signed char 8 -128 to 127

unsigned char 8 0 to 255

int or signed int 16 -32768 to 32767

unsigned int 16 0 to 65535

signed short int 8 -128 to 127

unsigned short int 8 0 to 255

signed long int 32 -2147483648 to 2147483647

unsigned long int 32 0 to 4294967295

float 32 3.4 e-38 to 3.4 e+38

double 64 1.7e-308 to 1.7e+308

long double 80 3.4 e-4932 to 3.4 e+4932

2 .User-defined data type: C supports a feature known as “type definition” that allows user to define an identifier that would represent existing data type. it takes the general form: typedef type identifier;example: typedef int marks; here marks symbolizes int. they can be later used to declare variables as follows: marks sub1,sub2…sub n; remember that the new type is new only in name, but not the data type.Another user defined data type is enumerated data type. The use of this datatype is to make programs more readable. It allows you to create your own datatype with predefined values. Though its form is like that of a structure, the values mentioned within its braces do not indicate variables but in fact are constant values that are enum can take.Syntax:enum identifier{value 1,value 2, .....Value n}; After this definition, we can declare variables to be of this 'new' type as Enum identifier v1,v2,v3.....vn;

The enumerated variables v1,v2,.......vn have only valuesamong value1,value2........value n.

TYPE CONVERSIONS IN EXPRESSIONS

Implicit type conversion

C permits mixing of constants and variables of different types in an expression. C automatically converts any intermediate values to the proper type so that the expression can be evaluated without loosing any significance. This automatic type conversion is know as implicit type conversion

During evaluation it adheres to very strict rules and type conversion. If the operands are of different types the lower type is automatically converted to the higher type before the operation proceeds. The result is of higher type.

The following rules apply during evaluating expressions

All short and char are automatically converted to int then

1. If one operand is long double, the other will be converted to long double and result .....will be long double.

2. If one operand is double, the other will be converted to double and result will be double.

3. If one operand is float, the other will be converted to float and result will be float.

4. If one of the operand is unsigned long int, the other will be converted into unsigned .....long int and result will be unsigned long int.

Explicit Conversion

Many times there may arise a situation where we want to force a type conversion in a way that is different from automatic conversion. The process of such a local conversion is known as explicit conversion or coasting a value. The general form is

variable= (type_name) expression

Input and Output Operations:

Reading, processing and writing of data are the three essential functions of a computer Program. Most programs take some data as input and display the processed data often known as information or results. There are two methods of providing data to the program data to the program variables One method is to assign values to variables through the assignment statements such as x=5, a=0 and so on. Another method to use the input function scanf which can read data from a terminal. For outputting results the function printf which sends results out to a terminal is used. 'C' does not have any built-in input and output statements as part of its syntax .All input and output operations are carried out through function calls such as printf and scanf.

Input function scanf: scanf is an input function. The general form of scan is: scanf(“control string”,arguments); The control string specifies the field format in witch the data is to b entered and the arguments specify the address of location where the data is stored. The format field specification for reading an integer number is : %wd

the percent sign(%) indicates that a conversion specification follows. W is an integer number, that specifies the field width of the number to be read and d known as data type character, indicates that the number to be read i in integer mode.

Example: scanf("%2d %5d",&num1,&num2);data line: 60 13456

The value 60 is assigned to num1 and 13456 to num2.Input data item must be separated by spaces, tab or new line. Punctuation mark do not count a separator.

Output function printf: Generally printf function prints everything between the starting and the ending of quote marks. The prototype of printf is: printf(“control string”,arguments);The control string consist of characters that will b printed on the screen as they appear, The format specification that defines the output format for display of each items, Escape sequence characters such as \n(new line), \t(tab) etc. The format specification for printing an integer number is %wd where w specifies the minimum field width for the output. However if a number is greater than the specified field width, it will be printed in full. Overriding the minimum specification d specifies the value tobe printed is an integer.

The other input and output functions are getchar() and putchar().These function are used for reading and writing character one at a time. Syntax’s : v=getchar(); & putchar(variable_name);

Some of the format specifier’s are %c for character, %s for strings, %d for integers, %f for floating point values , %ld for double, %u for unsigned integer. etc

DECISION MAKING AND BRANCHING

C Language must be able to perform different sets of actions depending on the circumstances. A C program is a set of statements which are normally executed sequentially and the order in which they appear. This happens when no options or no repetitions of certain calculations are necessary. However, in practice, we have a number of situations where we may have to change the order of execution of statements based on certain conditions; repeat a group of statements until certain specified conditions are met. This involves a kind of decision making to see whether a particular condition has occurred or not and then direct the computer to execute certain statements accordingly.

C has 3 decision making instructions, they are:

1. If Statement 2. Switch Statement 3. Goto Statement.

IF Statement:The if statement may be implemented in different

forms depending on the complexity of conditions to be tested.

Generally there are four types of If statementÿ Simple If statement.ÿ If-Else statement. ÿ Nested If-Else statement.ÿ Else-If ladder.

Simple IF Statement:The IF Statement is a powerful decision making statement and is used to control the flow of execution of statements.

The General form of IF statement is look like this:

if(Test expression){

Statement block;}

Statement x;It allows the computer to evaluate the Test expression first and then depending on whether the value of the expression (relation or condition) is 'TRUE' (non-zero) or FALSE (zero), it transfers the control to a particular statement. If the test expression is true, the statement block will be executed; otherwise the statement block will be skipped and the execution will jump to the statement x.

Ex: /* calculation of Bonus*/main(){int bonus, cy, yoi,yr_of_ser;

printf("Enter current Year and Year of joining");scanf(%d %d",&cy,&yoi);yr_of_ser=cy-yoi;if(yr_of_ser>3){bonus=2500;printf("Bonus=Rs. %d",bonus);}}

Observe that here the two statements to be executed on satisfaction of the condition have been enclosed within a pair of braces.

IF… Else Statement:

If. . .else statement is an extension of the simple IF statement.

Note: Notice that the ELSE is written exactly below the IF.

The general form is:

if (test condition)

{ True-Block statement(s)

} else {

False-Block statement(s) }

statement-x;

If the test expression is true, then the true-block statement will be executed; Otherwise the false-block statements are executed. In either case , either true-block or false-block will be executed, not both.

main(){

if(a==b)printf("a and b are equal");elseprintf("a and b are not equal");}

Nesting of If…Else statements:

When a series of decisions are involved, we may have to use more than one if else statement in nested form as follows

if (test condition1){if (test condition2)

{Statement-1;}else{Statement-2;}}else{Statement-3;}statement-x;If the condition-1 is false the statement-3 will be executed Otherwise if continues to perform the second test. If the condition-2 is true, the statement-1 will be executed; otherwise the statement-2 will be executed and then the control is transferred to the statement-x.

Ex: /* Demo of NESTED if-else*/main(){int i;printf("Enter either 1 or 2");scanf("%d",&I);if(i==1)printf("you pressed one");else{if(i==2)printf("you pressed two");elseprintf("Do not press other than these");}

Else If ladder:

The Else-If ladder is a chain of Ifs in which the statement associated with each else is an If

The general form is:

if (condition-1){Statement-1;}

else if (condition-2){Statement-2}……………….else if( condition-n){Statement-n}statement-x;

EX: main(){

int x=30,y=40;if(x==y)printf("\n x is equal to y");else if(x>y)printf("\n x is greater than y");else if(x< y)printf("\n x is less than y");}OUTPUT: x is less than y

Explanation: It compares in first IF whether x and y are equal or not,the comparison results FALSE,so the control comes to next IF it also fails.Finally the condition satisfied, thus the output.The Switch statement:

In real life we are often faced with situations where we are required to make a choice between a number of alternatives rather than only one or two. C provides a special control statement that allows us to handle such cases effectively; rather than using a series of IF statements where complexity of a program increases dramatically when the number of alternatives increases. This special multiway control statement is known as Switch.

The general form of the Switch statement is shown below:

switch(expression){case value-1:Statement(S)-1; break;

case value-2:Statement(S)-2; break;…….……………..case value-n:Statement(S)-n; break;default: default-Statement(S); break;}The expression is any C expression that will yield an integer constant like1,2 or 3, or an expression that evaluates to an integer.The keyword case is followed by an integer or a character constant(i.e.value-1,value-2……).The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement. The default is an optional case when present, it will be executed if no match is found with any of the case statements.

When we run the program containing the switch,first the integer expression following the keyword switch is evaluated. The value it gives is then matched ,one by one, against the constant values that follow the case statements. When a match is found, the program executes the statements following that case. If no match is found with any of the case statements, default is executed.

Rules for switch … case … break … default• Rules of Using Switch Case in C Programming• Case Label must be unique• Case Labels must ends with Colon• Case labels must have constants / constant expression• Case label must be of integral Type ( Integer,Character)• Case label should not be ‘floating point number ‘• Switch case should have at most one default label

• Default label is Optional• Default can be placed anywhere in the switch• Break Statement takes control out of the switch• Two or more cases may share one break statement• Nesting ( switch within switch ) is allowed.• Relational Operators are not allowed in Switch

Statement.• Macro Identifier are allowed as Switch Case Label.• Const Variable is allowed in switch Case Statement.• Empty Switch case is allowed.

/* program to simulate a simple calculator */#include<stdio.h>int main() {

float a,b;char opr;printf("Enter number1 operator number2 : ");scanf("%f %c %f",&a,&opr,&b); switch(opr){

case '+':printf("Sum : %f",(a + b));break;

case '-':printf("Difference : %f",(a - b));break;

case '*':printf("Product : %f",(a * b));break;

case '/':printf("Quotient : %f",(a / b));break;

default:printf("Invalid Operation!");}}

The GoTo statement::This Keyword is used when we want to transfer the

control to some point in the program which is not in the normal, stepby step sequence of a program. It takes control from one place to another unconditionally, so a different path for the execution of a program to set up.Backward Jump:label:statements;statements;goto label;

Forward Jump:goto label;statements;statements;label:

DECISION MAKING AND LOOPING:In looping, sequences of statements are executed until some conditions for termination of the loop are satisfied. The ‘C’ language provides three loop control statements to support the repeated execution of a single statement or statement block while a specified condition holds true. They are:

ÿ The while statement.ÿ The do statement.ÿ The for statement.

The for and while loops begin with a test of their truth condition. This means that either loop can terminate without execution of the associated statement or statement block. A third loop structure, the do while loop, guarantees that the statement or statement block is executed at least once—the condition is tested after execution.

The while statement:The simplest of all the looping structure in C is the while

statement. The basic format of the while is as follows:While (test-condition)

{ Body of the loop;

}The while is an entry-controlled loop. The test-condition is evaluated and if condition is true then the body of the loop is executed. After execution of body the process is repeated until the test condition becomes false and the control is transferred out of the loop.

/* sum of 1 to 10 numbers */#include<stdio.h>int main() {

int i = 1,sum = 0;while(i<=10)

{sum = sum + i;i = i + 1;

} printf(“Total : %d “,sum);

}

The do statement :The while loop we studied just before makes a test condition before loop executed. Therefore the body of loop may not be executed at all if the condition is not satisfied at the first attempt.On same occasions it might be necessary to execute body of the loop before test is performed Such conditions can be handled using do statement.This takes the following form:

do

{

body of the loop.

}while(test-condition);

Here the test-condition in the while statement is evaluated at the end of the loop is executed once if the test condition is wrong.For first

attempt otherwise the program continues to evaluate the body of as long as condition is true. The do-while is an exit control loop.there fore the body of the loop is executed at least once.

/* sum of 1 to 10 numbers */#include<stdio.h>int main() {

int i = 1,sum = 0;do{

sum = sum + i;i = i + 1;

} while(i<=10);printf(“Total : %d “,sum);

}

The for statement:

The for loop is another entry controlled loop that provides a more concise loop control structure. The general form of the loop is:

for(initialization; test-condition ;increment){

body of the loop}

The execution of the for statement is as follows:1. Initalization of the control variables is done first, using assignments statements such as i=1 and count=0.The variable i and count are known as loop-control.

2. The value of the control variable is tested using the test-condition.TheTest-condition is a relational expression such as (i<10)that determines when the loop will exit.If the condition is true,the body of loop is executed otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.3. When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the loop.Now,the control variable incremented using an assignment statement such as i=i+1 and the new value of the control variable is again tested to see whetherit satisfies the loop condition.If the condition is satisfied,the body of the loop is again executed.The process continues until the value of the control variables fails to satisfy the test condition.

/* sum of 1 to 10 numbers */#include<stdio.h>int main() {

int I,sum = 0;for(i=1;i<=10;i++) {

sum = sum + i;i = i + 1; }

printf(“Total : %d “,sum); } The continue Statement

In some programming situations we want to take the control to the beginning of the loop, bypassing the statements inside the loop, which have not yet been executed. The keyword continue allows us to do this. When continue is encountered inside any loop, control automatically passes to the beginning of the loop.

main( ){int i, j ;for ( i = 1 ; i <= 2 ; i++ ){for ( j = 1 ; j <= 2 ; j++ ){if ( i == j )continue ;printf ( "\n%d %d\n", i, j ) ;}}}

The output of the above program would be...1 22 1

The break Statement

If we want to jump out of a loop instantly, without waiting to get back to the conditional test. The keyword break allows us to do this. When break is encountered inside any loop, control automatically passes to the first statement after the loop. A break is usually associated with an if./* Program to find a given number is prime or not */main( ){int num, i ;printf ( "Enter a number " ) ;scanf ( "%d", &num ) ;i = 2 ;while ( i <= num - 1 ){if ( num % i == 0 ){printf ( "Not a prime number" ) ;break ;}i++ ;} == num )printf ( "Prime number" ) ;

}