0% found this document useful (0 votes)
15 views75 pages

CP - Unit-II

Unit II covers selection and repetition statements in C programming, including if, switch, while, for, and do-while statements. It explains decision control structures, compound statements, and looping concepts, along with examples of each type of statement. The document also discusses the syntax and rules for using these statements effectively in C programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views75 pages

CP - Unit-II

Unit II covers selection and repetition statements in C programming, including if, switch, while, for, and do-while statements. It explains decision control structures, compound statements, and looping concepts, along with examples of each type of statement. The document also discusses the syntax and rules for using these statements effectively in C programs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 75

UNIT-2

UNIT – II:

Statements- Selection Statements (making decisions) –


if and switch statements, Repetition statements (loops)-
while, for, do-while statements, Loop examples, other
statements related to looping – break, continue, go to,
Simple C Program examples.
Statements
: Selection Statements (making decisions) – if and
switch 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.


Types of Statements
 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
Decision Control Structures
 The decision is described to the computer as a conditional
statement that can be answered either true or false.

 If the answer is true, one or more action statements are


executed.

 If the answer is false, then a different action or set of actions


is executed.

Types of decision control structures:


 if
 if..else
 nested if…else
 else if ladder
 dangling else
 switch statement
Decision Control Statement: if
The general form of a simple if statement is:

if (condition)
{
statement-block;
}

Following are the properties of an if statement:

 If the condition is true then the statement-block will be executed.


 If the condition is false it does not do anything ( or the statement
is skipped)
 The condition is given in parentheses and must be evaluated as
true
(nonzero value) or false (zero value).
 If a compound statement is provided, it must be enclosed in
opening
Decision Control Statement: if
Flow Chart
Example:
Enter main()
{
int a=10,b=20;
Condition
if(a>b)
{
Body of the IF Statement printf(“%d”,a);
}
printf(“%d”,b);
Exit }
Decision Control Statement: if..else

if...else Logic Flow


Syntactical Rules for if…else Statements

 The expression or condition which is followed by if statement


must be enclosed in parenthesis.

 No semicolon is needed for an if…else statement.

 Both the true and false statements can be any statement (even
another if…else).

 Multiple statements under if and else should be enclosed


between curly braces.

 No need to enclose a single statement in curly braces.


Decision Control Statement: if..else

A Simple if...else Statement


Compound Statements in an if...else
Example for Decision Control Statement: if..else
Example for Decision Control Statement: if..else
Decision Control Statement: nested if…else

 Nested if…else means within the if…else you can include another if…else
either in
if block or else block.
Nested if…else Statements
Decision Control Statement: nested if…else
Decision Control Statement: nested if…else
Decision Control Statement: else if
if (condition1)
statements1;
else if (condition2)
statements2;
else if (condition3)
statements3;
else if (condition4)
statements4;
……
else if(conditionn)

statementsn;
else

 Thedefault_statement;
conditions are evaluated from the top to down.
 As statement x; condition is found the statement associated with it is executed
soon as a true
and the control is transferred to the statementx by skipping the rest of the ladder.
 When all n conditions become false,final else containing default_statement
that will be executed
main() {
Example program for nested if…else
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<75 && per>=60)
printf(“\nFirst Class”);
else {
if(per<60 && per>=50)
printf(“\nSecond Class”);
else {
if(per<50 && per>=40)
printf(“\nThird Class”);
else
printf(“\nFail”);
}//else
}//else
}//else
}//main
Example program for else if
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<75 && per>=60)
printf(“\nFirst Class”);
else if(per<60 && per>=50)
printf(“\nSecond Class”);
else if(per<50 && per>=40)
printf(“\nThird Class”);
else
printf(“\nFail”);
}//main
Dangling else
 else is always paired with the most recent unpaired if.

Dangling else
Dangling else
 (contd…)
To avoid dangling else problem place the inner if statement
with in the curly braces.

Dangling else Solution


 A simple if…else can be represented using the conditional (ternary)
expression.

Conditional Expression
Decision Control Statement: switch

 It is a multi-way conditional statement generalizing the if…else


statement.

 It is a conditional control statement that allows some particular group


of statements to be chosen from several available groups.

 A switch statement allows a single variable to be compared with


several possible case labels, which are represented by constant values.

 If the variable matches with one of the constants, then an execution


jump is made to that point.

 A case label cannot appear more than once and there can only be one
default expression.
Decision Control Statement: switch
 Note: switch statement does not allow less than ( < ), greater than
( > ).
 ONLY the equality operator (==) is used with a switch statement.
 The control variable must be integral (int or char) only.
 When the switch statement is encountered, the control variable is
evaluated.
 Then, if that evaluated value is equal to any of the values specified
in a case clause, the statements immediately following the colon
(“:”) begin to run.
 Default case is optional and if specified, default statements will
be executed, if there is no match for the case labels.
 Once the program flow enters a case label, the statements
associated with case have been executed, the program flow
continues with the statement for the next case. (if there is no
break statement after case label.)
Decision Control Statement: switch

General format of switch:


Decision Control Statement: switch

 The following results are possible, depending on the value of printFlag.

 If printFlag is 1, then all three printf statements are executed.

 If printFlag is 2, then the first print statement is skipped and the last two
are executed.

 Finally, if printFlag is neither 1 nor 2, then only the statement defined by


the default is executed.
Decision Control Statement: switch
Example1 for switch statement:
Decision Control Statement: switch
 If you want to execute only one case-label, C provides break
statement.

 It causes the program to jump out of the switch statement, that is go


to the closing braces (}) and continues the remaining code of the
program.

 If we add break to the last statement of the case, the general form of
switch case is as follows:
Decision Control Statement: switch
General format of switch:
Decision Control Statement: switch
Example2 for switch statement:
Repetitive control structures – Pre-test and post-test loops,
initialization and updation, event and counter controlled loops,
while, do..while, for, break and continue statements, comma
expression.

Repetition statements (loops)-while, for, do-while statements,


Loop examples, other statements related to looping – break,
continue, go to, Simple C Program examples.
Concept of a loop

 The real power of computers is in their ability to repeat an


operation or a series of operations many times.

 This repetition, called looping, is one of the basic structured


programming concepts.

 Each loop must have an expression that determines if the loop is


done.

 If it is not done, the loop repeats one more time; if it is done, the
loop terminates.
Concept of a Loop
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.
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.
Pretest and Post-test Loops
Minimum Number of Iterations in Two Loops
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.
Loop Initialization and Updating
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.
Event-controlled Loop Concept
Counter-controlled Loop Concept
Loop Comparisons
Loops in C
 C has three loop statements: the while, the for, and the do…while. The

first two are pretest loops, and the third is a post-test loop.

 We can use all of them for event-controlled and counter-controlled


loops.
A looping process, in general, would include the following four steps:
 Before a loop start, the loop control variable must be initialized; this
should be done before the first execution of loop body.

 Test for the specified condition for execution of the loop, known as loop
control expression.

 Executing the body of the loop, known as actions.

 Updating the loop control variable for performing next condition


checking.
C Loop Constructs
while
 The "while" loop is a generalized looping structure that employs a variable
or expression for testing the condition.

 It is a repetition statement that allows an action to be repeated while some


conditions remain true.

 The body of while statement can be a single statement or compound


statements.

 It doesn’t perform even a single operation if condition fails.


The while Statement
Compound while Statement
Example 1: To print 1 to 10 natural numbers

#include<stdio.h>
main()
{
int i;
i=1;
while (i<=10)
{
printf(“%d\n”,i);
i++;
}
}
Example 2: To print the reverse of the given number.

void main()
{
int n, rem, rev = 0;
printf("\n Enter a positive number: ");
scanf("%d",&n);
while(n != 0)
{
rem = n%10;
rev = rev*10+rem;
n = n/10;
}
printf("The reverese of %d is %d",n,rev);
}
do while
 The “do while" loop is a repetition statement that allows an action to be
done at least once and then condition is tested.

 On reaching do statement, the program proceeds to evaluate the body of


the loop first.

 At the end of the loop, condition statement is evaluated.

 If the condition is true, it evaluates the body of the loop once again.

 This process continues up to the condition becomes false.


do…while Statement
Example 3: To print fibonacci sequence for the given
number.

#include<stdio.h>
main()
{
int a=0,b=1,c,i;
i=1;
printf("%d%d",a,b);
do
{
c=a+b;
i++;
printf("%3d",c);
a=b;
b=c;
}while(i<=10);
}
Example 4: 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);
}
//Program to print 5 4 3 2 1 using while and do…while
Pre- and Post-test Loops
for
 A for loop is used when a loop is to be executed a known number
of times.

We can do the same thing with a while loop, but the for loop is
easier to read and more natural for counting loops.

General form of the for is:

for( initialization; test-condition; updation)


{
Body of the loop
}
for Statement
Compound for Statement
Comparing for and while Loops
A Simple Nested for Loop
We can write the for loop in the following ways:

Option 1:
for (k= 1; k< = 10 ;)
{
printf(“%d”, k);
k = k + 1;
}
Here the increment is done within the body of the for loop and not in
the for statement. Note that the semicolon after the condition is
necessary.
Option 2:
int k = 1;
for (; k< = 10; k++);
{
printf(“, k);
}
Here the initialization is done in the declaration statement itself, but
still the semicolon before the condition is necessary.
Option 3: The infinite loop
One of the most interesting uses of the for loop is the creation of the infinite loop.
Since none of the three expressions that form the for loop are required, it is
possible to make an endless loop by leaving the conditional expression empty.
For example: for (; ;)
printf(“The loop will run forever\n”);

Actually the for (; ;) construct does not necessarily create an infinite loop because
C’s break statement, when encountered anywhere inside the body of a loop, causes
immediate termination of the loop.

Program control then picks up the code following the loop, as shown here:
for (; ;)
{
ch = getchar( ); /* get a character */
if (ch = = ‘A’)
break ;
}
printf (“you typed an A”);
This loop will run until A is typed at the keyboard.
Option 3: For loop with no body

A statement, as defined by the C syntax, may be empty.


This means that the body of the for may also be empty.
This fact can be used to improve the efficiency of certain algorithms as well
as to create time delay loops.

The following statement shows how to create a time delay loop using a for
loop:

for (t = 0; t < SOME _VALUE; t++);


 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


Comparison of while and do…while
Comparison of while and do…while
break
 When a break statement is enclosed inside a block or loop, the loop is
immediately exited and program continues with the next statement
immediately following the loop.

 When loop are nested break only exit from the inner loop containing it.

The format of the break statement is:


Example 6: Program to demonstrate break statement.

#include<stdio.h>
main()
{
int i;
i=1;
while(i<=10)
{
if(i==8)
break;
printf(“%d\t”,i);
i=i+1;
}
printf(“\n Thanking You”);
}
continue
 When a continue statement is enclosed inside a block or loop, the loop is
to be continued with the next iteration.

 The continue statement tells the compiler, skip the following statements
and continue with the next iteration.

 The format of the continue statement is:


Example 5: Program to demonstrate continue statement.

#include<stdio.h>

main()
{
int i;
for(i=1;i<=5;i++)
{
if(i = = 3)
continue;
printf(" %d",i);
}
}

You might also like