Final Requirement for Fundamentals of                        Programming            http://eglobiotraining.com
• A program is a sequence of instruction written toperform a specified task with a computer. A computerrequires programs t...
• Computer source code is often writtenby computer programmers. Source code is writtenin a programming language that usual...
A computer programmer is a person whowrites computer software. The term computerprogrammer can refer to a specialist in on...
Programmers are people who design the programof events that turns input data into output data. Ithas been proved that such...
Programming is the iterative process of writingor editing source code. Editing source code involves testing,analyzing, and...
Programming is instructing a computer to dosomething for you with the help of a programminglanguage. The role of a program...
A programming language should both provide means todescribe primitive data and procedures and means tocombine and abstract...
In practicing programming one must know the basicprogram a programmer use. Dev C++ can help us oncomputing grades, making ...
• C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. Itis regarded as a...
C/C++ has a built-in multiple-branch selectionstatement, called switch, which successively tests thevalue of an expression...
Programs have a need to do different things dependingon user input or based on the flow of the program itself. Ifstatement...
In programming,a switch, case, select or inspect statement is a type of selection control mechanism that exists inmost imp...
switch (expression){case constant1:statement sequencebreak;case constant2:statement sequencebreak;case constant3:statement...
The expression must evaluate to a character or integervalue. Floating-point expressions, for example, are notallowed. The ...
• The switch differs from the if in that switch can onlytest for equality, whereas if can evaluate any type ofrelational o...
In programming switch case statement body consists aseries of case labels and an optional default label. Notwo constant ex...
The default label can appear only once. The labeledstatements are not syntactic requirements, butthe switch statement is m...
The constant-expression in each case label isconverted to the type of expression and comparedwith expression for equality....
// switch_statement1.cpp#include <stdio.h> int main(){ char *buffer = "Any character stream";int capa, lettera, nota;char ...
On the example given , capa is incremented if c is anuppercase A. The break statement after capa++ terminatesexecution of ...
In the series of the Programming language a loop statementshave an optional LABEL in their formal syntax. (You can put ala...
The ”while” statement in programming repeatedly executes theblock as long as EXPR is true. If the word while is replaced b...
The while or until statement can have an optional extrablock: the continue block. This block is executed everytime the blo...
while (my $line = <STDIN>) {$line = lc $line;}continue {print $line; # still visible}# $line now out of scope hereHere the...
The ”for ” loop has three semicolon-separatedexpressions within its parentheses. These expressionsfunction respectively as...
LABEL: for (my $i = 1; $i <= 10; $i++) {   ... }{             my $i = 1;LABEL:             while ($i <= 10) {             ...
A do-while loop in programming executes one ormore times, depending on the value of the terminationexpression. The do-whil...
// do_while_statement.cpp#include <stdio.h> int main(){              int i = 0;              do              {            ...
Iteration statements cause statements (orcompound statements) to be executed zero or more times,subject to some loop-termi...
http://eglobiotraining.com
#include <stdio.h>int main() {  int color = 1;  printf("Please choose a color(1: red,2: green,3: blue):n");  scanf("%d", &...
#include <iostream>using namespace std;void playgame(){  cout << "Play game called";}void loadgame(){  cout << "Load game ...
#include <iostream.h>int main(){  unsigned short int day;  cout << "Whats your favorite day of the week? ";  cin >> day;  ...
#include <iostream>#include <math.h>#include<stdio.h>using namespace std;int main(){    int number1;    int number2;    in...
cout << "Geometry Calculator" << endl;cout << "1. Calculate the Area of a Circle" << endl;cout << "2. Calculate the Area o...
#include <stdio.h>#include <iostream>using namespace std;int main(){               int nr = 0;               char ch = 0; ...
//This uses lowercase characters only                    cout << "nn Type in character a or b: ";                    cin >...
#include <iostream>#include <string>using namespace std;int main(){string choice = "y";while ( choice == "y" ){cout << "Sa...
#include <iostream>using namespace std;int main(){          int a;          cout << "How long do you want this program to ...
int main(){  int x = 0; /* Dont forget to declare variables */    while ( x < 16 ) { /* While x is less than 16*/      pri...
#include <stdio.h>int main(){  int x;    x = 0;    do {      /* "He who hesitates is lost.-Proverb" is printed at least on...
#include <stdio.h>int main(){    int i, count;    printf("Enter the number of the item: ");    scanf("%d", &count, 1);    ...
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
Switch Statement:•     The first line contains the basic keyword,usually switch, case or select, followed by anexpression ...
Each alternative begins with the particular value, orlist of values (see below), that the control variable maymatch and wh...
•      When the program starts the user is promptedto insert a starting number for the countdown. Thenthe while loop begin...
Submitted by:Jenica H. TubungbanuaBM10203             http://eglobiotraining.com
Upcoming SlideShare
Loading in …5
×

Switch case and looping statement

693 views
589 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
693
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
24
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Switch case and looping statement

  1. 1. Final Requirement for Fundamentals of Programming http://eglobiotraining.com
  2. 2. • A program is a sequence of instruction written toperform a specified task with a computer. A computerrequires programs to function, typically executing theprograms instructions in central processor. Theprogram has an executable form that the computer canuse directly to execute the instructions. The sameprogram in its human-readable source code form, fromwhich executable programs are derived (e.g.,compiled), enables a programmer to study and developits algorithms. http://eglobiotraining.com
  3. 3. • Computer source code is often writtenby computer programmers. Source code is writtenin a programming language that usually followsone of two main paradigms: imperativeprogramming or declarative programming. Sourcecode may be converted into an executablefile (sometimes called an executable program or abinary) by a compiler and later executed by acentral processing unit. http://eglobiotraining.com
  4. 4. A computer programmer is a person whowrites computer software. The term computerprogrammer can refer to a specialist in one areaof computer programming or to a generalist who writescode for many kinds of software. One who practices orprofesses a formal approach to programming may alsobe known as a programmer analyst. http://eglobiotraining.com
  5. 5. Programmers are people who design the programof events that turns input data into output data. Ithas been proved that such a program of events canbe designed using a structure composed ofsequences, iterations and selections. Code ismerely the way that the program is described. http://eglobiotraining.com
  6. 6. Programming is the iterative process of writingor editing source code. Editing source code involves testing,analyzing, and refining, and sometimes coordinating withother programmers on a jointly developed program. Aperson who practices this skill is referred to as acomputer programmer, software developer or coder. Thesometimes lengthy process of computer programming isusually referred to as software development. Theterm software engineering is becoming popular as theprocess is seen as an engineering discipline. http://eglobiotraining.com
  7. 7. Programming is instructing a computer to dosomething for you with the help of a programminglanguage. The role of a programming language can bedescribed in two ways:1. Technical: It is a means for instructing a Computer toperform Tasks2. Conceptual: It is a framework within which weorganize our ideas about things and processes. http://eglobiotraining.com
  8. 8. A programming language should both provide means todescribe primitive data and procedures and means tocombine and abstract those into more complex ones.The distinction between data and procedures is not thatclear cut. In many programming languages, procedures canbe passed as data (to be applied to ``real data) andsometimes processed like ``ordinary data. Conversely``ordinary data can be turned into procedures by anevaluation mechanism http://eglobiotraining.com
  9. 9. In practicing programming one must know the basicprogram a programmer use. Dev C++ can help us oncomputing grades, making test questionnaires andmany more things a teacher and a student can do.Programming is a an act of formulating a program for adefinite course of action; "the planning was more funthan the trip itself“. http://eglobiotraining.com
  10. 10. • C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. Itis regarded as an intermediate-level language, as it comprises acombination of both high-level and low-level language features.• C++ is one of the most popular programming languages and isimplemented on a wide variety of hardware and operatingsystem platforms. • C++ has greatly influenced many other popular programminglanguages, most notably C# and Java. Other successful languagessuch as Objective-C use a very different syntax and approach toadding classes to C. http://eglobiotraining.com
  11. 11. C/C++ has a built-in multiple-branch selectionstatement, called switch, which successively tests thevalue of an expression against a list of integeror character constants. When a match is found, thestatements associated with that constant are executed. http://eglobiotraining.com
  12. 12. Programs have a need to do different things dependingon user input or based on the flow of the program itself. Ifstatements can do this work, but sometimes it is mucheasier to use other forms that might work more easily formenu items or what to do with different rolls of a die. Theswitch statement can be very helpful in handling multiplechoices in programming. This program will ask the user to select a number froma predetermined set of numbers. Then the program willprint different things on the screen depending on whichnumber the user chose http://eglobiotraining.com
  13. 13. In programming,a switch, case, select or inspect statement is a type of selection control mechanism that exists inmost imperative programming languages suchas Pascal, Ada, C/C++,C#, Java, and so on. It is also includedin several other types of languages. Its purpose is to allow thevalue of a variable or expression to control the flow ofprogram execution via a multi way branch(or "goto", one ofseveral labels). The main reasons for using a switch includeimproving clarity, by reducing otherwise repetitive coding,and (if the heuristics permit) also offering the potential forfaster execution through easier compiler optimization inmany cases. http://eglobiotraining.com
  14. 14. switch (expression){case constant1:statement sequencebreak;case constant2:statement sequencebreak;case constant3:statement sequencebreak;defaultstatement sequence} http://eglobiotraining.com
  15. 15. The expression must evaluate to a character or integervalue. Floating-point expressions, for example, are notallowed. The value of expression is tested, in order,against the values of the constants specified in the casestatements. When a match is found, the statementsequence associated with that case is executed until thebreak statement or the end of the switch statement isreached. The default statement is executed if no matchesare found. The default is optional and, if it is not present,no action takes place if all matches fail. http://eglobiotraining.com
  16. 16. • The switch differs from the if in that switch can onlytest for equality, whereas if can evaluate any type ofrelational or logical expression.• No two case constants in the same switch can haveidentical values. Of course, a switch statementenclosed by an outer switch may havecase constants that are the same.• If character constants are used in the switchstatement, they are automatically converted to integers http://eglobiotraining.com
  17. 17. In programming switch case statement body consists aseries of case labels and an optional default label. Notwo constant expressions in case statements canevaluate to the same value. http://eglobiotraining.com
  18. 18. The default label can appear only once. The labeledstatements are not syntactic requirements, butthe switch statement is meaningless without them. Thedefault statement need not come at the end; it can appearanywhere in the body of the switch statement. A case ordefault label can only appear inside a switch statement. http://eglobiotraining.com
  19. 19. The constant-expression in each case label isconverted to the type of expression and comparedwith expression for equality. Control passes to thestatement whose case constant-expression matches thevalue of expression. If a matching expression isfound, control is not impeded bysubsequent case or default labels. The ”break ”statementis used to stop execution and transfer control to thestatement after the switch statement. Withouta break statement, every statement from the matchedcase label to the end of the switch, includingthe default, is executed. http://eglobiotraining.com
  20. 20. // switch_statement1.cpp#include <stdio.h> int main(){ char *buffer = "Any character stream";int capa, lettera, nota;char c;capa = lettera = nota = 0;while ( c = *buffer++ ) // Walks buffer until NULL {switch ( c ){case A: capa++; break;case a: lettera++;break;default: nota++; } }printf_s( "nUppercase a: %dnLowercase a: %dnTotal: %dn",capa, lettera, (capa + lettera + nota) );} http://eglobiotraining.com
  21. 21. On the example given , capa is incremented if c is anuppercase A. The break statement after capa++ terminatesexecution of the switch statement body and control passesto the while loop. Without the break statement, lettera and nota would also be incremented. A similar purpose isserved by the break statement for case a. If c is alowercase a, letter a is incremented andthe break statement terminates the switch statement body.If c is not an a or A, the default statement is executed. http://eglobiotraining.com
  22. 22. In the series of the Programming language a loop statementshave an optional LABEL in their formal syntax. (You can put alabel on any statement, but it has a special meaning to a loop.) Ifpresent, the label consists of an identifier followed by a colon. Itscustomary to make the label uppercase to avoid potentialconfusion with reserved words, and so it stands out better. Andalthough Perl wont get confused if you use a label that alreadyhas a meaning like if or open, your readers might. http://eglobiotraining.com
  23. 23. The ”while” statement in programming repeatedly executes theblock as long as EXPR is true. If the word while is replaced by theword until, the sense of the test is reversed; that is, it executesthe block only as long as EXPR remains false. The conditional isstill tested before the first iteration, though. http://eglobiotraining.com
  24. 24. The while or until statement can have an optional extrablock: the continue block. This block is executed everytime the block is continued, either by falling off theend of the first block or by an explicit next (a loop-control operator that goes to the next iteration). The“continue ”block is not heavily used in practice, but itsin here so we can define the for loop rigorously in thenext section http://eglobiotraining.com
  25. 25. while (my $line = <STDIN>) {$line = lc $line;}continue {print $line; # still visible}# $line now out of scope hereHere the scope of $line extends from its declaration in the control expression throughoutthe rest of the loop construct, including the continue block, but not beyond. If you wantthe scope to extend further, declare the variable before the loop. http://eglobiotraining.com
  26. 26. The ”for ” loop has three semicolon-separatedexpressions within its parentheses. These expressionsfunction respectively as the initialization, thecondition, and the re-initialization expressions of theloop. All three expressions are optional (but not thesemicolons); if omitted, the condition is always true http://eglobiotraining.com
  27. 27. LABEL: for (my $i = 1; $i <= 10; $i++) { ... }{ my $i = 1;LABEL: while ($i <= 10) { ... } continue { $i++; } }In programming a kind of “for” statement like this we ca see that the scope of the ”my” islimited thus , the three-part for loop can be defined in terms of thecorresponding while loop. http://eglobiotraining.com
  28. 28. A do-while loop in programming executes one ormore times, depending on the value of the terminationexpression. The do-while statement can alsoterminate when a break, go to, or return statement isexecuted within the statement body. http://eglobiotraining.com
  29. 29. // do_while_statement.cpp#include <stdio.h> int main(){ int i = 0; do { printf_s("n%d",i++); } while (i < 3);}If expression is false, the do-while statement terminates and control passes tothe next statement in the program. If expression is true (nonzero), the processis repeated, beginning with step 1. http://eglobiotraining.com
  30. 30. Iteration statements cause statements (orcompound statements) to be executed zero or more times,subject to some loop-termination criteria. When thesestatements are compound statements, they are executed inorder, except when either the break statement orthe continue statement is encountered. C++ program provides four iteration statements — while, do, for, and range-based for. Each of these iteratesuntil its termination on the programming expressionevaluates to zero (false), or until loop termination is forcedwith a break statement. The following table summarizesthese statements and their actions; each is discussed indetail in the sections that follow. http://eglobiotraining.com
  31. 31. http://eglobiotraining.com
  32. 32. #include <stdio.h>int main() { int color = 1; printf("Please choose a color(1: red,2: green,3: blue):n"); scanf("%d", &color); switch (color) { case 1: printf("you chose red colorn"); break; case 2: printf("you chose green colorn"); break; case 3: printf("you chose blue colorn"); break; default: printf("you did not choose any colorn"); } return 0;} http://eglobiotraining.com
  33. 33. #include <iostream>using namespace std;void playgame(){ cout << "Play game called";}void loadgame(){ cout << "Load game called";}void playmultiplayer(){ cout << "Play multiplayer game called";}int main(){ int input; cout<<"1. Play gamen"; cout<<"2. Load gamen"; cout<<"3. Play multiplayern"; cout<<"4. Exitn"; cout<<"Selection: "; cin>> input; switch ( input ) { case 1: // Note the colon, not a semicolon playgame(); break; case 2: // Note the colon, not a semicolon loadgame(); break; case 3: // Note the colon, not a semicolon playmultiplayer(); break; case 4: // Note the colon, not a semicolon cout<<"Thank you for playing!n"; break; default: // Note the colon, not a semicolon cout<<"Error, bad input, quittingn"; http://eglobiotraining.com break; }
  34. 34. #include <iostream.h>int main(){ unsigned short int day; cout << "Whats your favorite day of the week? "; cin >> day; switch (day){ case 1 : cout << "Sunday"; break; case 2 : cout << "Monday"; break; case 3 : cout << "Tuesday"; break; case 4 : cout << "Wednesday"; break; case 5 : cout << "Thursday"; break; case 6 : cout << "Friday"; break; case 7 : cout << "Saturday"; break;default : cout << "Not an allowable day number"; break; } cout << "nn"; return 0;} http://eglobiotraining.com
  35. 35. #include <iostream>#include <math.h>#include<stdio.h>using namespace std;int main(){ int number1; int number2; int number3; int number4; float Circle; float Rectangle; float Triangle; int choice; double pi; float length; float width; float base; float height; float radius;number1 = 1;number2 = 2;number3 = 3;number4 = 4;pi = 3.14159;Circle = pi * radius * radius;Rectangle = length * width;Triangle = base * height * .5; http://eglobiotraining.com
  36. 36. cout << "Geometry Calculator" << endl;cout << "1. Calculate the Area of a Circle" << endl;cout << "2. Calculate the Area of a Rectangle" << endl;cout << "3. Calculate the Area of a Triangle" << endl;cout << "4. Quit" << endl << endl;cout << "Enter your choice (1-4):" << endl;cin >> choice;switch(choice){ case 1 : cout << "Enter the radius of the circle:" << endl; cin >> radius; case 2 : cout << "Enter the length of the rectangle:" << endl; cin >> length; cout << "Enter the width of the rectangle:" << endl; cin >> width; case 3 : cout << "Enter the height of the triangle:" << endl; cin >> height; case 4 : cout << "Goodbye!" << endl; default: cout << "5 is not a valid entry." << endl;}return 0;} http://eglobiotraining.com
  37. 37. #include <stdio.h>#include <iostream>using namespace std;int main(){ int nr = 0; char ch = 0; //This uses numbers cout << "Type in number 1 or 2: "; cin >> nr; switch(nr) { case 1: cout << "The number typed was 1!n"; break; case 2: cout << "The number typed was 2!n"; break; default: cout << "You didnt type in 1 or 2!n"; break; } http://eglobiotraining.com
  38. 38. //This uses lowercase characters only cout << "nn Type in character a or b: "; cin >> ch; switch(ch) { case a: cout << "You typed in an A!n"; break; case b: cout << "You typed in an B!n"; break; default: cout << "You didnt type in a or b!n"; break; } //This uses lowercase an uppercase characters cout << "nnType in lowercase or uppercase a or b: "; cin >> ch; switch(ch) { case a: case A: cout << "You typed in an A!n"; break; case b: case B: cout << "You typed in an B!n"; break; default: cout << "You didnt type in a or b!n"; break; } getchar(); // wait for a key to be pressed. return 0;} http://eglobiotraining.com
  39. 39. #include <iostream>#include <string>using namespace std;int main(){string choice = "y";while ( choice == "y" ){cout << "Say something about this" << endl;cout << "Leave your comments." << endl;cin >> choice;}cout << "You exited the loop" << endl;} http://eglobiotraining.com
  40. 40. #include <iostream>using namespace std;int main(){ int a; cout << "How long do you want this program to run? "; cin >> a; while (a){ cout << a << "n"; --a; } return 0;} http://eglobiotraining.com
  41. 41. int main(){ int x = 0; /* Dont forget to declare variables */ while ( x < 16 ) { /* While x is less than 16*/ printf( "%dn", x ); x++; /* Update x so the condition can be met eventually */ } getchar();} http://eglobiotraining.com
  42. 42. #include <stdio.h>int main(){ int x; x = 0; do { /* "He who hesitates is lost.-Proverb" is printed at least one time even though the condition is false */ printf( "He who hesitates is lost.-Proverb" ); } while ( x != 0 ); getchar();} http://eglobiotraining.com
  43. 43. #include <stdio.h>int main(){ int i, count; printf("Enter the number of the item: "); scanf("%d", &count, 1); for(i = 1; i <= count; i = i + 1) printf(" %d", i); printf("n"); return 0;} http://eglobiotraining.com
  44. 44. http://eglobiotraining.com
  45. 45. http://eglobiotraining.com
  46. 46. http://eglobiotraining.com
  47. 47. http://eglobiotraining.com
  48. 48. http://eglobiotraining.com
  49. 49. http://eglobiotraining.com
  50. 50. http://eglobiotraining.com
  51. 51. http://eglobiotraining.com
  52. 52. http://eglobiotraining.com
  53. 53. http://eglobiotraining.com
  54. 54. http://eglobiotraining.com
  55. 55. Switch Statement:• The first line contains the basic keyword,usually switch, case or select, followed by anexpression which is often referred to as the controlexpression or control variable of the switch statement.• Subsequent lines define the actual cases (thevalues) with corresponding sequences of statementsthat should be executed when a match occurs. http://eglobiotraining.com
  56. 56. Each alternative begins with the particular value, orlist of values (see below), that the control variable maymatch and which will cause the control to go to thecorresponding sequence of statements. The value (orlist/range of values) is usually separated from thecorresponding statement sequence by a colon or animplication arrow. In many programming languages, everycase must also be preceded by a keyword suchas case or when. An optional default case is typically alsoallowed, specified by a default or else keyword; this isexecuted when none of the other cases matches the controlexpression. http://eglobiotraining.com
  57. 57. • When the program starts the user is promptedto insert a starting number for the countdown. Thenthe while loop begins, if the value entered by the userfulfills the condition n>0 (that n is greater than zero)the block that follows the condition will be executedand repeated while the condition (n>0) remains beingtrue.• The easiest way to think of the loop in theprogramming is when it reaches the brace at the end itjumps back up to the beginning of the loop, whichchecks the condition again and decides whether torepeat the block another time, or stop and move to thenext statement after the block. http://eglobiotraining.com
  58. 58. Submitted by:Jenica H. TubungbanuaBM10203 http://eglobiotraining.com

×