0% found this document useful (0 votes)
7 views

Psuc Unit II

Uploaded by

rashmithanangi26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Psuc Unit II

Uploaded by

rashmithanangi26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 136

UNIT-II

K.Vigneswara Reddy, Dept.of I.T, SNIST


Topics to be covered in UNIT-2

 C Tokens -
Identifiers, Keywords, Constants, Variables and Operators
 Expressions –
Arithmetic expressions, Precedence and Associativity, evaluating
Expressions
 Decision control structures –
if, Two-way selection- if else, nested if, dangling else, Multi way
selection- else if ladder and switch
 Repetitive control structures –
Pre-test and post-test loops – intialization and updation, do while,
while and for loop and nested loops.
 Unconditional statements –
break, continue and goto statements with example

K.Vigneswara Reddy, Dept.of I.T, SNIST


C Tokens:
In a passage of text, individual words and punctuation marks
are called as tokens.
The compiler splits the program into individual units, are known
as C tokens. C has six types of tokens.

K.Vigneswara Reddy, Dept.of I.T, SNIST


Character set
• Characters are used to form words,
numbers and expressions.
• Characters are categorized as
1. Letters
2. Digits
3. Special characters
4. White spaces.

K.Vigneswara Reddy, Dept.of I.T, SNIST


Character set
• Letters (upper case and lower case)
ABCDEFGHIJKLM
NOPQRSTUVWXYZ
abcdefghijklm
nopqrstuvwxyz
• Digits
0123456789
• Special Characters
‘"()*+-/:=
!&$;<>%?,.
ˆ#@˜‗{}[]\|
• White spaces
blank space
horizontal space
Carriage return, new line.

K.Vigneswara Reddy, Dept.of I.T, SNIST


Key words
• C word is classified as either keywords or identifiers.

• 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.

K.Vigneswara Reddy, Dept.of I.T, SNIST


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

K.Vigneswara Reddy, Dept.of I.T, SNIST


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.

K.Vigneswara Reddy, Dept.of I.T, SNIST


Variables
When you want to process some information, you can save
the values temporarily in variables.
Program
#include<stdio.h>
main() Note – variables must
{ be declared before
int a=10,b=20,c;
c=a+b; they are used, usually at
printf(―sum of a and b=%d\n‖,c); the beginning of the
return 0; function.
}
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 .

K.Vigneswara Reddy, Dept.of I.T, SNIST


Variables names
• There are some restrictions on the variable names
1. Names are made up of letters and digits and
underscore(_).
2. The first character of the name must be a letter
3. The underscore is also a legal first character, but its
use 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.

K.Vigneswara Reddy, Dept.of I.T, SNIST


• The following list contains some examples of
legal and illegal C variable names:
Variable Name Legality

Percent 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

K.Vigneswara Reddy, Dept.of I.T, SNIST


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 with single statement.
K.Vigneswara Reddy, Dept.of I.T, SNIST
syntax datatype identifier;

int a;
Variable declaration and definition

Variable name
a
23456 Garbage value

1000
Address of the variable
K.Vigneswara Reddy, Dept.of I.T, SNIST
Variable initialization
• While declaring the variable assign
initial value is called variable
initialization.
• Data type identifier= initial value;

Example int a=10;


float b=2.1;
float pi=3.14;
char ch=‗A‘;
K.Vigneswara Reddy, Dept.of I.T, SNIST
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.
K.Vigneswara Reddy, Dept.of I.T, SNIST
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;

K.Vigneswara Reddy, Dept.of I.T, SNIST


• Example Area of circle
#include<stdio.h>
void main()
{
float area, radius=3.0;
const float pi=3.14;
area=pi*radius*radius;
printf(―area of a circle= %f‖,area);
}

K.Vigneswara Reddy, Dept.of I.T, SNIST


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
2. 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‖.

K.Vigneswara Reddy, Dept.of I.T, SNIST


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
K.Vigneswara Reddy, Dept.of I.T, SNIST
printf(―hello\a‖);// beep sound
printf(―snist\b‖);// snis- deletes last character
printf(―hello\f‖);// clears complete screen
printf(―snist\n‖);// new line
printf(―snist\r‖);
printf(―this is \‘ECE\‘ branch‖);//this is ‗ECE‘ branch
printf(―this is \‖ECE\‖ branch‖);// this is ―ECE‖ branch
printf(―\n what is your name\?‖);// what is your name?
printf(―\n \\ this is used as escape character‖);

K.Vigneswara Reddy, Dept.of I.T, SNIST


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.

K.Vigneswara Reddy, Dept.of I.T, SNIST


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

K.Vigneswara Reddy, Dept.of I.T, SNIST


• 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.

K.Vigneswara Reddy, Dept.of I.T, SNIST


Examples of real constants
Type Representation Value

double 0. 0.0

double 0.0 .0

float -2.0f -2.0

long double 3.1415927654 3.1415927654


4L 4

K.Vigneswara Reddy, Dept.of I.T, SNIST


• #include<stdio.h>
void main()
{
const int a=10;
int b=20;
a=a+1;
b=b+1;
printf(―a=%d b=%d‖,a,b);
}

K.Vigneswara Reddy, Dept.of I.T, SNIST


Coding Constants: Different ways to create constants.
Literal constants:
A literal is an unnamed constant used to specify data.
Example: a = b + 5;

Defined constants:
By using the preprocessor command you can create a
constant.
Example: #define pi 3.14

Memory constants:
Memory constants use a C type qualifier, const, to indicate
that the data can not be changed.
Its format is: const type identifier = value;
Example: const float PI = 3.14159;

K.Vigneswara Reddy, Dept.of I.T, SNIST


operators
• C language is robust because it has rich set of
operators.
• Operator – a 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.
.
expression Operators- =, +
X=Y+Z
Operands- x,y,z
K.Vigneswara Reddy, Dept.of I.T, SNIST
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.
K.Vigneswara Reddy, Dept.of I.T, SNIST
1. Arithmetic operators
Performs arithmetic operations like add, sub, mul, div etc.

Arithmetic Meaning
operators c= a+b;
+ Addition or unary operator z= x-y;

- Subtraction or unary
operator
* Multiplication

/ Division- gives only quotient

% Modulo division- gives


remainder.
K.Vigneswara Reddy, Dept.of I.T, SNIST
2.Relational operators.
• Relational operators are used to compare the relationship
between two operands.

Relational Meaning
operators
< Is less than The value of a relational
Expression is either one or
> Is greater than zero. It is one if the
Specified relation is true and
<= Less than or equal to zero if the relation is false .

>= Greater than or equal


to
Relational operators are
== Equal to
used
!= Not equal to if and else, while, for
statements.
K.Vigneswara Reddy, Dept.of I.T, SNIST
3. Logical operators.
• Logical operators used to test more
than one condition and make decision.
• Yields a value either one or zero

Logical meaning
operator
&& Logical AND

Ex- (x<y)&&(x= = 8) || Logical OR


logical expression
! Logical NOT
K.Vigneswara Reddy, Dept.of I.T, SNIST
AND OR truth table

Op1 Op2 AND OR


0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1

K.Vigneswara Reddy, Dept.of I.T, SNIST


4. Assignment operators
• 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;

K.Vigneswara Reddy, Dept.of I.T, SNIST


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;

K.Vigneswara Reddy, Dept.of I.T, SNIST


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 evaluated
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; This is like if(a<b)


b=2; x=a;
x= (a<b)?a:b; else
K.Vigneswara Reddy, Dept.of I.T, SNIST x=b;
Bitwise Operators
 C has a special operator known as Bitwise operator for
manipulation of data at bit level.
 Bitwise operator may not be applied for float and double.
 Manipulates the data which is in binary form.
 Syntax: operand1 bitwise_operator operand2

Bitwise Meaning
Operators
& Bitwise AND
| Bitwise OR
^ Exclusive OR
<< Shift left
>> Shift right
~ One‘s compliment
K.Vigneswara Reddy, Dept.of I.T, SNIST
Examples:
& Bitwise AND 0110 & 0011  0010
| Bitwise OR 0110 | 0011  0111
^ Bitwise XOR 0110 ^ 0011  0101
~ One's complement ~0011  1100
Don't confuse bitwise & | with logical && ||

K.Vigneswara Reddy, Dept.of I.T, SNIST


 Shift right >> is a binary operator that requires two integral
operands. the first one is value to be shifted, the second one
specifies number of bits to be shifted.
 The general form is as follows:
variable >> expression;
 When bits are shifted right, the bits at the rightmost end are
deleted.
 Shift right operator divides by a power of 2. I.e. a>>n results in
a/2n, where n is number of bits to be shifted.
Example: a=8;
b=a>>1; // assigns 4
after shift right operation

K.Vigneswara Reddy, Dept.of I.T, SNIST


 Shift left<< is a binary operator that requires two integral
operands. the first one is value to be shifted, the second one specifies
number of bits to be shifted.
 The general form is as follows:
variable << expression;
 When bits are shifted left, the bits at the leftmost end are deleted.
Example: a=8;
b=a<<1; // assigns 16
after left shift operation
 Shift left operator multiply by a power of 2, a<<n results in a*2n,
where n is number of bits to be shifted.

K.Vigneswara Reddy, Dept.of I.T, SNIST


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
sizeof data
e.g.
int a = 5;
sizeof(a); //produces 4
Or
sizeof (data type)

e.g. sizeof (char); //produces 1


K.Vigneswara Reddy, Dept.of I.T, SNIST
• Unary operators- operators used on a
single operand - -, +, ++, --.
• Binary operators - operators used to
apply in between two operands- +, -, /,
%.

K.Vigneswara Reddy, Dept.of I.T, SNIST


Expressions

FIGURE Expression Categories


K.Vigneswara Reddy, Dept.of I.T, SNIST
• 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 contains operand
followed by one operator.

ex- a++; a- -;

Operand must be the variable in post fix expression.


K.Vigneswara Reddy, Dept.of I.T, SNIST
1. Value of the variable a is assigned to x
2. Value of the a is incremented by 1.

expression

FIGURE Result of Postfix a++


K.Vigneswara Reddy, Dept.of I.T, SNIST
Example on post fix expression
• #include<stdio.h>
void main()
{
a=10;
x=a++;
printf(“x=%d, a=%d”,x,a);
}
out put- x=10, a=11

K.Vigneswara Reddy, Dept.of I.T, SNIST


Prefix expression- operator followed by the operand.

ex- ++a;

FIGURE Prefix Expression


K.Vigneswara Reddy, Dept.of I.T, SNIST
FIGURE Result of Prefix ++a
K.Vigneswara Reddy, Dept.of I.T, SNIST
Example on pre fix expression
• #include<stdio.h>
void main()
{
a=10;
x=++a;
printf(“x=%d, a=%d”,x,a);
}
out put- x=11, a=11

K.Vigneswara Reddy, Dept.of I.T, SNIST


Unary expression- unary operator followed by the operand

FIGURE Unary Expressions


K.Vigneswara Reddy, Dept.of I.T, SNIST
Table Examples of Unary Plus And Minus Expressions

K.Vigneswara Reddy, Dept.of I.T, SNIST


Binary expressions- operator must be placed in between the
two operands.

1
Operand must be integral data type( int, float)
Ex- a+b
a-c

FIGURE Binary Expressions


K.Vigneswara Reddy, Dept.of I.T, SNIST
Precedence and association rules among
operators
• Precedence- the order in which different operators in
complex expression are 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- the order in which operators with
same precedence in a complex expression are
evaluated.

K.Vigneswara Reddy, Dept.of I.T, SNIST


K.Vigneswara Reddy, Dept.of I.T, SNIST
Precedence and Associativity of Operators in C (from higher to lower)

K.Vigneswara Reddy, Dept.of I.T, SNIST


Example program to illustrate operator precedence

K.Vigneswara Reddy, Dept.of I.T, SNIST


Example program to illustrate operator precedence (contd…)

void main()
{
int i=1;
printf(“ i= %d\t i=%d”,++i,i++);
}
Output
i=3 i=1

K.Vigneswara Reddy, Dept.of I.T, SNIST


FIGURE 3-8 Left-to-Right Associativity
K.Vigneswara Reddy,
57 Dept.of I.T, SNIST
Right-to-Left Associativity
K.Vigneswara Reddy, Dept.of I.T, SNIST
Type Conversion
 Up to this point, we have assumed that all of our
expressions involved data of the same type.
 But, what happens when we write an expression that
involves two different data types, such as multiplying an
integer and a floating- point number?
 To perform these evaluations, one of the types must
be converted.

 Type Conversion: Conversion of one data type to


another data type.

 Type conversions are classified into:


 Implicit Type Conversion
 Explicit Type Conversion (Cast)

K.Vigneswara Reddy, Dept.of I.T, SNIST


Implicit Conversion:
 In implicit type conversion, if the operands of an
expression are of different types, the lower data type is
automatically converted to the higher data type before the
operation evaluation.

 The result of the expression will be of higher data type.


 The final result of an expression is converted to the type
of the variable on the LHS of the assignment statement,
before assigning the value to it.
 Conversion during assignments:
char c = 'a';
int i;
i = c; /* i is assigned by the ascii of ‗a‘ */
 Arithmetic Conversion: If two operands of a binary operator
are not the same type, implicit conversion occurs:
int i = 5 , j = 1;
float x = 1.0, y;
y = x / i; /* y = 1.0 / 5.0 */
K.Vigneswara Reddy, Dept.of I.T, SNIST
y = j / i; /* y = 1 / 5 so y = 0 */
Explicit Conversion or Type Casting:

 In explicit type conversion, the user has to enforce the


compiler to convert one data type to another data type by
using typecasting operator.

 This method of typecasting is done by prefixing the


variable name with the data type enclosed within
parenthesis.
(data type) expression

 Where (data type) can be any valid C data type and


expression is any variable, constant or a combination of
both.

Example: int x;
x=(int)7.5;

K.Vigneswara Reddy, Dept.of I.T, SNIST


Conversion Rank (C Promotion Rules)
K.Vigneswara Reddy, Dept.of I.T, SNIST
Example program for Implicit Type Conversion

K.Vigneswara Reddy, Dept.of I.T, SNIST


Example program for Implicit Type Conversion (contd…)

K.Vigneswara Reddy, Dept.of I.T, SNIST


Example program for Implicit Type Conversion (contd…)

K.Vigneswara Reddy, Dept.of I.T, SNIST


Example program for Explicit Casts

K.Vigneswara Reddy, Dept.of I.T, SNIST


Example program for Explicit Casts (contd…)

K.Vigneswara Reddy, Dept.of I.T, SNIST


Example program for Explicit Casts (contd…)

K.Vigneswara Reddy, Dept.of I.T, SNIST


Statements
 A statement causes an action to be performed by the program.

 It translates directly into one or more executable computer


instructions.

 Generally statement is ended with semicolon.

 Most statements need a semicolon at the end; some do not.

K.Vigneswara Reddy, Dept.of I.T, SNIST


Control
statements

Types of Statements
K.Vigneswara Reddy, Dept.of I.T, SNIST
 Compound statements are used to group the statements
into a single executable unit.
 It consists of one or more individual statements
enclosed within the braces { }

Compound Statement
K.Vigneswara Reddy, Dept.of I.T, SNIST
Decision Control structures
 Control statements embody the decision logic that tells the
executing program what action to be carried out depending on
the values of certain variable or expressions.
 Control statements includes selection, iteration and jump
statements
 Selection or conditional statement
- allows us to decide which statement to execute next.
- decision is based on the condition or test expression that
evaluates to either true or false.( 0 or 1)
- the resultant of the expression determines which statement is
executed next.

K.Vigneswara Reddy, Dept.of I.T, SNIST


Selection or conditional Statements

Types of selection statements


 if
 if..else
 nested if…else
 else if ladder
 dangling else
 switch statement

K.Vigneswara Reddy, Dept.of I.T, SNIST


1. If statement
• Based on the condition execute the set of
instructions otherwise skip them.
• C uses the key word if to implement the decision
control instruction.
• general form of if statement

Condition following the


if must be enclosed within
if( condition\expression) parenthesis.
{ If the condition is true then
execute the statements; execute the given statement
} otherwise the statements not
executed.

K.Vigneswara Reddy, Dept.of I.T, SNIST


If statement

• If it has single statement to execute then curly


braces are optional.
• More than one statement curly braces are
compulsory.
Ex- int rno=4104;
if(rno==4104)
printf(―this is IT-F1‖);

K.Vigneswara Reddy, Dept.of I.T, SNIST


if is a C The condition must be a
reserved word Valid C expression.

Enter
if ( condition )
statement;

Test
If the condition is true, the
statement is executed.
If it is false, the statement is
Body of the IF Statement
skipped.

Exit

K.Vigneswara Reddy, Dept.of I.T, SNIST


If- else statements

• if statement will execute a single statement, or a group of


statements, 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 the
expression evaluates to true and another group of statements if
the expression evaluates to false, we need to use the If-else
statement.
• The syntax of If-else statement is as follows;

if (condition\expression){
The expression evaluated to true,
Statement1}
statement1 is executed.
else {
If false, statement2 is executed.
statement2 }
Both cases statement-x is executed.
statement-x
K.Vigneswara Reddy, Dept.of I.T, SNIST
The if-else Statement
An else clause can be added to an if statement to make an if-else
statement
Enter
Flowchart for if-else

Test

Body of the Body of the


IF Statement1 ELSE Statement2

Exit
If the condition is true, statement1 is executed; if the condition is
false, statement2 is executed
One or the other will be executed, but not both

K.Vigneswara Reddy, Dept.of I.T, SNIST


• Example
float percentage;
printf (―enter the percentage‖);
scanf (―%f‖, &percentage);
if (percentage<=50)
printf(―\nfailed‖);
else
printf(―\npassed‖);

K.Vigneswara Reddy, Dept.of I.T, SNIST


• 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( x>0)
{
if(a>b)
if(a>b)
z=a;
z=a;
else
}
z=b;
else
z=b;
K.Vigneswara Reddy, Dept.of I.T, SNIST
Nested if else- within the if else we can
include other if-else either in if block or
else block
F T

F T

K.Vigneswara Reddy, Dept.of I.T, SNIST


Nested if- else
• 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- third
class.
5. Percentage is below 40 – failed.

K.Vigneswara Reddy, Dept.of I.T, SNIST


#include<stdio.h>
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”);
Disadvantages-
else • care must be taken to match the
{
if(per<75 && per>=60) corresponding pair of braces.
printf(“\n first class”);
else{
if(per<60 && per>=50)
printf(“\n second class”);
else {
if(per<50 && per>=40)
printf(“\n third class”);
else
printf(“\nfail”);
}//else
}//else
}//else
K.Vigneswara Reddy, Dept.of I.T, SNIST
Else if statement
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.


K.Vigneswara Reddy, Dept.of I.T, SNIST
Nested if else else if clause
#include<stdio.h>
#include<stdio.h>
void main()
void main()
{ {
float m1,m2,m3,m4; float m1,m2,m3,m4;
float perc;
float perc;
printf(“enter marks\n”);
scanf(“%f%f%f%f”,&m1,&m2, printf(“enter marks\n”);
&m3,&m4); scanf(“%f%f%f%f”,&m1,&m2,
perc=(m1+m2+m3+m4)/4; &m3,&m4);
if(perc>=75)
printf(“\ndistinction”);
perc=(m1+m2+m3+m4)/4;
else if(perc>=75)
{ printf(“\ndistinction”);
if(per<75 && per>=60)
else if(per<75 && per>=60)
printf(“\n first class”);
else{ printf(“\n first class”);
if(per<60 && per>=50) else if(per<60 && per>=50)
printf(“\n second class”); printf(“\n second class”);
else {
if(per<50 && per>=40)
else if(per<50 && per>=40)
printf(“\n third class”); printf(“\n third class”);
else else
printf(“\nfail”);
printf(“\nfail”);
}//else
}//else }
}//else K.Vigneswara Reddy, Dept.of I.T, SNIST
}
Dangling else

 else is always paired with the most recent unpaired if.

Dangling else
K.Vigneswara Reddy, Dept.of I.T, SNIST
Dangling else (contd…)
 To avoid dangling else problem place the inner if statement
with in the curly braces.

Dangling else Solution


K.Vigneswara Reddy, Dept.of I.T, SNIST
Switch statement
• In else if statement as the no of
choices increases the program becomes
difficult to read.
• C has a built in multi way decision
statement call it as switch.
• The control statement that allows us to
make a decision from the number of
choices is called switch.

K.Vigneswara Reddy, Dept.of I.T, SNIST


Switch statement
General form of switch
1. The expression is any expression
switch (expression) that must evaluates to integer value.
{ 2. The keyword case followed by an
case value-1: integer or a character constant.
block1; 3. Each value in each case must be
break; different from all the others.
case value-2: 4. How this program runs? First
block2; expression is evaluated.
break; 5. This evaluated value compares
case value-n: against the values that follow the
blockn; case statements.
break; 6. When a match is found, executes the
default: statements following that case and
default block; all the other cases were skipped.
}//switch 7. If no match is found with any of the
statement-x; case statements, default block is execute
Break is used to exit from block 8. Default is optional.
9.Dept.of
K.Vigneswara Reddy, At I.T,last
SNIST statement –x is executed.
Tips about the usage of switch
 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

K.Vigneswara Reddy, Dept.of I.T, SNIST


Examples on switch
Void main() Void main()
{ {
int a; int a;
scanf(―%d‖,&a); scanf(―%d‖,&a);
switch(a) switch(a)
{ {
case 1: case 1:
printf(―One‖); printf(―One‖);
break; case 2:
case 2: printf(―two‖);
printf(―two‖); case 3:
break; printf(―three‖);
case 3: default:
printf(―three‖); printf(―this is default‖);
break; }//switch
default: }//main
printf(―this is default‖);
}//switch
Note-
K.Vigneswarathere
Reddy, Dept.ofis no break in default case.
}//main I.T, SNIST
 we can also use char values in case and switch.
char ch=‗x‘;
switch(ch) ch expression evaluated to the ascii
{ value of x it is also an integer value
case ‗A‘:
printf(―this is A‖);
break;
case ‗x‘:
printf ( ―this is small x‖);
break;
default:
printf (―other letter‖);
}//switch

K.Vigneswara Reddy, Dept.of I.T, SNIST


 can also execute a common set of statements for multiple
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‖);
} K.Vigneswara Reddy, Dept.of I.T, SNIST
}
 if there are multiple statements to be executed in the case no
need to enclose them in pair of curly braces.
 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 doesn‘t give any error. However that statement never
executed.
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

K.Vigneswara Reddy, Dept.of I.T, SNIST


 switch may occur within another switch called nested
switch.
 continue statement should not used in switch.
 Switch statement is mainly used for the menu driven
programs.
 value in the case must be an int constant or char
constant or an expression that evaluates to one of
these constants. even float is not allowed.
void main()
{ int x;
scanf("%d",&x);
switch(x)
{ case (x<=20):
printf("\nless than 20");
break;
default:
printf("\nsoryy it wont work");
}//switch
}
K.Vigneswara Reddy, Dept.of I.T, SNIST
/*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()
{ case 7:
float perc; case 6:
int index; printf("\n grade B");
clrscr(); break;
printf("\nenter the percentage marks"); case 5:
scanf("%f",&perc); printf("\ngrade C");
index=perc/10; break;
switch(index) case 4:
{ printf("\ngrade D");
case 10: break;
case 9: default:
case 8: printf("\n grade F");
printf("\n grade A"); }//switch
break; K.Vigneswara Reddy, Dept.of I.T, SNIST
Programs list
• Write an algorithm, flowchart and C program for following
1. Find area and circumference of a given circle
area= 3.14*radius*radius
circumference= 2*3.14*radius
2. Find the volume of a sphere of given radius
volume= (4/3.0)*3.14* radius*radius*radius
3. Find lateral surface area of a right circular cone of given base
radius and height.
area= 3.14*radius*sqrt(radius*radius+height*height)
4. Write a C program to convert the temperature from celcius to
fahrenheit and fahrenheit to celcius.
F= ((c*9/5.0)+32);
C= (5/9.0)*(fahr-32)
5. Find the selling price of an item, given its cost price and profit
percent.
profit= profit%*cost price
selling price= profit+costprice
K.Vigneswara Reddy, Dept.of I.T, SNIST
Concept of a Loop
K.Vigneswara Reddy, Dept.of I.T, SNIST
Pretest and Post-test Loops

 We need to test for the end of a loop, but


where should we check it—before or after
each iteration? We can have either a pre- or
a post-test terminating condition.

 In a pretest loop , the condition is checked


at the beginning of each iteration.

 In a post-test loop, the condition is checked


at the end of each iteration.

K.Vigneswara Reddy, Dept.of I.T, SNIST


Note
Pretest Loop
In each iteration, the control expression is tested
first. If it is true, the loop continues; otherwise, the
loop is terminated.

Post-test Loop
In each iteration, the loop action(s) are executed.
Then the control expression is tested. If it is true, a
new iteration is started; otherwise, the loop
terminates.

K.Vigneswara Reddy, Dept.of I.T, SNIST


Pretest and Post-test Loops
K.Vigneswara Reddy, Dept.of I.T, SNIST
Minimum Number of Iterations in Two Loops
K.Vigneswara Reddy, Dept.of I.T, SNIST
Initialization and Updating

In addition to the loop control expression, two other processes,


initialization and updating, are associated with almost all loops.

 Loop Initialization
 Loop Update

 Control expression is used to decide whether the loop should be


executed or terminated.

 Initialization is place where you can assign some value to a variable.

 Variable‘s value can be updated by incrementing a value by some


amount.

K.Vigneswara Reddy, Dept.of I.T, SNIST


Loop Initialization and Updating
K.Vigneswara Reddy, Dept.of I.T, SNIST
Event- and Counter-Controlled Loops

 All the possible expressions that can be used in a loop limit


test can be
summarized into two general categories:
1. Event-controlled loops and
2. Counter-controlled loops.

 In event-controlled loops, loop execution depends on the given


condition.

 In counter-controlled loops, loop execution depends on the


counter variable value.

K.Vigneswara Reddy, Dept.of I.T, SNIST


Event-controlled Loop Concept
K.Vigneswara Reddy, Dept.of I.T, SNIST
Counter-controlled Loop Concept
K.Vigneswara Reddy, Dept.of I.T, SNIST
Loop Comparisons

K.Vigneswara Reddy, Dept.of I.T, SNIST


Repetitive control structures
• 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 statement Loops in C

3. for statement

K.Vigneswara Reddy, Dept.of I.T, SNIST


C Loop Constructs
K.Vigneswara Reddy, Dept.of I.T, SNIST
While loop
• Set of instructions to be executed repeatedly until the
condition is satisfied.
• ex- print the integer numbers from 1 to 10.

Syntax for while

Single statement Compound statements


while( expression) while( expression)
Statement {
Statements
}

A group of statements in a block are called compound stat

K.Vigneswara Reddy, Dept.of I.T, SNIST


While statement

while is a
Key word If the condition is true, the
statement is executed.
while ( condition ) Then the condition is
statement; evaluated again.

The statement (or a block of statements) is executed


repetitively until the condition becomes false.
K.Vigneswara Reddy, Dept.of I.T, SNIST
 The expression may be relational or logical expression.
->while(i<=10&&j<=20)

 The statements in the loop may be single or block of statements.


If single the curly braces are optional.
 The expression must be eventually become false, otherwise the
loop would be executed forever, indefinitely.
Correct form
int i=1; i=1;
while(i<=10) while(i<=10)
{
printf(―%d‖,i) printf(―%d‖,i);
; i++;
}
 instead of increment, we can also decrement the variable va
int i=5;
while( i>=1)
{
printf(―%d‖,i);
K.Vigneswara Reddy, Dept.of I.T, SNIST
 Loop variable may also be a float.

float a=1.0;
while(a<=1.5)
{
printf(―%f‖,a);
a=a+0.1;}

 what would be the output of the following


program?
main() Output – program goes into
{ infinite loop.
int i=1; Range of the integer is -
while(i<=32767) 32768 to
{ +32767.
printf(―%d‖,i); -> it doesn‘t store the value
i++; 32768
} so i value become -32768.
K.Vigneswara Reddy, Dept.of I.T, SNIST
/* write a c program to print the numbers from 1 to
10.*/
void main()
{
int i=1;//initialiazation
while(i<=10)//test expression
{
printf(―%d‖,i); /* write a C program to print the numbers from 10
i++; to 1 */
} //while void main()
}// main {
int i=10;//initialization
while(i>=1)
{
printf(―%d‖,i);
i--;
}// while
}//main

K.Vigneswara Reddy, Dept.of I.T, SNIST


Write a c program to find the sum of the first n
natural numbers
While example
#include <stdio.h>
void main()
{
int n,i = 1, sum = 0;
printf(―\n enter n value‖);
scanf(―%d‖,&n);
while ( i<= n) {
sum = sum + i;
i++;
}
printf(―Sum of %d natural nos= %d\n‖,n, sum);
getch();
}

K.Vigneswara Reddy, Dept.of I.T, SNIST


The “do while” statement

Statements in the loop are


executed first (at least once, and
condition is tested last

Loop is controlled by a condition or


counter

Syntax
do {
statement;
statement;
} while (condition);
statement;

K.Vigneswara Reddy, Dept.of I.T, SNIST


Write a c program to find the sum of the first n natural
numbers
While example
do-while example
#include <stdio.h>
#include <stdio.h>
void main(void)
void main(void)
{
{
int n,i = 1, sum = 0;
int n,i = 1, sum = 0;
printf(―\nenter n value‖);
printf(―\nenter n value‖);
scanf(―%d‖,&n);
scanf(―%d‖,&n);
while ( i<= n) {
do{
sum = sum + i;
sum = sum + i;
i = i + 1;
i = i + 1;
}//while
} while ( i<= n) ;
printf(―Sum of %d natural
printf(―Sum of %d natural nos
nos=
%d\n‖,n, sum);
%d\n‖,n, sum);
getch();
getch();
}//main
}//main K.Vigneswara Reddy, Dept.of I.T, SNIST
Example : To print fibonacci sequence for the given
number.
#include<stdio.h>
void main()
{
int n,a=0,b=1,i=3,fib;
printf("\nenter the n value ");
scanf("%d",&n);
printf("%d,%d",a,b);
while(i<=n) Output
{
fib=a+b; 0, 1, 1 ,2,3
printf(",%d",fib);
a=b;
b=fib;
i++;
}//while

}//main K.Vigneswara Reddy, Dept.of I.T, SNIST


Example : To print multiplication table for 5.

#include <stdio.h>
void main()
{
int i = 1, n=5;
do
{
printf(― %d * %d = %d ―, n, i, n*i);
i = i + 1;
} while ( i<= 5);
}

K.Vigneswara Reddy, Dept.of I.T, SNIST


The “for” Loop
syntax
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
 for(i=1;i<=5;i++)
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 partsK.Vigneswara
can beReddy,
omitted, but the semicolons must be
Dept.of I.T, SNIST
keyword
final value of control variable
control variable i for which the condition is true

for (i=1; i <= n; i = i + 1)

initial value increment of control variable


of control loop continuation
variable condition

Examples
Vary the control variable from 1 to 100 in increments of 1
for (i = 1; i <= 100; i++)
Vary the control variable from 100 to 1 in decrements of -1
for (i = 100; i >= 1; i--)
Vary the control variable from 5 to 55 in increments of 5
for (i = 5; i <= 55; i+=5)
K.Vigneswara Reddy, Dept.of I.T, SNIST
Write a c program to find the sum of the first n natural
While example numbers
do-while example For example
#include <stdio.h> #include <stdio.h> #include <stdio.h>
void main(void) void main(void) void main(void)
{ { {
int n,i = 1, sum = 0; int n,i = 1, sum = 0; int n,i,sum = 0;
printf(“\nenter n value”); printf(“\nenter n value”); printf(“\nenter n value”);
scanf(“%d”,&n); scanf(“%d”,&n); scanf(“%d”,&n);
while ( i<= n) { do{ for(i=1;i<=n;i++)
sum = sum + i; sum = sum + i; sum=sum+i;
i = i + 1; i = i + 1; printf(“Sum of %d natural nos=
}//while } while ( i<= n) ; %d\n”,n, sum
printf(“Sum of %d natural printf(“Sum of %d natural nos=
nos= %d\n”,n, sum); %d\n”,n, sum);
getch(); getch();
}//main }//main

K.Vigneswara Reddy, Dept.of I.T, SNIST


Few more points to remember
 expr1,expr2 and expr3 in for can be replaced by any valid
expression.
ex:-
for (scanf(―%d‖,&i);i<=5;i++)
 If for loop have single statement we can omitt the curly braces.
for(i=1;i<=10;i++)
printf(―%d‖,i);
 Updation of a variable can done even inside of the loop.
for(i=0;i<=10;)
{
printf(―%d‖,i);
i=i+1;}

K.Vigneswara Reddy, Dept.of I.T, SNIST


Int i=1; Int i=1;
for(;i<=10;i++) for(;i<=10;)
printf(―%d‖,i); {
Semicolon is compulsory printf(―%d‖,i);
i++;
}
Multiple initialization and decrement/increment in for loops
must be seperated with the comma operator.
for(i=0,j=1;i<=n;i++,j++)
 but only one condition must be used.

K.Vigneswara Reddy, Dept.of I.T, SNIST


Nested for loops
Nested means there is a loop within a loop
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
Most compilers
for (loop1_exprs)
allow 15
{
nesting levels –
loop_body_1
DON‘T DO IT!!
for (loop2_exprs)// inner for loop
{
loop_body_2
}// inner loop
loop_body_1
}//outer loop K.Vigneswara Reddy, Dept.of I.T, SNIST
Nested for loops

int i,j,sum;
for(i=1,i<=3;i++)
{
for(j=0;j<2;j++)
{
sum=i+j;

printf(―i=%d,j=%d,sum=%d‖,i,j,sum);
}//inner for loop
}//outer for loop

K.Vigneswara Reddy, Dept.of I.T, SNIST


• 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);
}
K.Vigneswara Reddy, Dept.of I.T, SNIST
Unconditional Statements
break statement
 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;

K.Vigneswara Reddy, Dept.of I.T, SNIST


Write a program to find whether the given number is prime or not

#include<stdio.h>
void main()
{
int num,i;
printf(―\n enter the number‖);
scanf(―%d‖,&num);
i=2;
while(i<=num-1)
{
if(num%i==0)
{
printf(―not a prime number‖);
break;
}//if
i++;
}//while
if(i= = num)
printf(―\n it‘s a prime number‖);

}//main

K.Vigneswara Reddy, Dept.of I.T, SNIST


continue statement
• When continue statement is encountered in a loop, the following
statement are skipped and continue the next iteration.
• The format of the continue statement is:

K.Vigneswara Reddy, Dept.of I.T, SNIST


example
main()
{
int i,j;
for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
if(i==j) Output
continue; 12
printf(―\n %d 2 1
%d‖,i,j);
}//for
}//for
}//main
K.Vigneswara Reddy, Dept.of I.T, SNIST
 The operator comma , is used to separate the more than one
expressions.

 A pair of expressions separated by a comma is evaluated left


to right, and
the type and value of the result are the type and value of the
right
operand.

 Thus, in a for statement, it is possible to place multiple


expressions in
the various parts.

Nested Comma Expression


K.Vigneswara Reddy, Dept.of I.T, SNIST
goto statement
• The goto statement is a jump statement which is
sometimes also referred to as unconditional jump
statement.
• The goto statement can be used to jump from anywhere to
anywhere within a function.

K.Vigneswara Reddy, Dept.of I.T, SNIST


example
main()
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
{
goto hello; Output
} 1
printf(― %d\n‖,i); 2
}//for Welcome
hello: break;
printf(―Welcome ―);
}//main
K.Vigneswara Reddy, Dept.of I.T, SNIST
Sum of the digits of a given number

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

K.Vigneswara Reddy, Dept.of I.T, SNIST

You might also like