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

Chapter 3

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 50

Programming With C/C++

Chapter 4: Control Structures

Dr. Umair Ali Khan


Associate Professor & Chairman,
CSE Department, QUEST, Nawabshah
Email: umair.khan@quest.edu.pk
Website: https://umair-khan.quest.edu.pk
Contents
 Sequential control structure
 Selection control structure
 if statement (one-way)
 if-else statement (two-way)
 switch statement (multi-way)
 Repetitive control structure
 for loop
 while loop
 do-while loop
SEQUENTIA
L
•Statements can be executed in
Sequence one right after the other.

•No deviation from the specified sequence

CONTROL FLOWS FROM STATEMENT_1 TO


STATEMENT_2 AND SO ON TO STATEMENT_N.
SELECTION
• A selection
structure can be
used
• Which statement
is executed, is
selected by
whether the
expression or
condition is true or false
REPETITIVE

• Statements can be
repeated.
• The number of
repetitions depends
on when the
condition turns false
Selection structure - if Statement
• The if statement allows the programmer to make
decisions on whether a section of code executes or
not.
Syntax:
if ( conditional expression )
statement;
Example:
int m=40,n=40;
if (m == n)
printf("m and n are equal");
Structure of if Statement
• The if keyword is followed by the
parenthesis, which contain a conditional
expression using a relational operator.
• Following this, there is the body of the if
statement, consisting of either a single
statement or multiple statements enclosed
by braces.
• Statements making up the body of the if, will
not be executed at all, if the condition is false.
if Statement flow chart

If the condition
is true, the
statement is
executed.
If it is false,
nothing
happens
int main ()
{
int percentage = 70;
if( percentage > 60 )
Printf(“You are passed”);

Printf(“\n End of Program”);


getch();
}
if ( ) … else …
• Syntax:
if (condition)
statement1;
else
statement2;
Example:
int m=40,n=20;
if (m == n)
printf("m and n are equal");
else   
printf("m and n are not equal");
if ( ) … else … Flow Chart
• Allows to make two way selection
• If the condition is
true, statement1 is
executed
• Otherwise statement2
is executed
Example:
int m=40,n=20;
  if (m>n)
printf("m is greater than n");
  else if (m<n)
  printf("m is less than n");
  else
  printf("m is equal to n");
int main ()
{
int percentage = 70;
if( percentage >= 60 )
Printf(“You are passed”);
else // no condition after else
Printf(“ You are Fail”);

Printf(“ n End of Program”);


}
Compound Statements
• Consider the need for multiple
statements to be controlled by the if
• This is called
a compound
statement. Statement1;
Statement2;
• Group the Statement3;

statements in
curly brackets
Compound Statements . . .
• For example,
if (Condition)
{
statement_1; /*as many statements as
necessary*/
statement_2; /*can be placed within the braces*/
• /*each statement must end with ;
*/


statement_n;
}
Compound Statement . . .
Example
if ( percentage >= 60 )
{
Printf("Passed.\n”);
Printf(“Allowed to enter in next semester\n”);
}
else
{
Printf("Failed.\n”);
Printf("You must take this course again.\n”);
}

Without braces,
Printf(“Allowed to enter in next semester\n”);
Printf("You must take this course again.\n”);
always executes
Class Activity
• Write a program to read a number. The
program should determine whether the
number is even or odd.
Class Activity
Write a program that ask user to enter two
numbers. Program should determine which
is smaller one and display that number on
screen.
Output of program:
Enter first number: 10
Enter second number: 15
Smaller number: 10
The Switch Statement
• The control statement that allows us to
make a decision from the number of
choices is called a switch.
• The Switch statement provides an
alternative to the else – if statement
construct. It is similar to the else – if
statement, but has more flexibility and a
clearer format.
Structure of the Switch Statement
switch ( conditional variable)
{
case 1:
statement ;
break ;

case 2 :
statement ;
break ;
default :
statement ;
}
Structure of the Switch Statement
• The statement starts out with the keyword
switch, followed by the parenthesis
containing an integer or character variable
which we will call the switch variable.

• The keyword case is followed by an integer


or a character constant. Each constant in
each case must be different from all the
others.
Break and Default
• Break statement is often useful when a
condition suddenly occurs that makes it
necessary to leave a switch (or loop)
before the switch ends (or loop expression
becomes false).
• Default statement is used if the switch
variable does not match any of the case
constants.
void main (void)
{
int num1, num2 ;
ch op ;
printf("Type number , operator , number : \n “);
cin>> num1>>op>>num2 ;

switch ( op )
{
case ‘ + ‘ :
printf( “ = “<<, num1 + num2) ;
break ;
case ‘ - ‘ :
printf( “ = “, num1 - num2) ;
break ;
case ‘ * ‘ :
printf(= “, num1 * num2) ;
break ;
case ‘ / ‘ :
printf( “ = “, num1 / num2 ) ;
break ;
default :
printf(Unknown Operator “) ;
}
}
Class Activity
• Attendance Marks:
• 40 – 42 10 marks
• 37 – 39 9 marks
• 34 – 36 8 marks
• 30 – 33 7 marks
• < 30 0 marks
Class Activity
• Enter any character : A
• You pressed Capital letter

• Enter any character : d


• You pressed Small letter

• Enter any character: 5


• You pressed Numeric Digit
• Hint: Use ASCII table
Repetitive Control Structure
• In Programming; we frequently need to perform
an action more than once (repetitively).
• The mechanism that meets this need is the
“Loop”.
• Repeating some portion of the program either
specified number of times or until a particular
condition is being satisfied.
• Three methods (loops) by which we can repeat
the portion of program:
– Using a for statement
– Using a while statement
– Using a do-while statement
for loop
• Specifies counter-controlled repetition details in a
single line of code.
• Syntax
for (initialization expr; test expr; increment expr)
Body of for loop ;
Example:

for ( count = 1; count < 10; count + + )


// programming example using for loop
main ()
{
int count;

for ( count = 1; count <= 10; count + + )


printf( “ Count = \n”, count ); //body of for loop
}

Output of program on next slide . . .


Output of program:
Count = 1
Count = 2
Count = 3
Count = 4
Count = 5
Count = 6
Count = 7
Count = 8
Count = 9
Count = 10
for loop . . .
The following diagram illustrates the operation of a for loop

initialize Test exp


increment

Body of
for loop
Class Activity
1- Write a program which generates the following
output:
2 4 6 8 10 12 14 16 18 20

2- Write a program which generates the following


output:
19 17 15 13 11 9 7 5 3 1
Class Activity
1
2
3
4
6
7
8
9
10
Class Activity
• Write a program that ask user to enter 10
numbers. Program should determine how
many numbers are even or odd.
• Program output:
Enter 10 numbers:
5 7 2 3 60 8 11 17 99 100
Total Even numbers: 4
Total odd numbers: 6
Class Activity
• Write a program to print sum of the
numbers from 1 to n. Ask user to enter
value of n.

• Write a program to compute power of


a given number (without using pow
function). Ask user to enter values for
base and raised power.
for loop variations
Example 1: j = 1;
sum = 0;
for ( ; j <= 3; j = j + 1) {
sum = sum + j;
cout<<"sum = "<<sum<<"\n"; }
Output : 1, 3, 6
Example 2: j = 1;
sum = 0;
for ( ; j <= 3; ){
sum = sum + j; }
Output : infinite loop
Example 3: j = 1;
sum = 0;
for ( ; ; )
{ sum = sum + j; j++;
cout << "\n" << sum; }
Output : infinite loop
Nested for loop
• A for loop within the body of for loop is called
“Nested for loop”.
• Syntax:
for (initialization expression; test expr; increment expr) //outer loop
{
for (initialization expression; test expr; increment expr) //inner loop
{
Body of inner for loop ;
}
}
main( )
{
int r, c, sum ;
for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */
Output of program:
{ r = 1 c = 1 sum = 2
for ( c = 1 ; c <= 2 ; c++ ) /* inner r = 1 c = 2 sum = 3
r = 2 c = 1 sum = 3
loop */ r = 2 c = 2 sum = 4
{ r = 3 c = 1 sum = 4
r = 3 c = 2 sum = 5
sum = r + c ;
printf( "r =“ <<r << “c=“<<c <<“sum =
\n“<<sum ;
} /* end of inner loop */
} /* end of outer loop */
} /* end of main program */
Prime number – using break statment
main( ) {
int num, i ; if ( i == num )
printf ( "Enter a number " ) ;
printf ( "Prime number"
scanf ( "%d", &num ) ;
);
i=2;
} // End of main
while ( i <= num - 1 ) {
if ( num % i == 0 ) {
printf ( "Not a prime
number" ) ;
break ; } //End of if
i++ ;
} // End of While
Program to find Prime numbers
int main ()
{
int n , j ;
cout<<"Enter any number:\n” ;
cin>>n;
for ( j = 2 ; j <= n / 2 ; j++ )
if ( n % j = = 0)
{
printf(“its not prime number divisible by “ << j ;
exit ( 0 ) ; // terminate the main program.
}
printf(“ its prime number “);
getch ( );
}
While loop
• The while loop provides a mechanism for
repeating C statements until a condition is true.
Syntax:
While (control expression)
program statement ;
• The while statement works as follows:
1) Control expression is evaluated.
2) If it is FALSE, skip over the loop.
3) If it is TRUE, loop body is executed.
4) Go back to step 1
void main (void) Output of program:
1
{
2
int count = 1; 3
while (count < = 10) 4
{ 5
6
printf(“\n”<<count);
7
count ++ ;
8
} 9
} 10
Programmer is responsible for initialization and incrementation.
// Program using unexpected condition
void main (void)
{
int count ; char ch ;
clrscr( );
printf(“ Type in a phrase: \n “) ;
ch = getche ( );
while ( ch ! = ‘ \r ‘ ) // check for Return key
{
count + + ;
ch = getche ( );
}
printf(“ \n Character Count is =”<<count );
}
Output of program:
Type in a phrase:
This is while loop
Character count is = 18
Home Work
• Write a program that ask user to enter any
phrase. Program should count, and print,
how many words and characters are there
in that phrase. Program terminates when
user press Return key.
Output of program:
Enter any phrase:
This is while loop
Characters = 15 and Words = 4
do – while Loop
• The do while statement is a variant of the while loop in
which the condition test is performed at the “bottom” of
the loop.
• This guarantees that the loop is executed at least once
whether the condition is TRUE or FALSE.
The syntax of the do while statement is
do
program statement;
while (control expression) ;
and it works as follows
1) The body of the loop is executed.
2) The control expression is evaluated (“exit condition”).
3) If it is TRUE, go back to step 1.
4) If it is FALSE, exit loop.
do – while flow chart
void main (void)
{ int num;
do
{
printf(“ Enter any
number";
scanf(“%d”,&num);
} while ( num < 25 );
}
Class Activity
Output of program:
Enter first number: 5
Enter second number: 10
SUM = 15
Do you want to continue (Y/N): Y
Enter first number: 100
Enter second number: 200
SUM = 300
Do you want to continue (Y/N): N
Home work
• Write a program using nested for loop to
generate the following output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

You might also like