Problem Sloving Through C Programming
Problem Sloving Through C Programming
1.1 Introduction
A computer is a programmable machine that receives data, stores and manipulates data, and
provides output in a useful format.
In regards to today’s computers, the “machine” part of the computer is called the hardware, while
the “programmable” part is called the software.”
BINARY is the data format that the computer understands: not a high-level or low-level
programming language or a human language. All other data should be reduced and converted to
this BINARY format so that a computer system can understand and work on it.
Evolution of Computers:
2. In 1642, Blaise Pascal designed a calculator that employed gears and wheels
3. Analytical Engine: Designed by Charles Babbage. Input was applied through punched cards.
This engine could store 1000 20-digit numbers and a modifiable program. This machine employed
more than 50,000 mechanical parts and could not operate reliably
2. A mechanical machine driven by a single electric motor was developed in 1889 by Herman
Hollerith to count, sort and collate data stored in punch cards.
3. Z3 was the first electronic computer used by Germans during the World War II.
4. ENIAC: Electronic Numerical Integrator and Calculator was the first general purpose digital
computer. It used 17,000 vacuum tubes, over 500 miles of wires and weighed 30 tons. It could
perform around 10,000 operations per second.
6. Invention of transistors in Bell Labs in 1948 resulted in computers that were faster, smaller in
size, weighed less, needed less power and were more reliable.
7. Invention of Integrated Circuits (ICs) in 1958 resulted in computers such as IBM 360 which
were more compact and reliable. These computers incorporated MSI (Medium Scale Intgeration)
8. Intel introduced a single chip microprocessor 4004 which employed a Large Scale Integrated
circuit (LSI)
Generation of computers
First Generation:These computers were very large, required cooling, had low memory capacities,
slower operations and had huge power requirements. The input to such system was applied using
punched cards. These computers did not comprise of any operating systems.
Example: MARK I
Second Generation: Smaller size, faster operations, less power consumption and large memory
capacities when compared to the first generation. Transistor technology was used to develop
computers. These computers did not have any operating systems. Example: IBM 1401, MINSK-
2, B5000.
Third Generation: Enhanced speed and reliable computers when compared to first and second
generation. Used SSI (Small Scale Integration) and MSI (Medium Scale Integration) circuits and
the computers came with an operating system for user interface.
Examples: IBM 360/370, UNIVAC 1100.
Fourth Generation: The fourth generation computers were much more advanced with LSI and
VLSI (Large Scale and Very Large Scale Integrated Circuits) comprising of thousands to a
millions of transistors. These computers comprised of hardware and software and came with CPU
and memory modules. They had an operating systems and input/output interfacing circuits.
Example: ICL 2900, ALTAIR 8800, IBM-PC
Fifth Generation:The present generation of computers employing Ultra Large Scale Integrated
Circuits with nano-meter technology making the computers more compact, faster, large memory
capacities, low power consumption and affordable.
Organization of a computer
1. Central Processing Unit (CPU)/Microprocessor – CPU performs the computation of data and
controlling the hardware and Input/output devices.
A central processing unit (CPU) is the electronic circuitry within a computer that carries out the
instructions of a computer program by performing the basic arithmetic, logical, control and
input/output (I/O) operations specified by the instructions.
Arithmetic Logic Unit (ALU) is digital circuitry for arithmetic, logical and comparison operations
(addition, subtraction, multiplication, division, AND, OR etc.).
The Control Unit (CU) is digital circuitry contained within the processor that coordinates the
sequence of data movements into, out of, and between a processor's many sub-units. It fetches
instructions from memory, decodes the instruction and executes the instruction.
2. Main Memory (primary storage) – Holds the data that is fetched from secondary storage
which would be needed for computation. It is a volatile memory; the data will be wiped off when
the computer the power supply is disconnected. Example of primary storage is a RAM (Random
Access Memory)
3. Secondary Storage – Stores the data permanently. Its non-volatile memory and stores the data
even when powered off. Example for secondary storage devices would be ROM, Magnetic tapes,
Hard Drives etc.
4. Input and Output (I/O) devices – The devices that help in obtaining input from different
devices such as keyboard or tapes and display the output to a Monitor or a printer.
The two components at the heart of the hardware structure are the central processing unit (CPU)
and the main Memory. The CPU monitors and controls the operation of the other devices and the
flow of information to and from these devices, and it performs all the necessary manipulations of
the data. The Main Memory is used to store information for immediate access by the CPU. Main
Memory is also referred to as Primary Storage or Main Store. Secondary storage devices provide
permanent storage of large amounts of data. Secondary storage is also called: secondary memory,
external memory, backing store or auxiliary storage. This storage may consist of magnetic tapes,
magnetic disk, optical memory device, or similar device.
Input/output devices provide an interface between the computer and the user. There is at least one
input device (e.g. keyboard, mouse, measuring device such as a temperature sensor) and at least
one output device (e.g. printer, screen, control device such as an actuator). Input and output devices
like keyboards and printers, together with the external storage devices, are referred to as
peripherals
The computer system requires interconnections between the various components. When these data
paths carry more than one bit simultaneously from a number of different components, it is referred
to as a data bus or simply bus.
Storage devices are one of the core components of any computing device. They store all the
data and applications on a computer. They are available in different form factors depending on
the type of underlying device. For example, a standard computer has multiple storage devices
including RAM, cache, a hard disk, an optical disk drive and externally connected USB drives
Storage device can be classified as Primary and Secondary memory devices which are
explained in the upcoming sections.
5 At present the capacities of primary The capacities of hard disk drive currently can
memory ranges from 512 MB to be up to 60 Tera Bytes.
16GB for desktop computers and
can be of higher capacities for
Servers.
6 The contents of the primary memory The contents of the secondary memory are not
are directly accessible to the CPU.directly accessible by the CPU. The contents
have to be first copied to the primary memory
and then be accessed by the CPU.
7 This is a temporary memory when Secondary memory devices can be used to store
we speak in terms of RAM. data permanently
8 These are made up of semiconductor These are made up of magnetic
memories. and optical memories.
9 Example: RAM and ROM. Example: DVD ROM, CD-ROM and
Hard disk.
Types of RAM:
Static RAM
The word static indicates that the memory retains its contents as long as power is being
supplied.
The data is lost when the power supply is disconnected due to volatile nature.
SRAM cell is constructed with a matrix of 6-transistors and but no capacitors are used to
form a SRAM cell.
There is no leakage of current/charge in SRAM cell, so SRAM cell does not require a
refresh circuit to retain charge.
Due to the presence of 6 transistors for making up on SRAM cell, SRAM uses more space
than DRAM for the same amount of storage space, thus making the manufacturing costs
higher. It takes more transistors to store a bit of data using SRAM.
SRAM is used as cache memory and can be accessed in a very short of time.
Characteristics of SRAM
• Reliability
• Simplicity: There is no need of a refresh circuit.
• Faster
• Used as cache memory
• Large size
• Expensive
• Lower power consumption
Dynamic RAM
DRAMs are made up of memory cells which are composed of one transistor and one
capacitor.
The capacitor keeps discharging with time and hence a DRAM cell must be continually
refreshed in order to maintain the data.
Refreshing of DRAM cell is done with the help of refresh circuit that rewrites the data
present on the RAM periodically.
DRAM is used for most of the applications as system RAM memory as it is comparatively
cheaper and smaller when compared to SRAM.
ROM stands for Read Only Memory. (It is also called as firmware memory).
As the name says “read only” we can only read the content of it and not write any
information to it. Different types of ROMs are available to which information can be
written to and these will be discussed in the further sections.
ROM is a non-volatile type of memory. The data written to it remains unaltered even if the
power is disconnected.
The information is stored permanently in ROM during manufacturing time in case of One
Time Programmable ROMs.
ROMs are used to store instructions that are required to start a computer (boot sequence).
For such applications, the ROM is used as bootstrap memory.
ROMs are not only used in the computer but also in our day to day lives in electronic
appliances such as washing machines and microwave oven.
Types of ROMs
PROM is programmable read-only memory that can be modified only once by a user. It is
also called as One Time Programmable ROM (OTP ROM).
The user buys a blank PROM and enters the desired contents using a PROM program.
A PROM memory array consists of an array of fuses which are burnt open (to write a logic
0) during programming. Initially an unprogrammed PROM contains all 1’s (all the fuses
form a closed circuit) as shown in fig 1.8.
A PROM can be programmed only once and is not erasable.
The process of writing data to the PROM involves a special piece of equipment called a
device programmer.
The device programmer writes data to the device one word at a time by applying an
electrical charge to the input pins of the PROM chip.
Once a PROM has been programmed, its contents can never be changed.
Fig 1.9: Erasable Programmable ROM with a window to pass UV light to erase the contents
Super-computers are very fast and powerful machines. Their internal architecture enables themto
run at the speed of tens of MIPS (Million Instructions per Second). Super-computers are
veryexpensive and for this reason are generally not used for CAD applications. Examples of
supercomputersare: Cray and CDC Cyber 205.
Mainframe computers are built for general computing, directly serving the needs of business and
engineering. Although these computing systems are a step below super-computers, they are still
very fast and will process information at about 10 MIPS. Mainframe computing systems are
located in a centralized computing center with 20-100+ workstations. This type of computer is still
very expensive and is not readily found in architectural/interior design offices.
Minicomputers were developed in the 1960's resulting from advances in microchip technology.
Smaller and less expensive than mainframe computers, minicomputers run at several MIPS and
can support 5-20 users. CAD usage throughout the 1960's used minicomputers due to their low
cost and high performance. Examples of minicomputers are: DEC PDP, VAX 11.
Microcomputers were invented in the 1970's and were generally used for home computing and
dedicated data processing workstations. Advances in technology have improved microcomputer
capabilities, resulting in the explosive growth of personal computers in industry. In the 1980's
many medium and small design firms were finally introduced to CAD as a direct result of the low
cost and availability of microcomputers. Examples are: IBM, Compaq, Dell, Gateway, and Apple
Macintosh.
The average computer user today uses a microcomputer. These types of computers include PC's,
laptops, notebooks, and hand-held computers such as Palm Pilots.
A number system (or numeral system) is the one which is used for expressing (or) writing numbers.
It uses digits or other symbols to represent the numbers of a given set in appropriate manner.
Commonly used number systems are Decimal, Binary, Octal and Hexadecimal systems. Each system
has its own way of representing the numbers. For ex: 101 can be seen as “one hundred one” in decimal
notation, “five” in binary system and “sixty five” in octal system.
The number system that we use in our day-to-day life is the decimal number system. Decimal number
system has base 10 as it uses 10 digits from 0 to 9. In decimal number system, the successive positions
to the left of the decimal point represent units, tens, hundreds, thousands, and so on.
Ans = (4215)10
5 3 6 Binary point 1 5 9
5x102 3x101 6x100 1x10-1 5x10-2 9x10-3
Ans= 500+30+6+0.1+0.05+0.009 = (536.159)10
Ans = (21)10
1 0 1 1 0 1 1
Binary point
1x23 0x22 1x21 1x20 0x2-1 1x2-2 1x2-3
Ans = 8+0+2+1+0+0.25+0.125 = (11.375)10
82 81 80 . 8-1 8-2
2 3 1 Decimal 2 5
point
2x82 3x81 1x80 2x8-1 5x8-2
Ans = 128+24+1+0.25+0.078125 = (153.328125)10
Ans = (4388)10
A 0 2 Decimal point B 7
10x162 0x161 2x160 11x16-1 7x16-2
The below table below shows the Binary counting sequence and the representation to different
numbers systems.
Solution:
1. Starting from the radix point partition the given binary number into groups of
three, as per the given directions (left and right).
(001, 001, 111 . 110, 101, 010)2
2. Each group of three corresponds to a single octal digit. Using table 2.2 find the
octal number for each group.
1. Partition the given binary number into groups of three, starting at the radix point and
going left and right.
(1,011, 001, 100 . 001, 10)2
2. Each group of three corresponds to a single octal digit. But the last group on both left
hand and right hand side doesn’t have three digits. So add sufficient zero’s in the same
direction to make a group of three digits.
Solution:
1. Partition the given binary number into groups of four, starting at the radix point
and going left and right and right.
1111, 1100, 1010 . 0111, 11112
2. Each group of four corresponds to a single octal digit. Using table 4.3 find the
octal number for each group.
1. Partition the given binary number into groups of four, starting at the radix point and
going left and right.
(11, 1110, 1010 . 0111, 110)2
2. Each group of four corresponds to a single hexadecimal digit. But the last group on
both left hand and right hand side doesn’t have four digits. So add sufficient zero’s in
the same direction to make a group of four digits.
Solution: Each octal digit represents three binary bits. Use table 2.2 to find the three bits that
correspond to each octal digit and replace it with the binary digits.
7 3 5 . 5
Solution: Each hexadecimal digit represents four binary digits. Use table 2.2 to find the four bits
that correspond to each hexadecimal digit and replace it with the binary digits.
2 D=13 E=14 5 . 6 A=10
Step 1: In order to convert octal number to hexadecimal number, first the octal number is to be
converted into binary.
Step 2:Partition the above binary number into a group of four bits and write equivalent
hexadecimal number.
5 7 2 . 1 5
101111010.001101
Step 1: In order to convert hexadecimal number to octal number first the hexadecimal number is
to be converted into binary.
Step 2:Partition the above binary number into a group of three bits and write equivalent octal
number.
1 B E 5 . 3 A
0001101111100101.00111010
Step 2: 000,001,101,111,100,101 . 001,110,010
Final Ans: (15745.162)8
Solution:
Division Remainder Binary
25/2 = 12+ remainder of 1 1 (Least Significant Bit)
12/2 = 6 + remainder of 0 0
6/2 = 3 + remainder of 0 0
3/2 = 1 + remainder of 1 1
1/2 = 0 + remainder of 1 1 (Most Significant Bit)
Ans: (25)10= (11001)2
Fractions Conversion
In order to convert binary fraction into its equivalent decimal number each bit in the fractional
part is multiplied by its positional weight after the decimal point and representing the values from
the MSB to the LSB.
Solution: Fraction
Multiply .75 by 2 = 1.5 1 (MSB)
Multiply .5 by 2 = 1.0 1
Multiply 0 by 2 = 0.0 0 (LSB)
Ans: (.75)10 = (.110)2
Solution: The conversion is accomplished in two parts. First, convert the integer part of the
decimal number by successive division.
Division Remainder Binary
95/2 = 47+ remainder of 1 1 (Least Significant Bit)
47/2 = 23 + remainder of 1 1
23/2 = 11 + remainder of 1 1
11/2 = 5 + remainder of 1 1
5/2 = 2 + remainder of 1 1
2/2 = 1 + remainder of 0 0
1/2 = 0 + remainder of 1 1 (Most Significant Bit)
Ans: (95)10 = (1011111)2
Solution:
1. Convert the integer portion by successive division
Solution:
Exercise Problems:
=8+4+2+0+0.5+0.25+0.125 =0.5+0.25+0
=(14.875)10 =0.75=( 0.75 )10
5) Decimal to Binary 6) Decimal to Binary
(105.202)10 =(1101001.0011)2 (0.825)10 = (0.1101)2
2 105 0.202x2 0.404 0.825x2 = 1.650 Carry 1
2 52 1 .404x2 0.808 0.650x2 = 1.300 1
2 26 0 0.808x2 1.616 0.300x2 = 0.600 0
2 13 0 0.616x2 1.232 0.600x2 = 1.200 1
2 6 1
2 3 0
1 1
0.101 011 3 5 6 5
5 3 011 101 110 101
9)Binary to Hex 10) Hex to Binary
(10110101001.101011)2=(5A9.AC)16 (90AB.1C)16=(1001000010101011.00011100)2
0101 1010 1001 . 1010 1100 9 0 A B . 1 C
5 A 9 A C 1001 0000 1010 1011 0001 1100
11) Decimal to Octal 12) Octal to Decimal
(985.85)10=(1731.66314)8 (1234.56)8=
8 985 0.85x8= 6.80 C 6 3 2 1 0 . -1 -2
8 123 1 0.80x8= 6.40 6 1 2 3 4 . 5 6
8 15 3 0.40x8= 3.20 3 3 2 1 0 -1 -2
=1x8 + 2x8 + 3x8 + 4x8 + 5x8 + 6x8
1 7 0.20x8= 1.60 1 = 512+ 128 + 24 +4+ 0.625 +.09375
0.60x8= 4.80 4 =(668.71875)10
13) Decimal to Hexadecimal 14) Hexadecimal to Decimal
(988.86)10 =(?)16 (ABC.CD)16=(?)10
16 988 0.86x16 =13.76 (D)16 = Ax162+ Bx161+ Cx160. Cx16-1+ Dx16-2
16 61 C 0.76x16 =12.16 (C)16 =(2748.80)10
3 D 0.16X16 =2.56 (2)16
0.56X16 =8.96 (8)16
= (3DC.DC28)16
(284.65)10 = (11C.A666)16
16 284 0.65x16 = 10.40 = A
16 17 12 0.40x16 = 6.40 = 6
1 1 0.40x16 = 6.40 = 6
0.40x16 = 6.40 = 6
1.5 Algorithms and Flowcharts
1.5.1 Algorithms
Fig 1.8 Flowchart to find largest of 3 no’s developed using RAPTOR tool
Above figure demonstrates a flowchart in case of looping constructs such as “while” and “for”
loops. A variable such as “i” is initialized with a value. This variable is tested for a condition, the
statements in the loop (i=i+1) keeps executing until the condition i=5 is satisfied. It should also be
noted that the instructions in the loop gets executed until the condition is satisfied (in this case
PUT i, to print the value of gets printed until the condition is satisfied).
Chapter 2: C Programming Basics
2.1 Structure of a C Program
Global declarations involves declaration of the variables that are visible to all the parts of the
program.
All functions including main() can be divided into twosections—local definition and statements.
Local definitionswould be at the beginning of the functions which is followed
by statement section. It describes the data that will be usedin the function. Data objects in local
definitions as opposedto global declarations are visible only to the function thatcontains them.
Statement section consists of the instructionsthat cause the computer to do something.
The difference between a declaration and a definition is important. A declaration announces the
properties of a data object or a function. The main reason for declaringdata objects and functions
is type checking. If a variable or function is declared and later reference is made to it with data
objects that do not match the types in the declaration, the compiler will complain.
A definition, on the other hand, actually sets aside storage space (in the case of a data object) or
indicates the sequence of statements to be carried out (in the case of a function).
2.2. Basic Execution of a C Program
The steps involved in execution of a basic program are as listed as depicted in figure 2.3
We shall consider execution of simple program written as shown and explain with reference
this program.
The program is written using a text editor such as notepad and the file is saved as simple.c
File: simple.c
#include <stdio.h>
void main()
printf(“Hello C Language”);
Step 1: Create/Edit
Step 2: Compiling
1. Compiling C Program: C Source code with [.C] Extension is given as input to compiler
such as Turbo C and compiler converts it into Equivalent Machine Instruction.
2. Compiler Checks for errors. If source code is error-free then Code is converted into Object
File [.obj ].
Step 3: Checking Errors
1. During Compilation Compiler will check for error, if compiler finds any error then it will
report it.
2. User has to go back to the source program and edit the program to correct the errors.
3. After editing and saving the program, It is compiled again to check for any errors.
3. The process of linking the source program with libraries and header files is achieved using
a software called Linker.
1. Once the program is compiled and linked, an executable “.exe” file is generated. The
program is executed using this “.exe” file. The user has to thoroughly test the program for
different input combinations to identify and 33nalyse if there are any runtime errors (such as
divide by 0).
2. If there have been any run time errors then the programmer has to check the code and find
a solution to overcome the run time error. The program has to be tested again until it is error
free.
Figure 2.2 Basic execution flow of a C program
2.3Variables
A variable is a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable’s memory;
the range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.The name of a variable can be composed of letters, digits, and the
underscore character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C is case-sensitive.
Syntax
Data_type variable_list;
Here, type must be a valid C data type including char, int, float, double, bool, or any user-
defined object; and variable_list may consist of one or more identifier names separated by
commas.
Example:
int I;
float weight;
char section;
here the data types in the above three declarations are int for type integer, float for the type
real and char for character data type are declared using the keywords. The variable names are “i”,
“weight” and “section”.
2.4 Constants/Literals
A constant is a value or an identifier whose value cannot be altered in a program. An
identifier also can be defined as a constant.
example
const double PI = 3.14
2.5 Operators
Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction and
multiplication on numerical values (constants and variables).
* multiplication
/ division
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d \n", ++a);
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0;
}
Output
++a = 11
--b = 99
++c = 11.500000
++d = 99.500000
++a refers to pre increment operator. The value of “a” is incremented by 1 before the statement is
executed. Similarly C programming also has post increment operators such as a++ and a--.
The value of a gets incremented by 1 after the execution of the statement.
Example:
#include <stdio.h>
void main()
{
// program to demonstrate pre and post increment operators
int a=5;
printf("value of a before increment is %d \n",a++);
// increment within printf() does not get reflected in that printf() statement and output a=5
a++;
printf("Value of a after incrementing is %d \n",a);
}
/* output
value of a before increment is 5
Value of a after incrementing is 7
*/
Assignment Operators
An assignment operator is used for assigning a value to a variable. The assignment operator is =
Operator Example Same as
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
Example Program:
#include <stdio.h>
void main()
{
int a,b;// program to demonstrate pre and post increment operators
a=5;
b=3;
//sum
a+=b;
printf("Sum a+=b is %d \n",a);
a=5;
a*=b;
printf("Sum a*=b is %d \n",a);
a=5;
a/=b;
printf("Sum a/=b is %d \n",a);
a=5;
a%=b;
printf("Sum a mod b is %d \n",a);
a=5;
a-=b;
printf("Sum a-=b is %d \n",a);
}
/* Output
Sum a+=b is 8
Sum a*=b is 15
Sum a/=b is 1
Sum a mod b is 2
Sum a-=b is 2
*/
Relational Operators
A relational operator checks the relationship between two operands. If the relation is true,
it returns 1; if the relation is false, it returns value 0.Relational operators are used in decision
making and loops.
Bitwise Operators
During computation, mathematical operations like: addition, subtraction, addition and
division are converted to bit-level which makes processing faster and saves power. Bitwise
operators are used in C programming to perform bit-level operations.
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Explanation
The first expression conditionalExpression is evaluated first. This expression evaluates to
1 if it's true and evaluates to 0 if it's false.
If conditionalExpression is true, expression1 is evaluated.
If conditionalExpression is false, expression2 is evaluated.
Format specifiers in C
c Single character: Reads the next character. If a width different from 1 char *
is specified, the function reads width characters and stores them in the
successive locations of the array passed as argument. No null character
is appended at the end.
Escape sequences in C
Escape sequence Meaning
\n New line
\t Tab
\b Back space
\a Bell
\o Null character
\? To print question mark
\\ To print slash
\’ To print single quote
\” To print double quote
Explanation
The if statement evaluates the test expression inside the parenthesis.If the test expression
is evaluated to true (nonzero), statements inside the body of if is executed.If the test expression is
evaluated to false (0), a statement inside the body of if is skipped from execution. The flow of
work for if statement is as follows:
if-else statement
It is the basic form where the if statement evaluate a test condition and direct program
execution depending on the result of that evaluation.
Syntax:
if (<expression)>
<statement 1>
else
<statement 2>
Explanation
In if statement, if the <expression> in parentheses is nonzero (true), control passes
to <statement1>. If the else clause is present and the <expression> is zero (false), control will pass
to <statement2>. The else <statement2> part is optional and, if absent, a false <expression> will
simply result in skipping over the <statement1>. The flow of work for if statement is as follows:
Nested if...else statement
if (testExpression1)
Syntax
{
// statements to be executed if testExpression1 is true
}
else if (testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is true
}
.
.
else
{
// statements to be executed if all test expressions are false
}
The if...else statement executes two different codes depending upon whether the test
expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.The
nested if...else statement allows you to check for multiple test expressions and execute different
codes for more than two conditions.
switch statement
This is another form of the multi way decision. It is well structured, but can only be used in
certain cases where;
Only one variable is tested, all branches must depend on the value of that variable and the
variable must be an integral type. (int, long, short or char).
Each possible value of the variable can control a single branch. A final, catch all, default
branch may optionally be used to trap all unspecified cases.
Syntax:
switch (n)
case constant1:
break;
case constant2:
break;
default:
Explanation
The switch statement causes control to be transferred to one of several statements
depending on the value of an expression, which must have integral type. The substatement
controlled by a switch is typically compound. Any statement within the substatement may be
labeled with one or more case labels, which consist of the keyword case followed by a constant
expression and then a colon (:). The work flow of switch case statement is as follows:
2.7 Loops
Looping is a way by which we can execute any some set of statements more than one times
continuously .In c there are mainly three types of loops are use :
while Loop
do while Loop
for Loop
while Loop
Syntax
Initialization
while ( <expression> )
{
<Statement1>
<Statement2>
<Statement3>
}
The most basic loop in C is the while loop. A while loop has one control expression, and executes
as long as that expression is true. The while loops works in the following way:
FALSE
test condition
TRUE
continue
w ith next
iteration
statement body
end of statement
Loops generally consist of two parts: one or more control expressions which control the
execution of the loop, and the body, which is the statement or set of statements which is executed
over and over.
do while Loop
Syntax
Initialization
do
{
<Statement1>
<Statement2>
<Statement3>
}while( <expression> )
Explanation
This is very similar to the while loop except that the test occurs at the end of the loop body.
This guarantees that the loop is executed at least once before continuing. Such a setup is frequently
used where data is to be read. The test then verifies the data, and loops back to read again if it was
unacceptable.
statement body
continue
w ith next
iteration
TRUE
test condition
FALSE
end of statement
for loop
Syntax
Explanation
initialisation :- this is usually an assignment to set a loop counter variable for example.
condition :- determines when loop will terminate.
increment :- defines how the loop control variable will change each time the loop is executed.
statement body :- can be a single statement, no statement or a block of statements.
The for statement executes as follows :-
initialisation
FALSE
test condition
TRUE
continue
w ith next
iteration
statement body
increment
end of statement
Conditional Operator :- ?:
Syntax
if ( condition )
expr_1 ;
else
expr_2 ;
Explanation
The ?: operator is a ternary operator in that it requires three arguments. One of the
advantages of the ?: operator is that it reduces simple conditions to one simple line of code which
can be thrown unobtrusively into a larger section of code.
Example:
#include <stdio.h>
void main()
{
int a,b;// program to demonstrate pre and post increment operators
a=5;
b=3;
printf("%d",a>b?a:b);
}
The output of the above program is 5. The conditional operator ?: is used within the printf(). If a>b
is true then the value of “a” is printed, else the value of “b” is printed. Since a>b is true the output
value 5 gets printed on executing this program.
break statement
It is sometimes desirable to skip some statements inside the loop or terminate the loop
immediately without checking the test expression.The break statement terminates the loop
(for, while and do..while) immediately when it is encountered. The break statement can be used
with decision making statement such as if..else
Syntax
break;
continue statement
The continue statement skips some statements inside the loop. The continue statement is
used with decision making statement such as if...else.
syntax
continue;