[go: up one dir, main page]

0% found this document useful (0 votes)
9 views58 pages

CFP - Unit 3

The document covers decision control and looping statements in the C programming language, detailing structures such as if, if-else, and switch statements. It explains how to implement these control structures with examples, including nested if-else and cascaded if-else statements. Additionally, the document provides sample programs demonstrating the use of these constructs for decision-making in various scenarios.

Uploaded by

NAMDEO
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)
9 views58 pages

CFP - Unit 3

The document covers decision control and looping statements in the C programming language, detailing structures such as if, if-else, and switch statements. It explains how to implement these control structures with examples, including nested if-else and cascaded if-else statements. Additionally, the document provides sample programs demonstrating the use of these constructs for decision-making in various scenarios.

Uploaded by

NAMDEO
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/ 58

COMPUTER FUNDAMENTALS AND PROGRAMMING

UNIT 3

DECISION CONTROL AND LOOPING STATEMENTS

By. Prof. N. D. Kapale


No.
Unit Decision Control and Looping of CO
-III Statements Hou s
rs

Decision Control Structures In 'C': if,


if-else, nested if-else, cascaded if-else, C
switch statement 06 O
Loop Control: for, while, do-while 3
loops, break , continue, nested loops
Decisions Control
 Sequence control structure , where the various
steps are executed sequentially, i.e. in the same
order in which they appear in the program.
 However many a times, we want a set of
instructions to be executed in one situation, and
an entirely different set of instructions to be
executed in another situation.
 This kind of situation is dealt in C programs
using a decision control instruction.
Decisions Control
 We all need to alter our actions in the face of
changing circumstances. If the weather is fine, then
I will go for a picnic. If the highway is busy then I
would take a diversion, etc….
 All these decisions depend on some condition being
met.
 C language also provide support to perform different
sets of actions depending on the circumstances.
 C has three major decision making instructions
1. if statement
2. if-else statement
3. switch statement.
The if Statement
 C uses the keyword if to implement the decision
control instruction.
 The general form of if statement looks like this:
 if (condition is true ) execute this statement ;
 The condition following the keyword if is always
enclosed within a pair of parentheses.
 If the condition, is true, then the statement is
executed.
 If the condition is not true then the statement is not
executed.
The if Statement
 We express a condition using C’s ‘relational’
operators.
 The relational operators allow us to compare
two values
 whether they are equal to each other,
unequal, one is greater than the other.
/* Demonstration of if statement */

void main()  On execution of


the program, if
{ you type a
int num; number greater
than 10, you get
clrscr(); a message on
printf("Enter a number the screen
through
greaterthan 10");
printf(“---” ).
scanf("%d",&num);  If you type some
if(num>10) other number
the program
printf(“Good!!"); doesn’t do
} anything.
Example :
 While purchasing certain items, a
discount of 10% is offered if the quantity
purchased is more than 1000.
 If quantity and price per item are input
through the keyboard, write a program to
calculate the total expenses.
/* Calculation of total expenses sample
*/ interaction
void main( ) with the program.
1. Enter quantity
{
and rate 1200
int qty, dis = 0 ; 15.50
float rate, tot ; Total expenses =
printf ( "Enter quantity and rateRs."16740.000000
);
2. Enter quantity
scanf( "%d %f", &qty, &rate) ;
and rate 200 15.50
if ( qty> 1000 )
dis = 10 ; Total expenses =
tot = ( qty* rate ) -( qty* rate Rs.
* dis3100.000000
/ 100 ) ;
printf ( "Total expenses = Rs. %f", tot ) ;
}
IMP …..
 Note that in C a non-zero value is considered
to be true, whereas a 0 is considered to be
false.
 Example 1:
if ( a = 10 )
printf ( "Even this works" ) ;
 In the above example, 10 gets assigned to a
so the if is now reduced to if ( a ) or if ( 10 ).
Since 10 is non-zero, it is true hence again
printf( ) goes to work.
IMP …..
 Example 3:
if ( -5 )
printf ( "Surprisingly even this works" ) ;
 In the above example, -5 is a non-zero number,
hence true. So again printf( ) goes to work.
 In place of -5 even if a float like 3.14 were used
it would be considered to be true. So the issue is
not whether the number is integer or float, or
whether it is positive or negative.
 Issue is whether it is zero or non-zero.
The if-else Statement
 The if statement by itself will execute a single
statement, or a group of statements, when
the expression following if evaluates to true. It
does nothing when the expression evaluates
to false.
 The else statement Can execute one group of
statements if the expression evaluates to true
and another group of statements if the
expression evaluates to false.
If- Else
flow chart
syntax
if ( condition )
{
if body ;
}
else
{
else body ;
}
A few points worth noting...
 The group of statements after the if upto and
not including the else is called an ‘if block’.
Similarly, the statements after the else form
the ‘else block’..
 Notice that the else is written exactly below
the if. The statements in the if block and those
in the else block have been indented to the
right.
 Had there been only one statement to be
executed in the if block and only one
statement in the else block we could have
Continue…
 Example 1: In a company an employee is paid
as under:
If his basic salary is less than Rs. 1500, then
HRA = 10% of basic salary and DA = 90% of
basic salary.
If his salary is either equal to or above Rs.
1500, then HRA = Rs. 500 and DA = 98% of
basic salary.
If the employee's salary is input through the
keyboard write a program to find his gross
salary
/* Calculation of gross salary */
void main( )
{
float bs, gs, da, hra ;
printf ( "Enter basic salary " ) ;
scanf( "%f", &bs) ;
if ( bs< 1500 )
{
hra= bs* 10 / 100 ;
da = bs* 90 / 100 ;
}
else
{
hra= 500 ;
da = bs* 98 / 100 ;
}
gs= bs+ hra+ da ;
printf ( "gross salary = Rs. %f", gs) ;
Nested if-else
 It is perfectly all right if we write an
entire if-else construct within either the
body of the if statement or the body of
an else statement.
 This is called ‘nesting’ of ifs. This is
shown in the following program.
Nested If

Syntax

if(condition1)
{
/* code to be executed if condition1 is true */
if (condition2)
{
/* code to be executed if condition2 is true */
}
else
{
/* code to be executed if condition2 is false */
}
}
else
{
/* code to be executed if condition1 is false */
}
/* A quick demo of nested if-else */
void main( )
{
int i;
printf ( "Enter either 1 or 2 " ) ;
scanf( "%d", &i) ;
if ( i== 1 )
printf ( "You Entered One !" ) ;
else
{
if ( i== 2 )
printf ( "You Entered Two !!" ) ;
else
printf ( "You Entered Other than One and
Two !" ) ;
}
Continue…..

 Note that the second if-else construct is


nested in the first else statement. If the
condition in the first if statement is
false, then the condition in the second
if statement is checked. If it is false as
well, then the final else statement is
executed.
Example 2:
 The marks obtained by a student in 5 different
subjects are input through the keyboard. The
student gets a division as per the following
rules:
 Percentage above or equal to 60 - First division
 Percentage between 50 and 59 - Second division
 Percentage between 40 and 49 - Third division
 Percentage less than 40 – Fail .
 Write a program to calculate the division
obtained by the student. There are two ways in
which we can write a program for this example.
/* Method -I*/
void main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ;
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
if ( per >= 60 )
printf ( "First division ") ;
else
{
if ( per >= 50 )
printf ( "Second division" ) ;
else
{
if ( per >= 40 )
printf ( "Third division" ) ;
else
printf ( "Fail" ) ;
}
}
/* Method –II Using Logical Operators*/
void main( )
{
int m1, m2, m3, m4, m5, per ;
printf ( "Enter marks in five subjects " ) ;
scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4,
&m5 ) ;
per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
if ( per >= 60 )
printf ( "First division" ) ;
if ( ( per >= 50 ) && ( per < 60 ) )
printf ( "Second division" ) ;
if ( ( per >= 40 ) && ( per < 50 ) )
printf ( "Third division" ) ;
if ( per < 40 )
printf ( "Fail" ) ;
Program to print largest number

#include <stdio.h>
void main()
{
int num1, num2, num3;
printf("Enter the values of num1, num2 and
num3\n");
scanf("%d %d %d", &num1, &num2, &num3);
if (num1 > num2)
{
if (num1 > num3)
printf("%d is the largest number.", num1);
else
printf("%d is the largest number.", num3);
}
else
{
if (num2 > num3)
printf("%d is the largest number.", num2);
else
printf("%d is the largest number.", num3);
Cascaded If-else(If - else
Ladder)
 Allows to check between Flow chart
multiple conditions and
execute different statemants.
SYNTAX
if(condition1)
{
//statement1
}
else if(condition2)
{
//statement2
}
else if(condition3)
{
//statement3
}
else
{
//statement4
}
simple calculator
// C Program to make a Simple Calculatorelse if(ch==2)
using
#include <stdio.h> {
sub = number1 - number2; // Calculate
int main() { substraction
int number1, number2, ch,sum,sub,mul,div,rem;
printf("Substraction: %d", sub);
printf("Enter number1: "); }
scanf("%d", &number1); else if(ch==3)
{
printf("Enter number2: ");
mul = number1 * number2; //
scanf("%d", &number2); Calculate multiplication
printf("Enterchoice:: "); printf("Multiplication: %d", mul);
scanf("%d", &ch); }
if(ch==1) else if(ch==4)
{
{ div = number1/ number2; // Calculate
sum = number1 + number2; // Calculate sum
division
printf("Addition: %d", sum); printf("Division: %d", div);
} }
Example Cascaded if -else
#include<stdio.h>
int main( )
{
int m, ;
printf ( "Enter marksof students " ) ;
scanf ( "%d ", &m ) ;
if ( m <= 100 && m>=90 )
printf ( "GREAD is= A ") ;
else if( m <90 && m>=80 )
printf ( "GREAD is =B ") ;
else if( m <80 && m>=70 )
printf ( "GREAD is =C ") ;
else if( m <70 && m>=60 )
printf ( "GREAD is =D") ;
else if( m <60 && m>=50 )
printf ( "GREAD is =E ") ;
else if( m <50 )
printf ( "GREAD is =FAIL ") ;
else
printf ( "Enter Valid Scor between 0 to 100 ") ;
return (0);
}
Decisions Using switch
 The control statement that allows us to make a
decision from the number of choices is called a
switch, or more correctly a switch-case-default, since
these three keywords go together to make up the
control statement. They most often appear as
follows:
switch ( integer expression )
{
case constant 1 : do this ;
case constant 2 : do this ;
case constant 3 : do this ;
default : do this ;
Continue….
 The integer expression following the keyword
switch is any C expression that will yield an integer
value. It could be an integer constant like 1, 2 or 3,
or an expression that evaluates to an integer.
 The keyword case is followed by an integer or a

character constant.
 Constant in each case must be different from all the

others.
 The “do this” lines represent any valid C statement.
Continue…
 What happens when we run a program containing a
switch?
 First, the integer expression following the keyword switch
is evaluated.
 The value it gives is then matched, one by one, against the
constant values that follow the case statements.
 When a match is found, the program executes the
statements following that case, and all subsequent case
and default statements as well.
 If no match is found with any of the case statements, only
the statements following the default are executed.
void main( )
{ The output:
I am in case 2
int i = 2 ;
I am in case 3
switch ( i )
I am in default
{
case 1 :
printf ( "I am in case 1 \n" ) ;
case 2 :
printf ( "I am in case 2 \n" ) ;
case 3 :
printf ( "I am in case 3 \n" ) ;
default :
printf ( "I am in default \n" ) ;
}
C Program to make a Simple Calculator using
switch-case statements

#include <stdio.h> switch (op)


{
int main() case '+':
res = a + b;
{ break;
char op; case '-':
res = a - b;
float a, b, res; break;
case '*':
// Read the operator res = a * b;
break;
printf("Enter an operator (+, -, *, /):'/':");
case
scanf("%c", &op); res = a / b;
break;
// Read the two numbers default:
printf("Incorrect Operator
printf("Enter two operands: ");Value\n");
}
scanf("%f %f", &a, &b); printf("%.2f", res);
return 0;
// Define all four operations in the corresponding switch-case
Summary
 There are three ways for taking decisions in a
program. First way is to use the if-else
statement, second way is to use the conditional
operators and third way is to use the switch
statement.
 The default scope of the if statement is only
the next statement. So, to execute more than
one statement they must be written in a pair of
braces.
 An if block need not always be associated with
an else block. However, an else block is always
Loop Control
 In C programming, loops are use for performing
repetitive tasks.
 Loop repeat execution of block of statements until

condition holds true.


 There are two types of loops in C

 Entry-controlled loop:If test condition is true

then only it will be enter in to body of loop.


-Example: for loop and while loop
 Exit-controlled loop: Test condition is evaluated

at the end of loop body. Hence loop is executed at


least once irrespective of condition is true or false.
-Example: Do while loop
for loop
 Loop variable is used to control the loop
 first initialized this variable to some value

then check this value is less/greater than


counter value.
 If condition is true then statement is

executed and loop variable value get


updated.
 Steps are repeated till exit condition

reached.
Syntax
for(initilization ; Test Expression; Update)
{
working of for loop
 Initilization statement executed
only once
 If test expression is evaluated false
then loop terminited.
 If test expression is evaluated True
then the statements inside body of
for loop executed and update
expression updated.
 Again test expression is evaluated.
 This process is repeated until test
expression becomes false, when
test expression is false loop
Example: Print number from
1 to 10
#include <stdio.h>
int main()
{
int i;
for (i = 1; i <= 10; i++) // for loop without braces
printf("%d ", i);
printf("\nThis statement executes after for loop end!!!!");
// Statement print only once
return 0;
}
Write a C code to display a table of 3

#include <stdio.h>
int main()
{
int i,num,table;
printf("Enter the number whose table you want to print");
scanf("%d",&num);
for(i = 1; i <= 10; i++)
{
table=num*i;
printf("%dx %d = %d\n",num, i, table);
}
return 0;
}
Write a C code to display a sum of 1 to
10 numbers.

#include <stdio.h>
int main()
{
int i,sum = 0;
for(int i = 1; i <= 10; i++)
{
sum = sum+i; // Add i to sum
}
// Display the sum
printf("The sum of numbers from 1 to10 is: %d\n", sum);
return 0;
}
Write a C code to display the Factorial of
the accepted number.
#include <stdio.h>
int main()
{
int n, factorial = 1;
// Ask user for input
printf("Enter a number: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++)
factorial = factorial*i; // Multiply factorial by i
printf("Factorial of %d is: %d\n", n, factorial);
return 0;
}
Display Pattern
1
12
123
1234

#include <stdio.h>
int main()
{
// Loop for each row
for(int i = 1; i <= 4; i++)
{
// Loop to print numbers in each row
for(int j = 1; j <= i; j++)
{
printf("%d", j); // Print the number
}
printf("\n"); // Move to the next line after
each row
}
return 0;
}
Display Pattern
****
***
**
*

#include <stdio.h>
int main()
{
// Outer loop for rows
for (int i = 4; i >= 1; i--)
{
// Inner loop for printing '*' in each row
for (int j = 1; j <= i; j++)
{
printf("*");
}
printf("\n"); // Move to the next line after printing stars
}
return 0;
}
While loop
• Evaluates test expression
 used when we dont know
in side braces()
exact number of • If the test expression is
iteration/repetation before
true then statements inside
hand.
the body of loop are
 The loop terminated on the
executed, test expression is
basic of test condition. evaluated again.
Syntax • The process continue till
while (test expression) test expression is evaluated
{ true.
// body consisting of multiple • If test expression is
statements evaluated false loop
terminated.
Flow chart
//Program to print numbers from 0 to 5
#include <stdio.h>
int main()
{
// Initialization of loop variable
int i = 0;
// setting test expression as (i < 5)
while(i < 5)
{
printf("%d\n",i);
// updating the loop variable
i++;
}
return0;
}
}}};
}
Do-while loop
Use when code need to be executed
atleast once like in MENU driven
program.

Syntax
do
{
// body of do-while loop
}while(test expression);
Example Do-while
program to print table of given
number
int main() int main()
{ {
int i = 0; int i = 1,num=0;
do { printf(“Enter the
number”);
scanf(“%d”,&num);
printf("Sanjivani\n"); do {
i++; printf("%d",num*i);
} while (i < 3); i++;
return 0; } while (i <= 10);
} return 0;
infinite loop
 Endless loop:piece of coding that lacks functional exit so
that it repeats indefinetly.
-Occurs when condition always evaluated to true.
-Usually this is an error.
 Break statement

-terminate the loop immediately when it encountered.


Syntax
break;
-It is used almost always used with if-else statement inside
loop.
How break statement works
1. 2. 3.
while(test for(initilization; test
do
expresson; update)
expression) { {
{ if(condition to if(condition to
if(condition to break)break) break)
{ { {
break: break: break;
}
} }
code statement;
} }while(test
}
expression);
Example break statement using for loop

include<stdio.h>
void main()
{
int i;
for(i=0;i<10;i++)
{
printf(“%d”, i);
if(i==5)
break;
}
printf(“Came outside of loop i=%d”,i);
}
continue statement
-continue statement skip
current iteration of loop and
continue with next iteration.
-bring program control
begining of loop.
-skip some line of code
inside loop and continue
with next iteration.

Syntax
continue;
C program to demonstrate difference between
continue and break
int main()
{
printf("The loop with break produces output as: \n");
 output
for (int i = 1; i <= 7; i++) { The loop with break
// Program comes out of loop when i becomes produces output as: 1 2
multiple of 3.
if (i == 3) The loop with continue
break; produces output as:
else
printf("%d ", i); 124567
}
printf("\nThe loop with continue produces output as: \
n");
for (int i = 1; i <= 7; i++)
// The loop prints all values except those that are
multiple of 3.
if (i == 3)
continue;
printf("%d ", i);
}
return 0;
}
Go to statement
 Jump statement in C
 Transfer program control to predefined label.

 to repeat some part of code for particular condition.

 to break multiple loops ,which cannot be done by

single break statement.


 Go to is avoided as it is less readable and

complicated.
 Syntax

label:
some part of code;
go to label;
Drawbaks of go to
statement
 It makes program logic complicated.
 It make task of analyzing & verifying
correcteness of program very difficult.
 Its use can be avoided by using break &
continue statements.
use of go to statement
void main()
{
int num, i=1;
printf(“Enter the number whose table you want to print”);
scanf(“%d”,&num);
table:
printf(“%dx%d=%d\n”,num,i,num*i);
i++;
if(i<=10)
go to table;
}
Reference
1. Brian W. Kernighan, Dennis M. Ritchie,
“The C Programming Language”,
Prentice Hall, ISBN 0131103628,
Second Edition
2. Yashwant Kanetkar, “Let Us C”, BPB
Publication, ISBN-10:81-8333-163-7
3. E Balagurusamy, “Programming in ANSI
C” McGraw Hill ,9th edition

You might also like