PSCP Notes Co1 & Co2

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 32

Anitha Vemulapalli KL University, Hyd

COMPUTER FUNDAMENTALS
Definition:- Computer is defined as an electronic device used to accept data, processes it and
gives the result/information.
Data:- The input we give to the computer is known as data. The input to the computer should
consist of data as well as the instructions to work on that data. We can also define data as the
collection of facts and figures.
Process:- The work done by the computer is known as process.
Information:- Processed data is known as information. In other words, the output from the
computer that is got after processing is known as information.
Eg: Process

10 + 30 = 40
Information
Data

Characteristics or advantages of computers:- Computers have become a part of our daily life.
The following are the characteristics of computers.
a) Speed :- Computers have high speed. Due to this, the work which is taking a lot of time to
complete by humans is done with in a less time by the computer. The computers speed is
such that it can perform any type of calculation within a milli second (1/1000 th of a second),
micro second (1/106 th of a second), nano second (1/10 9 of a second) or even in a pico
second (1/1012 of a second) of time.
b) Time Saving:- Using computers, we can save a lot of time. This is because the speed of the
computer is very fast. The time that we are saving can be used to perform some other work.
c) Accuracy:- Computers give accurate or correct result for any complex problem we give to the
computer.
d) Large Memory:- Computers have large memory capacity. We can store any type of data and
any amount of data in the computers. The computer’s memory is unlimited.
e) Diligence:- Computers do not feel risk or boredom when we assign the same task again and
again to the computer. Any number of times you assign the same task, it will give accurate
result with same speed and within less time as it gave for the first time.
f) Reliability:- Computers output is generally very reliable. This is subject to the condition that
the input data entering the computer should be correct and the program or instructions should
be reliable and correct. Incorrect input data and unreliable programs give us wrong results.
Hence the phrase, GARBAGE IN - GARBAGE OUT.

Applications of computers:- Computers are used in different fields due to its advantages. The
following are the applications of Computers in different fields:
a) Industrial and Business field:- In this field, computers are used to store the details of the
employees who are working there, details of the company like production, amount spent,
amount received etc., So that it is easy for anyone to get the information from the computer
within a less time.
b) Scientific and Medical field:- Scientists use the computers for storing the result of any
experiments or research work. In the medical field, they are used to operate different medical
equipment like ECG and Scanning. These are also used to store patient’s history.

Computer Programming 1
Anitha Vemulapalli KL University, Hyd

c) Entertainment:- Computers are used for playing games, listening to songs and for viewing
films etc.
d) Communication:- In communication field, computers play a vital role. These are used to send
mails to person who are at far-off distance. This is possible because of Internet technology.
E-mail is the feature used in Internet to send the mails. This takes less time and is very
economical.
e) Graphics:- Using computers, we can create graphics in films and also can create cartoon
films within less time. The packages like AutoCAD can be used to draw drawings for civil,
mechanical and automobile works within a short period and without any risk.
f) Weather Forecast:- Computers play a vital role in the forecast of weather at different places
and also to know the temperatures recorded at various places.

Limitations of computers:- Although computers are very fast and accurate, still they have some
limitations. They are as follows:
1) Computer cannot think on its own. It processes the data according to the specifications
given by the user.
2) Computers can process towards a goal only when all the steps are properly specified.
3) They cannot take decisions on their own.
4) Unlike human beings they cannot learn from the past experience.

COMPUTER STUDY

Hardware Software

System software (Eg: OS) Application Software (Eg: paint, wordpad)

Language Package (Eg: MS-Office)

Low level Assembly level High Level


Language language language

Hardware:- Dealing with the mechanism or the internal parts of the computer is known as
hardware.
Software:- It is a set of programs. In other words, the subject which gives us the knowledge of
how to get our work done by using the computer is also known as software.
Program:- The set of instructions or commands is known as a program.
System Software:- It is the software, which makes the computer ready to work on it. Eg: Dos,
Windows
Application Software:- It is the software, which will work when the system is ready. This
software is used to perform a task.
Computer Programming 2
Anitha Vemulapalli KL University, Hyd

Package:- The set of readymade programs is known as package i.e., the instruction for the
work/task whichever is going to b e done by the user will be readily available. The user has to
just finish the work. Eg: MS-Office
Language:- It is an area where the user has to write his instructions and then use them. Nothing
will be predefined as in a package. There are 3 types of languages which are described below.
Eg: C, C++
1) Low Level Language:- It is the language, where the instructions are given in the
form of 0s and 1s. This is a language understood by the computer. It is also
known as Machine language or Binary language. The disadvantages with this
language is program becomes lengthy and creates a big problem for a small
mistake also.
2) Assembly Level Language:- In this language, instructions are written using short
English words. These short English words are known as Mnemonics. Eg: ADD,
CMP, STORE, etc.
3) High Level Language:- In this type of language, we use simple English sentences
to give instructions to the computer. Eg: C, C++, PASCAL,
Translators:- These are the programs used to convert user written programs into machine
language. There are 3 types of translators.
1) Assemblers:- These convert assembly language into low level language.
2) Compilers:- These are used to convert High level language into low level language.
The compilers compile(convert) the user program (source code) into machine code
(Object code) at a time and gives the list of errors after compilation. The object code
after compilation is stored as a file.
3) Interpreters:- These also convert High level language to low level language. These
compile line by line. When there are no errors in a line, it compiles that line and
proceeds to the next line. If any error is present in the line, the compilation stops there
itself. The object code which is got after compilation will not be saved as a file.

Memory of a computer
Memory means ability to store the data and instructions. Computer’s memory is divided into 2
types as primary memory and secondary memory.
(1) Primary Memory or Main Memory:- This is the most important memory to be present in
the system. Primary memory is divided into 2 types as Random Access Memory (RAM) and
Read Only Memory (ROM).
1) Random Access Memory (RAM):- This is also known as Read/Write Memory. We can read
as well as write instructions into this memory. This is also known as Volatile memory,
because, the contents in this memory will be lost when we switch off the power to the
system. Whatever input we give to the computer will be first stored in this memory. RAM is
again divided into 2 types as Static RAM and Dynamic RAM.
a) Static Ram (SRAM):- It provides volatile storage, but as it is supplied with power, it does
not need any special regenerator circuits to retain the stored data. The cost of these is
very high and they offer high performance.
b) Dynamic RAM (DRAM):- In this type of RAM, the charge in it gets discharged and so it
has to be periodically refreshed. For this special circuitry is present. This type of RAM
offer greatest capacities and lowest cost per bit, but are relatively slower.

Computer Programming 3
Anitha Vemulapalli KL University, Hyd

2) Read Only Memory:- As the name itself shows that we can only read instructions from this
memory. We cannot write anything into this memory. This is the memory provided by the
manufacturer during the manufacturing of the computer. Information present in this memory
will not get lost even when we switch off the power. Hence it is also known as non-volatile
memory. ROM is again of different types which are as follows:
a) Programmable Read Only Memory (PROM):- In this type of ROM, we can write
programs only once. If any mistakes are done while writing the program, then it cannot
be corrected and the ROM becomes useless. We have to take another PROM for storing
the program.
b) Erasable Programmable Read Only Memory (EPROM): - In this type of ROM, we can
write the program and if any mistake is done we can erase it and then write the program
again. This erasing is done by passing the ultra violet rays on to the memory.
c) Electrically Erasable Programmable Read Only Memory (EEPROM): -The information in
this type of ROM can be erased by passing electrical signals.

(2) Secondary Memory:- This is the permanent memory. It is also known as mass memory. All
the storage devices like hard disks, floppy disks, CDs, magnetic tapes and magnetic disks come
under this memory.
The computer’s memory is measured in the form of bytes. One byte is equal to 8 bits. A
bit is a short form for binary digit. Computers can understand instructions in the form of 0s and
1s only. It is because, the computer parts are comprised of switching components which will be
on and off continuously with a great speed. Every character on the keyboard has some special
code which is an ASCII(American Standard Code for Information Interchange) code in Hexa
Decimal number system. Each character occupies a memory of 1 Byte.

4 bits = 1 Nibble
8 bits = 1 Byte
1024 Bytes = 1 Kilo Byte (KB)
1024 KB = 1 Mega Byte (MB)
1024 MB = 1 Giga Byte (GB)
1024 GB = 1 Terra Byte (TB)

Cache Memory:- CPU registers are fast storage elements than main memory. If main memory
is also built with the same technology as CPU registers, then the operational speed of CPU and
main memory will match. But, this is too expensive. Also, the CPU has to fetch the data and
instructions from main memory. Because of the difference in their speed, the CPU remains idle
for some time while fetching data and instructions from main memory. This waiting time
substantially reduces the overall system performance. To solve this problem, a cache memory is
employed between the main memory and CPU which increase the processing speed of CPU.

CPU Main Memory


Cache
Memory

Computer Programming 4
Anitha Vemulapalli KL University, Hyd

Cache memory is a fast memory and its access time is far less than the main memory. Although,
cache memory is a fast device, it is very expensive. Hence, cache memory is used in small sizes
only such as 64K, 128K, etc. The contents of the cache memory are not accessible to users.
Cache contains that portion of the data which are frequently accessible. The memory read or
write operation is first checked with the cache. If the desired location is available, then it is used
by the CPU directly. Since, cache is faster than RAM, the information is more quickly available
to CPU.
Virtual Memory:- When very large programs and very large files of data can strain the
capacity of even large computer’s main memory, then modern operating systems and many
application programs store parts of their program or data outside the RAM until needed. This
type of storage is called virtual memory. The system that uses the virtual memory stores the
program in the main memory and if that memory is not sufficient, then the rest of the program is
stored in the hard disk. Here, a part of the hard disk is used as a RAM which we are calling it as
virtual memory.

ASCII Code :- ASCII stands for American Standard Code for Information Interchange. It is a
standard alphanumeric code that represents numbers, alphabetic characters and symbols using a
7-bit code format. The standard ASCII character set consists of 128 decimal numbers ranging
from 0 through 127 which are assigned to letters, numbers, punctuation marks and the most
common special characters. The extended ASCII character set consists of 128 decimal numbers
that range from 128 to 255 representing additional special, mathematical, graphic & foreign
characters.

Algorithms and Pseudocode:-Pseudocode is an artificial and informal language that helps


programmers to develop algorithms. An algorithm is a step-by-step procedure for solving a
problem using a pseudocode. Pseudocode is similar to everyday English. It is convenient and
user-friendly although it is not an actual computer programming language. Pseudocode programs
are not actually executed on computers. Rather they help the programmer to think out a program
before attempting to write it in a programming language such as C. The following are some of
the algorithms:
1) Algorithm to find the area of a circle
Step 1: Start
Step 2: read radius (r)
Step 3: compute area=3.14 * r* r
Step 4: Display area
Step 5: Stop

2) Algorithm to calculate the average of 3 numbers


Step 1: Start
Step 2: Read 3 numbers a,b,c
Step 3: compute total = a+b+c
Step 4: compute average=total/3
Step 5: display average
Step 6: Stop

Computer Programming 5
Anitha Vemulapalli KL University, Hyd

3) Algorithm to find the biggest of 2 numbers


Step 1: Start
Step 2: Read two numbers a, b
Step 3: if a is bigger than b, goto step 5
Step 4: display b is big goto step 6
Step 5: display a is big
Step 6: Stop

Flowchart:- A flowchart is a graphical representation of an algorithm or a portion of an


algorithm. Flowcharts are drawn using certain special purpose symbols such as rectangle,
diamond, oval etc. These symbols are connected by arrows called flow lines. Like pseudocode,
flowcharts are useful for developing and representing algorithms. Flowcharts clearly visually
show how control structures operate in a program. The most common symbols used in drawing
flowcharts are shown below.
Start/Stop

Read/Write

Process /
Computation

Decision Making

Module

n Connectors

Flow Lines

Use of Flowchart:- Flowchart is used for the following purposes:

Computer Programming 6
Anitha Vemulapalli KL University, Hyd

i) To assist the programmer in developing the program logic and to be used as


documentation for a complete program.
ii) To analyze or define a process
iii) To explain in details about he actions and decisions defined in the process (i.e., it can
be used as a communication or training aid).
iv) To assist the programmer, while searching potential problem points in a process.
v) To help the programmer, while examining the performance of a process.

Steps in program development:- Computers play a major role in solving a problem. This is
because of the good communication that exists between computers and their corresponding
users. In order to write a program, a process called programming is required. But, before writing
this, the problem to be solved should be analyzed and need to be prepared by generating a step-
by-step procedure. While developing a program the following steps are required.
1) Problem specification:- The problem should be studied and understood well. The
programmer should have the knowledge about what should be done in order to begin the first
step. A careful examination about the following is required to determine what has to be done
next.
i) Inputs provided
ii) Questions asked
iii) Outputs specifications type
iv) Manual processing
The information obtained during the problem specification phase is due to the input, output and
some other processing specification.
2) Outlining the solution:- In this step, the solution method using which the problem can be
solved is identified. The chosen method is a path defines, what is given and what is required to
solve the problem. While doing this, two conditions are to be considered. One is the time needed
to solve the problem and the other is vulnerability to errors.
3) Choosing and representing algorithm:- Once the appropriate solution method has been
defined, it is necessary to convert that methods into an algorithm, which is a means of
representing the solution for problem solving. These algorithms can be written using the
common language or by using the standard notations.
4) Programming or coding the algorithm:- In this step, the algorithm written is converted into
a program. Programs can be written in any programming languages depending on the problem’s
behavior and also on the availability of those languages.
5) Removing errors:- In this step, the errors generated while developing a program are detected
and then corrected. Program verification is a process that assures the correctness of a program,
and debugging is a mechanism that detects and removes the errors. There are 3 types of errors
that are generated while developing a program. They are described below:
a) Syntax errors:- These errors are generated when the statements are not written according to the
syntax or grammatical rules of a language.
b) Run-time errors:- These errors are generated when the program which is free from syntax
errors is being executed. Some of the most common runtime errors are divided by zero, square
root of a negative number, range out of bounds etc.

Computer Programming 7
Anitha Vemulapalli KL University, Hyd

c) Logical errors:- These errors are generated when there are logically incorrect statements in the
program. Such errors are very difficult to be detected, since they are found after examining the
program.
6) Testing and validation:- After writing a program, it must be tested and validated. It should
always produce correct and appropriate results. By a variety of conditions called test cases, the
program can be validated. Hence, the selection of a test datasets is a major factor which is done
through a better understanding of various logical paths present in the program.
7) Documentation and maintenance:- The information about the program is collected,
organized and maintained through a process called documentation. Any change in the program
should be done according to the requirements. This process is known as program maintenance.
The programs must be written in a clear and easy way, so that the other users who use the
program may not find any difficulty. In order to achieve this, the program should be maintained
well by using the following:
i) Proper comments
ii) Proper indentation for improving the readability and clarity.
iii) Detail description about the different methods used etc.

‘C’
Historical Development of C
‘C’ is a high level language. A language is a medium where we write the programs for
developing any application. Prior to ‘C’, there are different languages like COBOL (common
Business Oriented Language), BASIC (Beginners all purpose Symbolic Instruction Code),
FORTRAN (FORmula TRANslation) and PASCAL (named after the scientist Pascal). Each
language has been developed to perform a specific work only. COBOL is used for business
applications, PASCAL and FORTRAN for scientific applications and so on. So if a programmer
has to perform all these tasks, then he has to know all these languages which is very risky. To
overcome this problem, scientists at that thought of developing a language which will do all
these tasks. Meanwhile in the year 1960, ALGOL60 was developed for developing the system
programs as well as for application programming. But it has faced some problems like it is not
portable and is fully machine dependent. After this ‘CPL’ Combined Programming Language’
was developed in 1964. But, it too had some disadvantages. In 1967 ‘BCPL’ Basic Combined
Programming Language was developed by Martin Richards. This language is too abstract
(theoretical). Later in 1970 ‘B’ language was developed by Ken Thompson taking the concepts
of BCPL. Finally ‘C’ language was developed by Dennis Ritchie in the year 1972 at AT & T
Bell Laboratories. Taking the concepts of BCPL and B language and adding new features C
language is developed. Many commercial softwares that were written in other languages were
rewritten in C in order to take advantage of its efficiency and its portability.
FEATURES OF ‘C’:-
1. It is a high level language. It is also known as middle level language since it has the features
of both low level programming (interacting with machine parts) and high level programming
(dealing with real world applications).
2. It is used for developing system software e.g: Operating system and also for application
software like Accounting packages.

Computer Programming 8
Anitha Vemulapalli KL University, Hyd

3. It has the ability to write very concise source programs because of its large number of
operators, small set of instructions and extensive library functions.
4. C is highly portable. Most of the C programs can be processed on many different computers
with little or no alteration.
5. C compilers are commonly available for all types of computers having different operating
systems or different microprocessors etc.
6. C supports modular programming i.e., a program can be divided into small parts (modules)
so that it is easy for debugging (error checking).
APPLICATIONS OF C:-
C is used for writing programs for developing the following sofwares:
1. Operating Systems
2. Utilities & Tools
3. Compilers
4. Interpreters
5. Word processors
6. Spread Sheets
7. GUI

General Structure of a C Program


Documentation section
Link section or pre processor commands
Definition section
Global declarations
main()
{
local declarations
Executable statements
}
User defined functions(argument list)
{
local declarations
executable statements
}
Documentation section:- This is the comment area where we give the description of the program.
The comments are given between the symbols /* and */.
Link section:- In a C program we use different C statements whose programs are written in
separate files. These files are known as header files which have an extension of .h. Some of the
header files are stdio.h, conio.h, string.h, math.h, alloc.h, graphics.h etc. When we are using any
of these statements then we have to link the respective header files in our program. We can
include as many header files as we want in our program. This is done by using the preprocessor
directive #include. The following statement shows the linking of a header file stdio.h
#include <stdio.h>

Computer Programming 9
Anitha Vemulapalli KL University, Hyd

Definition section:- In this section, we define names to the constants. These values cannot be
changed in our program. While giving names to the constant we have to give them in UPPER
case, so that we can distinguish which is a variable and which is a constant. It is defined by using
the #define which is another preprocessor directive. This preprocessor directive is also used to
create macros in C.
Eg: #define A 45
Global declarations:- The variable declarations that are made outside the main are known as
global declarations. These variable values can be accesses outside the main () also.
main():- This is a special function name and should be included in the program. This is the first
function that will be executed when you run a program. Every C program should start with a
main().
{ and }:- All the C statements that form our program should be enclosed in { and } only.
Local declarations:-All the variables that are declared inside the main() are known as local
declarations. These can be accessed only in the main() and not outside the main().
Executable statements:- All the input and output statements, expressions that form our actual part
of the program are known as executable statements.

Rules For Writing A ‘C’ Program


1. All the C statements should be written in lowercase only.
2. C program should contain at least one main ( ).
3. The executable statements are enclosed in open brace ({ )and close brace( }).
4. Every statement should end with a semi colon (;)
5. We can write any number of statements in a single line separating them with a semi colon.
6. We can also write a single statement in multiple lines ending each line with a ‘\’.
7. The comments are written in between /* and */. We can write comments anywhere in the
program. These statements are ignored by the system. Comments are used to describe the
program, to describe a statement or to ignore some statements in the program.
C Tokens
In C program, the smallest individual units are known as C tokens. C has following tokens.
1) Character set
2) Identifiers
3) Keywords
4) Datatypes
5) Variables
6) Constants
7) Format Specifiers
8) Escape sequences
9) Operators
1) Character set:- The characters that can be used to form words, numbers and expressions
depend upon the computer on which the program is run. C uses the upper case letters from A to
Z, lower case letters from a to z, 0 – 9 digits and certain special characters as building blocks to
form basic program elements. Eg: constants, variables, expressions etc. The special characters
are +, -, *, / , =, %, &, #, !, ?, ^, “, ‘ | <, >, etc.

Computer Programming 10
Anitha Vemulapalli KL University, Hyd

2) Identifiers:- Identifiers are the names that are given to various program elements such as
variables, functions and array. These are user defined names and consist of a sequence of letters
and digits. Both upper case and lower case letters are permitted. The following are the rules for
identifiers.
i) An identifier should not contain a blank space.
ii) We can use underscore( _ ) in an identifier.
iii) The first character should be an alphabet or an underscore( _ ). It should not be a number.
iv) They cannot use a keyword.
v) They can be of any length but first 31 characters are significant.
3) Keywords:- C has certain reserved words which are known as keywords that have some
special meaning in C. These are used only for their intended purpose and not for naming a
variable, functions or constants. There are 32 keywords in ANSI (American National Standard
Institute) C which are as follows.
auto double int struct
break else long switch
case enum register typedef
char extern return union
constant for short unsigned
continue float signed void
default goto size of volatile
do if static while
4)Datatypes:- Computer programs usually work with different types of data and need way to
store the values being used. These values can be numbers or characters. C language is rich in its
datatypes. The variety of datatypes available allows the programmer to select the type
appropriate to the needs of the application as well as the machine. The datatypes in C are
categorized as follows.
i) Primary data type Eg: int, float, char, long, double
ii) User defined data type Eg: typedef, enum
iii) Derived data type Eg: Structure and union
iv) Empty data set Eg: void
The primary datatypes are the basic datatypes and they are classified as int, long int, float, double
and char. Their types, size and range are listed in the table below.

Datatype Memory Range


Occupied
int 2 bytes -32768 to 32767
signed int 2 bytes -32768 to 32767
unsigned int 2 bytes 0 to 65535
long int 4 bytes -2,147,483,648 to 2,147,483,647
signed long int 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long int 4 bytes 0 to 4,294,967,295

Computer Programming 11
Anitha Vemulapalli KL University, Hyd

float 4 bytes 3.4E-38 to 3.4E+38


double 8 bytes 1.7E-308 to 1.7E+308
char 1 byte -128 to 127
signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 255

int:- It is used to store numbers without decimals. It occupies a memory of 2 bytes (16 bits) in the
RAM. This can be used in the signed or unsigned form. Its range is from -32768 to 32767. Eg:
25, -45, 356, etc. Signed int has the same size and range as int datatype. Out of 16bits, the first
15 bits are used to represent the data and the 16 th bit to the left side is used to represent the sign
of the value. If the bit position has a ‘0’, then it indicates a positive number and if it has a ‘1’, it
represents a negative number. The unsigned int has no sign and all the 16bits are used to
represent the data value. Its range is from 0 to 65535.
long int :- It is also used to store numbers without decimals. It is used to store values greater than
the ‘int’ datatype range. Its size is 4 bytes and its range is -2,147,483,648 to 2,147,483,647, etc.
Eg: 76, 12500, 45367, 65600 etc. It can also be used in the signed form or in the unsigned form.
float:- This datatype is used to store numbers with decimal values i.e, floating point values. It
occupies a memory of 4 bytes and its range is 3.4E-38 to 3.4E+38. Eg: 3.56, 1.28, 66.78 etc.
double:- This datatype is used to store numbers with decimal points more than the float range. It
occupies a memory of 8 bytes and its range is 1.7E-308 to 1.7E+308.
char:- It is used to store characters. It occupies a memory of 1 byte and its range is -128 to 127.
Eg: ‘r’,’U’, ‘P’, ‘a’ ‘&’,’%’, etc. Here the character range is specified as a number. These
numbers are the ASCII code of the characters. This can be in the signed form or in the unsigned
form.
5) Variables:- A variable is an identifier that is used to represent a specified type of data. A
variable is used to store a single data item, wither numeric data or character data. Each variable
in a program must be declared before they are used in a C program. The following is the syntax
to declare a variable.
Syntax for declaring a variable:-
datatype <var_name>;
Eg: int num;
float price;
char ch;
char city[15];
The datatype is the type of value we want to store in the variable. Var_name is the name of the
variable. Whenever, we declare a variable, memory will be allocated in the RAM which is equal
to the size of its datatype. To assign a value to a variable, we use ‘=’ symbol as shown below.
Eg: num=10;
price=28.50;
ch=’y’;
Rules to be followed while naming a variable
1. Variable name should consist of alphabets and numbers.

Computer Programming 12
Anitha Vemulapalli KL University, Hyd

2. We should not use spaces in a variable name.


3. No special characters are allowed in a variable name except underscore( _ ).
4. The first character should be an alphabet or an underscore( _ ).
5. Variable name should be unique.
6. It should be short and meaningful.
7. Variable names should be in lowercase only.
8. We should not use C keywords to name a variable like if, else, auto etc.
6) Constants:- Constants refer to values that do not change during the execution of a program.
We use the keyword ‘const’ to declare a constant. There are 4 basic types of constants in C. They
are:
i) Integer constants
ii) Floating point (real) constants
iii) Character constants
iv) String constants
Integer and floating point constants represent numbers and they are often called numeric
constants. The following rules apply to all numeric type constants.
a) Commas and blank spaces are not permitted within the constant.
b) The constant can be preceded by a minus (-) sign if required.
c) The value of a constant must be within its minimum and maximum bounds of its
specified datatype.
i) Integer constant:- an integer constant is an integer valued number. It consists of a sequence of
digits. Integer constants can be written in 3 different number system as decimal (base 10), octal
(base 8) and hexadecimal (base 16).
Decimal integer constants consist of a set of digits form 0 through 9. Eg: 0 1 -56
32767 1234789L 65121U (unsigned integer constant)
Octal integer constant consists of any combination of digits between 0 through 7 with a
leading 0. Eg: 0 01 03456 07777
Hexadecimal integer constant must begin with ox or OX. It can then be followed by any
combination of digits 0 through 9 and a through f (or A to F). The letter A to F represents
decimal values 10 through 15 respectively. Eg: ox0 0x1 oxAF
ii) Floating point integer constant:- It is a base 10 number that contains either a decimal point or
exponent (or both).
Decimal notation : 1234.56, exponent or scientific notation : 1.23456E+3 (1.23456 x 103)
Eg: 0. 1. 0.00001 345.67
iii) Character constants:- A character constant is a character enclosed within single quotes. Eg:
‘y’ The character constants have integer values that are determined by the computer’s particular
character set. These may vary from one computer to another. All personal computers make use
of the ASCII character set. Eg: ‘A’ ‘a’ ‘+’ ‘?’ ‘ ’ , ‘5’
iv) String constants:- A string constant or string literal is a sequence of zero or more characters
surrounded by double quotes. Eg: “kakatiya” “yes” “ ” (empty string) “05P11A256”
7) Format specifiers:- These are used in the input and output statements when working with
variables. The following are the format specifiers used in C to accept or retrieve the values from
the variables.
%d int used for integer datatype
%ld long int used for long int
Computer Programming 13
Anitha Vemulapalli KL University, Hyd

%f float used for float values


%lf double used for double
%c char used for a single character
%s string used for group of characters of char datatype
%u unsigned used for unsigned values like, to display memory addresses.
%o octal used to display octal equivalent of a decimal number
%x hexadecimal used to display hexadecimal equivalent of a decimal number
%i used to display decimal or hexadecimal or octal
%e used to display floating point number in exponential form
%g used to display floating point number with trailing zeroes truncated

8) Escape sequences:- C Supports some special backslash characters that are used in output
functions. An escape sequence always begins with a backslash and is followed by one or more
special characters. The following are some of the escape sequences.
\n new line character
\t Horizontal tab character
\v Vertical tab character
\a alert (bell sound)
\b backspace character (the cursor will be placed one character back)
\f form feed, (moves the cursor to the next line)
\r carriage return (moves the cursor to the starting of the line)
\’ single quote (prints a single quote)
\” double quote (prints double quotes removing the specialty of ‘\’)
printf():- This is an output statement. It is used to display the messages on the screen and also
used to display the values in the variables using the respective format specifiers.
Syntax:
printf( “control string “, arguments);
Control string may consist of format specifiers, escape sequences and some text. Arguments are
the variable names whose values we want to display. The printf( ) cane be used in different forms
as per our requirement.
Eg: printf(“\nHello”);
printf(“\nThe value is \t %d”, a);
printf(“\t”);

scanf():- This is an input statement used to enter or give values through the keyboard during run
time.
syntax:
scanf(“control string”, arguments);
Control string should consist of only format specifiers and should not consist of any special
characters. Arguments are the variables into which we want to store the values.
Eg: scanf(“%d%d”,&a,&b);
The ‘&’ symbol here is known as ‘address of’ operator and the value we give is stored in the
address of the variable.

Computer Programming 14
Anitha Vemulapalli KL University, Hyd

Programs using printf() and scanf()

/*program to display a simple text message */


#include <stdio.h>
#include <conio.h>
main( )
{
printf(“\nHello, Welcome to All”);
printf(“\nThis is C Program”);
printf(“\nGood Luck to All”);
}

/*program to find the sum of 2 numbers*/


#include <stdio.h>
#include <conio.h>
main( )
{
int a,b,sum;
clrscr( );
printf(“\nEnter 2 numbers”);
scanf(“%d%d”,&a,&b);
sum=a+b;
printf(“\nSum of %d and %d is %d”,a,b,sum);
getch( );
}

Steps involved in executing a C program:- A ‘C’ program has to pass through many phases
for its successful execution and to achieve desired output. The phases or steps required for
successful execution of a C program can be visualized as follows:

Editing the program

Compiling the program

Linking the program

Executing the program

Computer Programming 15
Anitha Vemulapalli KL University, Hyd

Editing Phase:- In the editing phase, the C program is entered into a file (i.e., source code)
through a text editor. The file is saved on the disk with an extension of ‘.c’. Corrections in the
program at later stages are done through these editors. Once the program has been written, it
requires to be translated into machine language (i.e., compilation phase).
Compilation Phase:- This phase is carried out by a program called compiler. Compiler
translates the source code into the object code (i.e., machine understandable code). The
compilation phase cannot be processed successfully until and unless the source code is error-free
(i.e., no syntactic and semantic errors). The compiler generates messages if it encounters
syntactic errors in the source code. The error-free source code is translated into object code and
stored in a separate file with an extension ‘.obj’.
Linking phase:- In this phase, the linker links all the files and functions with the object code
under execution. For example, if a user uses a ‘printf’ function in his/her program, the linker
links the user programs object code with the object code of the printf function available in the
‘stdio.h’ library. Now, the object code is ready for next phase i.e., execution phase.
Execution phase:- In this phase, the executable object code is loaded into the memory and the
program execution begins. We may encounter errors during the execution phase, even though
compilation phase is successful. The errors may be runtime errors and logical errors.
The process of execution of a C program can be represented by a flow chart as follows:

Start

Editing Source Code

Compiling Source code

Yes
Errors?

No
System Linking object code
Library

Loading object code


Input
Executing object code

Data Yes
Errors?

No
Output

Stop
Computer Programming 16
Anitha Vemulapalli KL University, Hyd

After writing a C program in editor, you have to save the file. The default filename is
noname.c . To save the file press ‘F2’ or select ‘save’ option from ‘File’ menu. The name we
give is taken as the filename with the extension .c. One more file is created with the same name
and with the extension .bak. After saving a file, you have to compile it, by pressing Alt+F9 or
using ‘compile to obj’ option from compile menu. It will convert the total source program (user
program) into object code (machine language) and gives the errors if present any in the program.
While compiling it, it creates a file with the extension .obj with the same name as the filename.
After removing the errors, finally, it will create an executable file with the same name as the C
file and with extension .exe. To get the output of the program, you have to run the file. This you
can do by pressing, Ctrl+F9 or using ‘run’ option from ‘run’ menu.
After executing the file, you will be back to your program. To see the result of
your program, you have to press Alt+F5 which will take you to the user screen where output will
be displayed. If you give a getch() command at the end of program before the ending brace,
there is no need for you to use Alt+F5.

Types of errors:-There are different types of errors encountered in any programming language.
There are 3 types of errors which are described below.
1) Syntactic errors:- Syntactic errors are found quickly at the time of compiling the program.
These errors occur due to the usage of wrong syntaxes for the statements.
Eg: x= a * y +b
The syntax error here is, semi colon (;) is missing at the end.
2) Runtime errors:- These errors may occur during the execution of programs even though the
program is successfully compiled without syntax errors. The most common types of runtime
errors are eg: (1) Array range out of bound (2) Divided by zero
3) Logical Errors:- These occur due to incorrect usage of the instructions in the program. These
errors are neither detected during compilation or execution nor cause any stoppage to the
program execution. They only produce incorrect outputs. When the program ends up with
incorrect outputs, the logical errors are the most probable reason. Logical errors are to be
detected by analyzing the outputs for different possible inputs that can be applied to the program.
This is considerably a difficult task.

OPERATORS IN ‘C’
Expression:- An expression consists of a single entity such as a constant, a variable, an array
element or a reference to a function or can be a combination of such entities joined together
using one or more operators. An expression can also represent logical condition, that is either
true or false, which can be represented using integer values like ‘1’ and ‘0’ respectively. Some of
the examples are as follows:
1) c= a+b*d;
2) x=y;
3) a = = b;
4) a+=b;
C supports a rich set of built-in operators. An operator is a symbol that tells the computer to
perform certain mathematical or logical manipulations. Operators are used in programs to

Computer Programming 17
Anitha Vemulapalli KL University, Hyd

manipulate data and variables. They form a part of mathematical or logical expressions. The data
items that operators act upon are called operands (variables & constants). C operators can be
classified into the following categories:
1) Arithmetic Operators
2) Relational Operators
3) Logical Operators
4) Unary Operators
5) Assignment Operators
6) Conditional Operator or Ternary Operator
7) Bitwise Operators
8) Special operators

1) Arithmetic Operators:- C provides all the basic arithmetic operators. The different arithmetic
operators are those which we generally use in mathematics like + (addition), - (subtraction), *
(multiplication), and / (division). Apart from these, there is another operator % which is
known as modulus operator. This modulus operator gives you the remainder after division.
2) Relational Operators:- We often compare two quantities and depending on their relation,
take certain decisions. These comparisons can be done with the help of relational operators.
The relational operators that we use in C are to relate two operands are <(less than), >
(greater than), <= (less than or equal to), >= (greater than or equal to), = = (equal to) and !=
(not equal to). The double equal to (= =) is used to compare the equality of the operands and
is known as the equality operator.
3) Logical Operators:- The logical operators are used to check for more than one condition
at a time. The different logical operators available in C are logical AND (&&), logical
OR(||) and logical NOT(!). The && operator returns true when all the conditions are
satisfied only. The || operator returns true when any of the condition is true and
returns false only when all the conditions are false. The following table shows the
operations of these operators.
condition 1 condition2 condition1 condition 1 !condition1
&& ||
condition2 condition 2
F F F F T
F T F T T
T F F T F
T T T T F

4) Unary Operators:- The unary operators available in C are – (unary minus i.e., negative sign),
++ (increment operator) and -- (decrement operator). These operators work on a single
operand. The unary minus (-) is used to assign a negative value to a variable.
Eg: a=5; b = -a;  It stores –5 in ‘b’.
Increment Operator(++):- This operator increments the operand value (variable value) by 1.
There are 2 types of increment operators. (a) Pre increment operator and (b) Post increment
operator.

Computer Programming 18
Anitha Vemulapalli KL University, Hyd

The Pre increment operator first increments the operand value by 1 and then
assigns the operand value to the Left Hand Side (LHS) variable. The operator is placed
before the variable. The following example illustrates this.
main()
{
int a=5,b;
b=++a;
printf(“\na=%d”,a);
printf(“\nb=%d”,b);
}
In the above program the values are 6 and 6 in ‘a’ and ‘b’ respectively.
The Post decrement operator first assigns the value to the variable on the LHS and
then the increments the operand value by 1. The operator is placed after the operand.
main()
{
int a=5,b;
b=a++;
printf(“\na=%d”,a);
printf(“\nb=%d”,b);
}
In the above program the values in ‘a’ and ‘b’ are 6 and 5 respectively.
Decrement Operator:- This is similar to increment operator but here the operand value is
decremented by 1. Here also we have 2 types of decrement operators and they are pre
decrement and post decrement operators.
The Pre decrement operator function is similar to pre increment operator but here
the value is decremented. In this, first value in the operand (variable) is decremented and
then assigned to the LHS variable. The following example illustrates this.
main()
{
int a=5,b;
b=--a;
printf(“\na=%d”,a);
printf(“\nb=%d”,b);
}
In the above program the values are 4 and 4 in ‘a’ and ‘b’ respectively.
The Post decrement operator first assigns the value to the LHS variable and then
the value of the operand is decremented.
main()
{
int a=5,b;
b=a--;
printf(“\na=%d”,a);
printf(“\nb=%d”,b);
}
In the above program the values in ‘a’ and ‘b’ are 5 and 4 respectively.

Computer Programming 19
Anitha Vemulapalli KL University, Hyd

5) Assignment Operators:- These operators are used to assign a value or the result of an
expression to another variable. The basic assignment operator is =. Apart from this operator,
there are otther assignment operators such as +=, -=, *=, /= and %=. These operators
perform the respective operations on the variables and again store the result in the same
variable. Here, we require only one variable.
Eg: a+=5 indicates that a value of 5 is added to the variable ‘a’ and again the result is
stored in the same variable. i.e. a+=5;  a=a+5;
Similarly,
a-=5;  a=a-5;
a*=4;  a=a*4;
a/=10;  a=a/10;
a%=6;  a=a%6;

6) Conditional Operator (Ternary operator)(? : ) :- Using this operator, we can check a


condition and depending on the condition, the respective statements can be executed. If the
condition is true it executes the statement present in the ‘statement_if_true’ and if it is false,
it executes the statement present in the ‘statement_if_false’.
Syntax:
(condition? Statement_if_true : Statement_if_false);
Eg:
main()
{
int a,b;
clrscr();
printf(“\nEnter 2 values :”);
scanf(”%d%d”,&a,&b);
(a>b)? printf(“\n%d is big”,a):printf(“\n%d is big”,b);
getch();
}
7) Bitwise operators:- C supports special operators known as bitwise operators for manipulation
of data at bit level. These operators are used for testing the bits or shifting them right or left.
These operators are not applied to float or double. These work on the values by converting
them into binary numbers (0s and 1s). The different bitwise operators are Bitwise AND(&),
Bitwise Or(| ) and bitwise negation(~), Bitwise X-OR(^), <<(left shift) and >>(right shift).
The & operator gives 1 when the two bits in the corresponding positions of two variables is
equal to 1 otherwise it will give 0 in that position.
Eg:
A B A&B
0 0 0
0 1 0
1 0 0
1 1 1

The | operator gives 1 when two variables contain a 1 or 0 in their respective positions. We
get 0 when those are 0 only.

Computer Programming 20
Anitha Vemulapalli KL University, Hyd

Eg:
A B A|B
0 0 0
0 1 1
1 0 1
1 1 1
The ~ operator gives 1 when it is 0 and 0 when it is 1.
Eg:
A ~A
0 1
1 0
The ‘^’ operator returns 1 only when either of the bits has 1 or 0 only, but not both, i.e., it
returns 0 when all are 0s or all are 1s in the respective positions of the variables.
Eg:
A B A^B
0 0 0
0 1 1
1 0 1
1 1 0

The ‘<<’ operator shifts the specified number of bits to left side. Left shift of 1 bit is nothing
but multiplying by 2.
The ‘>>’ operator shifts the specified number of bits to right side. Right shift of 1 bit is
nothing but dividing by 2.

Example:
main(){int a,b,c;clrscr();
printf("\nEnter 2 values :");
scanf("%d%d",&a,&b);
c=a&b;
printf("\nAfter bitwise AND, c : %d",c);
c=a|b;
printf("\nAfter bitwise OR : %d",c);
c=a^b;
printf("\nAfter bitwise X-OR : %d",c);
c=~a;
printf("\nAfter negation of a : %d",c);
c=a<<1;
printf("\nLeft shift a, c : %d",c);
c=a>>1;
printf("\nRight shift a, c : %d",c);
getch();
}

Computer Programming 21
Anitha Vemulapalli KL University, Hyd

8) Special operators:- C supports some special operators like Comma(,) , sizeof(), pointer
operators (& and *) and member selection operators (. and ->). Comma (,) is used to separate
the variable names in the declaration when they are of same datatype. Sizeof() is used to find
the memory occupied by a variable or a datatype.
Precedence of operators:- Each operator in C has a precedence associated with it. This
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 at higher level of precedence are evaluated first. The operators of the same
precedence are evaluated either from ‘left to right’ or from ‘right to left’ depending on the level.
This is known as the associativity property of an operator. The following table shows the
different ranks (levels) and the associativity of the operators.
Operator Description Associativity Rank
() Function call Left to Right 1
[] Array elements reference Left to Right 1
+ Unary plus Right to Left 2
- Unary minus Right to Left 2
++ Increment operator Right to Left 2
-- Decrement operator Right to Left 2
! Logical negation Right to Left 2
~ Ones complement Right to Left 2
* Pointer reference Right to Left 2
& Address of operator Right to Left 2
Sizeof Size of an object Right to Left 2
(type) Type cast (conversion) Right to Left 2
* Multiplication Left to Right 3
/ Division Left to Right 3
% Modulus operator Left to Right 3
+ Addition Left to Right 4
- Subtraction Left to Right 4
<< Left shift Left to Right 5
>> Right shift Left to Right 5
< Less than Left to Right 6
<= Less than or equal to Left to Right 6
> Greater than Left to Right 6
>= Greater than or equal to Left to Right 6
== Equality Left to Right 7
!= Inequality Left to Right 7
& Bitwise AND Left to Right 8
^ Bitwise XOR Left to Right 9
| Bitwise OR Left to Right 10
&& Logical AND Left to Right 11
|| Logical OR Left to Right 12
?: Conditional expression Right to Left 13
=, *=, /=, %=, Assignment operators Right to Left 14

Computer Programming 22
Anitha Vemulapalli KL University, Hyd

+=, -=. &=,


^=, |=
, Comma operator Left to Right 15

Type conversion:- Type conversion means converting one form of datatype to another form. In
C we have two types of type conversions. They are implicit and explicit conversion.
Implicit conversion:- C automatically converts any intermediate value to the proper type so that
the expression can be evaluated without losing any significance. This automatic conversion is
known as implicit type conversion. During evaluation it adheres to very strict rules of type
conversions. 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.
Explicit conversion:- Sometimes, we want to force a type conversion in a way that is different
from the automatic conversion. This conversion is known as explicit conversion or type casting.
Following is the syntax for explicit conversion.
(type_name) expression;
Here, ‘type_name’ is one of the standard C datatypes. The ‘expression’ may be a constant,
variable or an expression.

CONSTRUCTS OR CONTROL STATEMENTS


Control statements are used to control the flow of execution of the program. In C language, the
control statements are divided into 2 types. They are (i) Branching statements and (ii) Looping
statements.
(i) Branching statements:- Branching statements are used when we want to move the control
from one part of the program to other part of the program either conditionally or unconditionally.
The branching statements are again classified into conditional statements and unconditional
statements.
a) Conditional statements:- The conditional statements jumps the control from one part to
another part of the program on a given condition. There are two types of conditional statements
in C.
i) If statement
ii) Switch statement
b) Unconditional statement:- The unconditional statement jumps the control from one part of
the program to another part unconditionally. ‘Goto’ statement comes under unconditional
statement.

1) If statement:- There are 4 types of ‘if’ statements used in C language. They are (a) simple if
(b) if else (c) ladder if (if else if else) and (d) nested if.

a) Simple if:-In simple if , we check an expression and when it is true, the control enters into the
‘if’ block and executes the statements in the block and then comes out of ‘if’ and executes the
statements present after the ‘if’ block. When the condition is false nothing is done and the
statements after the ‘if’ block gets executed.
Syntax for simple if:
if(expression)

Computer Programming 23
Anitha Vemulapalli KL University, Hyd

{
statement 1;
statement 2;
----------
----------
statement n;
}
Pointes to remember while using conditional statement:
1) Condition should be in ( ).
2) Condition should not end with semi colon (;)
3) When there are more than one statement to be executed when the condition is true then, we
have to enclose them in { and }. If we have only one statement then there is no need of { }.

/*Program to display biggest of 2 numbers*/


#include <stdio.h>
#include <conio.h>
main()
{
int a,b;
printf(“\nEnter 2 values :”);
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“\n%d is bigger”,a);
printf(“\nEnd of program”);
}

b) if else:- In this type of statement, the control checks the condition. If it is true, it executes the
statements present in the ‘if’ block otherwise it executes the statements present in the ‘else’
block.
Syntax:
if(expression)
{
statement 1;
statement 2;
----------
statement n;
}
else
{
statement 1;
statement 2;
----------
statement n;
}
/*Program to display biggest of 2 numbers*/

Computer Programming 24
Anitha Vemulapalli KL University, Hyd

#include <stdio.h>
#include <conio.h>
main()
{
int a,b;
printf(“\nEnter 2 values :”);
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“\n%d is bigger”,a);
else
printf(“\n%d is bigger”,b);
printf(“\nEnd of program”);
}
c) Ladder if (if else if else):- This type of statement is used to check more than one condition
when a condition is not satisfied. First, the control checks the first expression. If it is true, it
executes the statements present in the block following it and when it is false, it will check the
next expression or condition which is given in ‘else if’. If it is also false, it checks the next
condition present in next ‘else if’ and so on. If a matching condition is found, it executes the
statements in the respective block. If it does not find a match, then it executes the statements
which are present in ‘else’ block. The else block is optional.
Syntax:
if(expression 1)
{
statement 1;
statement 2;
----------
statement n;
}
else if(expression 2)
{
statement 1;
statement 2;
----------
statement n;
}
else if(expression 3)
{
statement 1;
statement 2;
----------
statement n;
}
else
{
statement 1;

Computer Programming 25
Anitha Vemulapalli KL University, Hyd

statement 2;
----------
statement n;
}

c) Nested if :- Using an ‘if’ statement inside another ‘if’ statement is known as ‘nested if’. The
‘if’ statement may be any type of ‘if’ statement. The following is one of the forms of nested if.
syntax:
if(expr 1)
{
if(expr 2)
{
statement 1;
statement 2;
----------
statement n;
}
else
{
statement 1;
statement 2;
---------
statement n;
}
}
else
{
if(expr 2)
{
statement 1;
statement 2;
----------
statement n;
}
else
{
statement 1;
statement 2;
---------
statement n;
}
}
/*program to find the biggest of 3 numbers*/
#include <stdio.h>
#include <conio.h>

Computer Programming 26
Anitha Vemulapalli KL University, Hyd

main()
{
int a,b,c; clrscr();
printf(“\nEnter 3 values :”);
scanf(“%d%d%d”, &a,&b,&c);
if(a>b)
{
if(a>c)
printf(“\n%d is bigger”,a);
else
printf(“\n%d is bigger”,c);
}
else
{
if(b>c)
printf(“\n%d is bigger”,b);
else
printf(“\n%d is bigger”,c);
}
getch();
}

2) Switch case:- It is also similar to ladder if, but here we cannot check the logical and relational
expression. It is used to check whether the value in the variable is matching with the case value
or not. This statement directly goes to the matching case value, executes the statements in that
case and comes out of the switch. If no case value matches, it executes the statements present in
the ‘default’ block.
Syntax:
switch(variable)
{
case value1:
statements
break;
case value2:
statements
break;
case value3:
statements
break;
case value4:
statements
break;
default :
Statements
}

Computer Programming 27
Anitha Vemulapalli KL University, Hyd

If we do not use a ‘break’ statement, all the statements in all the cases will be executed whether
the case value matches or not. That is why we have to terminate each case with a ‘break
statement except the default case which is present at the end of the case. In switch, default can be
given anywhere, in such a case, we have to give a break statement in the default block.
Eg: main()
{
int no; clrscr();
printf(“\nEnter a number :”);
scanf(“%d”,&no);
switch (no)
{
case 1:
printf(“\nIt is Sunday”);
break;
case 2:
printf(“\nIt is Monday”);
break;
case 3:
printf(“\nIt is Tuesday”);
break;
case 4:
printf(“\nIt is Wednesday”);
break;
case 5:
printf(“\n It is Thursday”);
break;
case 6:
printf(“\nIt is Friday”);
break;
case 7:
printf(“\nIt is Saturday”);
break;
default :
printf(“\n Invalid choice “);
}
getch();
}
If you want to check the case values of character data type, then you have to enclose the values
in ‘single quotes’ Eg: case ‘a’: .
Goto statement:-The goto command comes under the unconditional branching statement. Along
with goto command, we have to specify the label name also, where the control has to shift for
executing the statements. We can use goto to come out of a loop but, we cannot use goto to enter
into a loop directly.

Computer Programming 28
Anitha Vemulapalli KL University, Hyd

While executing the statements in the program, when it encounters goto, the control shifts
to the location specified by the label name. When the location is after these executable
statements, then this type of branching is known as forward branching.
goto label;
--------
--------
label:
-------
------
When the label is present previous to these executable statements as shown below, then
this type of branching is known as backward branching. In this type, care must be taken to come
out of the loop otherwise the system gets hanged up in the loop.
label :
-------
-------
goto label;
Eg:/*program to find the square roots of the first 5 numbers*/
#include<math.h>
main(){
int count=1,a;
read:
printf(“\nEnter a number :”);
scanf(“%d”, &a);
printf(“\nSquare root of %d is %d”,a,sqrt(a));
count++;
if(count<=5)
goto read;
getch();
}

Looping statements:- The loops are used when we require some group of statements to be
executed repeatedly for a particular number of times. While loop, do while loop and for loop are
known as iterative loops. In C, loops are categorized into 2 types as Entry control loop and Exit
control loop. In the entry control loop, when the condition is satisfied only the statements are
executed, otherwise it will come out of the loop. The ‘while’ loop comes under ‘entry control
loop’. In the exit control loop, when the condition is satisfied or not the statements are executed
at least once. The ‘do while’ loop comes under ‘exit control loop’.
1) While Loop:- In this loop, when the condition is satisfied, the controls enters into the loop
and executes the statements inside it. After executing the statements, again it goes for checking
the condition. If the condition is true again, it enters into the loop, executes the statements there
and again checks the condition. This process goes on until give condition or expression becomes
false. When using loops, care must be taken to use a statement in the loop that makes the
condition false at some point so that control comes out of the loop. Otherwise, it becomes an
infinite loop and we have to use ‘ctrl+break’ to come out of the loop.
Syntax:

Computer Programming 29
Anitha Vemulapalli KL University, Hyd

while(expression)
{
statement 1;
statement 2;
----------
statement n;
}
/*program to display numbers from 1 to 10*/
#include <stdio.h>
#include <conio.h>
main()
{
int i=1,n;
clrscr();
printf(“\nEnter a number :”);
scanf(“%d”,&n);
while( i<=n)
{
printf (“\n%d”,i );
i++;
}
getch();
}
2) Do while loop:- In this type of loop, the statements are executed first and then the expression
is checked. If it is true, the control enters into the loop and executes the statements present in it.
If it is false, it will not enter into the loop and comes out of the loop. In this way, the statements
are executed at least once, even though the condition is not satisfied.
Syntax:
do
{
statement 1;
statement 2;
----------
statement n;
} while(expression);
/*program to display the sum of squares of numbers till the given number*/
Eg: main()
{
int n, i=1,sum=0;
clrscr();
printf(“\nEnter the number :”);
scanf(“%d”,&n);
do{
sum=sum+( i*i);
i++;

Computer Programming 30
Anitha Vemulapalli KL University, Hyd

}while(i<=n);
printf(“\nSum of squares is %d”,sum);
getch(); }
3) For loop:- It is the most flexible, simple and mostly used loop. All the three, i.e.,
initialisation, condition and iteration (incrementation / decrementation) are written in a single
statement. So there will be no problem of missing any statement as may be the case with other
loops.
Syntax:-
for(initialisation; condition; iteration)
{
statement 1;
statement 2;
----------
statement n;
}
In ‘for’ loop, first initialization is done and then the condition is evaluated. If it is true, the
control enters into the loop and executes the statements in the loop. After executing the
statements in the loop, the control goes to the iteration part and then checks the condition. If the
condition is true again, it enters into the loop and executes the statements there. This process
goes on until the given condition is satisfied.
We can initialize more than one variable in for loop by separating the variables with a
comma. Similarly, we can give more than one iteration statement, in such case separate them
with comma.
We can leave the initialization part blank for loop with a semi colon when the
initialization is done before only. Similarly, it is the case with iteration also.

Eg: /*program to display numbers from 1 to 10*/


main()
{
int i,n;clrscr();
printf(“\nEnter a number :”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
printf(“\n%d”,i);
getch();
}
Break:- The break statement is used to come out of the loop. When it is encountered in a loop,
the control comes out of the loop, even though the condition is satisfied.
Syntax:
break;
Continue:- It is also used in the loops. When the control encounters a continue statement, the
statements following this statement in the loop are skipped and the control goes to check for next
iteration condition.
Syntax:
continue;

Computer Programming 31
Anitha Vemulapalli KL University, Hyd

Exit():- This statement when encountered in the program terminates the program.
Syntax:
exit();

Computer Programming 32

You might also like