0% found this document useful (0 votes)
3 views40 pages

Module 2-Operators and Decision Control Statements

The document outlines the course structure for 'Principles of Programming using C' at Acharya Institute of Technology, detailing course outcomes, program outcomes, educational objectives, and specific outcomes for students. It includes a comprehensive overview of C programming concepts such as operators, decision control, and looping statements. Additionally, it provides insights into the application of C programming in solving engineering problems and emphasizes the importance of ethical practices and lifelong learning in the field.

Uploaded by

vishuuvishnu57
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)
3 views40 pages

Module 2-Operators and Decision Control Statements

The document outlines the course structure for 'Principles of Programming using C' at Acharya Institute of Technology, detailing course outcomes, program outcomes, educational objectives, and specific outcomes for students. It includes a comprehensive overview of C programming concepts such as operators, decision control, and looping statements. Additionally, it provides insights into the application of C programming in solving engineering problems and emphasizes the importance of ethical practices and lifelong learning in the field.

Uploaded by

vishuuvishnu57
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/ 40

ACHARYA INSTITUTE OF TECHNOLOGY

Soladevanahalli, Bengaluru – 560107

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Principles of Programming using C


(BPOPS203)

Prepared by
Mrs. Reshma
Assistant Professor,
Department of CS&E,
Acharya Institute of Technology

2024-2025
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

COs, POs, PEOs, PSOs

COURSE OUTCOMES (COS)


1. Illustrate the basic concepts of computer system and C programming fundamentals.
2. Apply the C programming constructs to solve simple problems.
3. Write C programs using arrays and functions to develop applications.
4. Apply the concepts of strings and pointer in writing the program for data
manipulation and memory management.
5. Write C programs using structures, unions and Enumerated data-types to solve
given problems.
6. Implement programs using C constructs, structures, strings, pointers and file I/O
operations for given problems.

PROGRAM OUTCOMES (POS)


1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems
2. Problem analysis: Identify, formulate, review research literature, and analyse complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences
3. Design / development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
2|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions
11. Project management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change

PROGRAM EDUCATIONAL OBJECTIVES (PEOS)

PEO-1 Students shall, have a successful career in academia, R&D organizations, IT industry
or pursue higher studies in specialized field of Computer Science and Engineering and allied
disciplines.
PEO-2 Students shall, be competent, creative and a valued professional in the chosen field.
PEO-3 Students shall, engage in life-long learning, professional development and adapt to
the working environment quickly
PEO-4 Students shall, become effective collaborators and exhibit high level of
professionalism by leading or participating in addressing technical, business, environmental
and societal challenges.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
3|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

PROGRAM SPECIFIC OUTCOME (PSOS)

PSO-1 Students shall, apply the knowledge of hardware, system software, algorithms,
networking and data bases.
PSO-2 Students shall, design, analyze and develop efficient, Secure algorithms using
appropriate data structures, databases for processing of data.
PSO-3 Students shall, be Capable of developing stand alone, embedded and web-based
solutions having easy to operate interface using Software Engineering practices and
contemporary computer programming languages.

CO-PO -PSO Mapping

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
4|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

TABLE OF CONTENTS
Module Module Page Nos
Operators in C, Type conversion and typecasting.
Decision control and Looping statements:
Introduction to decision control, Conditional
2
branching statements, iterative statements, nested
loops, break and continue statements, goto
statement.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
5|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Operators in C:
An operator is a symbol that specifies the mathematical, logical or relational operation to be
performed. C language supports a lot of operators to be used in expressions. These operators
can be categorized into the following major groups:
 Arithmetic operators
 Relational Operators
 Equality Operators
 Logical Operators
 Unary Operators
 Conditional Operators
 Bitwise Operators
 Assignment operators
 Comma Operator
 sizeof Operator

Arithmetic Operators:
Consider three variables declared as,
int a=9, b=3, result;
Below figure shows the arithmetic operators, their syntax, and usage in C
language.

OPERATION OPERATOR SYNTAX COMMENT RESULT

Multiply * a*b result = a * b 27


Divide / a/b result = a / b 3
Addition + a+b result = a + b 12
Subtraction - a-b result = a – b 6
Modulus % a%b result = a % b 0
Arithmetic operators can be applied to any integer of floating-point numbers. The
operator % (modulus) finds the remainder of an integer division. This operator
can be applied only to integer operands and cannot be used on float or double
operands.

When both operands of the division operator (/) are integers, the division is
performed as an integer division. Integer division always results in an integer
result. So, the result is always rounded-off by ignoring the remainder.
Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering
Intended for internal circulation only
6|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
Therefore,
9/4 = 2 and -9/4 = -3

If op1 and op2 are integers ad the quotient is not an integer, then we have two
cases:
1. If op1 and op2 have the same sign, then op1/op2 is the largest
integer less the true quotient.
2. If op1 and op2 have opposite signs, then op1/op2 is the smallest
integer greater than the true quotient.
Note that it is not possible to divide any number by zero. This is an illegal
operation that results in a run-time division-by-zero exception, thereby
terminating the program.

Relational Operator:
Relational operator is also known as a comparison operator, it is an operator
that compares two values. Expressions that contain relational operators
are called relational expressions. Relational operators return true or false
value, depending on whether the conditional relationship between the two
operands holds or not.
For example, to test if x is less than y, relational operator < is used as x <
y. This expression will return true (1) if x is less than y; otherwise the value of
the expression will be false (0).

OPERATOR MEANING EXAMPLE


< LESS THAN 3 < 5 GIVES 1
> GREATER THAN 7 > 9 GIVES 0
>= LESS THAN OR EQUAL TO 100 >= 100 GIVES 1

<= GREATER THAN EQUAL TO 50 >=100 GIVES 0

When arithmetic expressions are used on either side of a relational operator,


then first the arithmetic expression will be evaluated and then result will be
compared. This is because arithmetic operators have higher priority over
relational operators.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
7|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
Equality Operators:
C language supports two kinds of equality operators to compare their operands
for strict equality or inequality. They are equal to (==) and not equal to (!=)
operator.
The equality operators have lower precedence than the relational operators.
 The equal-to operator (==) returns true (1) if operands on both sides of
the operator have same value; otherwise, it returns false (0).
 On the contrary, the not-equal-operator (!=) returns true (1) if the
operands do not have the same values; else it returns false (0).

OPERATOR MEANING

== RETURNS 1 IF BOTH OPERANDS ARE EQUAL, 0 OTHERWISE

!= RETURNS 1 IF OPERANDS DO NOT HAVE THE SAME VALUE, 0 OTHERWISE

Logical Operators:
● C language supports three logical operators. They are- Logical AND
(&&), Logical OR (||) and Logical NOT (!).
● As in case of arithmetic expressions, the logical expressions are
evaluated from left to right.

Logical AND
Logical AND operator is a binary operator, which simultaneously evaluates
two values or relational expressions. If both the operands are true, then the
whole expression evaluates to true. If both or one of the operands is false, then
the whole expression evaluates to false.
A B A
&&B
0 0 0
0 1 0
1 0 0
1 1 1

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
8|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
Logical OR
Logical OR returns a false value of both the operands are false. Otherwise it
returns a true value.

A B A || B
0 0 0
0 1 1
1 0 1
1 1 1

Logical NOT
The logical NOT operator takes a single expression and negates the
value of the expression. That is, logical NOT produces a 0 if the expression
evaluates to a non-zero value and produces a 1 if the expression produces a
zero. In other words, it just reverses the value of the expression.
A !A
0 1
1 0

Unary Operators:
 Unary operators act on single operands. C language supports three unary operators.
They are unary minus, increment and decrement operators.
 When an operand is preceded by a minus sign, the unary operator negates its value.
 The increment operator is a unary operator that increases the value of its operand
by 1.
 Similarly, the decrement operator decreases the value of its operand by 1.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
9|Page
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

For example,
int x = 10, y;
y = x++;
is equivalent to writing
y = x;
x = x + 1; whereas, y = ++x;
is equivalent to writing
x = x + 1;
y = x;

Conditional Operators:
 The conditional operator, operator (?:) is just like an if .. else statement that can be
written within expressions.
 The syntax of the conditional operator is exp1 ? exp2 : exp3
 Here, exp1 is evaluated first. If it is true then exp2 is evaluated and becomes the
result of the expression, otherwise exp3 is evaluated and becomes the result of the
expression.
For example,
large = ( a > b) ? a : b
 Conditional operators make the program code more compact, more readable, and
safer to use as it is easier both to check and guarantee that the arguments that are
used for evaluation.
 Conditional operator is also known as ternary operator as it is neither a unary nor a
binary operator; it takes three operands.

Bitwise Operators:
Bitwise operators perform operations at bit level. These operators include:
bitwise AND, bitwise OR, bitwise XOR and shift operators.
 The bitwise AND operator (&) is a small version of the boolean AND (&&) as it
performs operation on bits instead of bytes, chars, integers, etc.
 The bitwise OR operator (|) is a small version of the boolean OR (||) as it performs
operation on bits instead of bytes, chars, integers, etc.
 The bitwise NOT (~), or complement, is a unary operation that performs logical
Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering
Intended for internal circulation only
10 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
negation on each bit of the operand. By performing negation of each bit, it actually
produces the ones' complement of the given binary value.
 The bitwise XOR operator (^) performs operation on individual bits of the operands. The
result of XOR operation is shown in the table.

Bitwise Shift Operators:


In bitwise shift operations, the digits are moved, or shifted, to the left or right.
The CPU registers have a fixed number of available bits for storing numerals, so when we
perform shift operations; some bits will be "shifted out" of the register at one end, while the
same number of bits are "shifted in" from the other end.
In a left arithmetic shift, zeros are shifted in on the right. For example;
unsigned int x = 11000101; Then
x << 2 = 00010100
If a right arithmetic shift is performed on an unsigned integer then zeros are shifted on the
left.
unsigned int x = 11000101;
Then
x >> 2 = 00110001

Assignment Operators:
The assignment operator is responsible for assigning values to the variables.
While the equal sign (=) is the fundamental assignment operator, C also supports other
assignment operators that provide shorthand ways to represent common variable
assignments. They are shown in the table.
The assignment operator has right-to-left associativity,
So the expression
a = b = c = 10; is evaluated as (a = (b = ( c = 10)))

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
11 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

OPERATOR SYNTAX EQUIVALENT TO


/= variable /= expression variable = variable / expression
*= variable *= expression variable = variable * expression
+= variable += expression variable = variable + expression
-= variable -= expression variable = variable - expression
&= variable &= expression variable = variable & expression
^= variable ^= expression variable = variable ^ expression
<<= variable <<= amount variable = variable << amount
>>= variable >>= amount variable = variable >> amount

Comma Operator:
The comma operator in C takes two operands. It works by evaluating the first and
discarding its value, and then evaluates the second and returns the value as the result of
the expression.
Comma separated operands when chained together are evaluated in left-to-right sequence
with the right-most value yielding the result of the expression.
Among all the operators, the comma operator has the lowest precedence.
For example,
int a=2, b=3, x=0; x = (++a, b+=a);
Now, the value of x = 6.

sizeof Operator:
sizeof is a unary operator used to calculate the sizes of data types. It can be applied to all
data types.
The operator returns the size of the variable, data type or expression in bytes.
'sizeof' operator is used to determine the amount of memory space that the
variable/expression/data type will take.
For example,
sizeof(char) returns 1, that is the size of a character data type.
If we have,
int a = 10;
unsigned int result;
result = sizeof(a); then result = 2

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
12 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

C operators have two properties: priority and associativity. When the expression has more
than one operator then it is the relative priority of the operator with respect to each other that
determine the order in which the expression will be evaluated. Associativity defines the
direction in which the operator acts on the operands. It can be either left-to-right or right-to-
left. Priority is given precedence over associativity to determine the order in which the
expressions are evaluated. Associativity is then applied, if the need arises.
Rules for Evaluation of Expression
1. First, parenthesized sub expressions from left to right are evaluated.
2. If parentheses are nested, the evaluation begins with the innermost sub- expression.
3. The precedence rule is applied in determining the order of application of operators in
evaluating sub-expressions.
4. The associativity rule is applied when two or more operators of the same precedence level
appear in a sub-expression.
5. Arithmetic expressions are evaluated from left to right using the rules of precedence.
6. When parentheses are used, the expressions within parentheses assume highest priority.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
13 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
14 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

TYPE CONVERSION
• Type conversion is used to convert data of one type to data of another type.
• Type conversion is of 2 types as shown in below figure:

IMPLICIT TYPE CONVERSION


C permits mixing of constants and variables of different types in an expression. C
automatically converts any intermediate values to the proper type so that the expression can
be evaluated without losing any significance. This automatic conversion is known as
implicit type Conversion.
During evaluation it adheres to very strict rules of type conversion. If the operands are of
different types, the „lower‟ type is automatically converted to the higher type before the
operation proceeds. The result is of the higher type.
Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering
Intended for internal circulation only
15 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

The sequence of rules that are applied while evaluating expressions. All short and char are
automatically converted to int; then
1. If one of the operands is long double, the other will be converted to long double and
the result will be long double;
2. Else, if one of the operands is double, the other will be converted to double and the
result will be double;
3. Else, if one of the operands is float, the other will be converted to float and result will
be float;
4. Else, if one of the operands is unsigned long int, the other will be converted to
unsigned long int and result will be unsigned long int;
5. Else, if one of the operands is long int, the other will be converted to unsigned int,
then
 If unsigned int can be converted to long int, the unsigned int operand will be
converted as such and the result will be long int;
 Else, both operands will be converted to unsigned long int operand will be
unsigned long int;
6. Else, if one of the operands is long int, the other will be converted to long int and
result will be long int;
7. Else, if one of the operands is unsigned int, the other will be converted to unsigned
int and result will be unsigned int;

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
16 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
Note that some versions of C automatically convert all floating-point operands to double
precision
The final result of an expression is converted to the type of the variable on the left of the
assignment sign before assigning the value to it. However, the following changes are
introduced during the final assignment.
1. float to int causes truncation of the fractional part.
2. double to float causes rounding of digits.
3. long int to int causes dropping of the excess higher order bits.

EXPLICIT CONVERSION
• When the data of one type is converted explicitly to another type with the help of some pre-
defined functions, it is called as explicit conversion.
• There may be data loss in this process because the conversion is forceful.
• The syntax is shown below:
data_type1 v1;
data_type2 v2= (data_type2) v1;
where v1 can be expression or variable
• For ex:
float b=11.000000; int c = 22;
float d = b/(float)c =11.000000/22.000000 = 0.500000

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
17 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
18 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Decision control and Looping statements

Introduction to Decision Control Statements


C program is executed sequentially from the first line of the program to its last line, i.e., the
second statement is executed after the first, the third statement is executed after the second,
and so on.
Although this is true, but in some cases we want only selected statements to be executed.
Such type of conditional processing extends the usefulness of programs.
C supports two type of decision control statements that can alter the flow of a sequence of
instructions. These include conditional type branching and unconditional type branching.
Below figure shows the categorization of decision control statements in C language.

Conditional Branching Statements


● Decision control statements are used to alter the flow of a sequence of
instructions.
● These statements help to jump from one part of the program to another
depending on whether a particular condition is satisfied or not.
● These decision control statements include:
 Simple If statement
 If else statement
 If else if statement
 Switch statement

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
19 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Simple if statement
 If statement is the simplest form of decision control statements that is frequently used
in decision making. The general form of a simple if statement is shown in the figure.
 First the test expression is evaluated. If the test expression is true, the statement of if
block (statement 1 to n) are executed otherwise these statements will be skipped and
the execution will jump to statement x.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
20 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
if-else Statement:
This is basically a “two-way” decision statement.
This is used when we must choose between two alternatives.
In the if-else construct, first the test expression is evaluated. If the expression
is true, statement block 1 is executed and statement block 2 is skipped.
Otherwise, if the expression is false, statement block 2 is executed and
statement block 1 is ignored. In any case after the statement block 1 or 2 gets
executed the control will pass to statement x. Therefore, statement x is
executed in every case.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
21 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

if-else-if Statement (if-else-if Ladder in C):


● C language supports if else if statements to test additional conditions apart from the initial
test expression. The if-else-if construct works in the same way as a normal if statement.
● if-else-if construct is also known as nested if construct. It is illustrated in the below figure.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
22 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Example programs:

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
23 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
24 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Rules for Indentation:


When using control structures, a statement often controls many other
statements that follow it. In such situations it is a good practice to use
indentation to show that the indented statements are dependent on the
preceding controlling statement. Some guidelines that could be followed
while using indentation are listed below:
 Indent statements that are dependent on the previous statements;
provide at least three spaces of indentation.
 Align vertically else clause with their matching of clause.
 Use braces on separate lines identify a block of statements.
 Indent the statements in the block by at least three spaces to the
right of the braces.
 Align the opening and closing braces.
 Use appropriate comments to signify the beginning and end of the block.
 Indent the nested statements as per the above rules.
 Code only one clause or statement on each line.

switch case:
This is an alternative to the if else if ladder that can be used to execute the conditional code
based on the value of the variable specified in the switch statement. The switch block consists
of cases to be executed based on the value of the switch variable.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
25 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Example:

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
26 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Advantages of Using a switch case statement:


Switch case statement is performed by programmers due to the following reasons:
1.Easy to debug
2.Easy to read and understand
3.Ease of maintenance as compared with its equivalent if-else statement
4.Like if-else statements, switch statements can also be nested.
5.Executes faster than its equivalent if-else statement.

ITERATIVE STATEMENTS
Iterative statements are used to repeat the execution of a list of statements, depending on the
value of an integer expression. C language supports three types of iterative statements also
known as looping statements. They are:
 While loop
 Do-while loop
 For loop

while Loop
 The while loop is used to repeat one or more statements while a
particular condition is true.
 Below figure shows the syntax and general form representation of a while
loop.
 In the while loop, the condition is tested before any of the statements
in the statement block is executed.
 If the condition is true, only then the statements will be executed
otherwise the control will jump to the immediate statement outside the
while loop block.
 We must constantly update the condition of the while loop.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
27 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Do-while Loop
 The do-while loop is similar to the while loop. The only difference is that in a do- while
loop, the test condition is tested at the end of the loop.
 Note that the test condition is evaluated at the end, this clearly means the body of the
loop gets executed at least one time (even if the condition is false).
 The do while loop continues to execute whilst a condition is true. There is no choice
whether to execute the loop or not. Hence, entry in the loop is automatic there is only
a choice to continue it further or not.
 The major disadvantage of using a do while loop is that it always executes at least once,
so even if the user enters some invalid data, the loop will execute.
Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering
Intended for internal circulation only
28 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
 Do-while loops are widely used to print a list of options for a menu driven program.

for Loop
Like the while and do-while loops, the for loop provides a mechanism to repeat a task until a
particular condition is true. For loop is usually known as a deterministic or definite loop
because the programmer knows as a exactly how many times the loop will repeat. The general
syntax and form of for loop is shown below.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
29 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

 When a for loop is used, the loop variable is initialized only once.
 With every iteration of the loop, the value of the loop variable is updated and
the condition is checked. If the condition is true, the statement block of
the loop is executed else, the statements comprising the statement block of the
for loop are skipped and the control jumps to the immediate statement
following the for loop body.
 Updating the loop variable may include incrementing the loop variable,
decrementing the loop variable or setting it to some other value like, i +=2,
where i is the loop variable.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
30 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Nested Loops
C allows its users to have nested loops, i.e., loops that can be placed inside other loops.
Although this feature will work with any loop such as while, do-while, and for, it is most
commonly used with the for loop, because this is easiest to control.
A for loop can be used to control the number of times that a particular set of statements will
be executed. Another outer loop could be used to control the number of times that a whole
loop is repeated.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
31 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
Syntax
The syntax for a nested for loop statement in C is as follows: −
for ( initialization; condition; increment )
{
for ( initialization; condition; increment )
{
statement(s);
}
statement(s);
}

Example: Program to print triangles using *, numbers and characters

*
* *
* **
* ***
* ****

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
32 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
Example 2: Program to print half pyramid a using numbers

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
33 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Programs to print inverted half pyramid using * and numbers

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
34 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Break and continue Statement:


Loops perform a set of operations repeatedly until the control variable fails to
satisfy the test-condition. The number of times a loop is repeated is decided
in advance and the test condition is written to achieve this. Sometimes, when
executing a loop it becomes desirable to skip a part of the loop or to leave the
loop as soon as a certain condition occurs.
Consider a searching program, loop written for reading and testing the
names 100 times must be terminated as soon as the desired name if found. C
permits a jump from one statement to another statement within a loop as well
as a jump out of a loop.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
35 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering
THE break STATEMENT
• The break statement is jump statement which can be used in switch
statement and loops.
• The break statement works as shown below:
1) If break is executed in a switch block, the control comes out of the
switch block and the statement following the switch block will be
executed.
2) If break is executed in a loop, the control comes out of the loop and
the statement following the loop will be executed.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
36 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Example:

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
37 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

THE continue STATEMENT


During execution of a loop, it may be necessary to skip a part of the loop
based on some condition.
In such cases, we use continue statement.
• The continue statement is used only in the loop to terminate the current
iteration.
• The syntax is shown below:

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
38 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

Example:

goto Statement:
• goto statement can be used to branch unconditionally from one point to another in the
program.
• The goto requires a label in order to identify the place where the branch is to be made.
• A label is any valid variable name and must be followed by a colon( : ).
• The label is placed immediately before the statement where the control is to be
transferred.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
39 | P a g e
ACHARYA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF Computer Science and Engineering

• The syntax is shown below:

The label: can be anywhere in the program either before or after the goto label; statement.
During running of a program when a statement like
goto begin;
Note that a goto breaks the normal sequential execution of the program. If the label: is before
the statement goto label; a loop will be formed and some statements will be executed
repeatedly. Such a jump is known as a backward jump. On the other hand, if the label: is
placed after the goto label; some statements will be skipped and jump is known as a forward
jump.

Example: Program to detect the entered number as to whether it is even or odd. Use goto
statement.

Mrs. Reshma– Principles of Programming using C – Computer Science and Engineering


Intended for internal circulation only
40 | P a g e

You might also like