Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Switch case and looping statement


Published on

  • Be the first to comment

  • Be the first to like this

Switch case and looping statement

  1. 1. Final Requirement for Fundamentals of Programming
  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.
  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.
  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.
  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.
  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.
  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.
  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
  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“.
  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.
  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.
  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
  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.
  14. 14. switch (expression){case constant1:statement sequencebreak;case constant2:statement sequencebreak;case constant3:statement sequencebreak;defaultstatement sequence}
  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.
  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
  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.
  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.
  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.
  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) );}
  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.
  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.
  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.
  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
  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.
  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
  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.
  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.
  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.
  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.
  31. 31.
  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;}
  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"; 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;}
  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;
  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;}
  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; }
  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;}
  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;}
  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;}
  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();}
  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();}
  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;}
  44. 44.
  45. 45.
  46. 46.
  47. 47.
  48. 48.
  49. 49.
  50. 50.
  51. 51.
  52. 52.
  53. 53.
  54. 54.
  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.
  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.
  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.
  58. 58. Submitted by:Jenica H. TubungbanuaBM10203