0% found this document useful (0 votes)
14 views30 pages

Chapter2-Decision Making Statements

The document explains decision-making statements in C programming, including if, if...else, if...else if...else, and switch statements, with examples for each. It also covers loop structures such as while, do...while, and for loops, as well as the break and continue statements. Additionally, it introduces the goto statement for altering program execution flow.

Uploaded by

Haftu Mesele
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)
14 views30 pages

Chapter2-Decision Making Statements

The document explains decision-making statements in C programming, including if, if...else, if...else if...else, and switch statements, with examples for each. It also covers loop structures such as while, do...while, and for loops, as well as the break and continue statements. Additionally, it introduces the goto statement for altering program execution flow.

Uploaded by

Haftu Mesele
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/ 30

3/24/15

Decision Making Statements

 There will be many situations when you will be given two or more
options and you will have to select an option based on the given
conditions. For example, we want to print a remark about a student
based on secured marks and following is the situation: Assume
given marks are x for a student. 1) If given marks are more than
95 then Student is brilliant 2) If given marks are less than 30 then
Student is poor 3) If given marks are less than 95 and more than
30 then Student is average .
decision making statements which work based on the following flow
diagram:

1
3/24/15

Decision Making Statements


 Let's write a C program with the help of if conditional statements to convert
the above given situation into programming code:
#include <stdio.h>
main()
•When above program is executed, it
{
produces the following result:
•Student is average
int x = 45;
if( x > 95)
•Above program makes use of if
{
conditional statements. Here, first if
printf( "Student is brilliant\n");
statement checks whether given
} condition i.e., variable x is greater
if( x < 30) than 95 or not and if it finds condition
{ is true, then the conditional body is
printf( "Student is poor\n");entered to execute given statements.
} Here we have only one printf()
if( x < 95 && x > 30 ) statement to print a remark about
{ the student.
•Similar way, second if statement
printf( "Student is average\n");
} works. Finally, third if statement is
} executed, here we have following two
conditions: 2
3/24/15

if...else statement

 An if statement can be followed by an optional else statement,


which executes when the boolean expression is false. The syntax
of an if...else statement in C programming language is:
if(boolean_expression)
{
/* Statement(s) will execute if the boolean expression is
true */
}
else
{
/* Statement(s) will execute if the boolean expression is
false */
}

 Above syntax can be represented in the form of a flow diagram


as shown:
3
3/24/15

if...else statement
 An if...else statement is useful when we have to take a decision out of two
options. For example, if student secures more marks than 95, then student is
brilliant otherwise no, such situation can be coded as follows:
#include <stdio.h>
main()
{
int x = 45;
if( x > 95)
{
printf( "Student is brilliant\n");
}
else
{
printf( "Student is not brilliant\n");
}
}
 When above program is executed, it produces the following result:

Student is not brilliant


4
3/24/15

if...elseif...else statement

 An if statement can be followed by an optional else if...else statement, which is very useful
to test various conditions using single if...else if statement. When using if , else if , else
statements, there are few points to keep in mind:
 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of the remaining else if's or else's will be tested.
 The syntax of an if...else if...else statement in C programming language is:
if(boolean_expression 1) Now with the help of if...elseif...else
{ statement, very first program can
be coded as follows:
/* Executes when the boolean expression 1 is true */
} #include <stdio.h>
else if( boolean_expression 2)
{ main()
/* Executes when the boolean expression 2 is true { */
int x = 45;
}
else if( boolean_expression 3) if( x > 95)
{ {
/* Executes when the boolean expression 3 is trueprintf( */ "Student is brilliant\n");
} }
else else if( x < 30)
{
{
printf( "Student is poor\n");
/* Executes when the none of the above condition } is true */
} else if( x < 95 && x > 30 ) 5
3/24/15

if...elseif...else statement
Now with the help of if...elseif...else statement, very first
program can be coded as follows:
#include <stdio.h>
main()
{
int x = 45;

if( x > 95)


{
printf( "Student is brilliant\n");
}
else if( x < 30)
{
printf( "Student is poor\n");
When above program is executed, it
} produces the following result:
else if( x < 95 && x > 30 ) Student is average
{
printf( "Student is average\n");
}
} 6
3/24/15

The switch statement

 A switch statement is an alternative of if statements which allows a


variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each
switch case. This has following syntax:
The expression used in a switch
switch(expression)
statement must give an integer
{
value, which will be compared for
case ONE :
equality with different cases given.
statement(s);
break; Wherever, expression value matches
case TWO: with case value, the body of that
statement(s); case will be executed and finally
break; switch will be terminated using
...... break statement. If break statement
is not provided, then computer
default : continues executing other
statement(s); statements available below to the
} matched case. If none of the cases
matches, then default case body is 7
3/24/15

The switch statement

 Above syntax can be represented in the form of a flow diagram


as shown below:

8
#include <stdio.h> 3/24/15

main() Now, let's consider another example


{ where we want to write equivalent
int x = 2; English word for the given number. Then,
switch( x ) it can be coded as follows:
{
case 1 :
printf( "One\n");
break;
case 2 :
printf( "Two\n");
break;
case 3 :
printf( "Three\n");
break;
case 4 :
printf( "Four\n");
break;
default :
printf( "None of the above...\n");
}
}When above program is executed, it produces the following
result:
Two
9
3/24/15

Computer Programming - Loops


 Let's consider a situation when you want to write Hello,
World! five times. Here is a simple C program to do the same:
#include <stdio.h> Loops are used to execute one or
main() more statements repeatedly.
{ Let's write this C program with the
printf( "Hello, help of a while loop and later we will
World!\n"); discuss how does this loop work:
printf( "Hello, #include <stdio.h> O/P:
World!\n"); main() Hello, World!
printf( "Hello, { Hello, World!
World!\n"); int i = 0; Hello, World!
printf( "Hello, while ( i < 5 ) Hello, World!
World!\n"); { Hello, World!
printf( "Hello, printf( "Hello, World!\n");
World!\n"); i = i + 1;
} }
O/P : }
Hello, World!

Hello, World! 10
3/24/15

Computer Programming - Loops


 Above program makes use of while loop, which is
being used to execute a set of programming
statements enclosed within {....}. Here, computer
first checks whether given condition, i.e., variable "a"
is less than 5 or not and if it finds condition is true
then the loop body is entered to execute given
statements. Here, we have the following two
statements in the loop body:
 First statement is printf() function, which prints
Hello World!
 Second statement is i = i + 1, which is used to
increase the value of variable I

 After executing all the statements given in the loop


body, computer goes back to while( i < 5) and given
condition, (i < 5), is checked again, and the loop is
executed again if condition is true. This process
repeats till the given condition remains true which
means variable "a" has a value less than 5.

 To conclude, a loop statement allows us to execute a


statement or group of statements multiple times and
following is the general form of a loop statement in
most of the programming languages:
11
3/24/15

The while Loop

 A while loop available in C Programming language has


following syntax: There are following important points to
while ( condition ) note about a while loop:
{ •A while loop starts with a keyword
while followed by a condition enclosed
/*....while loop bodyin....*/
( ).
} •Further to while() statement you will
have body of the loop enclosed in curly
braces {...}.
•A while loop body can have one or more
lines of source code to be executed
repeatedly.
•If while loop body has just one line,
then its optional to use curly braces
{...}.
•A while loop keeps executing its body
till given condition is true. As soon as
condition becomes fast, while loop
comes out and continue executing from
12
immediate next statement after while
3/24/15

The do...while Loop

 While loop checks given condition before it executes given


statements of the code. However, do...while loop and allows to
execute a loop body before checking given condition. This has
following syntax: If you will write above example using do...while
loop, then Hello, World will produce the same
do result:
{ #include <stdio.h>
main()
/*do...while loop body
{ */
} while ( condition ); int i = 0;
do
{
printf( "Hello, World!\n");
i = i + 1;
}while ( i < 5 );
}
When above program is executed, it produces the
following result:
Hello, World!
Hello, World!
Hello, World!
Hello, World! 13
Hello, World!
3/24/15

for Loop
 Loops cause program to execute the certain block of code repeatedly until
test condition is false. Loops are used in performing repetitive task in
programming. Consider these scenarios:
 You want to execute some code/s 100 times.
 You want to execute some code/s certain number of times depending upon input from user.
 for Loop Syntax:
for(initialization; test expression; update statement)
{
code/s to be executed;
}
 The initialization statement is executed only once at the beginning of the for
loop
 Then the test expression is checked by the program.
 If the test expression is false, for loop is terminated.
 But if test expression is true then the code/s inside body of for loop is
executed and then
 update expression is updated. This process repeats until test expression is
false.

14
3/24/15

For loop

 This flowchart describes the working of


for loop in C programming.

15
3/24/15

For loop
 for loop example: Write a program to find the sum of the first n natural
numbers where n is entered by user. Note: 1,2,3... are called natural
numbers.
Output
#include <stdio.h>
Enter the value of n.
int main()
19
{ Sum=190
int n, count, sum=0; In this program, the user is asked
printf("Enter the value of n.\n");
to enter the value of n. Suppose
scanf("%d“, &n); you entered 19 then, count is
for(count=1;count<=n;++count) initialized to 1 at first. Then, the
test expression in the for loop,i.e.,
//for loop terminates if count>n
{ (count<= n) becomes true. So,
sum+=count;
the code in the body of for loop is
executed which makes sum to 1.
/* sum=sum+count */
Then, the expression ++count is
} executed and again the test
printf("Sum=%d“, sum); expression is checked, which
return 0; becomes true. Again, the body of
} for loop is executed which makes
sum to 3 and this process
16
3/24/15

The break statement

 When the break statement is encountered inside a loop, the


loop is immediately terminated and program control resumes
at the next statement following the loop. The syntax for a
break statement in C is as follows:
break;
 A break statement#include
can be represented
<stdio.h> in the form of a flow
main()
diagram as shown below:
{
int i = 0; When the program is
do executed, it produces the
{ following result:
printf( "Hello, World!\n");
i = i + 1; Hello, World!
if( i == 3 ) Hello, World!
{ Hello, World!
break;
}
}while ( i < 5 );
} 17
3/24/15

The continue statement


 The continue statement in C programming language works
somewhat like the break statement. Instead of forcing
termination, however, continue forces the next iteration of the
loop to take place, skipping any code in between. The syntax
for a continue statement in C is as follows:
continue;
 A continue statement can be represented in the form of a flow
diagram as shown below:

18
3/24/15

The continue statement

Following is a variant of the above program but it will skip


printing when variable has a value equal to 3:
#include <stdio.h>

main() When above program is executed,


{ it produces the following result:
int i = 0; Hello, World!
Hello, World!
do Hello, World!
{ Hello, World!
if( i == 3 )
{
i = i + 1;
continue;
}
printf( "Hello, World!\n");
i = i + 1;
}while ( i < 5 );
}
19
3/24/15

goto Statement

 In C programming, goto statement is used for altering the


normal sequence of program execution by transferring control
to some other part of the program.
 Syntax of goto statement
goto label;
.........
.........
.........
.........
label:
statement;
 In this syntax, label is an identifier. When, the control of
program reaches to goto statement, the control of the program
will jump to the label: and executes the code below it.

20
3/24/15

Example of goto statement



If user
/* C program to demonstrate the working of goto statement. *//* This program calculates the average of numbers entered by user. *//*
enters negative number, it ignores that number and calculates the average of number entered
before it.*/
Output
#include<stdio.h>
int main()
Maximum no. of
{ inputs: 4
float num, average,sum; Enter n1: 1.5
int I, n; Enter n2: 12.5
printf("Maximum no. of inputs: "); Enter n3: 7.2
scanf("%d",&n); Enter n4: -1
for(i=1;i<=n;++i)
Average: 7.07
{
printf("Enter n%d: ",i);
scanf("%f",&num); Though goto
if(num<0.0) statement is
goto jump; /* control of the program moves to label jump */ included in ANSI
sum=sum+num; standard of C, use
} of goto statement
jump:
should be reduced
average=sum/(i-1);
printf("Average: %.2f",average);
as much as
return 0; possible in a
} program.
21
3/24/15

Reasons to avoid goto statement


 Though, using goto statement gives power to jump
to any part of program, using goto statement makes
the logic of the program complex and tangled.
 In modern programming, goto statement is
considered a harmful construct and a bad
programming practice.
 The goto statement can be replaced in most of C
program with the use of break and continue
statements.
 In fact, any program in C programming can be
perfectly written without the use of goto statement.
All programmer should try to avoid goto statement
as possible as they can.
22
3/24/15

Examples
 Write a C program to find the factorial of a number using while
loop, where the number is entered by user. (Hints: factorial of
n = 1*2*3*...*n
 /*C program to demonstrate the working of while loop*/
#include <stdio.h>
Output
Enter a number.
int main()
5
{
Factorial=120
int number, factorial;
printf("Enter a number.\n");
scanf("%d“, &number);
factorial=1;
while (number>0)
{
/* while loop continues until test condition number>0 is true */
factorial=factorial*number;
- - number;
}
printf("Factorial=%d“, factorial);
return 0; 23
3/24/15

examples
 Write a C program to add all the numbers entered by a user until user
enters 0.using do..while loop.
 /*C program to demonstrate the working of do...while statement*/
#include <stdio.h>
Output
int main() Enter a number
{ 3
int sum=0,num; Enter a number-
/* Codes inside the body of do...while
2 loops
are at least executed once. */ Enter a number
do 0
{ sum=1
printf("Enter a number\n");
scanf("%d“, &num); In this C program, user is asked a
sum+=num; number and it is added with sum.
} Then, only the test condition in
while(num!=0); the do...while loop is checked. If
the test condition is true,i.e, num
printf("sum=%d“, sum);
is not equal to 0, the body of
return 0;
do...while loop is again executed
}
until num equals to zero. 24
3/24/15

examples
 Write a C program to find average of maximum of n positive numbers entered by user.
But, if the input is negative, display the average(excluding the average of negative input)
and end the program.
 /* C program to demonstrate the working of break statement by terminating a loop, if
user inputs negative number*/
Output
#include<stdio.h>
int main()
Maximum no. of inputs
{ 4
float num, average, sum; Enter n1: 1.5
int I, n; Enter n2: 12.5
printf("Maximum no. of inputs\n");
Enter n3: 7.2
scanf("%d“, &n);
for(i=1;i<=n;++i)
Enter n4: -1
{ Average=7.07
printf("Enter n%d: “, i); In this program, when the user
scanf("%f”, &num); inputs number less than zero, the
if(num<0.0) loop is terminated using break
break; //for loop breaks if num<0.0
sum=sum+num;
statement with executing the
} statement below it i.e., without
average=sum/(i-1); executing sum=sum+num.
printf("Average=%.2f",average);
return 0;
}
25
3/24/15

examples
 Write a C program to find the product of 4 integers entered by a user. If user
enters 0 skip it.
 //program to demonstrate the working of continue statement in C
programming
#include<stdio.h> Output
int main() Enter num1: 3
{ Enter num2: 0
int i, num,product; Enter num3: - 5
for(i=1,product=1;i<=4;++i) Enter num4: 2
{ product= - 30
printf("Enter num%d:",i);
scanf("%d",&num);
if(num==0)
continue; / *In this program, when num equals to zero, it skips the statement
product*=num and continue the loop. */
product*=num;
}
printf("product=%d“, product);
return 0;
}

26
3/24/15

Examples
 Write a program that asks user an arithmetic operator('+','-','*' or '/') and two operands and perform the
corresponding calculation on the operands.
/* C program to demonstrate the working of switch...case statement */
/* C Program to create a simple calculator for addition, subtraction, multiplication and division */
# include <stdio.h>
int main() Output
{
char o; Enter operator either + or -
float num1,num2; or * or /
printf("Select an operator either + or - or * or / \n");
scanf("%c",&o); *
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
Enter two operands: 2.3
switch(o) 4.5
{
case '+':
2.3 * 4.5 = 10.3
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case '-':
The break statement at the
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2); end of each case cause
break;
case '*': switch statement to exit. If
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
break statement is not
case '/': used, all statements below
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
that case statement are
also executed.
default: /* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
return 0;
27
}
3/24/15

examples

 Write a program that asks user to enter a character and checks


whether that character is vowel or not [use logical OR
operator].
#include<stdio.h>
int main()
{
char c;
printf("Enter an alphabet: ");
scanf("%c",&c); if(c=='a'||c=='A'||c=='e'||c=='E'||
c=='i'||c=='I'||c=='o'||c=='O'||c=
Output ='u'||c=='U')
1
printf("%c is a vowel.",c);Enter an alphabet: i
i is a vowel.
else
printf("%c is a consonant.“, c); 2
Output
return 0; Enter an alphabet: G
G is a consonant.
}
28
3/24/15

example

 /* C program to check whether a character is vowel or


consonant using conditional operator */
#include<stdio.h>
int main()
{
char c;
printf("Enter an alphabet: ");
scanf("%c“,&c); (c=='a'||c=='A'||c=='e'||c=='E'||
c=='i'||c=='I'||c=='o'||c=='O'||c=='u'||c=='U') ?
printf("%c is a vowel.",c) : printf("%c is a
consonant.“, c);
return 0;
}
29
3/24/15

example
 Write a program to ask a user to enter three numbers and this
program will find the largest number among three numbers
/* Centered
programbytouser.
find largest /* C program to find largest number using
if...else statement */
number using if statement #include <stdio.h>
only */ int main()
#include <stdio.h> {
int main() float a, b, c;
printf("Enter three numbers: ");
{ scanf("%f %f %f", &a, &b, &c);
float a, b, c; if (a>=b)
printf("Enter three {
if(a>=c)
numbers: "); printf("Largest number =
scanf("%f %f %f", &a, &b, %.2f",a);
&c); else
if(a>=b && a>=c) printf("Largest number =
%.2f",c);
printf("Largest number = %.2f", a);
}
if(b>=a && b>=c) else
printf("Largest number = %.2f", b); {
if(b>=c)
if(c>=a && c>=b)
printf("Largest number =
printf("Largest number = %.2f", c); %.2f",b);
return 0; else 30
printf("Largest number =

You might also like