SlideShare une entreprise Scribd logo
1  sur  47
Control Structures
Control Structures ,[object Object]
The following approaches can be chosen depending on the problem statement:
Sequential
In a sequentialapproach, all the statements are executed in the same order as it is written
Selectional
In a selectional approach, based on some conditions, different set of statements are executed
Iterational (Repetition)
In an iterational approach certain statements are executed repeat,[object Object]
Simple if Statement  In a simple ‘if’ statement, a condition is tested  If the condition is true, a set of statements are executed  If the condition is false, the statements are not executed and the program control goes to the next statement that immediately follows if block Syntax: if (condition)   { 	Statement(s); } Next Statement;  if (iDuration >= 3) { /* Interest for deposits equal to or more than 3 years          is   6.0% */ fRateOfInterest = 6.0; }
else Statement (1 of 2) ,[object Object]
The statement ‘else’ provides the sameSyntax: 	if (condition)     { 		Statement set-1; 	} 	else  	{ 		Statement set-2; 	} 	Next Statement;
 else Statement (2 of 2) ,[object Object],	if (iDuration >= 3) { /* If duration is equal to or more than 3 years,     		Interest rate is 6.0 */ fRateOfInterest = 6.0; 	} 	else { /* else, Interest rate is 5.5 */ fRateOfInterest = 5.5; 	}
 else if Statement (1 of 2) ,[object Object]
When one condition is false, it checks for the next condition and so on
When all the conditions are false the ‘else’ block is executed
The statements in that conditional block are executed and the other ‘if’ statements are skipped Syntax: if (condition-1)   { 	Statement set-1; } else if (condition-2)   { Statement set-2; } ……………………………… else if (condition-n)   { Statement set-n; 	} else   	{ 	Statement set-x; 	}
else if Statement (2 of 2) ,[object Object],  tested.  ,[object Object],  This increases the execution time
Example (1 of 2 ) #include<stdio.h> #include<conio.h> main() { int result; printf("Enter your mark:"); scanf("%d",&result);       if (result >=55) 	{ printf("Passed"); printf("Congratulations"); 	} 	else { printf("Failed"); printf("Good luck repeating this subject :D "); } getch(); return 0; } 77 55 48 21
Example (2 of 2 ) #include<stdio.h> #include<conio.h> main() { int test1,test2; int result; printf("Enter your mark for Test 1:"); scanf("%d",&test1); printf("Enter your mark for Test 2:"); scanf("%d",&test2);       result=(test1+test2)/2;             if(result>=80) { printf("Passed: Grade A");                      }       	else if (result>=70) {  printf("Passed: Grade B");                      }       	else if (result >=55) {  printf("Passed: Grade C");                       }       	else { printf("Failed");                       }        getch(); return 0; }
Assignment(=) vs. Equality Operator (==) (1 of 3) The operator ‘=’ is used for assignment purposes whereas the operator ‘==’ is used to check for equality  It is a common mistake to use ‘=’ instead of ‘==’ to check for equality  The compiler does not generate any error message Example: 	if (interest = 6.5) { printf(“Minimum Duration of deposit: 6 years”); 	} 	else if (interest = 6.0) { printf(“Minimum Duration of deposit: 3 years”); 	} 	else { printf(“No such interest rate is offered”); 	}  		The output of the above program will be  “Minimum Duration of deposit: 6 years”  		the control structure Is ignored
Assignment(=) vs. Equality Operator (==) (2 of 3) ,[object Object]
Example:	if (6.5 = interest) { printf(“Minimum Duration of deposit: 6 years”); 	} 	else if (6.0 = interest) { printf(“Minimum Duration of deposit: 3 years”); 	} 	else { printf(“No such interest rate is offered”); 	}  ,[object Object]
This helps in trapping the error at compile time itself, even before it goes to unit testing ,[object Object]
Nested if Statement ,[object Object]
Example:	if (iDuration > 6 )  { if (dPrincipalAmount > 25000)  { printf(“Your percentage of incentive is 4%”); 		} 		else  		{ printf(“Your percentage of incentive is 2%”); 		} 	else  	{ printf(“No incentive”); }
#include<stdio.h> #include<conio.h> main() { intiDuration, dPrincipalAmount; printf("Enter value for iDuration:"); scanf("%d",&iDuration); if (iDuration > 6 ) { printf("What is youtdPrincipalAmount:"); scanf("%d",&dPrincipalAmount); 		if (dPrincipalAmount > 25000) { printf("Your percentage of incentive is 4%"); 		} 		else { printf("Your percentage of incentive is 2%"); 		}                     } else { printf("No incentive"); 	 } getch(); return 0; } What the output if iDuration=9 dPrincipalAmount=26000 iDuration=10 dPrincipalAmount=21000 iDuration=4 dPrincipalAmount=21000
Example Nested if What the output if num1=55 	num2=55 num1=25 	num2=89 num1=90 	num2=10 #include<stdio.h> #include<conio.h> main() { int num1; int num2; printf("Please enter two integers"); printf("Num1:"); scanf("%d",&num1); printf("Num2:"); scanf("%d",&num2);       if(num1<=num2)  { if(num1<num2)  { printf("%d < %d", num1,num2); } else { printf("%d==%d",num1,num2); } } else   { printf("%d > %d",num1, num2);                      }        getch(); return 0; }
What is the output of the following code snippet? iResult = iNum % 2; if ( iResult = 0) { printf("The number is even"); } else { printf("The number is odd"); } CASE 1:  When iNum is 11 CASE 2: When iNum is 8 The output is  "The number is odd" The output is  "The number is odd" Explains???
Switch case Statement ,[object Object]
It is very similar to ‘if’ statement
But ‘switch’ statement cannot replace ‘if’ statementin all situations Syntax: Switch(integer variable or integer expression or character variable) { 	case integer or character constant-1 :  			Statement(s); 			break; 	case integer or character constant-2 : 			Statement(s); 			break; 	…………… 	case integer or character constant-n :  			Statement(s);						        	break; 	default:                                                 			Statement(s); 		    	break;	 }
What is the output of the following code snippet? intiNino= 2; switch(iNino){ 	case 1: printf(“ONE”); 		break; 	case 2: printf(“TWO”); 		break; 	case 3: printf(“THREE”); 		break; 	default: printf(“INVALID”); 		break; } Output: TWO
What is the output of the following code snippet? switch (departmentCode){ 	case 110 : printf(“HRD”); 		break; 	case 115 :  printf(“IVS”); break;  	case 125 : printf(“E&R”); break;  	case 135 :  printf(“CCD”); } ,[object Object],[object Object]
What is the output of the following code snippet? unsigned int iCountOfItems = 5; switch (iCountOfItems) { 	case iCountOfItems >=10 :	 			printf(“Enough Stock” ); 			break; 	 default :  			printf(“Not enough stock”); 			break;  }  Error: Relational Expressions cannot be used in switch statement
An Example – switch case #include<stdio.h> #include<conio.h> main() { char ch; printf("Enter the vowel:"); scanf("%c",&ch); switch(ch) { 	case 'a' : printf("Vowel"); 		      break; 	case 'e' : printf("Vowel"); 	           break; 	case 'i' : printf("Vowel"); 		      break; 	case 'o' : printf("Vowel"); 		      break; 	case 'u' : printf ("Vowel"); 		      break; 	default : printf("Not a vowel"); }		 getch(); return 0; }
An Example – switch case char ch=‘a’; switch(ch) { 	case ‘a’ : printf(“Vowel”); 		      break; 	case ‘e’ : printf(“Vowel”); 	           break; 	case ‘i’ : printf(“Vowel”); 		      break; 	case ‘o’ : printf(“Vowel”); 		      break; 	case ‘u’ : printf (“Vowel”); 		      break; 	default : printf(“Not a vowel”); }		 char ch=‘a’; switch(ch) { 	case ‘a’ : 	case ‘e’ : 	case ‘i’ : 	case ‘o’ : 	case ‘u’ : 	printf(“Vowel”); 		break; 	default :  		printf(“Not a                    vowel”); }
An Example – switch case #include<stdio.h> #include<conio.h> main() { int greeting; printf("Enter the number of your desired greetings :"); scanf("%d",&greeting);       switch (greeting){ 	case 1: printf("Happy Hari Raya"); 	break; 	case 2:  printf("Happy Deepavali"); 	break; 	case 3: printf("Happy New Year"); 	break; 	default: printf("You choose wrong choice");      break;	 	  		 } getch(); return 0; } If you choose  1…Happy Hari Raya 2…Happy Deepavali 3… Happy New Year Other than that……. You choose wrong choice
Iteration Control Structures ,[object Object]
The statements are executed as long as the condition is true
These kind of control structures are also called as loop control structures
are three kinds of loop control structures:
while
do while
for,[object Object]
do while Loop Control Structure Execution proceeds as follows:  First the loop is executed, next the condition is evaluated, if condition evaluates to true the loop continues execution else control passes to the next statement following the loop The do-while statement can also terminate when a break, goto, or returnstatement is executed within the statement body. This is an example of the do-while statement: do{   	a = b ;  			b = b – 1;  } while ( b > 0 ); In the above do-while statement, the two statements a = b; and b = b - 1; are executed, regardless of the initial value of b. Then b > 0 is evaluated. If b is greater than 0, the statement body is executed again and b > 0 is reevaluated. The statement body is executed repeatedly as long as b remains greater than 0. Execution of the do-while statement terminates when b becomes 0 or –ve. The body of the loop is executed at least once.
do while Loop Control Structure Example 	int iNumber, iSum = 0; 	do { 		printf(“Enter a number. Type 0(zero) to end the input ”); 		scanf(“%d”,&iNumber); 		iSum = iSum + iNumber; 	} while (iNumber != 0);

Contenu connexe

Tendances

operators and control statements in c language
operators and control statements in c languageoperators and control statements in c language
operators and control statements in c languageshhanks
 
Java if else condition - powerpoint persentation
Java if else condition - powerpoint persentationJava if else condition - powerpoint persentation
Java if else condition - powerpoint persentationManeesha Caldera
 
Selection Statements in C Programming
Selection Statements in C ProgrammingSelection Statements in C Programming
Selection Statements in C ProgrammingKamal Acharya
 
Control and conditional statements
Control and conditional statementsControl and conditional statements
Control and conditional statementsrajshreemuthiah
 
9. statements (conditional statements)
9. statements (conditional statements)9. statements (conditional statements)
9. statements (conditional statements)Way2itech
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Neeru Mittal
 
Control structure C++
Control structure C++Control structure C++
Control structure C++Anil Kumar
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programmingPriyansh Thakar
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Shipra Swati
 
Control structure of c language
Control structure of c languageControl structure of c language
Control structure of c languageDigvijaysinh Gohil
 
C programming decision making
C programming decision makingC programming decision making
C programming decision makingSENA
 
Control statements and functions in c
Control statements and functions in cControl statements and functions in c
Control statements and functions in cvampugani
 
Structure in programming in c or c++ or c# or java
Structure in programming  in c or c++ or c# or javaStructure in programming  in c or c++ or c# or java
Structure in programming in c or c++ or c# or javaSamsil Arefin
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements Tarun Sharma
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
Decision Making Statement in C ppt
Decision Making Statement in C pptDecision Making Statement in C ppt
Decision Making Statement in C pptMANJUTRIPATHI7
 

Tendances (19)

operators and control statements in c language
operators and control statements in c languageoperators and control statements in c language
operators and control statements in c language
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
Java if else condition - powerpoint persentation
Java if else condition - powerpoint persentationJava if else condition - powerpoint persentation
Java if else condition - powerpoint persentation
 
Selection Statements in C Programming
Selection Statements in C ProgrammingSelection Statements in C Programming
Selection Statements in C Programming
 
Control and conditional statements
Control and conditional statementsControl and conditional statements
Control and conditional statements
 
9. statements (conditional statements)
9. statements (conditional statements)9. statements (conditional statements)
9. statements (conditional statements)
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
 
Control statement in c
Control statement in cControl statement in c
Control statement in c
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programming
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Control structure of c language
Control structure of c languageControl structure of c language
Control structure of c language
 
C programming decision making
C programming decision makingC programming decision making
C programming decision making
 
Flow of control ppt
Flow of control pptFlow of control ppt
Flow of control ppt
 
Control statements and functions in c
Control statements and functions in cControl statements and functions in c
Control statements and functions in c
 
Structure in programming in c or c++ or c# or java
Structure in programming  in c or c++ or c# or javaStructure in programming  in c or c++ or c# or java
Structure in programming in c or c++ or c# or java
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Decision Making Statement in C ppt
Decision Making Statement in C pptDecision Making Statement in C ppt
Decision Making Statement in C ppt
 

En vedette

Karta uslug doradczych 1
Karta uslug doradczych 1Karta uslug doradczych 1
Karta uslug doradczych 1annamull
 
Building Google Authorship Authority
Building Google Authorship AuthorityBuilding Google Authorship Authority
Building Google Authorship AuthorityMarvin Libron
 
Essentials Of Networking
Essentials Of NetworkingEssentials Of Networking
Essentials Of Networkingjsuarez1560
 
Era de hielo la pelicula
Era de hielo la peliculaEra de hielo la pelicula
Era de hielo la peliculaclaremar
 
Ud 0 final juani
Ud 0 final juaniUd 0 final juani
Ud 0 final juanijuanapardo
 
Anuncios sexistas
Anuncios sexistasAnuncios sexistas
Anuncios sexistasjuanapardo
 
Podcast tutorial
Podcast tutorialPodcast tutorial
Podcast tutorialMayci Neal
 
14 o codigo_xenetico
14 o codigo_xenetico14 o codigo_xenetico
14 o codigo_xeneticojuanapardo
 
24 celula citoplasma
24 celula citoplasma24 celula citoplasma
24 celula citoplasmajuanapardo
 
Villamarín,gabriela evidence 1_ glossary
Villamarín,gabriela evidence 1_ glossaryVillamarín,gabriela evidence 1_ glossary
Villamarín,gabriela evidence 1_ glossaryGabriela Villamarin
 
52206811 pequenos-musicos-vol-1
52206811 pequenos-musicos-vol-152206811 pequenos-musicos-vol-1
52206811 pequenos-musicos-vol-1Dinita Lemos
 
Preparazione anno 1980
Preparazione anno 1980Preparazione anno 1980
Preparazione anno 1980Stefano Merlo
 
How to manage your home improvement projects
How to manage your home improvement projectsHow to manage your home improvement projects
How to manage your home improvement projectsHomeZada
 

En vedette (20)

HucksterBot 2.0
HucksterBot 2.0HucksterBot 2.0
HucksterBot 2.0
 
Е 2015
Е 2015Е 2015
Е 2015
 
Karta uslug doradczych 1
Karta uslug doradczych 1Karta uslug doradczych 1
Karta uslug doradczych 1
 
Building Google Authorship Authority
Building Google Authorship AuthorityBuilding Google Authorship Authority
Building Google Authorship Authority
 
ICA Membership
ICA MembershipICA Membership
ICA Membership
 
Essentials Of Networking
Essentials Of NetworkingEssentials Of Networking
Essentials Of Networking
 
La energia.
La energia.La energia.
La energia.
 
Era de hielo la pelicula
Era de hielo la peliculaEra de hielo la pelicula
Era de hielo la pelicula
 
Ud 0 final juani
Ud 0 final juaniUd 0 final juani
Ud 0 final juani
 
Anuncios sexistas
Anuncios sexistasAnuncios sexistas
Anuncios sexistas
 
Podcast tutorial
Podcast tutorialPodcast tutorial
Podcast tutorial
 
14 o codigo_xenetico
14 o codigo_xenetico14 o codigo_xenetico
14 o codigo_xenetico
 
24 celula citoplasma
24 celula citoplasma24 celula citoplasma
24 celula citoplasma
 
Villamarín,gabriela evidence 1_ glossary
Villamarín,gabriela evidence 1_ glossaryVillamarín,gabriela evidence 1_ glossary
Villamarín,gabriela evidence 1_ glossary
 
52206811 pequenos-musicos-vol-1
52206811 pequenos-musicos-vol-152206811 pequenos-musicos-vol-1
52206811 pequenos-musicos-vol-1
 
Tema 4 cmc
Tema 4 cmcTema 4 cmc
Tema 4 cmc
 
Takethetime
TakethetimeTakethetime
Takethetime
 
18 xenoma 1
18 xenoma 118 xenoma 1
18 xenoma 1
 
Preparazione anno 1980
Preparazione anno 1980Preparazione anno 1980
Preparazione anno 1980
 
How to manage your home improvement projects
How to manage your home improvement projectsHow to manage your home improvement projects
How to manage your home improvement projects
 

Similaire à Dti2143 chap 4 control structures aka_selection

Unit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment exampleUnit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment exampleumaghosal12101974
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programmingnmahi96
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in Csana shaikh
 
C Control Statements.docx
C Control Statements.docxC Control Statements.docx
C Control Statements.docxJavvajiVenkat
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 
C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c languagechintupro9
 
C language UPTU Unit3 Slides
C language UPTU Unit3 SlidesC language UPTU Unit3 Slides
C language UPTU Unit3 SlidesRakesh Roshan
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptSanjjaayyy
 
Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Abou Bakr Ashraf
 
Decision Control Structure If & Else
Decision Control Structure If & ElseDecision Control Structure If & Else
Decision Control Structure If & ElseAbdullah Bhojani
 
3. control statements
3. control statements3. control statements
3. control statementsamar kakde
 
Programming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-ExpressionsProgramming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-ExpressionsLovelitJose
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxLikhil181
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)Jyoti Bhardwaj
 

Similaire à Dti2143 chap 4 control structures aka_selection (20)

Unit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment exampleUnit_3A_If_Else_Switch and a if else statment example
Unit_3A_If_Else_Switch and a if else statment example
 
Control statements-Computer programming
Control statements-Computer programmingControl statements-Computer programming
Control statements-Computer programming
 
CH-4 (1).pptx
CH-4 (1).pptxCH-4 (1).pptx
CH-4 (1).pptx
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 
ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
 
C Control Statements.docx
C Control Statements.docxC Control Statements.docx
C Control Statements.docx
 
M C6java5
M C6java5M C6java5
M C6java5
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c language
 
C language UPTU Unit3 Slides
C language UPTU Unit3 SlidesC language UPTU Unit3 Slides
C language UPTU Unit3 Slides
 
control statement
control statement control statement
control statement
 
Controls & Loops in C
Controls & Loops in C Controls & Loops in C
Controls & Loops in C
 
CONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.pptCONTROLSTRUCTURES.ppt
CONTROLSTRUCTURES.ppt
 
Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3
 
Decision Control Structure If & Else
Decision Control Structure If & ElseDecision Control Structure If & Else
Decision Control Structure If & Else
 
3. control statements
3. control statements3. control statements
3. control statements
 
Programming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-ExpressionsProgramming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-Expressions
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptx
 
Loops
LoopsLoops
Loops
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)
 

Plus de alish sha

T22016 – how to answer with ubs 9
T22016 – how to answer with ubs 9T22016 – how to answer with ubs 9
T22016 – how to answer with ubs 9alish sha
 
July 2014 theory exam (theory)
July 2014 theory exam (theory)July 2014 theory exam (theory)
July 2014 theory exam (theory)alish sha
 
Accounting basic equation
Accounting basic equation Accounting basic equation
Accounting basic equation alish sha
 
It 302 computerized accounting (week 2) - sharifah
It 302   computerized accounting (week 2) - sharifahIt 302   computerized accounting (week 2) - sharifah
It 302 computerized accounting (week 2) - sharifahalish sha
 
It 302 computerized accounting (week 1) - sharifah
It 302   computerized accounting (week 1) - sharifahIt 302   computerized accounting (week 1) - sharifah
It 302 computerized accounting (week 1) - sharifahalish sha
 
What are the causes of conflicts (Bahasa Malaysia)
What are the causes of conflicts (Bahasa Malaysia)What are the causes of conflicts (Bahasa Malaysia)
What are the causes of conflicts (Bahasa Malaysia)alish sha
 
Lab 9 sem ii_12_13
Lab 9 sem ii_12_13Lab 9 sem ii_12_13
Lab 9 sem ii_12_13alish sha
 
Lab 10 sem ii_12_13
Lab 10 sem ii_12_13Lab 10 sem ii_12_13
Lab 10 sem ii_12_13alish sha
 
Lab 5 2012/2012
Lab 5 2012/2012Lab 5 2012/2012
Lab 5 2012/2012alish sha
 
Purpose elaborate
Purpose elaboratePurpose elaborate
Purpose elaboratealish sha
 
Test 1 alish schema 1
Test 1 alish schema 1Test 1 alish schema 1
Test 1 alish schema 1alish sha
 
Lab 6 sem ii_11_12
Lab 6 sem ii_11_12Lab 6 sem ii_11_12
Lab 6 sem ii_11_12alish sha
 
Test 1 skema q&a
Test 1 skema q&aTest 1 skema q&a
Test 1 skema q&aalish sha
 
Test 1 skema q&a
Test 1 skema q&aTest 1 skema q&a
Test 1 skema q&aalish sha
 
Final project
Final projectFinal project
Final projectalish sha
 
Final project
Final projectFinal project
Final projectalish sha
 
Attn list test
Attn list testAttn list test
Attn list testalish sha
 
Carry markdam31303
Carry markdam31303Carry markdam31303
Carry markdam31303alish sha
 

Plus de alish sha (20)

T22016 – how to answer with ubs 9
T22016 – how to answer with ubs 9T22016 – how to answer with ubs 9
T22016 – how to answer with ubs 9
 
July 2014 theory exam (theory)
July 2014 theory exam (theory)July 2014 theory exam (theory)
July 2014 theory exam (theory)
 
Accounting basic equation
Accounting basic equation Accounting basic equation
Accounting basic equation
 
It 302 computerized accounting (week 2) - sharifah
It 302   computerized accounting (week 2) - sharifahIt 302   computerized accounting (week 2) - sharifah
It 302 computerized accounting (week 2) - sharifah
 
It 302 computerized accounting (week 1) - sharifah
It 302   computerized accounting (week 1) - sharifahIt 302   computerized accounting (week 1) - sharifah
It 302 computerized accounting (week 1) - sharifah
 
What are the causes of conflicts (Bahasa Malaysia)
What are the causes of conflicts (Bahasa Malaysia)What are the causes of conflicts (Bahasa Malaysia)
What are the causes of conflicts (Bahasa Malaysia)
 
Lab 9 sem ii_12_13
Lab 9 sem ii_12_13Lab 9 sem ii_12_13
Lab 9 sem ii_12_13
 
Lab 10 sem ii_12_13
Lab 10 sem ii_12_13Lab 10 sem ii_12_13
Lab 10 sem ii_12_13
 
Lab 6
Lab 6Lab 6
Lab 6
 
Lab 5 2012/2012
Lab 5 2012/2012Lab 5 2012/2012
Lab 5 2012/2012
 
Purpose elaborate
Purpose elaboratePurpose elaborate
Purpose elaborate
 
Lab sheet 1
Lab sheet 1Lab sheet 1
Lab sheet 1
 
Test 1 alish schema 1
Test 1 alish schema 1Test 1 alish schema 1
Test 1 alish schema 1
 
Lab 6 sem ii_11_12
Lab 6 sem ii_11_12Lab 6 sem ii_11_12
Lab 6 sem ii_11_12
 
Test 1 skema q&a
Test 1 skema q&aTest 1 skema q&a
Test 1 skema q&a
 
Test 1 skema q&a
Test 1 skema q&aTest 1 skema q&a
Test 1 skema q&a
 
Final project
Final projectFinal project
Final project
 
Final project
Final projectFinal project
Final project
 
Attn list test
Attn list testAttn list test
Attn list test
 
Carry markdam31303
Carry markdam31303Carry markdam31303
Carry markdam31303
 

Dti2143 chap 4 control structures aka_selection

  • 2.
  • 3. The following approaches can be chosen depending on the problem statement:
  • 5. In a sequentialapproach, all the statements are executed in the same order as it is written
  • 7. In a selectional approach, based on some conditions, different set of statements are executed
  • 9.
  • 10. Simple if Statement In a simple ‘if’ statement, a condition is tested If the condition is true, a set of statements are executed If the condition is false, the statements are not executed and the program control goes to the next statement that immediately follows if block Syntax: if (condition) { Statement(s); } Next Statement; if (iDuration >= 3) { /* Interest for deposits equal to or more than 3 years is 6.0% */ fRateOfInterest = 6.0; }
  • 11.
  • 12. The statement ‘else’ provides the sameSyntax: if (condition) { Statement set-1; } else { Statement set-2; } Next Statement;
  • 13.
  • 14.
  • 15. When one condition is false, it checks for the next condition and so on
  • 16. When all the conditions are false the ‘else’ block is executed
  • 17. The statements in that conditional block are executed and the other ‘if’ statements are skipped Syntax: if (condition-1) { Statement set-1; } else if (condition-2) { Statement set-2; } ……………………………… else if (condition-n) { Statement set-n; } else { Statement set-x; }
  • 18.
  • 19. Example (1 of 2 ) #include<stdio.h> #include<conio.h> main() { int result; printf("Enter your mark:"); scanf("%d",&result); if (result >=55) { printf("Passed"); printf("Congratulations"); } else { printf("Failed"); printf("Good luck repeating this subject :D "); } getch(); return 0; } 77 55 48 21
  • 20. Example (2 of 2 ) #include<stdio.h> #include<conio.h> main() { int test1,test2; int result; printf("Enter your mark for Test 1:"); scanf("%d",&test1); printf("Enter your mark for Test 2:"); scanf("%d",&test2); result=(test1+test2)/2; if(result>=80) { printf("Passed: Grade A"); } else if (result>=70) { printf("Passed: Grade B"); } else if (result >=55) { printf("Passed: Grade C"); } else { printf("Failed"); } getch(); return 0; }
  • 21. Assignment(=) vs. Equality Operator (==) (1 of 3) The operator ‘=’ is used for assignment purposes whereas the operator ‘==’ is used to check for equality It is a common mistake to use ‘=’ instead of ‘==’ to check for equality The compiler does not generate any error message Example: if (interest = 6.5) { printf(“Minimum Duration of deposit: 6 years”); } else if (interest = 6.0) { printf(“Minimum Duration of deposit: 3 years”); } else { printf(“No such interest rate is offered”); } The output of the above program will be “Minimum Duration of deposit: 6 years” the control structure Is ignored
  • 22.
  • 23.
  • 24.
  • 25.
  • 26. Example: if (iDuration > 6 ) { if (dPrincipalAmount > 25000) { printf(“Your percentage of incentive is 4%”); } else { printf(“Your percentage of incentive is 2%”); } else { printf(“No incentive”); }
  • 27. #include<stdio.h> #include<conio.h> main() { intiDuration, dPrincipalAmount; printf("Enter value for iDuration:"); scanf("%d",&iDuration); if (iDuration > 6 ) { printf("What is youtdPrincipalAmount:"); scanf("%d",&dPrincipalAmount); if (dPrincipalAmount > 25000) { printf("Your percentage of incentive is 4%"); } else { printf("Your percentage of incentive is 2%"); } } else { printf("No incentive"); } getch(); return 0; } What the output if iDuration=9 dPrincipalAmount=26000 iDuration=10 dPrincipalAmount=21000 iDuration=4 dPrincipalAmount=21000
  • 28. Example Nested if What the output if num1=55 num2=55 num1=25 num2=89 num1=90 num2=10 #include<stdio.h> #include<conio.h> main() { int num1; int num2; printf("Please enter two integers"); printf("Num1:"); scanf("%d",&num1); printf("Num2:"); scanf("%d",&num2); if(num1<=num2) { if(num1<num2) { printf("%d < %d", num1,num2); } else { printf("%d==%d",num1,num2); } } else { printf("%d > %d",num1, num2); } getch(); return 0; }
  • 29. What is the output of the following code snippet? iResult = iNum % 2; if ( iResult = 0) { printf("The number is even"); } else { printf("The number is odd"); } CASE 1: When iNum is 11 CASE 2: When iNum is 8 The output is "The number is odd" The output is "The number is odd" Explains???
  • 30.
  • 31. It is very similar to ‘if’ statement
  • 32. But ‘switch’ statement cannot replace ‘if’ statementin all situations Syntax: Switch(integer variable or integer expression or character variable) { case integer or character constant-1 : Statement(s); break; case integer or character constant-2 : Statement(s); break; …………… case integer or character constant-n : Statement(s); break; default: Statement(s); break; }
  • 33. What is the output of the following code snippet? intiNino= 2; switch(iNino){ case 1: printf(“ONE”); break; case 2: printf(“TWO”); break; case 3: printf(“THREE”); break; default: printf(“INVALID”); break; } Output: TWO
  • 34.
  • 35. What is the output of the following code snippet? unsigned int iCountOfItems = 5; switch (iCountOfItems) { case iCountOfItems >=10 : printf(“Enough Stock” ); break; default : printf(“Not enough stock”); break; } Error: Relational Expressions cannot be used in switch statement
  • 36. An Example – switch case #include<stdio.h> #include<conio.h> main() { char ch; printf("Enter the vowel:"); scanf("%c",&ch); switch(ch) { case 'a' : printf("Vowel"); break; case 'e' : printf("Vowel"); break; case 'i' : printf("Vowel"); break; case 'o' : printf("Vowel"); break; case 'u' : printf ("Vowel"); break; default : printf("Not a vowel"); } getch(); return 0; }
  • 37. An Example – switch case char ch=‘a’; switch(ch) { case ‘a’ : printf(“Vowel”); break; case ‘e’ : printf(“Vowel”); break; case ‘i’ : printf(“Vowel”); break; case ‘o’ : printf(“Vowel”); break; case ‘u’ : printf (“Vowel”); break; default : printf(“Not a vowel”); } char ch=‘a’; switch(ch) { case ‘a’ : case ‘e’ : case ‘i’ : case ‘o’ : case ‘u’ : printf(“Vowel”); break; default : printf(“Not a vowel”); }
  • 38. An Example – switch case #include<stdio.h> #include<conio.h> main() { int greeting; printf("Enter the number of your desired greetings :"); scanf("%d",&greeting); switch (greeting){ case 1: printf("Happy Hari Raya"); break; case 2: printf("Happy Deepavali"); break; case 3: printf("Happy New Year"); break; default: printf("You choose wrong choice"); break; } getch(); return 0; } If you choose 1…Happy Hari Raya 2…Happy Deepavali 3… Happy New Year Other than that……. You choose wrong choice
  • 39.
  • 40. The statements are executed as long as the condition is true
  • 41. These kind of control structures are also called as loop control structures
  • 42. are three kinds of loop control structures:
  • 43. while
  • 45.
  • 46. do while Loop Control Structure Execution proceeds as follows: First the loop is executed, next the condition is evaluated, if condition evaluates to true the loop continues execution else control passes to the next statement following the loop The do-while statement can also terminate when a break, goto, or returnstatement is executed within the statement body. This is an example of the do-while statement: do{ a = b ; b = b – 1; } while ( b > 0 ); In the above do-while statement, the two statements a = b; and b = b - 1; are executed, regardless of the initial value of b. Then b > 0 is evaluated. If b is greater than 0, the statement body is executed again and b > 0 is reevaluated. The statement body is executed repeatedly as long as b remains greater than 0. Execution of the do-while statement terminates when b becomes 0 or –ve. The body of the loop is executed at least once.
  • 47. do while Loop Control Structure Example int iNumber, iSum = 0; do { printf(“Enter a number. Type 0(zero) to end the input ”); scanf(“%d”,&iNumber); iSum = iSum + iNumber; } while (iNumber != 0);
  • 48. Difference between while and do while loops
  • 49. do – while and whileExample #include<stdio.h> #include<conio.h> int main(void) { int x=1; do{ printf("%d", x++); } while (x<5); getch(); return 0; } #include<stdio.h> #include<conio.h> int main(void) { int x=1; while(x<5){ printf("%d", x); x++; } getch(); return 0; } 2 3 4
  • 50. for Loop Control Structure The ‘for’ loops are similar to the other loop control structures The ‘for’ loops are generally used when certain statements have to beexecuted a specific number of times Advantage of for loops: All the three parts of a loop (initialization, condition and increment) can be given in a single statement Because of this, there is no chance of user missing out initialization or increment steps which is the common programming error in ‘while’ and ‘do while’ loops Syntax: for (Initialization; Termination-Condition; Increment-Step) { Set of statement(s); } Next Statement;
  • 51. Syntax: for (Initialization; Termination-Condition; Increment-Step) { Set of statement(s); } Next Statement; In executing a for statement, the computer does the following: Initializationis executed. Then the Termination-conditionis evaluated. If it computes to zero the loop is exited. If the (1)Termination-conditiongives a nonzero value, the (2)LoopBody is executed and then the (3)Increment-stepis evaluated. The Termination-condition is again tested. Thus, the LoopBody is repeated until the Termination-condition computes to a zero value.
  • 52. for Loop Control Structure Example: int iCount; for (iCount = 1; iCount <= 10; iCount++) { printf(“%d”,iCount); } 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
  • 53. for Loop Control Structure /* Check for n number of students, whether they have passed or not */ #include<stdio.h> #include<conio.h> int main(void) { intiCounter, iNoOfStudents; float fMark1, fMark2, fMark3, fAvg, fSum; for(iCounter=1; iCounter<=iNoOfStudents; iCounter++) { /* Accepting the marks scored by the students in 3 subjects */ /* Display a message before accepting the marks*/ printf("Enter the marks scored by the student %d in 3 subjects", iCounter); printf("Subject1:"); scanf("%f",&fMark1); printf("Subject2:"); scanf("%f",&fMark2); printf("Subject3:"); scanf("%f",&fMark3); /* calculating the average marks */ fSum=fMark1+fMark2+fMark3; fAvg=fSum/3; /* compare the average with 65 and decide whether student has passed or failed */ if ( fAvg >= 65.0) printf("Student %d - PASSES", iCounter); else printf("Student %d - FAILS", iCounter); } getch(); return 0;}
  • 54. for Loop Control Structure #include<stdio.h> #include<conio.h> int main(void) { int x, y; for(x=0,y=1;x<y;x++) printf("%d %d",x,y); getch(); return 0; } O 1
  • 55. for Loop Control Structure #include<stdio.h> #include<conio.h> int main(void) { int x; for(x=1;x<5;x++) printf("%d",x); getch(); return 0; } 1 2 3 4
  • 56. What is the output of the following code snippet? int iNum; int iCounter; int iProduct; for(iCounter=1; iCounter<= 3; iCounter++) { iProduct = iProduct * iCounter; } printf("%d", iProduct); The output is a junk value -- WHY??? This is because iProduct is not initialized
  • 57. What is the output of the following code snippet? for(iCount=0;iCount<10;iCount++); { printf("%d",iCount); } The output is 10 int iCount; for(iCount=0;iCount<10;iCount++) { printf("%d",iCount); } The output is 0 1 2 3 4 5 6 7 8 9
  • 58. for and while loops Rewrite it using while statement #include<stdio.h> #include<conio.h> int main(void) { intiSum,iCtr,iNum; iSum=0,iCtr=0; while(iCtr<10){ printf("Enter mark: "); scanf("%d",&iNum); iSum=iSum+iNum; iCtr=iCtr+1; } printf("%d",iSum); getch(); return 0; } Given #include<stdio.h> #include<conio.h> int main(void) { int iSum,iCtr,iNum; for(iSum=0,iCtr=0; iCtr<10;iCtr=iCtr+1){ printf("Enter mark: "); scanf("%d",&iNum); iSum=iSum+iNum; } printf("%d",iSum); getch(); return 0; }
  • 59. Quitting the Loops – break Statement The break statement is used to: Force thetermination of a loop. When a break statement is encountered in a loop, the loop terminates immediately and the execution resumes the next statementfollowing the loop. Note: Break statement can be used in an if statement only when the if statement is written in a loop Just an if statement with break leads to compilation error in C
  • 60. What is the output of the following code snippet? int iCounter1=0; int iCounter2; while(iCounter1 < 3) { for (iCounter2 = 0; iCounter2 < 5; iCounter2++) { printf("%d",iCounter2); if (iCounter2 == 2){ break; } } printf(""); iCounter1 += 1; } 0 1 2 0 1 2 0 1 2
  • 61.
  • 62. In case of for loop, continue makes the execution of the increment portion of the statement and then evaluates the conditional part.
  • 63. In case of while and do-while loops, continue makes the conditional statement to be executed.Example: for(iCount = 0 ; iCount < 10; iCount++) { if (iCount == 4) { continue; } printf(“%d”, iCount); } The above code displays numbers from 1 to 9 except 4.
  • 64. Comparison of break, continue and exit
  • 65. What is the output of the following code snippet? 1 2 3 4 5 6 7 8 9 Case 1: Case 3: 1 3 5 7 9 iCount = 1; do { printf(“%d”,iCount); iCount++; if (iCount == 5) { continue; } } while(iCount < 10); for (iCount=1;iCount <= 10; iCount++) { if (iCount % 2 == 0) { continue; } printf(“%d”,iCount); } Case 4: Case 2: for (iCount=1;iCount <= 5; iCount++) { for (iValue =1; iValue <= 3; iValue++) { if (iValue == 2) { break; } printf(“%d”,iValue); } } iCount = 1; while (iCount < 10) { if (iCount == 5) { continue; } printf(“%d”,iCount); iCount++; } 1 2 3 4 1 1 1 1 1
  • 66.
  • 67. A ‘while’ loop is used when the number of times the loop gets executed is not known and the loop should not be executed when the condition is initially false
  • 68.