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

14EC320 - PROBLEM SOVING

USING COMPUTER

CONTROL STRUCTURES
CONTROL STRUCTURE
Control structures control the flow of execution in
program or function.
Types:
Selection structure
Repetition structure
FLOWCHART SYMBOLS USED WITH CONTROL
STRUCTURES

 Sequence

no yes

 Selection

no
 Repetition
yes

3
SEQUENCE
Example: Draw flowchart to determine velocity and acceleration and print the result

4
SELECTION
Example: Flowchart to check whether denominator is <0.0001. If
so print denominator close to zero, otherwise find fraction value
and print it.

5
REPETITION
Example: Draw flow chart to find velocity and print over a period of
time t.

6
CONTROL STRUCTURE
SELECTION STRUCTURE:
- used in decision making

Decision control instruction can be implemented in C using


1. if statement
2. if-else statement
3. switch statement
CONTROL STRUCTURE

if Statement
Syntax:
if ( this condition is true ) if ( this condition is true )
execute statement1 ; {
statement1 ;
statement2 ;
}

if ( condition is true ) if ( this condition is true )


{ execute statement1 ;
statement1 ; else
statement2 ; if (condition true)
statement 1;
} else
else statement 2;
{
statement1 ;
statement2 ;
}
CONTROL STRUCTURE
conditional Operators:

Logical Operators
Logical AND -&&
Logical OR - ||
Logical NOT - !
Example:
 Expressions 1 to 4 below contain different operands and operators.
Each expression’s value is given in the corresponding comment,
assuming x , y , and z are type double , flag is type int and the
variables have the values

1. !flag /* !0 is 1 (true) */
2. x + y / z <= 3.5 /* 5.0 <= 3.5 is 0 (false) */
3. !flag || (y + z >= x - z) /* 1 || 1 is 1 (true) */
4. !(flag || (y + z >= x - z)) /* !(0 || 1) is 0 (false) */
CONTROL STRUCTURE
/* Demonstration 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 !" ) ;
}
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 ;
break;
case constant 2 :
do this ;
break;
default :
Do this ;
}
Decisions Using switch
switch statement:
 The switch can only test for equality, whereas if can
evaluate any type of relational or logical expression.
 No two case constants in the same switch can have
identical values.
a switch statement enclosed by an outer switch may have same
case constants.
 character constants used in the switch statement, are
automatically converted to integers
Use
 used to process keyboard commands, such as menu
selection.
void menu(void)
{
char ch;
printf("1. Check Spelling\n");
printf(''2. Correct Spelling Errors\n");
printf("3. Display Spelling Errors\n");
printf("Strike Any Other Key to Skip\n");
printf(" Enter your choice: ");
ch = getchar(); /* read the selection from the keyboard */
switch(ch)
{
case '1':
check_spelling ();
break;
case '2':
correct_errors ();
break;
case '3':
display_errors ();
break;
default :
printf("No option selected");
}
}
PROBLEM
 Suppose that we have a temperature reading from a sensor inside a large
piece of machinery. We want to print a message on the control screen to
inform the operator of the temperature status. If the status code is 10, the
temperature is too hot and the equipment should be turned off; if the status
code is 11, the operator should check the temperature every 5 minutes; if
the status code is 13, the operator should turn on the circulating fan; for all
other status codes, the equipment is operating in a normal mode.
SOLUTION USING NESTED IF-ELSE
if (code == 10)
printf("Too hot - turn equipment off \n");
else
{
if (code == 11)
printf("Caution - recheck in 5 minutes \n");
else
{
if (code == 13)
printf("Turn on circulating fan \n");
else
printf("Normal mode of operation \n");
}
}
SOLUTION USING NESTED SWITCH-
CASE
switch (code)
{
case 10:
printf("Too hot - turn equipment off \n");
break;
case 11:
printf("Caution - recheck in 5 minutes \n");
break;
case 13:
printf("Turn on circulating fan \n");
break;
default:
printf("Normal temperature range \n");
}
SELF CHECK
Convert the following nested if/else statements to a switch statement:
if (rank==1 || rank==2)
printf("Lower division \n");
else
{
if (rank==3 || rank==4)
printf("Upper division \n");
else
{
if (rank==5)
printf("Graduate student \n");
else
printf("Invalid rank \n");
}
}
WHAT IS THE OUTPUT OF THIS C CODE?
#include <stdio.h> #include <stdio.h>
int main() void main()
{ {
int a = 1, b = 1; int ch;
switch (a) printf("enter a value btw 1 to 2:");
{ scanf("%d", &ch);
switch (ch)
case a*b:
{
printf("yes ");
case 1:
case a-b:
printf("1\n");
printf("no\n");
default:
break; printf("2\n");
} }
} }
a) yes b) no a) 1 b) 2
c) Compile time error c) 1 2 d) Run time error

d) yes no
CONTROL STRUCTURE
Repition /looping structure
C contains three different loop structures—
 while loop,

 do/while loop,

 for loop.
while Loop ( entry checking)

The general form of a while loop follows:

while (condition)
{
statements;
}
 Statements within loop gets executed only when the
condition is true i-e non-zero value
 When the condition evaluated to false i-e zero value, the
statements within loop gets doesn’t get executed .
PROBLEM
 Generate a conversion table for converting degrees to
radians (note that the degree values start at 0°, increment
by 10°, and go through 360°) using while loop

Algotithm:

 set degrees to zero


 while degrees ≤ 360
 convert degrees to radians
 print degrees, radians
 add 10 to degrees
#include <stdio.h>
#define PI 3.141593
int main(void)
{
int degrees=0; /* Declare and initialize variables. */
double radians;
/* Print radians and degrees in a loop. */
printf("Degrees to Radians \n");
while (degrees <= 360)
{
radians = degrees*PI/180;
printf("%6i %9.6f \n",degrees,radians);
degrees += 10;
}
return 0; /* Exit program. */

}
REPETITION/LOOPING STATEMENTS
do/while Loop
 The do/while loop is similar to the while loop except that
the condition is tested at the end of the loop instead of
at the beginning of the loop.
The general form of the do/while loop is as follows:

do
{
statements;
} while (condition);
REPETITION/LOOPING STATEMENTS
do/while Loop
 The do/while loop is similar to the while loop except that
the condition is tested at the end of the loop instead of
at the beginning of the loop.
The general form of the do/while loop is as follows:

do
{
statements;
} while (condition);
PROBLEM
 Generate a conversion table for converting degrees to
radians (note that the degree values start at 0°, increment
by 10°, and go through 360°) using while loop

Algotithm:

 set degrees to zero


 do
 convert degrees to radians
 print degrees, radians
 add 10 to degrees

while degrees ≤ 360


#include <stdio.h>
#define PI 3.141593
int main(void)
{
int degrees=0; /* Declare and initialize variables. */
double radians;
/* Print radians and degrees in a loop. */
printf("Degrees to Radians \n");
do
{
radians = degrees*PI/180;
printf("%6i %9.6f \n",degrees,radians);
degrees += 10;
} while (degrees <= 360);
return 0; /* Exit program. */
}
for LOOP
The general form of the for loop is as follows:

for (expression_1; expression_2; expression_3)


{
statements;
}
 Expression_1 is used to initialize the loop-control
variable
 expression_2 specifies the condition that should be true
to continue the loop repetition,
 expression_3 specifies the modification to the loop-
control variable.
e.g. 1 for(i=0; i<n; i++)
{
printf(“ I = %d \n”, i);
}
e.g . 2
for (n=20; n>=0; n=n–2)
{
statements;
}
 The following expression computes the number of times that a for
loop will be executed:
/* This program prints a degree-to-radian table */
/* using a for loop structure. */
#include <stdio.h>
#define PI 3.141593
int main(void)
{
int degrees; /* Declare variables. */
double radians;
printf("Degrees to Radians \n");
for (degrees=0; degrees<=360; degrees+=10)
{
radians = degrees*PI/180;
printf("%6i %9.6f \n",degrees,radians);
}
return 0;
}
FOR LOOP -
 The initialization and modification expressions in a for loop can
contain more than one statement, as shown in this statement that
initializes and updates two variables in the loop:

for (k=1, j=5; k<=10; k++, j++)


{
sum1 += k; //sum1=sum1+k;
sum2 += j; //sum2=sum2+j;
}
FLOWCHART TO FIND SIMPLE INTEREST
WITH DIFFERENT P, N, R
REVERSING THE DIGITS OF AN INTEGER
Problem
 Design an algorithm that accepts a positive integer and
reverses the order of its digits.
 E.g Input: 27953
Output: 35972

Algorithm Development:
 to make reversal we need to access individual digits of the
input number.
 Since the number of digits in a number is not known, better to
start from accessing least significant digit.
REVERSING THE DIGITS OF AN INTEGER
Algorithm Development (contn)
The number 27953 is actually

 We can get the number 2795 by integer division of the original


number by 10

 3 is the remainder that results from dividing 27953 by 10. To get this
remainder we can use the mod function.

Therefore if we apply the following two steps

iteratively we can access the individual digits of the input number.


REVERSING THE DIGITS OF AN INTEGER
to carry out the digit reversal.
 If the original number was 53 then we could obtain its reverse by
first extracting the 3, multiplying it by 10, and then adding 5 to
give 35.

 to build the reversed integer we can use the construct:


dreverse : = (previous value of dreverse)* 10
+ (most recently extracted rightmost digit)
REVERSING THE DIGITS OF AN INTEGER
Algorithm description
1. input n, the positive integer to be reversed.
2. Set the initial condition for the reversed integer dreverse.
3. While the integer being reversed is greater than zero do
(a) use the remainder function to extract the rightmost digit of the
number being reversed;
(b) increase the previous reversed integer representation dreverse by a
factor of 10 and add to it the most recently extracted digit r to give the
current dreverse value;
dreverse = dreverse*10 + r
(c) use integer division by 10 to remove the rightmost digit from the
number being reversed.

Applications
 Hashing and information retrieval, data base applications.
REVERSING THE DIGITS OF AN INTEGER
 PROBLEMS:
1. Design an algorithm that counts the number of digits in an integer.
2. Design an algorithm to sum the digits in an integer.
3. Design an algorithm that reads in a set of n single digits and converts them
into a single decimal integer. For example, the algorithm should convert the
set of 5 digits {2,7,4,9,3) to the integer 27493.
ARMSTRONG NUMBER

  Armstrong number: An n-digit number equal to the


sum of the nth powers of its digits.
 All the 1 digit numbers (1-9) are Armstrong number
because
 There are no 2 digit Armstrong numbers.

 An Armstrong number of three digit is a number such


that that sum of the cubes of it's digits is equal to the
number itself. E.g
1*1*1=1
5 * 5 * 5 = 125
3 * 3 * 3 = 27
_______________
Sum of= 153
FLOWCHART FOR 3 DIGIT
ARMSTRONG NUMBER

You might also like