Date post: | 04-Apr-2018 |
Category: |
Documents |
Upload: | anjan-prasad |
View: | 231 times |
Download: | 0 times |
of 131
7/30/2019 UNIT-II(c programming)
1/131
UNIT-II
Dennis Ritchie
7/30/2019 UNIT-II(c programming)
2/131
1.History of c language
ALGOL
BCPL
B
C
7/30/2019 UNIT-II(c programming)
3/131
History of c language
project multics to develop an operating system.1969, language B was developed by Ken
Thompson.
c was develop in 1972 by Dennis M. Ritchieat Bell Labs(AT&T) in USA.
1988 c language was standardized by ANSI as
ANSI CANSI- American National Standards Institute.
7/30/2019 UNIT-II(c programming)
4/131
2. Features of C language1. Robust rich set of built in functions and operators can be used to write
any complex programs.
2. C compilers combines the capabilities of low level languages withfeatures of high level language. Therefore it is suitable for writing thesystem softwar5. e, application software and most of the compilers ofother languages also developed with c language.
3. Efficient and fast- rich variety of data types and powerful operators.
4. Portable- c program written on one computer can also run on the othercomputer with small or no modification.
ex- c program written in windows can also run on the linux operatingsystem.
5. Structured programming- every program in c language is divided into
small module or functions so that it makes the program much simpleand debugging, maintenance of the program is easy.
6. Ability to extend itself- A C program is basically a collection of variousfunction supported by C library (also known as header files). We can alsoadd our own functions to the C library. These functions can be reused inother applications or programs by passing pieces of information to the
functions, you can create useful, reusable code.
7/30/2019 UNIT-II(c programming)
5/131
3. Structure of c program
7/30/2019 UNIT-II(c programming)
6/131
Include
information
about standard
library
Main calls library
function printf to
print this message.
7/30/2019 UNIT-II(c programming)
7/131
C program consists of functions and variables.
Function contains the statements that specify
computation operation to be done.
Variables stores the values used during thecomputation.
Function can be named whatever you like. However,
main is the special function where the programexecution starts. Very program must have a main
some where.
7/30/2019 UNIT-II(c programming)
8/131
Preprocessor commands
The preprocessor command always starts withsymbol #
#include this is called preprocessorcommand.
Include command tells the preprocessor that we needthe information from selected libraries called headerfile.
Header file- collection of library files.
-> it tells the compiler to include the information aboutthe standard input\ output library.
-> every program must need at least one libraryfunctions which are available in the header file.
7/30/2019 UNIT-II(c programming)
9/131
Global variables.
The variables which are declared at the starting
of the program called global variable.
They are visible to all the parts of the program.
7/30/2019 UNIT-II(c programming)
10/131
C program consists of functions and variables.
Function contains the statements that specify
computation operation to be done.
Variables stores the values used during thecomputation.
Function can be named whatever you like. However,main is the special function where the programexecution starts. Very program must have a mainsome where.
Functions are communicate each other by passinglist of values called arguments.
Main is defined to be a function that expects noarguments.
7/30/2019 UNIT-II(c programming)
11/131
Local variables
The variables which are declared in a function
are called local variables to that function.
These variables visible only within the
function.
7/30/2019 UNIT-II(c programming)
12/131
Local variables
The variables which are declared in a function
are called local variables to that function.
These variables visible only within the
function.
7/30/2019 UNIT-II(c programming)
13/131
All the statements of main are enclosed in braces.
A function can be called by naming it, followed by aparanthesized list of arguments.
Main calls the printf with argument hello world\n.
The string \n in the string is C notation for thenewline character, which when printed advances theoutput to the left margin on next line.
Printf(hello world\n);
7/30/2019 UNIT-II(c programming)
14/131
printf(hello world
);
C compiler prints the error message.
same program can also rewrite as
#includemain()
{
printf(hello);
printf(world);printf(\n);
return 0;
}
7/30/2019 UNIT-II(c programming)
15/131
Main function may return some integer value to the
operating system
So at the end of the main add the statement return0.
main() is same as the int main()- it means that the
function main returns some integer value to the os. Otherwise write the main as void main()- it does not
return any value to the operating system and not
necessary to write the return statement.
Each statement in c program must end with (;)
specifies that the instruction is ended.
7/30/2019 UNIT-II(c programming)
16/131
Comments
To make the program more readable use the
comments.
They may used to make the program easier to
understand.
Two types of comments
1. block comment
2. line comment.
7/30/2019 UNIT-II(c programming)
17/131
1. Block comment
/* write a program for the addition of two integernumbers*/
#include
main()
{
int a=10,b=20,c;
c=a+b;
printf(sum of a and b=%d,c);return 0;
}
7/30/2019 UNIT-II(c programming)
18/131
1. Block comment
above two lines
/* write a program for the addition of two integer
numbers*/
are a comment, which explains what the program does.
Any characters between /* and */ are ignored by thecompiler.
Comments may appear anywhere a blank or tab or
newline. /* and */ is used to comment the multiple lines of
code which ignored by the compiler.
/*/*..*/ - nested block comments are invalid.
7/30/2019 UNIT-II(c programming)
19/131
2. Line comment
It uses two slashes // .
This is used to comment single line.
// #include
7/30/2019 UNIT-II(c programming)
20/131
Character set
Characters are used to form words, numbers
and expressions.
Characters are categorized as
1.Letters
2.Digits
3.Special characters4.White spaces.
7/30/2019 UNIT-II(c programming)
21/131
Character set Letters (upper case and lower case)A B C D E F G H I J K L MN O P Q R S T U V W X Y Za b c d e f g h i j k l mn o p q r s t u v w x y z
Digits0 1 2 3 4 5 6 7 8 9
Special Characters " ( ) * + - / : =
! & $ ; < > % ? , . # @ { } [ ]\ | White spacesblank space
horizontal spaceCarriage return, new line.
7/30/2019 UNIT-II(c programming)
22/131
Key words and identifiers
C word is classified as either keywords oridentifiers.
Keywords have fixed meanings these
meanings cannot be changed Keywords must be in lowercase.
Keywords depends on compilers that must be
identified from the c manuals.
7/30/2019 UNIT-II(c programming)
23/131
Key words
C key words
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
7/30/2019 UNIT-II(c programming)
24/131
identifiers
Identifiers are name of the variables and
functions.
Identifiers are user defined names means
name given to the variable whatever user
likes.
Ex- int a;// a is identifier
int sum;// sum is identifier.
7/30/2019 UNIT-II(c programming)
25/131
variables
When you want to process some information, you can save
the values temporarily in variables.
Program
#include
main()
{int a=10,b=20,c;
c=a+b;
printf(sum of a and b=%d\n,c);
return 0;
}
o/p- sum of a and b=30
Definition- variable which stores the value in the memory location, that value varies
during program execution
variables in the above program are a b and c .
Notevariables must
be declared before they
are used, usually at the
beginning of the
function.
7/30/2019 UNIT-II(c programming)
26/131
Variables names There are some restrictions on the variable names
1. Names are made up of letters and digits andunderscore(_).
2. The first character of the name must be a letter
3. The underscore is also a legal first character, but itsuse is not recommended.
4. Upper case and lower case letters are distinct, so a
and A are two different names.
5. C keywords can't be used as variable names
6. White space is not allowed in variable names.
7/30/2019 UNIT-II(c programming)
27/131
The following list contains some examples of
legal and illegal C variable names:
Variable Name LegalityPercent Legal
y2x5__fg7h Legal
annual_profit Legal
_1990_tax Legal but not advised
savings#account Illegal: Contains the illegal character #
double Illegal: Is a C keyword
9winter Illegal: First character is a digit
7/30/2019 UNIT-II(c programming)
28/131
Data types in C Type specifies a set of values and a set of operations
that can be applied on those values.
The data type defines the amount of storage allocated
to variables, the type of values stored in variables.
There are only a few basic data types in c
char a single byte, capable of holding one character in
the local character set
intan integer, typically reflecting the natural size of
integers on the host machine float single-precision floating point
double double-precision floating point
7/30/2019 UNIT-II(c programming)
29/131
There are number of qualifiers that can be applied to the basic
types
The qualifiers are also used to increase the range of the values.
Qualifiers are signed, unsigned, short and long.
Signed, unsigned are applied to char and integers.
short apply to integers.
long is used for integers and double.
unsigned numbers are always positive or zero, and obey the 2n,
signed numbers are
short int a;
long int b;
the word int can omitted
7/30/2019 UNIT-II(c programming)
30/131
The charData Type
The shortest data type is character.
It is stored in 1 byte in memory.
Corresponding integer values for all characters are defined in ASCII
code (American Standard Code for Information Interchange).
For example:
character constant ahas an int value 97, b - 98, A- 65 etc.
The keywordchar is used to declare a variable of a character type.
char letter =A;
char letter = 65;
7/30/2019 UNIT-II(c programming)
31/131
The int Data Type
An integer number (also called whole number) has no fractional part or
decimal point.
-> The keyword int is used to specify an integer variable.
-> it occupies 2 bytes (16 bits) or 4 bytes (32 bits), depending on themachine architecture.
16-bit integer can have values in the range of
- 32768to
32767
One bit is used for sign.
For 32-bit integer the range is about from -2 to +2 billions
The sizes of the data types are machine dependent
7/30/2019 UNIT-II(c programming)
32/131
The sizes of the data types are machine dependent.
Short is 16bits, long 32 bits and int either 16 bits or
32 bits.
These sizes are chosen by the compiler for its ownhardware.
In 16 bit processor short2, int- 2, long- 4
In 32 bit processor short-2, int -4, long-4. They are restricted that short is no longer than int, int
is at least 16 bits , long is at least 32 bits.
Unsigned integer
7/30/2019 UNIT-II(c programming)
33/131
Unsigned integer
If you know that the variable cannot have negative values, you may
declare it as unsigned.
unsignedvariable type occupies the same amount of computer memoryas int but the actual value can be twice as large as the maximum
available int, because all values are positive.
To decrease the size of allocated memory for a variable which is not too
large, you may use theshort type which is stored in 2 bytesThefloatData Type
-> The data typefloat represents a floating point number (also called a
real number or numbers with decimal ).->The keywordfloat is used to declare a variable of the type float.
Ex: float float_num1=1.34;
-> The float type variable is usually stored in 4 bytes, which means it is
at least 6 digits of precision.
7/30/2019 UNIT-II(c programming)
34/131
ThedoubleData Type
A floating point number can also be represented by thedouble data type.
The data type double is stored on most machines in 8 bytes which is
about 15 decimal places of accuracy.To declare a variable of the type double, use the keyworddouble.
Types in C
7/30/2019 UNIT-II(c programming)
35/131
Types in C
typesize
(byte)
smallest
number
largest
numberprecision constant
format
specifier
long double 10 3.4E - 4932 1.1E+4932 1.08E - 191.2345L,
1.234E - 5L%Lf, %Le, %Lg
double 8 1.7E - 308 1.7E+308 2.22E - 161.2345,
1.234E - 5%lf, %le, %lg
float 4 1.7E -38 3.4E+38 1.19E - 71.2345F,
1.234E - 5F%f, %e, %g
unsigned long 4 0 4294967295 123UL %lu
long 4 - 2147483648 2147483647 123L %ld, %li
unsigned 4 0 4294967295 123U %u
int 4 - 2147483648 2147483647 123 %d, %i
unsigned short 2 0 65535 123U %hu
short 2 - 32768 32767 123 %hd, %hi
unsigned char 1 0 255 a, 123, \n %c
char 1 - 127 or 0 127 or 255 a, 123, \n %c-128 127
7/30/2019 UNIT-II(c programming)
36/131
Formatted input/ output
The data is to be arranged in a particular format. The data is input to and out put from a stream.
A stream is a source or destination of the data. it isassociated with a physical device, such as terminals
(keyboard, monitor). C has two forms of streams- text stream and binary
stream.
Text stream consists of sequence of characters.
Binary stream consists of a sequence of data in 0sand 1s.
7/30/2019 UNIT-II(c programming)
37/131
FIGURE Stream Physical Devices
7/30/2019 UNIT-II(c programming)
38/131
The data is formatted using the printf andscanf functions.
Scanf() converts the text stream coming from
the keyboard to data values (char, int,ect) andstores them in the program variables.
Printf() converts the data stored in variablesinto the text stream for output the keyboard.
7/30/2019 UNIT-II(c programming)
39/131
IGURE Output Formatting Concept
printf() takes the set of data values and converts them to text stream using
formatting instructions contained in a format control string.
Fomat control specifiers are used to format the text stream.
7/30/2019 UNIT-II(c programming)
40/131
Format specifier specifies the data values type, sizeand display position.
Printf statement takes two arguments
1. control string and 2.data values( variables)
Control string contains the format specifiers andsome text.
syntaxprintf(control string,var1,var2,..varn);
Ex-
int a=10, b=20;
printf(a=%d b=%d, a,b);
7/30/2019 UNIT-II(c programming)
41/131
URE Output Stream Formatting Example
7/30/2019 UNIT-II(c programming)
42/131
URE Formatting Text from an Input Stream
scanf(control string,&var1,&var2.. &varn);
control string includes format specifiers and specifies the field width.
7/30/2019 UNIT-II(c programming)
43/131
int a=12,b=23145;
scanf(%2d %5d,&a,&b);
V i bl d l i
7/30/2019 UNIT-II(c programming)
44/131
Variable declaration Each variable must be declared and defined before
used in the program.
Variable declaration-
1. tells the compiler what is the name of the variable.
2. specifies what type of data values the variable can
hold.
variable definition- reserves the memory for the
declared variable and store some value is called
garbage value.-> variable declaration and variable definition done at the same
time.
7/30/2019 UNIT-II(c programming)
45/131
int a;Variable declaration and definition
23456
a
1000
Variable name
Garbage value
Address of the variable
7/30/2019 UNIT-II(c programming)
46/131
Variable initialization
While declaring the variable assign initial
value is called variable initialization.
Data type identifier= initial value;
ex int a=10;
float b=2.1;float pi=3.14;
char ch=A;
7/30/2019 UNIT-II(c programming)
47/131
constants Constants- fixed values those cannot be
changed during the program execution.
Several types of constants are used
1.Character constants
1.1 single character constants
1.2 string constants.
2. Numeric constants.2.1 integer constant
2.2 real constants.
7/30/2019 UNIT-II(c programming)
48/131
Type qualifier const
One way to use the constant is with memory
constants. Memory constants use a c type
qualifier; const.
This indicates that the data cannot be
changed.
const type identifier= value;
const float pi=3.14;
7/30/2019 UNIT-II(c programming)
49/131
Ex-#include
void main()
{
float area,radius=3.0;
const float pi=3.14;
area=pi*radius*radius;
printf(area of a circle= %f,area);}
7/30/2019 UNIT-II(c programming)
50/131
1. Character constants
A single character constants are enclosed in
single quotes.
Ex- 1 X %
Character constants have integer values called
ASCII values.
char ch=A;
printf(%d,ch); ->65
similarly printf(%c,65)-> A
7/30/2019 UNIT-II(c programming)
51/131
String constants- string a collection of
characters or sequence of characters enclosed
in double quotes.
The characters may be letters, numbers,special characters and blank space.
Ex- snist
2011
A.
Backslash \escape characters
7/30/2019 UNIT-II(c programming)
52/131
Backslash \escape characters Backslash characters are used in output functions.
These backslash characters are preceded with the \ symbol.
Constant meaning
\a Alert(bell)
\b Back space
\f Form feed
\n New line
\r Carriage return
\v Vertical tab
\t Horizontal tab
\ Single quote
\ Double quotes
\? Question mark
\\ Backslash
\0 null
7/30/2019 UNIT-II(c programming)
53/131
Numeric constants
1. integer constant- sequence of digits like
0to 9.
Ex- 123 -678 0 +78.
Rules
1. Integer constant have at least one digit
2. No decimal points
3. No commas or blanks are allowed.4. The allowable range for integer constant is
-32768 to 32767.
7/30/2019 UNIT-II(c programming)
54/131
To store the larger integer constants on 16 bit machine
use the qualifiers such as U,L,UL.
Type Representation Value
int +245 245
int -678 678
unsigned integer 65342u/65342U 65342
unsigned long int 99999UL 99999
long integer 999999L 999999
7/30/2019 UNIT-II(c programming)
55/131
2. Real constants- the numbers containing
fractional parts like 3.14.
1.9099 -0.89 +3.14
Real constants are also expressed in
exponential notation.
Mantissa e exponent
The part appearing before e is called mantissa this may
be the fractional number or integer number and part following e is called
exponent .
Ex 215.65 may be written as 2.1565e2.
7/30/2019 UNIT-II(c programming)
56/131
Examples of real constants
Type Representation Value
double 0. 0.0
double 0.0 .0
float -2.0f -2.0
long double 3.14159276544L 3.14159276544
7/30/2019 UNIT-II(c programming)
57/131
#include
void main()
{
const int a=10;int b=20;
a=a+1;
b=b+1;
printf(a=%d b=%d,a,b);
}
operators
7/30/2019 UNIT-II(c programming)
58/131
operators
C language is robust because it has rich set of
operators. Operatora symbol used to perform a
mathematical or logical manipulations.
Operands- data values\variables are called
operands.
Operators must be applied on the operands.
Expression- combination of operands and operators,
which evaluated to one value i.e either true or false..
X=Y+Z
expression
Operands- x,y,z
Operators- =, +
7/30/2019 UNIT-II(c programming)
59/131
Types of operators
Following are the c operators.1.Arithmetic operators
2.Relational operators.
3.Logical operators.4.Assignment operators.
5.Increment and decrement operators.
6.Conditional operators.7.Bitwise operators.
8.Special operators.
1 Arithmetic operators
7/30/2019 UNIT-II(c programming)
60/131
1. Arithmetic operators
Arithmeticoperators
Meaning
+ Addition or unary operator
- Subtraction or unary operator
* Multiplication
/ Division- gives only coefficient.
% Modulo division- givesremainder.
c= a+b;
z= x-y;
2.Relational operators.
7/30/2019 UNIT-II(c programming)
61/131
p
Relational operators are used to compare the
relationship between two operands.
Relationaloperators
Meaning
< Is less than> Is greater than
= Greater than or equal to
= = Equal to
!= Not equal to
The value of a relational
Expression is either one or
zero. It is one if the
Specified relation is true and
zero if the relation is false .
Relational operators are used
if and else, while, for
statements.
3 Logical operators
7/30/2019 UNIT-II(c programming)
62/131
3. Logical operators. Logical operators used to test more than one
condition and make decision. Yields a value either one or zero
Logicaloperator
meaning
&& Logical AND
|| Logical OR
! Logical NOT
Ex- x
7/30/2019 UNIT-II(c programming)
63/131
AND OR truth table
Op1 Op2 AND OR
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
4. Assignment operators
7/30/2019 UNIT-II(c programming)
64/131
g p
The value of an expression assigned to a
variable.
Assignment operator is =
variable = expression;
a= a+1; =>a+=1;
x= x-1; => x-=1;
x=x*(y-1); =>x*=y-1;
x=x/(y-1); => x/=y-1; x=x%y; =>x%=y;
5 Increment and decrement operators
7/30/2019 UNIT-II(c programming)
65/131
5. Increment and decrement operators.
Increment operator- ++
Decrement operator - --
++- add one(1) value to the operand
-- - subtracts one value to the operand.
++x; equal to x=x+1;or x+=1;
--y; equal to y=y-1;or y-=1;
6 Conditional operators ?:
7/30/2019 UNIT-II(c programming)
66/131
6. Conditional operators ?:
Another name is ternary operator
Syntax
Exp1?exp2:exp3;
where exp1, exp2,exp3 are expressions.
Exp1 evaluated first if it is non zero (true), then the exp2 is evaluate
and becomes the value of the expression.
if exp1 is zero(0), then exp3 is evaluated and become the value of
the expression.
?:
ex- a=1;
b=2;
x= (a
7/30/2019 UNIT-II(c programming)
67/131
p
Manipulates the data which is in binary form.
Bitwise
operators
Meaning
& Bitwise AND
| Bitwise OR
^ Exclusive OR
> Shift right
~ Ones compliment
7/30/2019 UNIT-II(c programming)
68/131
/Examples:& Bitwise AND 0110 & 0011 0010
| Bitwise OR 0110 | 0011 0111
^ Bitwise XOR 0110 ^ 0011 0101
Right shift 01101110 >> 3 00001101
~ One's complement ~0011 1100
Notice: > multiply/divide by 2n
Don't confuse bitwise & | with logical && ||
7/30/2019 UNIT-II(c programming)
69/131
8. Special operators
Special operators- *, -> ., , sizeof()Sizeof()- unary operator (operates on a single value)
Produces a result that represent the size in bytes or the data specified
Format
sizeofdata
e.g.
int a = 5;
sizeof(a);//produces 4
Orsizeof(data type)
e.g. sizeof(char);//produces 1
7/30/2019 UNIT-II(c programming)
70/131
Unary operators- operators used on a single
operand - -, +, ++, --.
Binary operators - operators used to apply in
between two operands- +, -, /, %.
7/30/2019 UNIT-II(c programming)
71/131
FIGURE Expression Categories
Primary expression
7/30/2019 UNIT-II(c programming)
72/131
Primary expression
An expression as only one operand no
operator is called primary expression. It may be name of the variable, constant, or a
parenthesized expression.
a, snist,1.56, (x=10*2).
Post fix expression- expression containsoperand followed by one operator.
ex- a++; a- -;Operand must be the variable in post fix expression.
7/30/2019 UNIT-II(c programming)
73/131
FIGURE Result of Postfix a++
expression
1. Value of the variable a is assigned to x
2. Value of the a is incremented by 1.
7/30/2019 UNIT-II(c programming)
74/131
Example on post fix expression
#includevoid main()
{
a=10;
x=a++;
printf(x=%d, a=%d,x,a);
}
out put- x=10, a=11
7/30/2019 UNIT-II(c programming)
75/131
FIGURE Prefix Expression
Prefix expression- operator followed by the operand.
ex- ++a;
7/30/2019 UNIT-II(c programming)
76/131
FIGURE Result of Prefix ++a
7/30/2019 UNIT-II(c programming)
77/131
Example on pre fix expression
#includevoid main()
{
a=10;
x=++a;
printf(x=%d, a=%d,x,a);
}
out put- x=11, a=11
7/30/2019 UNIT-II(c programming)
78/131
FIGURE Unary Expressions
Unary expression- unary operator followed by the operand
7/30/2019 UNIT-II(c programming)
79/131
Table Examples of Unary Plus And Minus Expressions
7/30/2019 UNIT-II(c programming)
80/131
FIGURE Binary Expressions
Binary expressions- operator must be placed in between the
two operands.
1Operand must be integral data type( int, float)
Ex- a+ba-c
Precedence and association rules among
7/30/2019 UNIT-II(c programming)
81/131
operators Precedence- the order in which expression is
evaluated.
Every operator has a special precedence.
The operators which has higher precedence in the
expression is evaluated first. example- a=8+4*2; a=?
Associativity- Operators on the same line in the chart
have the same precedence, and the "Associativity"column on the right gives their evaluation order.
Operator Precedence ChartOperator Type Operator Associativity
7/30/2019 UNIT-II(c programming)
82/131
Primary Expression Operators () [] . -> expr++ expr-- left-to-right
Unary Operators * & + - ! ~ ++expr --expr (typecast) sizeof right-to-left
Binary Operators * / % left-to-right
+ -
>> =
== !=
&
^
|
&&
||
Ternary Operator ?: right-to-left
Assignment Operators = += -= *= /= %= >>=
7/30/2019 UNIT-II(c programming)
83/131
83
FIGURE 3-8 Left-to-Right Associativity
Implicit Conversion
Type conversion- converting from one data type to another data type
7/30/2019 UNIT-II(c programming)
84/131
Implicit Conversion
If the compiler expects one type at a position, but another type is provided, thenimplicit conversion occurs. Compiler itself converts one type to other.
Conversion during assignments:
char c = 'a';
int i;
i = c; /* i is assigned by the ascii of a */
Arithmetic conversionif two operands of a binary operator are not the sametype, implicit conversion occurs:
int i = 5 , j = 1;float x = 1.0, y;
y = x / i; /* y = 1.0 / 5.0 */
y = j / i; /* y = 1 / 5 so y = 0 */
You can override Cs default conversions by specifying your own temporary type
change using the format:
(data type) expression
(data type) can be any valid C data type and expression is any variable, constant or
a combination of both
int x;
x=(int)7.5;
Explicit Conversion or type casting
Decision control structures
7/30/2019 UNIT-II(c programming)
85/131
Decision control structuresTill now we have used sequence control structure in the programs, in which the various
steps are executed sequentially i.e. in the same order in which they appear in the
program.In C programming the instructions are executed sequentially, by default.
At times, we need a set of instructions to be executed in one situation and an another
set of instructions to be executed in another situation.
In such cases we have to use decision control instructions.This can beacheived in C using;
(a)The if statement
(b)The if-else statement
(c)The conditional operators
1 If
7/30/2019 UNIT-II(c programming)
86/131
1. If statement
Based on the condition execute the set ofinstructions otherwise skip them.
C uses the key word if to implement the
decision control instruction. general form of if statement
if( condition\expression)
{
execute the statements;
}
Condition following the
if must be enclosed within
parenthesis.If the condition is true then
execute the given statement
otherwise the statements not
executed.
If
7/30/2019 UNIT-II(c programming)
87/131
If statement
If it has single statement to execute then curlybraces are optional.
More than one statement curly braces are
compulsory.
Ex- int rno=2408;
if(rno==2408)
printf(this is ECE-C2);
f condition
7/30/2019 UNIT-II(c programming)
88/131
condition
statement
statement
if ( condition )
statement;
Enter
Test
Body of the IF Statement
Exit
If l
7/30/2019 UNIT-II(c programming)
89/131
If- else statements
if statement will execute a single statement, or a group ofstatements, when the expression following if evaluates to true.But it does nothing when the expression evaluates to false.
In case, we want to execute one group of statements if theexpression evaluates to true and another group of statements ifthe expression evaluates to false, we need to use the If-elsestatement.
The syntax of If-else statement is as follows;if (condition\expression){
Statement1}
else {
statement2 }
statement-x
The expression evaluated to true,statement1 is executed.
If false, statement2 is executed.
Both cases statement-x is executed
The if-else StatementAn else clausecan be added to an if statement to make an if-else
7/30/2019 UNIT-II(c programming)
90/131
statement
If the condition is true, statement1 is executed; if the condition isfalse, statement2 is executed
One or the other will be executed, but not both
Enter
Test
Body of the
IF Statement1
Exit
Body of the
ELSE Statement2
Flowchart for if-else
7/30/2019 UNIT-II(c programming)
91/131
Examplefloat percentage;
printf (enter the percentage);
scanf (%f, &percentage);
if (percentage
7/30/2019 UNIT-II(c programming)
92/131
Few points to remember
else must be written exactly below the if
If there is only one statement in if and else
block we can drop the pair of curly braces.
if( x>0)
if(a>b)
z=a;else
z=b;
if( x>0)
{
if(a>b)
z=a;
}
else
z=b;
Nested if else- within the if else we caninclude other if-else either in if block or
7/30/2019 UNIT-II(c programming)
93/131
else block
TF
TF
Nested if- else
7/30/2019 UNIT-II(c programming)
94/131
Marks obtained by the student must given through
keyboard. Print the result as per the following
rules.
1. Percentage is above or equal to 75- distinction.
2. Percentage is less than 75 and equal to 60- first
class.3. Percentage is less than 60 and equal to 50- second
class.
4. Percentage is less than 50 and equal to 40- thirdclass.
5. Percentage is below 40 failed.
#includevoid main()
{
float m1 m2 m3 m4;
7/30/2019 UNIT-II(c programming)
95/131
float m1,m2,m3,m4;
float perc;
printf(enter marks\n);
scanf(%f%f%f%f,&m1,&m2,
&m3,&m4);
perc=(m1+m2+m3+m4)/4;
if(perc>=75)
printf(\ndistinction);
else
{
if(per=60)
printf(\n first class);
else{if(per=50)
printf(\n second class);
else {
if(per=40)
printf(\n third class);
else
printf(\nfail);
}//else
}//else
}//else
Disadvantages-
care must be taken to match thecorresponding pair of braces.
Else if statement
7/30/2019 UNIT-II(c programming)
96/131
if(expression1)
statement-1;else if(expression-2)
statement-2;
else if(expression-3)
statement-3;else if (expression-n)
statement-n;
else
statement-x;statement-y
Draw the flowchart for the else if statement.
else if clauseNested if else
7/30/2019 UNIT-II(c programming)
97/131
#include
void main()
{
float m1,m2,m3,m4;float perc;
printf(enter marks\n);
scanf(%f%f%f%f,&m1,&m2,
&m3,&m4);
perc=(m1+m2+m3+m4)/4;
if(perc>=75)
printf(\ndistinction);
else
{
if(per=60)
printf(\n first class);
else{
if(per=50)
printf(\n second class);
else {if(per=40)
printf(\n third class);
else
printf(\nfail);
}//else
}//else
}//else
#include
void main()
{
float m1,m2,m3,m4;float perc;
printf(enter marks\n);
scanf(%f%f%f%f,&m1,&m2,
&m3,&m4);
perc=(m1+m2+m3+m4)/4;
if(perc>=75)printf(\ndistinction);
else if(per=60)
printf(\n first class);
else if(per=50)
printf(\n second class);
else if(per=40)
printf(\n third class);
else
printf(\nfail);
Nested if else
Switch statement
7/30/2019 UNIT-II(c programming)
98/131
Switch statement
In else if statement as the no of choiceincreases the program becomes difficult to
read.
C has a built in multi way decision statementcall it as switch.
The control statement that allows us to make
a decision from the number of choices iscalled switch.
Switch statement
7/30/2019 UNIT-II(c programming)
99/131
General form of switchswitch (expression)
{case value-1:
block1;
break;
case value-2:
block2;break;
case value-n:
blockn;
break;
default:
default block;
}//switch
statement-x;
1. The expression is any expression
that must evaluates to integer value.
2. The keyword case followed by aninteger or a character constant.
3. Each value in each case must be
different from all the others.
4. How this program runs? First
expression is evaluated.5. This evaluated value compares
against the values that follow the
case statements.
6. When a match is found, executes the
statements following that case andall the other cases were skipped.
7. If no match is found with any of the
case statements, default block is executed.
8. Default is optional.
9. At last statementx is executed.Break is used to exit from block
Examples on switch
7/30/2019 UNIT-II(c programming)
100/131
Void main()
{
int a;scanf(%d,&a);
switch(a)
{
case 1:
printf(One);break;
case 2:
printf(two);
break;
case 3:
printf(three);break;
default:
printf(this is default);
}//switch
}//main
Void main()
{
int a;scanf(%d,&a);
switch(a)
{
case 1:
printf(One);
case 2:printf(two);
case 3:
printf(three);
default:
printf(this is default);}//switch
}//main
Note- there is no break in default case.
Tips about the usage of switch
case al es ma not be in the ascending order We can p t the
7/30/2019 UNIT-II(c programming)
101/131
case values may not be in the ascending order. We can put the
cases in any order.
int a;
scanf(%d,&a);
switch(a)
{
case 3:
printf(One);
break;
case 1:printf(two);
break;
case 2:
printf(three);
break;
default:
printf(this is default);
}//switch
we can also use char values in case and switch.
7/30/2019 UNIT-II(c programming)
102/131
char ch=x;
switch(ch)
{case A:
printf(this is A);
break;
case x:
printf ( this is small x);
break;
default: printf (other letter);
}//switch
ch expression evaluated to the asciivalue of x it is also an integer value
can also execute a common set of statements for multiple
7/30/2019 UNIT-II(c programming)
103/131
cases.
ex- write a program to test whether the given alphabet is vowel
or consonant.Void main(){ char ch;
printf( enter the alphabet);
scanf(%c,&ch);
switch(ch)
{case a:
case e:
case i:
case o:
case u:printf (\nthe alphabet is vowel);
break;
default:
printf(\nthe alphabet is consonant);
}
if there are multiple statements to be executed in the case noneed to enclose them in pair of curly braces.
7/30/2019 UNIT-II(c programming)
104/131
Every statement in the switch must belong to some case or
other. Even if a statement does not belong to any other case the
compiler doesnt give any error. However that statement neverexecuted.
Ex-
switch(x)
{
printf(\nhai);case 1:
printf(one);
break;
}//switch if no default case, the compiler executes the statement immediately
following the close brace of switch
switch may occur within another switch called
7/30/2019 UNIT-II(c programming)
105/131
nested switch.
continue statement should not used in switch.
Switch statement is mainly used for the menu drivenprograms.
value in the case must be an int constant or char
constant or an expression that evaluates to one ofthese constants. even float is not allowed.void main()
{ int x;
scanf("%d",&x);
switch(x)
{ case (x
7/30/2019 UNIT-II(c programming)
106/131
/*An institution gives grades to its students as follows:
a. Grade A if he gets 80 or more marks
b. Grade B if he gets between 60 and 79(both inclusive)
c. Grade C if he gets between 50 and 59(both inclusive)d. Grade D if he gets between 40 and 49(both inclusive)
e. Grade F otherwise.*/
void main()
{
float perc;int index;
clrscr();
printf("\nenter the percentage marks");
scanf("%f",&perc);
index=perc/10;
switch(index){
case 10:
case 9:
case 8:
printf("\n grade A");
break;
case 7:
case 6:
printf("\n grade B");break;
case 5:
printf("\ngrade C");
break;
case 4:
printf("\ngrade D");break;
default:
printf("\n grade F");
}//switch
Repetitive control structures
P ll t f t f i t ti
7/30/2019 UNIT-II(c programming)
107/131
Program allows to perform a set of instructions
repeatedly until a particular condition is being
satisfied.
This is called repetitive control structures or
loop control structures.
Loop control structures are:
1. while statement
2. do- while statement3. for statement
Loops in C
While loop
7/30/2019 UNIT-II(c programming)
108/131
Set of instructions to be executed repeatedly
until the condition is satisfied.
ex- print the integer numbers from 1 to 10.
Compound statements
while( expression)
{
Statements
}
Syntax for while
Single statementwhile( expression)
Statement
While statement
7/30/2019 UNIT-II(c programming)
109/131
The statement (or a block of statements) is executed
repetitively until the condition becomes false.
while ( condition )
statement;
while is a
reserved word If the condition is true, the
statement is executed.
Then the condition is
evaluated again.
The expression may be relational or logical expression.
The statements in the loop may be single or block of statements. If single
->while(i
7/30/2019 UNIT-II(c programming)
110/131
p y g g
the curly braces are optional.
The expression must be eventually become false, otherwise the loop would
be executed forever, indefinitely.
int i=1;
while(i
7/30/2019 UNIT-II(c programming)
111/131
float a=1.0;
while(a loop goes into infinite loop.
Write a c program to find the sum of the first n naturalnumbers
7/30/2019 UNIT-II(c programming)
112/131
While example
#include
void main(void){
int n,i = 1, sum = 0;
printf(\nenter n value);
scanf(%d,&n);while ( i
7/30/2019 UNIT-II(c programming)
113/131
Statements in the loop are executed
first (at least once, and condition istested last
Loop is controlled by a condition orcounter
Syntax
do {
statement;
statement;
} while (condition);statement;
Write a c program to find the sum of the first n naturalnumbers
7/30/2019 UNIT-II(c programming)
114/131
While example
#include
void main(void){
int n,i = 1, sum = 0;
printf(\nenter n value);
scanf(%d,&n);while ( i
7/30/2019 UNIT-II(c programming)
115/131
for (expr1; expr2; expr3)
statement;
expr1 controls the looping action,
expr2 represents a condition that
ensures loop continuation, expr3
modifies the value of the control
variable initially assigned by expr1
When a for statement is executed for first time i=1 is initialized.
Next expr2 is evaluated and tested at the beginning of each pass
through the loop. if it true it executes the body of the loop.When control reaches to closed braces, control return back to expr3 ass
If the loop continuation condition is initially false, the body part of the
loop is not performed
Any of the three parts can be omitted, but the semicolons must be kept
for(i=1;i
7/30/2019 UNIT-II(c programming)
116/131
for (i=1; i
7/30/2019 UNIT-II(c programming)
117/131
#include
void main(void)
{int n,i = 1, sum = 0;
printf(\nenter n value);
scanf(%d,&n);
while ( i
7/30/2019 UNIT-II(c programming)
118/131
expr1,expr2 and expr3 in for can be replaced
by any valid expression.
ex:-
for (scanf(%d,&i);i
7/30/2019 UNIT-II(c programming)
119/131
If for loop have single statement we can omittthe curly braces.
for(i=1;i
7/30/2019 UNIT-II(c programming)
120/131
Int i=1;for(;i
7/30/2019 UNIT-II(c programming)
121/131
Executed from the inside out
Each loop is like a layer and has its own counter variable, its own loop
expression and its own loop body
In a nested loop, for each value of the outermost counter variable, the complete
inner loop will be executed once
General form
for (loop1_exprs) {
loop_body_1
for (loop2_exprs) {
loop_body_2}
loop_body_1b
}
Most compilersallow 15 nesting
levelsDONT
DO IT!!
Nested for loops
7/30/2019 UNIT-II(c programming)
122/131
Nested for loops
int i,j,sum;
for(i=1,i
7/30/2019 UNIT-II(c programming)
123/131
char ch= y
int i;
while(ch==y)
{
printf(\n enter the i value);scanf(%d,&i);
printf(%d =%d %d,i=i*i);
printf(\n do want to enter another i value);
scanf(%c,&ch);
}
break statement
7/30/2019 UNIT-II(c programming)
124/131
break statement is used to exit from the loop or
a block. When break statement is encountered control
automatically exit from the loop and passes to
the first statement after the loop. Use keyword break followed by semicolon.
break;
Write a program to find whether the given number is
prime or not
7/30/2019 UNIT-II(c programming)
125/131
#include
void main()
{int num,i;
printf(\n enter the number);
scanf(%d,&num);
i=2;
while(i
7/30/2019 UNIT-II(c programming)
126/131
the statements inside the loop which have not yet been executed.
When continue is encountered in the program the control automatically
goes to the beginning of the loop.
main()
{
int i,j;
for(i=1;i
7/30/2019 UNIT-II(c programming)
127/131
1. draw the block diagram of the computer. Explain about the components of thecomputer.
2. explain about the system development life cycle.
3. define algorithm and flowchart. Write an algorithm and flowchart for thefollowing problems.
a. largest of three numbers.
b. nature of quadratic equations.
4. explain about different data types in c language.
5. explain about the different operators in c language.6. explain about the repetitive control structures (while, do- while, for loops).
7. write a c program to find whether the given no is prime or not.
8. write a c program to display an institution gives grades to its students asfollows:
a. Grade A if he gets 80 or more marks
b. Grade B if he gets between 60 and 79(both inclusive)
c. Grade C if he gets between 50 and 59(both inclusive)
d. Grade D if he gets between 40 and 49(both inclusive)
e. Grade F otherwise.*/
Last date for submission- 29/10/2011
Towers of Honoi
Recursion a function which calls itself
7/30/2019 UNIT-II(c programming)
128/131
Recursion a function which calls itself.
To develop the algorithm for the recursive method use the
towers of Hanoi. Suppose three pegs, labeled A,B, and C are given, and suppose
on peg A there are placed a finite number of n disks indecreasing order.
The objective of the game is to move the disk from peg A topeg C using peg B as an auxiliary.
The rules of this problem are as follows
1. only one disk may be moved at a time. Specifically, only thetop disk on any peg may be moved to any other peg.
2. at no time can a larger disk be placed on a smaller disk.
A B C
7/30/2019 UNIT-II(c programming)
129/131
321
A B C
A->CA->B
C->B
A->C
B->AB->C
A->C
f(n)= 2n-1 moves for n disks
fibonacci sequence and golden ratio
7/30/2019 UNIT-II(c programming)
130/131
0,1,1,2,3,5,8,13.- fibonacci sequence
Golden ratio a/b=1.618
~algorithm for fibonacci sequence.1. read n
2. initialize a=0,b=1,i=2.
3. print a and b.
4. while( i
7/30/2019 UNIT-II(c programming)
131/131
g g
Algorithm
1. read n
2. while(n>0)
2.1 y=n%10
2.2 n=n/10
2.3 sum=sum+y
3. print sum