180 likes | 315 Views
Programming Paradigms. Lecturer Hamza Azeem. Lecture 5. Decision Control Structure. Decision Control Structure. A conditional statement allows us to control whether a program segment is executed or not. Two constructs if statement if if-else if-else-if switch statement.
E N D
Programming Paradigms LecturerHamza Azeem
Lecture 5 Decision Control Structure
Decision Control Structure • A conditionalstatement allows us to control whether a program segment is executed or not. • Two constructs • if statement • if • if-else • if-else-if • switch statement
The Basic if Statement • Syntax if(condition) action • if the condition is true then execute the action. • action is either a single statement or a group of statements within braces. condition false true action
The Basic if Statement • Put multiple action statements within braces if (it's raining){ <take umbrella> <wear raincoat> }
Example Program // Program to read number and print its absolute value int main(){ int value=0; printf("Enter integer: “); scanf(“%d”,&value); if(value < 0) value = value * -1; printf("The absolute value is %d“, value); }
Relational Operators • The keyword iftells the compiler that what follows, is a decision control instruction. • The condition is specified using Relational Operators.
Example // Program to verify a specific combination int main() { int a=0,b=0; printf("Enter integer #1: “); scanf(“%d”,&a); printf(“\nEnter integer #2: “); scanf(“%d”,&b); if( (a > 2) && ( b > 4) ) printf(“Correct Combination”); }
Example // Program to sort two variables from low to high int value1; int value2; int temp; printf("Enter integer #1: “); scanf(“%d”,&value1); printf("Enter integer #2: “); scanf(“%d”,&value2); if (value1 > value2) temp = value1; value1 = value2; value2 = temp; } Printf (“The values are nor sorted in order %d %d”, value1, value2);
Predict the output int i=0; printf(“Enter value of i: “); scanf(“%d”, &i); if(i = 5) printf(“You entered 5”);
The if-else Statement condition • Syntax if(condition) Action_AelseAction_B • if the condition is true then execute Action_Aelse execute Action_B • Example: if(value == 0) printf( "value is 0“); else printf( "value is not 0“); false true Action_A Action_B
Example int value1; int value2; int larger; printf("Enter integer #1: “); scanf(“%d”,&value1); printf("Enter integer #2: “); scanf(“%d”,&value2); if(value1 > value2) larger = value1; else larger = value2; printf( "Larger of inputs is: %d“, larger);
Example int value; printf("Enter integer: “); scanf(“%d”,&value); if(value%2 == 0) printf(“Even Number”); else printf(“Not Number”);
Different uses of IF 1) if(condition) do this; 2) if(condition) { do this; and this; }
Different uses of IF 3) if(condition) do this; else do this; 4) if(condition) { do this; and this; } else { do this; and this; }
Different uses of IF 5) if(condition) do this; else { if(condition) do this; else { do this; and this; } }