Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 2 Conrol Folow

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 58

Course: Computer Programming

Chapter 2
control-flow
MOHAMED HASSAN ABDULLE
HORMUUD UNIVERSITY
EMAIL: JALAQSANE2003@GMAIL.COM
FACEBOOK: MOHAMED HASSAN
Mobile: +252615825152 Or +252615000196
HTTP://HU.EDU.SO/
Course: computer Programming Lecturer : Eng . Ugaska
Outline
1. Introduction
2. If statement
3. If – else statement
4. If – else if statement (nested if statement)
5. Switch statement
6. For loop
7. while loop
8. Do – while loop
9. Exercise
Introduction
 The control-flow statements of a language specify the order
in which computations are performed.
 We have already met the most common control-flow
constructions in earlier examples;
 before we discuss control-flow statements let us study
statements and blocks.
Statements
 an expression such as x = 0 or i++ or printf () becomes

a statement when it is followed by a semicolon; as in:


x = 0;
i++;
printf(...);
 In C, the semicolon is a statement terminator.
Blocks
A block is a section of code which is grouped together.
Blocks consist of one or more declarations and statements.
All definitions, declarations, and statements enclosed within a single set
of braces are treated as a single statement. You can use a block
wherever a single statement is allowed.
block = { < statements > }

{ // beginning

int x = 10 ;

++ x ;

printf("%d", x);

} // ending
A block is syntactically equivalent to a single statement.
Blocks
if, else, while, for all have blocks
Variables can be declared inside any block.
There is no semicolon after the right brace that ends a block.
Example
#include<stdio.h>
Main()
{
int x = 0;
{
int x = 5;
printf("Inside: x = %d\n", x);
}
printf("Outside: x = %d\n", x);
}
Output : inside: x=5
outside: x =0
Flow of Control
 Flow of control is the order in which a program
performs actions.

Up to this point, the order has been sequential.

A branching statement chooses between two or


more possible actions.

A loop statement repeats an action until a


stopping condition occurs.
Flow of Control
 There are three types of control structures available in C:
1. Sequence statements(straight line paths)
2. Decision control statements
1. If statement
2. If – else statement
3. If – else if statement (nested if statement)
4. Switch statement
3. Loop statements (repetition of a set of activities)
1. For loop
2. while loop
3. Do – while loop
Sequence Statements
Decision control statements
Loop Statements
IF Statement
 Like most languages, C uses the keyword if to implement the
decision control instruction. The general form of if statement
looks like this:

if ( this condition is true )


execute this statement ;
Example of IF Statement
main( )

int num ;
 
printf ( "Enter a number less than 10 " ) ;
scanf ( "%d", &num ) ;
  if ( num <= 10 )
printf ( "What an obedient servant you are !" ) ;

 
IF Statement
The if-else Statement
 A branching statement that chooses between two possible
actions.
Syntax

if (Boolean Expression)
Statement_1
else
Statement_2
The if-else Statement
 Example

#include<stdio.h>
main()
{
int num;
printf("enter number");
scanf("%d",&num);
if(num<=10)
printf("thanks");
else
printf("mahadsanid");
}
The if-else Statement
Other
 Example
#include<stdio.h>

main()

int qty,dis=10;

float rate,total;

printf("Enter quantity and rate");

scanf("%d%f",&qty,&rate);

if(qty>1000)

dis=10;

total=(qty * rate)- (qty*rate*dis/100);

printf("The Total Expencse is = %f",total);


Compound Statements
Toinclude multiple statements in a branch, enclose the statements in braces.
Example

#include<stdio.h>
main()
{
int z,y;
int x =10;
if(x>=10)
{
z = 5;
y = 6;
printf("z is = %d\n",z);
printf("y is = %d",y);
}}
 If the else part is omitted and the expression after the if is false, no action occurs.
Omitting The Else Part
 Syntax

if (Boolean_Expression)

Statement

#include<stdio.h>
main()
{
int z,y;
int x =10;
if(x>=11)
{
z = 5;
y = 6;
printf("z is = %d\n",z);
printf("y is = %d",y);
} }
C Comparison Operators

Math Notation Name C Notation C Example

= Equal to == Balance == 0
= Not equal to != Balance != 0
> Greater than > Balance > 0
> Greater than >= Balance >= 0
Or equal to
< Less than < Balance < 0
< Less than <= Balance <= 0
Or equal to
C Logical Operators

Operator Description C Example


Called Logical AND operator. If both
&& the operands are non-zero, then the (A && B) is false.
condition becomes true.
Called Logical OR Operator. If any of
|| the two operands is non-zero, then (A || B) is true.
the condition becomes true.
Called Logical NOT Operator. It is
used to reverse the logical state of
! its operand. If a condition is true, !(A && B) is true.
then Logical NOT operator will
make it false.
Compound Boolean Expressions
 Boolean expressions can be combined using the “and” (&&)
operator.
 Example

if ((score > 0) && (score <= 100))


...
 Not Allowed

if (0 < score <= 100)


Compound Boolean Expressions
Boolean expressions can be combined using the “and” (&&) operator.

#include<stdio.h>
main()
{
int score;
printf("Enter between 1 to 100\n");
scanf("%d",&score);
if ((score > 0) && (score <= 100))
printf("Welcome to hormuud");
else
printf(“Welcome to computer science ");
}
Compound Boolean Expressions
 Boolean expressions can be combined using the “or” (||) operator.
 Example
if ((quantity > 5) || (cost < 10))
 Syntax
main()
{
int score;
printf("Enter between 1 to 100\n");
scanf("%d",&score);
if ((score > 0) || (score <= 1000))
printf("Welcome to hormuud");
else
printf(“Welcome to mohamed");
}
Compound Boolean Expressions
The NOT operator is often used to reverse the logical value of a single variable, as in the
expression.
if ( ! score )
This is another way of saying
  if (score == 0 )

Example
#include<stdio.h>
main()
{
int score =1;
if (!score)
printf("Welcome HORMUUD\n");
else
{
printf("Welcome BCS3");
}
}
Truth Tables
Nested Statements
 An if-else statement can contain any sort of statement within
it.
 In particular, it can contain another if-else statement.
 An if-else may be nested within the “if” part.

 An if-else may be nested within the “else” part.

 An if-else may be nested within both parts.


Nested Statements
 syntax
if (Boolean_Expression_1)
if (Boolean_Expression_2)
Statement_1
else
Statement_2
else
if (Boolean_Expression_3)
Statement_3
else
Statement_4
#include<stdio.h>
Example Nested Statements
main( )
{
int i ;
printf ( "Enter either 1 or 2 " ) ;
scanf ( "%d", &i ) ;
if ( i == 1 )
printf ( “Welcome to Somalia!" ) ;
else
{
if ( i == 2 )
printf ( " Welcome to kenya" ) ;
else
printf ( " Welcome to djabuti!" ) ;
Nested Statements

 Each else is paired with the nearest unmatched if.

 Indentation can communicate which if goes with which

else.

 Braces are used to group statements.


Multi branch if-else Statements
 syntax
if (Boolean_Expression_1)
Statement_1
else if (Boolean_Expression_2)
Statement_2
else if (Boolean_Expression_3)
Statement_3
else if …
else
Default_Statement
Multi branch if-else Statements
 Class Grader
if (score >= 90)
#include<stdio.h> grade = 'A';

main() else if (score >= 80)


grade = 'B';
{
else if (score >= 70)
int score; grade = 'C';

char grade; else if (score >= 60)


grade = 'D';
printf("Enter your marks\n");
else
scanf("%d",&score); grade = 'F';
printf("The grade is = %c",grade);
}
common mistake while using the if statement
To use the assignment operator = instead of the relational operator ==.
main( )

int i ;
printf ( "Enter value of i " ) ;
scanf ( "%d", &i ) ;
if ( i = 5 )
printf ( "You entered 5" ) ;
else
printf ( "You entered something other than 5" ) ;
}
common mistake while using the if statement
 Another common mistake while using the if statement is to
write a semicolon (;) after the condition, as shown below:
  main( )

{
int i ;
  printf ( "Enter value of i " ) ;
scanf ( "%d", &i ) ;
if ( i == 5 ) ;
printf ( "You entered 5" ) ;
}
Switch Statement, Cont.
 The action associated with a matching case label is
executed.

 If no match is found, the case labeled default is executed.

 The default case is optional, but recommended, even if it


simply prints a message.

 Repeated case labels are not allowed.


Switch Statement, Cont.
 The action for each case typically ends with the word
break.

 The optional break statement prevents the consideration


of other cases.

 The controlling expression can be anything that evaluates


to an integral type (integer or character).
Switch Statement, Cont.
 Syntax

switch (Controlling_Expression)
{
case Case_Label:
Statement(s);
break;
case Case_Label:

default:

}
Example of switch
#include<stdio.h>
case 2 :
main()
printf ( "I am in case 2 \n" ) ;
{
int i; break ;
printf("Enter Num between 1 to 3\n"); case 3 :
scanf("%d",&i);
printf ( "I am in case 3 \n" ) ;
switch ( i )
break ;
{
case 1 : default :

printf ( "I am in case 1 \n" ) ; printf ( "I am in default \n" ) ;


break ;
}

}
Loop Statements
 A portion of a program that repeats a statement or a group
of statements is called a loop.

 The statement or group of statements to be repeated is called


the body of the loop.

 A loop could be used to compute grades for each student in a


class.

 There must be a means of exiting the loop.


Loop Statements
 The While Statement

 The Do-while Statement

 The For Statement


While Statement
 also called a while loop

 a controlling Boolean expression

 True -> repeats the statements in the loop body

 False -> stops the loop

 Initially false (the very first time)

 loop body will not even execute once


While Statement
 syntax
while (Boolean_Expression)
Body_Statement
or
#include<stdio.h>
main()
{
int x=1;
while(x<100)
{ printf("x is = %d\n",x);
x++;
}
}
do-while Statement
 also called a do-while loop (repeat-until loop)

 similar to a while statement

except that the loop body is executed at least once

 syntax

do

Body_Statement

while (Boolean_Expression);

don’t forget the semicolon at the end!


do-while Statement
 First, the loop body is executed.

 Then the Boolean expression is checked.

 As long as it is true, the loop is executed again.

 If it is false, the loop exits.


Example do-while Statement
#include<stdio.h>
with end less loop
main()
{
int x=1;
do
{
printf("The value of x : %d\n",x);
x++;
}
while(x<=x);
}
Example do-while Statement
#include<stdio.h>

main()

int x=1;

do

printf ( "X IS = %d\n",x) ;

x++;

} while ( x<=5) ; }
Infinite Loops

 A loop which repeats without ever ending

 the controlling Boolean expression (condition to continue)

never becomes false


For Loops
 A for statement executes the body of a loop a fixed number of times.

 Example

#include<stdio.h>
main()
{
int num=1;
for(num=1;num<=10;num++)
{
printf("number is = %d\n",num);

}}
Choosing a Loop Statement
 If you know how many times the loop will be iterated, use a for loop.

 If you don’t know how many times the loop will be iterated, but

it could be zero, use a while loop

it will be at least once, use a do-while loop.


 Generally, a while loop is a safe choice.
Nested Loops
 The body of a loop can contain any kind of statements,
including another loop.
Example of Nested Loops
#include<stdio.h>
int main()
{
int line,star;
for(line=0;line<=10;line++)
{
for(star=0;star<line;star++)
printf("*");
printf("\n");
}
}
if, if-else, Nested if-else Exercise
1. Question one
2. What would be the output of the following programs:
main( )
{
int a = 300, b, c ;
if ( a >= 400 )
b = 300 ; c = 200 ;
printf ( "\n%d %d", b, c ) ;
}
 
2. Question Two Exercise
main( )
{
int a = 500, b, c ;
if ( a >= 400 )
b = 300 ;
c = 200 ;
printf ( "\n%d %d", b, c ) ;
}
3. Question three
Point out the errors, if any, in the following programs:
Exercise
(a) main( )
{
float a = 12.25, b = 12.52 ;
if ( a = b )
printf ( "\na and b are equal" ) ;
4. Question Four
main( )
{
if ( 'X' < 'x' )
printf ( "\nascii value of X is smaller than that of x" ) ;
}
5. Question Five Exercise
Any integer is input through the keyboard. Write a
program to find out whether it is an odd number or
even number
6. Question Six
Any character is entered through the keyboard, write a
program to determine whether the character entered
is a capital letter, a small case letter, a digit or a
special symbol. The following table shows the range
of ASCII values for various characters.
Exercise
7. Question Seven
Write a program to find the greatest of the
three numbers entered through the keyboard
using conditional operators.
8. Question Eight
Exercise
A university has the following rules for a student to qualify for a
degree with A as the main subject and B as the subsidiary
subject:
(a) He should get 55 percent or more in A and 45 percent or more in
B.
(b) If he gets than 55 percent in A he should get 55 percent or more
in B. However, he should get at least 45 percent in A.
(c) If he gets less than 45 percent in B and 65 percent or more in A
he is allowed to reappear in an examination in B to qualify.
(d) In all other cases he is declared to have failed.
Write a program to receive marks in A and B and Output whether
the student has passed, failed or is allowed to reappear in B.
Computer Programming

Questions
?

INSTRUCTOR : MOHAMED HASSAN ABDULLE COURSE :Computer Programming

You might also like