CP Module 1 Material
CP Module 1 Material
The term computer is derived from the word compute. The word
compute means to calculate. A computer is an electronic machine that
accepts data from the user, processes the data by performing calculations
and operations on it, and generates the desired output results.
Characteristics of Computer:
Speed: The computer can process data very fast, at the rate of millions of
instructions per second.
Diligence: When used for a longer period of time, It can perform long and
complex calculations with the same speed and accuracy from the start till
the end.
Reliability: It is measurement of performance of a computer, which is
measured against pre determined standards for operation without any
failure.
GENERATION OF COMPUTERS
First Generation:
Application They were used for scientific applications as they were the
fastest computing device of their time.
The first generation computers used a large number of vacuum tubes and
thus generated a lot of heat. They consumed a great deal of electricity and
were expensive to operate. The machines were prone to frequent
malfunctioning and required constant maintenance. Since first generation
computers used machine language, they were difficult to program.
Second Generation:
Second generation computers generated a lot of heat but much less than
the first generation computers. They required less maintenance than the
first generation computers.
Third Generation:
Hardware Technology The third generation computers used the
Integrated Circuit (IC) chips. Consist of single chip with many
components such as transistors, resistors & capacitors fabricated on it.
Punched cards & printouts are replaced by keyboards & monitors &
interfaced with operating system. Magnetic disks were used for secondary
storage.
The third generation computers used less power and generated less heat
than the second generation computers. The cost of the computer reduced
significantly, as individual components of the computer were not required
to be assembled manually. The maintenance cost of the computers was also
less compared to their predecessors.
Fourth Generation:
Hardware Technology
They use the Large Scale Integration (LSI) and the Very Large Scale
Integration (VLSI) technology. Thousands of transistors are integrated on
a small silicon chip using LSI technology. VLSI allows hundreds of
thousands of components to be integrated in a small chip. ULSI increased
that number into millions.
Uses an extension of third generation technology of this generation is
based on IC But these have been made readily available because of
development of the microprocessor (Circuit containing millions of
transistors).
Magnetic core memories were substituted by semiconductor memories
resulted in RAM.
Secondary memories –hard disk became economical, smaller & bigger in
capacity.
CLASSIFICATION OF COMPUTER
Based on applications:
General purpose computers: can work in all environments.
Special purpose computers: can perform only a specified task.
Micro-computer
Laptops (Notebook):
Same as PCs in functionality
More Compact, Portable
Less Power requirement, operated on battery/s
Less capacity compared to PCs
Maintenance and actually are costlier compared to PCs
Theft prone
Netbook:
These are smaller notebooks optimized for low weight and low cost,
and are designed for accessing web-based applications.
Tablet Computer:
It has features of the notebook computer but it can accept input from
a stylus or a pen instead of the keyboard or mouse.
It is a portable computer.
Minicomputers
Mainframe Computer
Mainframe computers are multi-user, multi-programming and high
performance computers.
They operate at a very high speed, have very large storage capacity
and can handle the workload of many users.
Mainframe computers are large and powerful systems generally used
in centralized databases.
It can support hundreds or thousands of users using the feature of
time sharing supported by systems like Linux.
Mainframes can concurrently run multiple programs even with a
single CPU. The processor speed in a mainframe is measured in
MIPS (million instructions per second).
The user accesses the mainframe computer via a terminal that may
be a dumb terminal, an intelligent terminal or a PC. A dumb
terminal cannot store data or do processing of its own. It has the
input and output device only. An intelligent terminal has the input
and output device, can do processing, but, cannot store data of its
own. The dumb and the intelligent terminal use the processing power
and the storage facility of the mainframe computer.
Mainframe computers are used in organizations like banks or
companies, where many people require frequent access to the same
data, on-line processing of large number of transactions & require
computer systems which have massive data storage & processing
capabilities.
Some examples of mainframes are CDC 6600 and IBM ES000 series.
Super Computers
Supercomputers are the fastest and the most expensive machines.
They have high processing speed compared to other computers.
The speed of a supercomputer is generally measured in FLOPS
(Floating point Operations per Second).
Some of the faster supercomputers can perform trillions of
calculations per second. A supercomputer uses multiple CPUs for
parallel data processing, which means portions of the same program
are handled independently by multiple processors.
Supercomputers are used for highly calculation-intensive tasks, such
as, weather forecasting, Analysis of geological data, climate research
(global warming), molecular research, biological research, nuclear
research and aircraft design.
They are also used in major universities, military agencies and
scientific research laboratories.
Some examples of supercomputers are IBM Roadrunner, IBM Blue
gene and Intel ASCI red.
PARAM is a series of supercomputer assembled in India by C-DAC
(Center for Development of Advanced Computing), in Pune. PARAM
Padma is the latest machine in this series. The peak computing
power of PARAM Padma is 1 Tera FLOP (TFLOP).
The user interacts with the computer via the I/O unit. The Input unit
accepts data from the user, into a form that is understandable by the
computer. Input devices are classified as follows
Human data entry devices
Input devices that require data to be entered manually to the computer are
identified as human data entry devices.
Keyboard
Pointing devices—mouse, trackball, joystick, digitizing tablet
Pick devices—light pen, touch screen
Source data entry devices
Source data entry devices do not require data to be typed-in, keyed-in or
pointed to a particular location.
Audio input—speech recognition
Video input—digital camera
Scanner—hand-held scanner, flat-bed scanner
Optical Scanner—OCR, OMR, MICR, barcode reader
Output unit
Output devices provide output to the user, which is generated after
processing the input data.
The processed data, presented to the user via the output devices
could be text, graphics, audio or video.
Output devices are classified as follows
Hard Copy Devices
The output obtained in a tangible form on a paper or any surface is called
hard copy output.
Printer
Plotter
Computer Output on Microfilm (microfiche)
Soft Copy Devices
The output obtained in an intangible form on a visual display, audio unit or
video unit is called soft copy output.
Monitor
Visual Display Terminal
Video Output
Audio Response
Control Arithmeti
Unit c Logic
Unit
Registers
Primary Memory
Primary memory is the main memory of computer. It is used to store
data and instructions during the processing of data. Primary memory
is semiconductor memory.
Primary memory is of two kinds—Random Access Memory (RAM) and
Read Only Memory (ROM).
RAM is volatile. It stores data when the computer is on. The
information stored in RAM gets erased when the computer is turned
off. RAM provides temporary storage for data and instructions.
ROM is non-volatile memory, but is a read only memory. The storage
in ROM is permanent in nature, and is used for storing standard
processing programs that permanently reside in the computer. ROM
comes programmed by the manufacturer.
RAM stores data and instructions during the execution of instructions.
The data and instructions that require processing are brought into the
RAM from the storage devices like hard disk. CPU accesses the data
and the instructions from RAM, as it can access it at a fast speed than
the storage devices connected to the input and output unit.
The input data that is entered using the input unit is stored in RAM,
to be made available during the processing of data. Similarly, the
output data generated after processing is stored in RAM before being
sent to the output device. Any intermediate results generated during
the processing of program are stored in RAM.
RAM provides a limited storage capacity, due to its high cost.
Secondary Memory
The secondary memory stores data and instructions permanently. The
information can be stored in secondary memory for a long time
(years), and is generally permanent in nature unless erased by the
user. It is a non-volatile memory.
It provides back-up storage for data and instructions. Hard disk drive,
floppy drive and optical disk drives are some examples of storage
devices.
The data and instructions that are currently not being used by CPU,
but may be required later for processing, are stored in secondary
memory.
Secondary memory has a high storage capacity than the primary
memory.
Secondary memory is also cheaper than the primary memory.
It takes longer time to access the data and instructions stored in
secondary memory than in primary memory.
Magnetic tape drives, disk drives and optical disk drives are the
different types of storage devices.
Instruction
A computer program is a set of instructions that describe the steps to
be performed for carrying out a computational task. The program and
the data, on which the program operates, are stored in main memory,
waiting to be processed by the processor. This is also called the stored
program concept.
A processor has a set of instructions that it understands, called as
instruction set.
The primary responsibility of a computer processor is to execute a
sequential set of instructions that constitute a program. CPU executes
each instruction in a series of steps, called instruction cycle.
Fetching: The processor fetches the instruction from the memory.
The fetched instruction is placed in the Instruction Register.
Program Counter holds the address of next instruction to be
fetched and is incremented after each fetch.
Decoding: The instruction that is fetched is broken down into
parts or decoded. The instruction is translated into commands so
that they correspond to those in the CPU’s instruction set. The
instruction set architecture of the CPU defines the way in which
an instruction is decoded.
Executing: The decoded instruction or the command is executed.
CPU performs the operation implied by the program instruction.
For example, if it is an ADD instruction, addition is performed.
Storing: CPU writes back the results of execution, to the
computer’s memory.
A CPU performance is measured by the number of instructions it
executes in a second, i.e., MIPS (million instructions per second), or
BIPS (billion instructions per second).
Part of the computer that are responsible for processing or converting
data into meaningful information.
Processor
Buses
System Clock
Processor
CPU referred to as a Processor Performs processing and control
activities performed by different parts of computer.
Buses
Electrical pathway that transfer data and instructions among
different parts of computer.
Main memory is directly/indirectly connected to the processor via a
bus.
Data Bus - Data bus is Bidirectional because the Microprocessor
can read data from memory or write data to the memory.
Address Bus - Address bus is Unidirectional because the
microprocessor is addressing a specific memory location.
Control Bus – Control the activities all the software's and
hardware’s
System Clock – Clock used to synchronizing the activities performed by
the computer.
Factors that affect the performance of the computer
Registers - The bigger the size, the more quickly it can process data.
RAM - Larger the RAM size when the computer is switched on, the
operating system, device drivers, the active files and running programs are
loaded into RAM is very fast.
System Clock- Higher clock frequencies mean more clock ticks per
second. A CPUs performance is measured by the number of instructions it
executes in a second
Bus - The data bus width affects the speed of computer.
Cache memory – Size (amount of cache memory) and level L1, L2 and L3.
Larger the size of cache, the better it is. PCs nowadays have a L1 cache of
256KB and L2 cache of 1MB.
Computer Language
Low-Level Languages:
• Supports low level tasks such as transferring data from memory to
disk, or rendering text onto a display.
• Low level language is machine dependent i.e. a program written for
one type of computer does not work on other computers.
Machine Language –
• First Generation Language Instructions are represented by
combinations of 0’s and 1’s.
• Machine languages are the only languages understood by computers.
Assembly Language –
• Second Generation Language. Machine language instructions are
replaced with simple pneumonic abbreviations (e.g. ADD, MUL, DIV
etc…).
• Computer can’t execute it directly. Programs need to translate into
machine language to run. Assembler translates assembly language
into Machine codes.
High-Level Languages:
• Any language that is independent of the machine such as C, C++,
and Java.
• High level languages uses English like statements and mathematical
notations.
SOFTWARE
System Software
System software is "Background" software that helps the computer
manage its own internal resources.
It enables the application software to interact with the computer
hardware. E.g. Operating System, Device Drivers, Utility Software,
and Translators etc...
Most system software is run by the computer on startup, first from a
ROM and then from the hard disk. The others are invoked when
programs need them, say, for printing a report. In some cases, a user
may also directly use a program of this type. System software
includes but is not restricted to the following:
Application Software
Program Logic
• Logic is a just an idea or a blue print for a part of a program which
consists of set of instructions to solve the given problem.
• Logic of the program consists of the statements which will be then
converted into programming language statements that will be
executed by the computer in order to solve the problem.
Problem formulation:
Top down analysis: Subdivide the large problem into several small tasks
or parts for ease of analysis.
Two essential ideas in top down analysis:
Subdivision of a problem
Hierarchy of tasks
Four steps in top down analysis:
Step 1: Define the complete scope of the problem to determine the basic
requirement for its solutions.
Input: what data is required to be processed by the program?
Process: What must be done with the input data? What type of processing
is required?
Output: What information should the program produce? In what form
should it be presented?
Step 2: Based on the definition of the problem, divide the problem into two
or more parts/tasks.
Step 3: Define the scope of ease of these tasks and subdivide them further
if necessary, divide into two or more smaller tasks.
Step 4: Repeat step 3 at lowest level describes a simple tasks, which
cannot be broken further.
Algorithms
An algorithm is a
well organized,
Set of step-by-step instructions that perform a specific task or
operation
Natural language NOT programming language
It helps the programmer in breaking down the solution of a problem into a
number of sequential steps.
Features:
Finiteness. An algorithm must always terminate after a finite
number of steps.
Definiteness. Each step of an algorithm must be precisely defined;
the actions to be carried out must be rigorously and unambiguously
specified for each case.
Input. An algorithm has zero or more inputs, i.e., quantities which
are given to it initially before the algorithm begins.
Output. An algorithm has one or more outputs i.e, quantities which
have a specified relation to the inputs.
Effectiveness. An algorithm is also generally expected to be
effective. This means that all of the operations to be performed in the
algorithm must be sufficiently basic that they can in principle be done
exactly and in a finite length of time.
Properties of an algorithm:
No ambiguity
No uncertainty about which instruction to be executed next(written
in sequence)
Conclude after a finite number of steps(algorithm will terminate)
General enough to deal with any contingency
Factors used to measure the algorithm:
Time
Memory
Accuracy
Sequence etc,.
Flowcharts:
It is the pictorial representation of an algorithm in which steps are
drawn in the form of different shapes of boxes and the logical flow is
indicated by interconnecting arrows.
Boxes represent operations
Arrows represent sequence in which operations are implemented
Primary purpose : help programmer in understanding the logic
Flowchart=Blue print of building
Flowchart Symbols:
Terminal symbol
It is used to represent the start, end of the program logic.
Input/output
It is used for input or output.
Process Symbol
It is used to represent the calculations, data movements,
initialization ope rations etc,.
Decision Symbol
It is used to denote a decision to be made at that point
Flow lines
It is used to connect the symbols
Connectors
It is used to connect the flow lines.
Loop
It is used to denote loops involved in the process.
Benefits of Flowcharts:
Makes logic clear
Communication: Flowcharts are better way of communicating the
logic of a system
Effective analysis: Problem can be analyzed in more effective way.
Proper documentation: Flowcharts serve as a good program
documentation
Efficient Coding: Flowcharts act as a guide or blueprint during the
systems analysis and program development phase.
Proper testing and Debugging: Flowchart helps in debugging
process.
Efficient Program Maintenance: The maintenance of operating
program becomes easy with the help of flowchart.
Sequence
All the instructions are executed one after another is called sequence
execution.
Example: Add two numbers
Step 1: Start
Step 2: get a,b
Step 3: Calculate c=a+b
Step 4: Display c
Step 5: Stop
Selection
Mainfunction()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop
Step1:Function start
Step2:Get a,b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return
Examples:
Algorithm Flowchart Pseudocode
Addition of two numbers
Step1: Start READ a,b
Step2: Read two C=a+b
numbers say a, b WRITE C
Step3: Add the value of STOP
a with b and store the
result in c.
Step4: Display the
value of c
Step5: Stop
Odd or even
Step 1:Start START
Step 2: read a Number READ number
Step 3:if (Number%2) IF number MOD 2=0 THEN
is 0,Print/Show as DISPLAY “ Even Number”
even number else ELSE
show as odd number DISPLAY “Odd Number”
Step 4: Stop END IF
STOP
Largest number among 3 numbers
Step1: Start READ a, b, c
Step2: Read the IF (a>b) and (a>c) THEN
value of a, b, c WRITE a is largest
Step3: Check if ELSE IF (b>c) THEN
(a>b) and (a>c) WRITE b is largest
then, print a is ELSE
largest WRITE c is largest
else check if (b>c) ENDIF
then, print b is STOP
largest
else
print c is largest
Step4: Stop
History of C
Ken Thompson created the B language in 1969 from martin Richard’s BCPL (Basic
Combined Programming Language). He used assembly language and B to produce the initial
versions of the UNIX operating system. BCPL and B were type less languages in which
variables were simply words in memory. Dennis Ritchie of Bell Laboratories latter converted
B into C by retaining most of B’s syntax in 1972 and wrote the first compiler, In 1978,
Kernighan and Ritchie wrote a book entitled ‘ The C programming Language’ that become the
language definition almost a decade. By mid 1980s, popularity of C becomes wide spread.
Numerous C compilers were written for computers of all sizes.
What is C?
Why Learn C?
C is a core language: In computing, C is a general-purpose, cross-platform, block structured
procedural, imperative computer programming language. A number of common and popular
computer languages are based on C. Having learnt C, it will be much easier to learn languages
that are largely or in part based upon C. Such languages include C++, Java, and Perl.
C is a small language: C has only thirty-two keywords and only about twenty of them are in
common use. This makes it relatively easy to learn compared to bulkier languages.
C is quick: We can write codes which run quickly, and the program can be very ‘close to the
hardware’. This implies that you can access low-level facilities in your computer quite easily,
without the compiler or run-time system stopping you from doing something potentially
dangerous.
C is portable: C programs written on one system can be run with little or no modification on
other systems. If modifications are necessary, they can often be made by simply changing a
few entries in a header file accompanying the main program.
A program is a set of instructions for performing a particular task. These instructions are just
like English words. The computer interprets the instructions as 1’s and 0’s. A program can be
written in assembly language as well as in high-level language. This written program is called
the source program. The source program is to be converted to the machine language, which is
called an object program. A translator is required for such a translation.
Program translator translates source code of programming language into machine language
instruction code. Generally, computer programs are written in languages like COBOL, C,
BASIC and ASSEMBLY LANGUAGE, which should be translated into machine language
before execution.
Programming language translators are classified as follows.
(i) Assembler
(ii) Compiler
(iii) Interpreter
Assembler: An assembler translates the symbolic codes of programs of an assembly language
into machine language instructions. The assembler programs translate the low-level language
o the machine code.
Mnemonic
Assembler Machine code
language
Compiler: Compilers are the translators, which translate all the instructions of the program
into machine codes, which can be used again and again The program, which is to be
translated, is called the source program and after translation the object code is generated.
The source program is input to the compiler. The object code is output for the secondary
storage device. The entire program will be read by the compiler first and generates the object
code.
Interpreter: Interpreters also come in the group of translators. It helps the user to execute the
source program with a few differences as compared to compilers. The source program is just
like English statements in both interpreters and compilers. The interpreter generates object
codes for the source program. Interpreter reads the program line by line, whereas in compiler
the entire program is read by the compiler, which then generates the object codes. Interpreter
directly executes the program from its source code.
Mnemonic Compilers/Inte
Machine codes
language rpreters
This program acts on lines that begin with a #. They occur mostly at the beginning of a
program and are called preprocessor directives. A directive may insert the contents of a header
file at that location (like #include <stdio.h>) or perform a substitution (like #define PI 3.142)
in the program itself. Preprocessing It processes include-files, conditional compilation
instructions, and macros. The C preprocessor is used to modify the program according to the
preprocessor directives in the source code.
Compilation
It is the second step of the compiling process. The process of converting of the source code
into machine code/Object code is called compiling. The program that is used to convert the
source code into machine code is called compiler. The compiler examines each program
statement contained in the source program and checks it to ensure that it conforms to the
syntax and semantics of the language. The compiler creates object code and saves it in a new
file on the disk. The file name has an extension .obj.
Before creating the object code, the compiler scans the source code for errors. If there are
errors in the source code, it does not compiler the source code and indicates the error. All the
errors must be removed from the source code before creating the object code of the program.
Assembly
It is the third stage of compilation. It takes the assembly source code and produces an
assembly listing with offsets. The assembler output is stored in an object file. After the
program has been translated into an equivalent assembly language program, the next step in
the compilation process is to translate the assembly language statements into actual machine
instructions.
Linking
A C program may contain predefined routines and functions. These functions are contained in
separate files and these files are part of the C compilers and are called library files or runtime
libraries.
In this step the necessary libraries are linked to the object code and executable file of the
program is created. The functions are the part of the standard C library, provided by every C
compiler. The program may use other source programs that were previously processed by the
compiler. These functions are stored as separate object files which must be linked to the object
file. Linker handles this linking. The process of compiling and linking a program is often
called building.
The linker also detects errors and does not create the executable file. These errors are removed
in the source code and new object file is created. The new object file is then linked to libraries
to create executable file. The executable file created with .exe extension.
When the program is executed, each of the statements of the program is sequentially executed.
If the program requests any data from the user, known as input, the program temporarily
suspends its execution so that the input can be entered. Or, the program might simply wait for
an event, such as a mouse being clicked, to occur. Results that are displayed by the program,
known as output, appear in a window, sometimes called the console. Or, the output might be
directly written to a file on the system.
Errors
If all goes well, the program performs its intended task. If the program does not produce the
desired results, it is necessary to go back and reanalyze the program. Three types of errors
may occur:
Compile errors: These are given by the compiler and prevent the program from running.
Linking errors: These are given by the linker or at run time and end the program. The linker
can also detect and report errors, for example, if part of the program is missing or a
nonexistent library component is referenced.
Run-time errors: These are given by the operating system.
Debugging
Removing errors from a program is called debugging. Any type of error in a program is
known as a bug. During debugging, an attempt is made to remove all the known problems or
bugs from the program.
A debugger is a program that enables the programmer to run another program step-by-step
and examine the value of that program’s variables.
The programming language are designed to support certain kind of data, such as numbers,
characters, strings, to get useful output known as result/information. Data consists of digits,
alphabets and symbols.
Execution Flow (Simple description)
2) Expanded source code is sent to compiler which compiles the code and converts it
into assembly code.
3) The assembly code is sent to assembler which assembles the code and converts it into
object code. Now a simple.obj file is generated.
4) The object code is sent to linker. Linker links it to the library such as header files.
Then it is converted into executable code. A simple.exe file is generated.
5) The executable code is sent to loader which loads it into memory and then it is
executed. After execution, output is sent to console.
Definition Section
In this section, variables are defined and values are set to these variables.
Main function
Every C program is started from main function and this function contains two major sections
called declaration section and executable section.
int main(void) -The int main(void) is a function that takes no arguments and returns a value
of type int.
void main(void) and void main()
The program execution begins with the opening brace “{“and ends with a closing brace “}”
Declaration Part: The declaration part declares the entire local variables that are used in
executable part. Local variable scope is limited to that function where the local variables are
declared.
Executable part
This part includes the statements following the declaration of variables
/*
Documentation section
C programming basics & structure of C programs
Author: fresh2refresh.com
Date : 01/01/2012
*/
• The program can be written in assembly language as well as high level language. This
is source program.
• The source program is to be converted to the machine language which is called object
program.
Alphabets
Digits
2. DELIMITERS
The language C uses special kind of symbol, which are called delimiters.
3. C TOKENS
The smallest individual units of a program are known as tokens. The C programs can be
written using the tokens and its syntax rules.
KEYWORDS
Keywords are reserved words whose meaning has already been explained to the
compiler and that has a particular meaning the programming language.
There are 32 keywords available in C and must written in lower case.
CONSTANTS
A constant is an entity whose value remains the same throughout the execution of a
program. Constants are assigned to variables.
It can be placed on the right side of the assignment operator. Ex: X=3; 3 is a constant.
Numerical Constants
Integer Constants: These constants are represented with whole numbers. They require a
minimum of 2 bytes and a maximum of 4 bytes of memory.
(a) Numerical constants are represented with numbers. At least one digit is needed for
representing the number.
(b) The decimal point, fractional part, or symbols are not permitted. Neither blank spaces nor
commas are permitted
(c) Integer constant could be either positive or negative or may be zero.
(d) A number without a sign is assumed as positive.
They can also be represented in octal or hexadecimal number system based on the
requirement. The octal numbers are 0, 1, 2, 3, 4, 5, 6, and 7 and the hexadecimal numbers are
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,A, B, C, D, E, and F.
Real Constants: Real constants are often known as floating point constants. Real constants
can be represented in exponential or fractional form.
The following concepts are essential to follow the real numbers:
(a) The decimal point is permitted.
(b) Neither blank spaces nor commas are permitted.
(c) Real numbers could be either positive or negative.
(d) The number without a sign is assumed as positive.
The real constants can be written in exponential notation, which contains fractional and
exponential parts.
For example, the value 2456.123 can be written as 2.4561 X e+3. The part that precedes e is
called mantissa and the part that follows it is an exponent. In this example, 2.4561 is the
mantissa and +3 is the exponent.
The following points must be noted while constructing a real number in exponential form:
Character Constant
String Constants: String constants are a sequence of characters enclosed within double quote
marks. The string may be a combination of all kinds of symbols.
Example: “Hello”, “India”, “444”, “a”.
IDENTIFIERS
Data types
The data type defines the possible values that an identifier can have and the valid operations
that can be applied on it. The memory requirement for each data will be determined by the
possible range of values for the data type.
C data
type
Pointers Structure
Integer(int) void Union
Functions
Character Enumeratio
(char) Arrays
n
Float Typedef
double
long doube
• Characters are generally stored using 8 bits (1 Byte) of the internal storage.
Floats and Doubles: single precision (float) and double precision (double) floating points
Integer Representation
+7 is represented as 0 0000111
The signed negative integers can be represented in any one of the following forms:
(a) signed—magnitude form
(b) signed—1’s complement form
(c) signed—2’s complement form
In the signed magnitude form, the sign of the number is represented as 1 and the magnitude
by equivalent
binary form.
Example:
−7 is represented as 1 0000111
In the signed 1’s complement form, the sign of the integer is indicated by 1 and the
magnitude is shown in 1’s complement form as follows,
−7 is represented as 1 1111000
In the above signed − 2’s complement form, the sign is indicated by 1 and magnitude by 2’s
complement form as follows,
−7 is represented by 1 1111001
Floating-Point Representation
The system of the number representation that keeps track of the position of binary and decimal
point is better than the fixed-point representation. This system is called floating-point
representation.
The real number 454.45 can be written as 4.5445 × 102 or 0.45445 × 103 .
0.45445 3
Mantissa Exponent
Void
The void type has no values and no operations.
Both the set of values and the set of operations are empty.
DERIVED DATA TYPE
• These data types are derived from the basic data types.
1. Array type
2. Pointer type
3. Function type
USER DEFINED DATA TYPE
• The c language provides flexibility to the user to create new data types.
• These newly created data types are called as user defined data types.
1. Structure
2. Union
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
float b=10.88;
char c=‘$’;
char d[5]=“hello”;
clrscr();
printf(“Integer value : %d\n”,a);
printf(“Float value : %f\n”,b);
printf(“Character : %c\n”,c);
printf(“String : %s”,d);
getch();
Volatile qualifier: - Declaring an object as volatile means the object has some special
properties relevant to optimization.
void main()
{
volatile int x;
volatile const int y=10;
clrscr();
printf(“Enter an integer:”);
scanf(“%d”,&x);
printf(“Entered integer is :%d”,x);
x=3;
printf(“\nChanged value of x is :%d”,x);
printf(“\nValue of y:%d”,y);
/* y=8;*/
getche();
}
OUTPUT:
Enter an integer:5
Entered integer is :5
Changed value of x is :3
Value of y:10
x is initialized with keyword volatile and y is with volatile constant. Value
of x can be changed but volatile const cannot be changed. ‘Cannot modify
a const value’.
Type modifiers:
It modifies the base type to yield new type. It modifies the range and arithmetic
properties of the base type (Key words are signed, unsigned, short, long).
Type Conversion
In C, it is possible to convert one data type to another.
Explicit type conversion- programmer needs the result in certain data type. For
example division of 5 with 2 should return float value.
Implicit type conversion- In C automatically ‘lower’ data type is promoted to ‘upper’
data type. For example, data type char or short is converted to int.
In case an expression contains one of the operands as unsigned operands and another
non -unsigned, the latter operand is converted to unsigned.
Initializing Variables
Variables declared can be assigned or initialized using assignment operator ‘=’. The
declaration and initialization can also be done in the same line.
Static initialization
Syntax:
variable_name = constant; or data_type variable_name= constant;
Example:
int y =2 ; where y is an integer variable.
Dynamic Initialization
The initialization of variable at run time is called dynamic initialization. Dynamic refers
to the process during execution.
void main()
{
int r=2;
float area=3.14*r*r;
clrscr();
printf(“Area=%g”,area);
}
OUTPUT:
Area=12.56
In the above program, area is calculated and assigned to variable area. The expression is
solved
at a run time and assigned to area at a run time. Hence, it is called dynamic
initialization.
RULES FOR DEFINING VARIABLES
Capital letters A-Z, lowercase letters a-z, digits 0-9, and the underscore character
Operator Precedence:
Precedence means priority. Every operator in C has assigned precedence (priority). An
expression may contain a lot of operators. The operations on the operands are carried out
according to the priority of the operators. The operators having higher priority are evaluated
first and then lower priority.
The parenthesized sub-expressions are evaluated first.
If the parentheses are nested, the innermost sub-expression is evaluated first.
The precedence rules are applied to determine the order of application of operators
while evaluating sub-expressions.
The associativity rule is applied when two or more operators of the same precedence
appear in the sub-expression.
BODMAS – Brackets->of->Division->Multiplication->Addition->Subtraction.
# include <stdio.h>
# include <conio.h> In this program, in the expression j = a
main () + b c, first multiplication operation is
{ performed followed by addition
int a=1,b=2,c=3,j; operation;
clrscr(); Hence, value of j is 7. In the second
j=a+b*c; expression, the parentheses give first
printf (“\n j=%d”,j); priority to the addition operation.
j=(a+b)*c; Hence, addition of ‘a’ and ‘b’ is
printf (“\n j=%d”,j); performed first and followed by
} multiplication is performed.
OUTPUT:
j=7
j=9
Associativity
Left to right: In this type, expression, evaluation starts from left to right direction.
Example: 12 4 / 8 % 2
In the above expression, all operators are having the same precedence, and so associativity
rule is followed (i.e. direction of execution is from left to right).
= 48 / 8 % 2
=6%2
= 0 (The above modulus operation provides remainder 0)
(ii) Right to left: In this type, expression, evaluation starts from right to left direction.
Example: a=b=c
In the above example, assignment operators are used. The value of c is assigned to b and then
to a. Thus, evaluation is from right to left.
CLASSIFICATION OF OPERATORS
The operators in C classified based on
1. The number of operands on which an operator operates.
2. The role of an operator.
i. Unary operators
ii. Binary operators
iii. Ternary operators
Unary operators
#include<stdio.h>
main() a=3, b=3, c=3, d=2
{ Reasons:
int a=2, b=2,c,d; • The value of a is incremented and
c=++a; then it is assigned to c as a is pre
d=b++; incremented
printf(“a=%d, b=%d, c=%d, d=%d”,a,b,c,d); • The value of b is assigned to d
} before it is incremented as b is post-
incremented
Decrement operator
The decrement operator can appear towards the left side or towards the right side of its
operand.
If the decrement operator appears towards the left side of its operand, it is known as the
pre decrement operator. Ex: --a. The pre decrement operation decrements a value by 1
and then assigns value to ‘a’.
If the decrement operator appears towards the right side of its operand it is known as the
post decrement operator. Ex: a--. The post decrement operation assigns the value to ‘a ‘
then decrements the value by 1.
a=1, b=1, c=1, d=2
Reasons:
#include<stdio.h>
• The value of a is decremented
main()
and then it is assigned to c as a is
{
pre decremented
int a=2, b=2,c,d;
• The value of b is assigned to d
c=−−a;
before it is decremented as b is
d=b−−;
post-decremented
printf(“a=%d, b=%d, c=%d, d=%d”,a,b,c,d);
}
Division operator
The division operator is used to find the quotient.
The sign of the result of evaluation of the division operator depends upon the sign of
both the numerator as well as the denominator.
If both are positive, the result will be positive. If both are negative, the result will be
positive. If either of the two is negative, the result will be negative.
For example: 4/3=1, −4/3=−1, 4/−3=−1 and −4/−3=1.
Modulus operator
Modulus operator is used to find the remainder.
The operands of modulus operator must be of integer type. It cannot have floating point
type operands.
The sign of modulus operator depends only upon the sign of numerator.
#include<stdio.h>
Compilation error “Illegal use of
main()
floating point in the function main”
{ Reason:
int a; • Operands of modulus operator should
a=2%3.0; be of integer type
b=15%2; What to do?
c=12%2; • Write 3 instead of 3.0 or type cast 3.0
to int by writing (int) 3.0
printf(“The value of a is %d”,a);
The result will be a=2
printf(“The value of b is %d”,b); b=1;
printf(“The value of c is %d”,c); c=0;
}
include <stdio.h>
int main()
Output
{
int a = 9,b = 4, c; a+b = 13
c = a+b;
a-b = 5
printf("a+b = %d \n",c);
c = a-b; a*b = 36
printf("a-b = %d \n",c);
c = a*b; a/b = 2
printf("a*b = %d \n",c); Remainder when a divided by b=1
c=a/b;
printf("a/b = %d \n",c);
c=a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
2. Relational operators
Relational operators are used to compare two quantities/variables (their operands).
There should be no white-space character between two symbols of a relational operator.
The result of relational operator is a Boolean constant.
The relational operator forms a condition.
5 <= 5 = 1
void main()
{
OUTPUT:
clrscr();
Condition: Return Values
printf(“\nCondition : Return Values\n” );
10!=10 : 0
printf(“\n10!=10 : %5d”,10!=10);
10==10 : 1
printf(“\n10==10 : %5d”,10==10);
10>=10 : 1
printf(“\n10>=10 : %5d”,10>=10);
10<=100: 1
printf(“\n10<=100: %5d”,10<=100);
10!=9 : 1
printf(“\n10!=9 : %5d”,10!=9);
}
3. Logical Operators
The logical relationship between the two expressions is tested with logical operators. After
checking the conditions, it provides logical true (1) or false (0) status. The operands could be
constants, variables and expressions.
void main()
{ OUTPUT:
clrscr(); Condition : Return Values
printf(“\nCondition : Return Values\n” ); 5>3 && 5<10 : 1
printf(“\n5>3 && 5<10 : %5d”,5>3 && 5<10); 8>5 || 8<2 : 1
printf(“\n 8>5 || 8<2 : %5d”,8>5 || 8<2); !(8==8) : 0
printf(“\n !(8==8) : %5d”,!(8==8));
}
#include <stdio.h>
int main()
{ Output
int a = 5, b = 5, c = 10, result; (a == b) && (c > b) equals to 1
result = (a == b) && (c > b);
printf("(a == b) && (c > b) equals to %d \n", result); (a == b) && (c < b) equals to 0
result = (a == b) && (c < b); (a == b) || (c < b) equals to 1
printf("(a == b) && (c < b) equals to %d \n", result);
result = (a == b) || (c < b); (a != b) || (c < b) equals to 0
printf("(a == b) || (c < b) equals to %d \n", result);
!(a != b) equals to 1
result = (a != b) || (c < b);
printf("(a != b) || (c < b) equals to %d \n", result); !(a == b) equals to 0
result = !(a != b);
printf("!(a == b) equals to %d \n", result);
result = !(a == b);
printf("!(a == b) equals to %d \n", result);
return 0;
}
4. Bitwise operators
Bitwise operators operate on the individual bits of the operands and are used for bit
manipulation.
These operators do not consider the operand as one entity.
128 64 32 16 8 4 2 1
0 0 0 0 1 0 0 0
After execution of the program: the inputted data x is to be shifted by 2 bits right side.
128 64 32 16 8 4 2 1
0 0 0 0 0 0 1 0
Shifting two bits right means the inputted number is to be divided by 2𝑠 where s is the number
of shifts. Simply, y=n/2𝑠 , where n = number and s = the number of position to be shift.
Shifting three bits left means the number is multiplied by 8; in short y=n*2𝑠
Where n = number and s = the number of position to be shifted.
As per the program given above, Y=2*23 = 16.
Bitwise AND operator: &
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25 00001100 &
00011001
________
00001000 = 8 (In decimal)
void main()
{
int a,b,c;
clrscr();
printf(“Read The Integers from keyboard (a & b) :-”);
scanf(“%d %d”, &a,&b);
c=a & b;
printf(“The Answer after ANDing is (C)= %d”,c);
}
OUTPUT:
Read The Integers from keyboard (a & b) : 12 25
The Answer after ANDing is (C) = 8
Bitwise OR operator: |
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR Operation of 12 and 25 00001100 |
00011001
________
00011101 = 29 (In decimal)
void main()
{
int a,b,c;
clrscr();
printf(“Read The Integer from keyboard (a & b) :-”);
scanf(“%d %d”, &a,&b);
c=a | b;
printf(“The Oring operation bewteen a & b in c = %d”,c);
getche();
}
OUTPUT:
Read The Integer from keyboard (a & b):- 12 25
The Oring operation between a & b in c = 29
Exclusive OR Bitwise Operator: ^
The operator ~ is used for inverting the bits with this operator 0 becomes 1 & 1 becomes 0.
void main()
{
unsigned int v=35;
clrscr(); OUTPUT:
printf(“\n %u”, ~v); 220
}
5. Assignment operators
A variable can be assigned a value by using an assignment operator.
Operator Name of operator Example Equivalent Statement
Initial value c = 9
= Simple assignment c=5; or c= a+b; Value 5 and a+b assigned to c.
*= Assign product c*=10 c=c*10, c=90
/= Assign quotient c/=5 c=c/5, c=1
%= Assign modulus c%=5 c=c%5 , c=4
+= Assign sum c += 7 c = c + 7, c=16
-= Assign difference c -=8 c=c-8 , c=1
&= Assign bitwise c&=2 c=c&2
AND
|= Assign bitwise OR c|=2 c=c|2
^= Assign bitwise c^=2 c=c^2
XOR
<<= Assign left shift c<<=2 c=c<<2
>>= Assign right shift c>>=2 c=c>>2
void main()
{
int a=10,b=20,c=50,x=5;
printf(“\nInitial value of a =10,b=20,c=50,x=5”);
a+=x;
b-=x;
c*=x; Initial value of a =10,b=20,c=50,x=5
printf(“\n a+=x is equal to %d”,a); a+=x is equal to 15
printf(“\n a-=x is equal to %d”,b); a-=x is equal to 15
printf(“\n a*=x is equal to %d”,c); a*=x is equal to 250
}
void main()
{
int x,y;
printf(“Read the integer from keyboard(x):- ”);
scanf(“%d”,&x);
x>>2;
Read the integer from keyboard(x):-8
y=x;
printf(“The right shifted data is=%d”,y); The right shifted data is=2
}
6. Miscellaneous Operators
Conditional operator:
Conditional operator is the only ternary operator available in C. The conditional operator
contains condition followed by two statements or values. If the condition is true, the first
statement is executed, otherwise the second statement is executed.
Syntax: Condition? Expression 1: Expression 2
If the condition is true expression 1 gets evaluated, otherwise expression 2 gets evaluated.
#include <stdio.h>
#include <conio.h>
Output:
void main()
Greatest of two numbers is 7
{
int a=6,b=7;
getch();
Comma operator
• The operator size of gives the size of the data type or variable in terms of bytes
occupied in the memory.
• Syntax: sizeof(expression) sizeof(3+4) or sizeof(type_name) sizeof(int)
•
• The operand may be a variable, a constant or a data type qualifier.
Example
int sum;
m = sizeof (sum);
m will return 2 bytes
include <stdio.h>
return 0;
Address-of Operator
void main()
{
int a;
int b=10; Output:
int addr=&b; Enter value of a 12
scanf(“%d”,&a);
printf(“enter value of %d”,a); Value -1052642724
printf(“value %d”,addr);
printf(“value %d”,&addr);
}
INPUT OUTPUT OPERATIONS
Formatted Input/output:
C uses two functions for formatted input and output.
Formatted input: reads formatted data from the keyboard. Flow from input device to
main memory.
Formatted output: writes formatted data to the monitor. Bytes flow from main
memory to output devices.
In formatted functions read and write of all the types of data values require format
string to produce formatted results.
Formatted output :(printf)
The formatted output as per requirement is displayed on the screen with printf()
The values of variables are printed according to the sequence.
The printf () function prints all types of data values to the console.
It requires format conversion symbol or format string and variable names to print the
data and it should be same in number and type.
The syntax : printf(“Control string”, variable1, variable2,…, variable n);
A control string specifies the field format such as %d, %s, %f, %c.
void main()
{
int x=2; Output: -
float y=2.5; 2 2.5000 C
Char z= ‘C’;
printf(“%d %f %c”, x , y , z );
}
int main()
Output:
{
A 65
int y = 65;
clrscr();
printf(“%c %d”, y , y)
return 0;
}
Flags, width and precision with format string:
Void main()
{ Output
Int x = 55, y = 33;
clrscr(); 22
printf(“\n%3d”, x-y); 22
printf(“\n%6d”, x-y); 22
printf(“\n%*d”, 15 , x-y); 22
printf(“\n%*d”, 5 , x-y);
}
Examples for the use of precision specifier
void main()
{ Output
float = 123.456789; 123.5
clrscr(); 123.46
printf(“\n% .1f”, g); 123.457
printf(“\n% .2f”, g);
printf(“\n% .3f”, g);
}
%wd – format for integer output
w is width in integer
d is conversion specification of integer.
%w.cf - format for float numbers
w- Width in integer
c- Specifies the number of digits point
f- Specifies the conversion specification
%w.cs –format for string output
w – Width for total number characters
c - displaying leading blanks
s- Conversion specification of string.
void main()
{
clrscr(); OUTPUT:
printf(“\n%5d”,12); 12
printf(“\n%5d”,123); 123
printf(“\n%5d”,1234); 1234
printf(“\n %4.5f”,6.12); 6.12000
16.120000
printf(“\n %4.6f”,16.12);
167.1200000
printf(“\n %4.7f”,167.12); 1678.12000000
printf(“\n %4.8f”,1678.12); Amitkumar
printf(“\n %8s”,“Amitkumar”); Am
printf(“\n %8.2s”,“Amitkumar”);
getche();
}
#include <stdio.h>
int main()
{
int a;
float b;
printf("Enter integer and then a float: ");
Output:
// Taking multiple inputs
scanf("%d%f", &a, &b); Enter integer and then a float: -3
printf("You entered %d and %f", a, b); 3.4
return 0; You entered -3 and 3.400000
}
Character Test Function
#include <math.h>
OUTPUT:
void main()
2.000000 raised to 3.000000 is 8.000000
{
double x = 2.0, y = 3.0;
clrscr();
printf(“%lf raised to %lf is %lf\n”, x, y, pow(x, y));
}
Unformatted I/O:
Works only with character data type.
In case values of other data types passed to these functions they are treated as character
data.
Character I/O
String I/O
File I/O
Character I/O
getchar() & putchar(): Available in stdio.h header file.
getchar() -It reads one character at a time from standard input.
putchar() - It prints one character on the screen at a time.
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
Output:
void main()
{ enter the character : A
char x; a
printf("enter the character:");
x=getchar();
if(islower(x))
putchar(toupper(x));
else
putchar(tolower(x));
getch();
}
getc () and putc():Available in stdio.h header file.
getc()-Gets one character from the keyboard and putc() displays one character to display
#include<stdio.h>
#include<conio.h>
#include<ctype.h> Output:
void main() enter the character: a
{ A
char x;
printf("enter the character:");
x=getc(stdin);
if(islower(x))
putc(toupper(x),stdout);
else
putc(tolower(x),stdout);
getch();
}
getch() ,putch() and getche()
These functions read the alphanumeric characters from the standard input device. The
character entered is not displayed by getch() function.
putch() This function prints any alphanumeric character taken by the standard input device.
void main()
OUTPUT:
{
Enter any two alphabets A
clrscr();
printf(“Enter any two alphabets”); In the above program, even though the two characters
getche(); are entered, the user can see only one character on
getch(); the screen. The second character is accepted but not
} displayed on the console. The getche() accepts and
displays the character, whereas getch() accepts but
does not display the character.
void main() OUTPUT:
{ Press any key to continue You Pressed: 9
char ch,ch1; 7
clrscr();
The function getch() reads a key stroke and
printf(“Press any key to continue”);
ch=getch(); assigns to the variable ch. putch() displays
printf(“\n You Pressed :”); the character pressed. getche() read 7 and
putch(ch); displayed.
getche(ch1);
}
String I/O
gets() & puts()
gets() This function is used for accepting any string through stdin (keyboard) until enter key is
pressed.
puts() This function prints the string or character array.
gets() accept a string from the user at the run time is by using the gets library function.
puts() displays the strings to the console.
Unlike the scanf function, the gets function reads the entire line of text until a new line
character is encountered and does not stop upon encountering any other whitespace character.
gets() function is suited for reading multi-word strings
#include <stdio.h>
#include<conio.h>
void main()
{
char c[80];
clrscr(); Output:
printf("Input a string:"); Input a string:qwerty
gets(c);
printf("The string is:"); The string is:qwerty
puts(c);
getch();
}
The input functions are categorized into buffered input functions and un buffered input
functions.
1. In buffered input, the input given is kept in a temporary memory area known as the buffer
and is transmitted to the program when the Enter key is pressed. The pressed Enter key is
also transmitted to the program in the form of a new line character, which the program
must handle.
2. In un buffered input, the given input is immediately transferred to the program without
waiting for the Enter key to be pressed.
3. The examples of buffered input functions are scanf, getchar and gets function.
4. The examples of un buffered input functions are getch and getche function.
DECISION STATEMENT AND LOOP CONTROL STATEMENTS:
Program Control Structure
A program is nothing but the execution of one or more instructions sequentially in the order in
which they come into sight.
Program statements that affect the order in which statements are executed or that affect
whether statements are executed are called control structures.
• 3 control structures are:
• Sequential control structures
• Selection (decision /branched) control structures
• Iteration /looping control structures
Sequential control structures
The statements in the program are executed one after another in a sequential manner. This is
called the sequential execution.
Selection (decision /branched) control structures
Based upon the outcome of a particular condition, selection statements transfer control from
one point to another. Selection statements select a statement to be executed among a set of
various statements.
Iteration /looping control structures
Where the logic (sequence of steps) is repeated in a loop until the desired output is obtained
Transfer of control: The C statements such as if, goto, break, continue, switch allow a
program to transfer the control at different places in the program. This is accomplished by
skipping one or more statements appearing in a sequential flow. This jumping of control is
called the transfer of control.
Branching Statements
Branching statements are used to transfer the program control from one point to another.
Conditional branching:
In conditional branching, also known as selection, program control is transferred from one
point to another based upon the outcome of a certain condition. The following selection
statements are available in C: if statement, if-else statement and switch stamen.
Unconditional branching:
In unconditional branching, also known as jumping, program control is transferred from
one point to another without checking any condition. The following jump statements are
available in C: goto statement breaks statement, continue statement and return statement.
DECISION STATEMENT
A statement is the smallest logical entity that can independently exist in a C program.
Decision-making statements in a programming language help the programmer to
transfer the control from one part to other parts of the program.
Thus, these decision-making statements facilitate the programmer in determining the
flow of control.
This involves a decision-making condition to see whether a particular condition is
satisfied or not.
On the basis of real time applications it is essential:
(i) To alter the flow of a program.
(ii) To test the logical conditions.
(iii) To control the flow of execution as per the selection.
If
if else
else if ladder
Nested if
Nested if else and
switch statements
if Statement
if(expression) //if header
Statement //if body
Syntax: if statement :-
if (condition or expression) /* no semi-colon */
{
Statements; //code block for true expression
}
Explanation:
If the expression is true then the statement or block of statements gets
executed otherwise these statements are skipped.
The important points about an if statement is as follows:
#include<stdio.h>
#include<conio.h>
void main(){ Enter the number: 56
int n; The number is positive number.
clrscr();
printf(“Enter the number:”);
scanf(“%d”,&n);
if(n>0)
{
printf(“The number is positive number”);
getch();
}
}
If-else statement:
The if–else statement takes care of the true and false conditions. It has two blocks. One block
is for if and it is executed when the condition is true. The other block is of else and it is
executed when the condition is false.
The else statement cannot be used without if. No multiple else statements are allowed with
one if.
if(expression) //if-else header
statement1 //if body
else //else clause
statement2 //else body
}
#include<stdio.h>
#include<conio.h>
void main(){ Enter the number: -3
int n; The number is negative number.
clrscr();
printf(“Enter the number:”);
scanf(“%d”,&n);
if(n>0)
{
printf(“The number is positive number”);
else
printf(“The number is negative number”);
getch();
}
}
If the body of the if statement is another if statement or contains another if statement, then we
say that if’s are nested and the statement is known as a nested if statement.
In a nested if-else statement, the if body or else body of an if-else statement is, or contains,
another if statement or if-else statement.
In if else if statement the else statements contains another if statements.
The careless use of a nested if-else statement introduces a source of potential ambiguity
referred to as the dangling else ambiguity. When a statement contains more number of if
clauses than else clauses, then there exists a potential ambiguity regarding with which if
clause does the else clause properly matches up. This ambiguity is known as dangling else
problem.
Syntax of nested if-else statement Syntax of if –else if statement
if(condition) if(condition)
{ {
/*Inside first if block*/ statement 1; /*if block*/
if(condition) statement 2;
{ }
statement 1; /*if block*/ else if(condition)
statement 2; {
} statement 3; /*second if block*/
else statement 4;
{ }
statement 3; /*else block*/ else if(condition)
statement 4; {
} statement 5; /*third if block*/
} statement 6;
else }
{ else
/*Inside else block*/ {
if(condition) statement 7; /*else block*/
{ statement 8;
statement 5; /*if block*/ }
statement 6;
}
else
{
statement 7; /*else block*/
statement 8;
}
}
Figure : if -else -if flow diagram
Program example for nested if else:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf(“Enter three numbers\n”);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b) Enter three numbers
{
if(a>c) 3 6 7
printf(“The biggest number is =%d”,a); The biggest number is 7
}
else
{
printf(“The biggest number is=%d”,c);
}
else
if(b>c)
{
printf(“The biggest number is=%d”,b);
}
else
{
printf(“The biggest number is=%d”,c);
}
}
}
getch();
}
void main()
{
int initial,final,consumed;
float total;
clrscr();
printf(“\n Initial & Final Readings :”);
scanf(“%d %d”, &initial, &final);
consumed = final-initial; OUTPUT:
if(consumed>=200 && consumed<=500) Initial & Final Readings : 800 850
total=consumed * 3.50; Total bill for 50 unit is 75.000000
else if(consumed>=100 && consumed<=199)
total= consumed * 2.50;
else if(consumed<100)
total=consumed*1.50;
printf(“Total bill for %d unit is %f”,consumed,total);
getche();
}
Switch-The switch statement is a multi way branching statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
A switch statement is used to control complex branching operations. When there are many
conditions, it becomes too difficult and complicated to use if and if-else constructs. In such
cases, the switch statement provides an easy and organized way to select among multiple
options, depending upon the outcome of a particular condition.
The important points about a switch statement are as follows:
1. A switch statement consists of a switch header and a switch body.
2. A switch header consists of the keyword switch followed by a switch selection expression
enclosed within parentheses.
3. The switch selection expression must be of integral type (i.e. integer type or character
type).
4. The switch body consists of a statement. The statement constituting a switch body can be a
null statement, an expression statement, a labeled statement, a flow control statement,
a compound statement, etc.
5. Generally, a switch body consists of a compound statement, whose constituent statements
are case-labeled statements, expression statements, flow control statements and
an optional default-labeled statement.
6. Case labels of case-labeled statements constituting the body of a switch statement should
be unique, i.e. no two case labels should have or evaluate to the same value.
7. There can be at most one default labeled statement within the switch body.
#include<stdio.h>
int main()
/*local variable definition*/
char grade=’B’;
switch(grade){
case ‘A’:
printf(“Excellent!\n”); Output:
case ‘B’:
Good!
printf(“Good!\n”);
case ‘C’:
printf(“You passed!\n”);
case ‘D’:
printf(“Better try again!\n”);
default:
printf(Invalid grade!\n”);
}
Printf(“Your grade is %c\n”,grade);
return 0;
}
Nested switch case
The inner switch can be a part of an outer switch.
void main()
{
int x,y;
clrscr();
printf(“\n Enter a Number :”);
OUTPUT:
scanf(“%d”,&x);
Enter a Number: 5
switch(x)
Number is Odd.
{
case 0 :
printf(“\n Number is Even.”);
break;
case 1 :
printf(“\n Number is Odd .”);
break;
default :
y=x%2;
switch(y)
{
case 0:
printf(“\n Number is Even.”);
break;
default :
printf(“\n Number is Odd.”);
}
}
getche();
}
Jump Statements
A jump statement transfers the control from one point to another without checking any
condition, i.e. unconditionally. The following jump statements are present in C language:
1. goto statement
2. break statement
3. continue statement
4. return statement
1) goto Statement
The goto statement is used to branch unconditionally from one point to another within a
function.
It provides a highly unstructured way of transferring the program control from one point to
another within a function. This statement does not require any condition.
User has to define the goto statement as follows:
goto label;
program to detect the entered number as to whether it is even or odd. Use the goto
statement.
# include <stdlib.h>
void main()
{
int x;
clrscr();
printf(“Enter a Number :”);
Enter a Number: 5
scanf(“%d”,&x);
5 is Odd Number.
if(x%2==0)
goto even; In the above program, a number is entered.
else The number is checked for even or odd with
goto odd; modules division operator. When the number
even : is even, the goto statement transfers the
printf(“\n %d is Even Number.”,x); control to the label even. Similarly, when the
return; number is odd the goto statement transfers
odd: the control to the label odd and respective
printf(“\n %d is Odd Number.”,x); message will be displayed.
}
//break statement
Example – Use of break in a while loop
#include <stdio.h>
int main() {
int num =0;
Output:
while(num<=100)
value of variable num is: 0
{
value of variable num is: 1
printf("value of variable num is: %d\n", num);
value of variable num is: 2
if (num==2)
Out of while-loop
{
break;
}
num++; }
printf("Out of while-loop"); return 0;
}
The continue statement is used inside loops. When a continue statement is encountered inside
a loop, control jumps to the beginning of the loop for next iteration, skipping the execution of
statements inside the body of loop for the current iteration.
Syntax: continue;
4) return statement
• The return statement is used to terminate the execution of a function and transfer
program control back to the calling function.
• A function may or may not return a value. A return statement returns a value to the
calling function and assigns to the variable in the left side of the calling function.
Syntax
return; or //Form 1
#include<stdio.h>
Void_eligible_or_not (int x);
int main()
{ int n;
printf("Enter age: ");
scanf("%d", &n); Expected Output:
eligible_or_not(n); 1st run:
// signal to operating system everything works fine Enter age: 16
return 0; You are not yet ready
} 2nd run:
void_eligible_or_not(int age) Enter age: 17
{ Try next year
if(age >= 18)
{
printf("You are eligible to vote");
return;
}
else if(age == 17 )
{
printf("Try next year");
return;
}
else
{printf("You are not yet ready"); return}
}
LOOP CONTROL AND ITERATION CONTROL
Iteration is a process of repeating the same set of statements again and again until the
Specified condition holds true. A loop is defined as a block of statements which are repeatedly
executed for certain number of times.
1. for statement
2. while statement
3. do-while statementutline
Print the first five numbers starting from 1 together with their squares.
void main()
{ OUTPUT:
int i; Number: 1 it’s Square: 1
clrscr(); Number: 2 it’s Square: 4
Number: 3 it’s Square: 9
for(i=1;i<=5;i++)
Number: 4 it’s Square: 16
printf(“\n Number: %5d it’s Square: %5d”,i,i*i); Number: 5 it’s Square: 25
}
void main()
{
int i;
clrscr(); OUTPUT:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
for(i=1;i<=15;i=i+1)
printf(“%5d”,i);
}
Nested for Loops
In nested for loops one or more for statements are included in the body of the loop.
The numbers of iterations in this type of structure will be equal to the number of iteration in
the outer loop multiplied by the number of iterations in the inner loop.
Syntax:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
Program to perform subtraction of two loop variables. Use nested for loops.
void main()
{
int a,b,sub; OUTPUT:
a=3 b=1 a-b = 2
clrscr();
a=3 b=2 a-b = 1
for(a=3;a>=1;a–-) a=2 b=1 a-b = 1
{ a=2 b=2 a-b = 0
for(b=1;b<=2;b++) a=1 b=1 a-b = 0
{ a=1 b=2 a-b =-1
sub=a-b;
printf(“a=%d\t b=%d\t a-b=%d\n”,a,b,sub);
}
}
}
2. while loop
The while loop is frequently used in programs for the repeated execution of statement/s in
a loop. Until a certain condition is satisfied the loop statements are executed.
The while statement is executed as follows:
The while controlling expression is evaluated.
i. If it evaluates to true, the body of the loop is executed.
ii. If it evaluates to false, the program control is transferred to the statement present next to the
while statement.
b. After executing the while body, the program control returns back to the while header.
c. Steps a and b are repeated until the while controlling expression in Step a evaluates to false.
7. While making the use of while statement, always remember to initialize the loop counter
before the while controlling expression is evaluated and to manipulate the loop counter
inside the body of while statement, i.e. before the while controlling expression is evaluated
again. (that is increment or decrement manipulation).
Program to add 10 consecutive numbers starting from 1. Use the while loop.
void main()
{
int a=1,sum=0;
clrscr();
while(a<=10) OUTPUT:
{ 1 2 3 4 5 6 7 8 9 10
printf(“%3d”,a); Sum of 10 numbers : 55
sum=sum+a;
a++;
}
printf(“\n Sum of 10 numbers :%d”,sum);
}
3. do while loop
do //do-while header
statement //do-while body
while(expression); //while clause
An array:-
An array is a very popular and useful data structure used to store data elements in
successive memory locations. More than one element is stored in a sequence, so it is
also called a composite data structure.
An array is a linear and homogeneous data structure. It means that similar types of
elements are stored contiguously in the memory and that too under one variable name.
An array is a data structure_ that is used for the storage of homogeneous data i.e., an
array is a collection of elements of the same data type. The data type of an element is
called element type.
Characteristics of an Array
1) An array holds elements that have the same data type.
2) Array elements are stored in subsequent/contiguous memory locations.
3) The individual elements of an array are not named. All the elements of an array share a
common name, i.e. the array name.
4) Elements of an array are accessed using an index value. ...index starting from 0.
5) Two-dimensional array elements are represented as matrix. A matrix can be
represented as a table of rows and columns.
6) Array size should be mentioned in the declaration. Only constants and literal values (an
integer value like 5, 10, 12,...) can be assigned the number of elements in an array
7) Array name represents the address of the starting element
#include<stdio.h>
int main() {
int arr[30], num, i, loc;
printf("\nEnter no of elements :");
scanf("%d", &num);
for(i=0;i<n;i++); Output:
while (i < j) {
temp = arr[i]; Output
arr[i] = arr[j];
Enter no of elements: 5
arr[j] = temp;
i++; // increment i 11 22 33 44 55
j--; // decrement j
Result after reversal: 55 44 33 22
}
11
//Print out the Result of Insertion
printf("\nResult after reversal : ");
for (i = 0; i < num; i++) {
printf("%d \t", arr[i]); }
return (0);
}
7. C Program to Find Largest Element in Array
#include<stdio.h>
int main() {
int a[30], i, num, largest;
printf("\nEnter no of elements :");
scanf("%d", &num);
//Read n elements in an array
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
Output:
//Consider first element as largest
largest = a[0]; Enter no of elements: 5
for (i = 0; i < num; i++) {
11 55 33 77 22
if (a[i] > largest) {
largest = a[i]; Largest Element: 77
}
}
// Print out the Result
printf("\nLargest Element : %d", largest);
return (0);
}
8. C Program to Find Smallest Element in Array
#include<stdio.h>
int main() { Output:
int a[30], i, num, smallest;
printf("\nEnter no of elements :"); Enter no of elements: 5
scanf("%d", &num); 11 44 22 55 99
//Read n elements in an array Smallest Element: 11
for (i = 0; i < num; i++)
scanf("%d", &a[i]);
//Printing of total
printf("\nSum=%d", sum);
return (0);
}
10.Sort the elements in an array in ascending order
#include<stdio.h>
#define MAX_SIZE 100 //maximum array size
int main()
{
int arr[max_size];
int size;
int i,j,temp;
/*input size of array*/
for(i=0;i<size;i++)
for(i=0;i<size;i++)
{
/* place current selected element array[i] to its correct place.*/
for(j=i+1;j<size;j++);
{
/*swap if currently selected array element is not as its correct position*/
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
/*print the sorted array*/
\
for(i=0;i<size;i++);
Output:
{
\ enter size of array: 5
}
enter elements in array: 10 9 5 11 2
return 0;
} elements of array in ascending order:
2 5 9 10 11
Two dimensional arrays
Two dimensional arrays is nothing but array of array. A two-dimensional array
has its elements arranged in a rectangular grid of rows and columns. The elements of a two-
dimensional array can be accessed by using a row subscript (i.e. row number) and a column
subscript (i.e. column number).
A two-dimensional array is popularly known as a matrix.
Array declaration:
}
}
Matrix multiplication using two dimensional arrays
#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
printf("enter the number of row=");
scanf("%d",&r);
scanf("%d",&c);
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
} }
{
for(j=0;j<c;j++)
scanf("%d",&b[i][j]);
} }
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]); 666
} 12 12 12
printf("\n"); 18 18 18
return 0;
}
Draw backs of Linear Arrays
1. The number of elements, which are to be stored in an array, is to be known first.
2. When an array is declared, memory is allocated to it. If array is not filled completely, the
vacant place occupies memory.
3. Once the array is declared, its dimension can be changed.