Mark asoi ppt

225 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
225
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
4
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Mark asoi ppt

  1. 1. Switch case And LoopingSubmitted by:Mark Kazuyoshi P. Asoi
  2. 2. We first define the word “Programming”, it is a computer languageprogrammers use to develop applications, scripts, or other set ofinstructions for a computer to execute. Programming is instructing a computer to do something for you with the help of a Programming language. The role of a Programming language can be described in two ways:Technical: It is a means for instructing aComputer to perform TasksConceptual: It is a framework within whichwe organize our ideas about things andprocesses. http://eglobiotraining.com 2
  3. 3. Computer Programming (often shortenedto Programming or coding) is the process of designing,writing, testing, debugging, and maintaining the sourcecode of computer programs. This source code is written in one ormore Programming Language (such as Java, C++, C#, Python,etc.). The purpose of Programming is to create a set ofinstructions that computers use to perform specific operations orto exhibit desired behaviors. The process of writing source codeoften requires expertise in many different subjects, includingknowledge of the application domain,specialized algorithms and formal logic. http://eglobiotraining.com 3
  4. 4. As an individual, I have learned that Programming is a very broad because itcomposes many scripts, applications and can be used to run a program thathas been part of the programming language. A Programming language should both provide means to describe primitive data and procedures and means to combine and abstract those into more complex ones.The distinction between data and procedures is not that clear cut. In manyProgramming languages, procedures can be passed as data (to be applied to“real” data) and sometimes processed like “ordinary” data. Conversely``ordinary data can be turned into procedures by an evaluation mechanism. http://eglobiotraining.com 4
  5. 5. At first, Programming is confusing because you have so much tounderstand about codes that will enable to run a program.Programming has applications and program development, the bestexample for this is the Internet browser… Programming is a creative process done by programmers to instruct a computer on how to do a task. Programming languages let you use them in different ways, e.g adding numbers, etc… or storing data on disk for later retrieval. http://eglobiotraining.com 5
  6. 6. You have to consider languages to run or write your own program,most demanded language in Programming is the DEV C++ (a full-featured Integrated Development Environment (IDE)). C++ is one of the most used Programming languages in the world. Also known as "C with Classes". New to Programming or thinking about it? It might surprise you to know that there are many programmers who program just for fun and it can lead to a job. http://eglobiotraining.com 6
  7. 7. Within software engineering, Programming (the implementation)is regarded as one phase in a software development process.There is an ongoing debate on the extent to which the writing ofprograms is an art form, a craft or an engineering discipline.] Ingeneral, good Programming is considered to be the measuredapplication of all three, with the goal of producing an efficient andevolvable software solution (the criteria for "efficient" and"evolvable" vary considerably). The discipline differs from manyother technical professions in that programmers, in general, donot need to be licensed or pass any standardized (orgovernmentally regulated) certification tests in order to callthemselves "programmers" or even "software engineers."Because the discipline covers many areas, which may or may notinclude critical applications, it is debatable whether licensing isrequired for the profession as a whole. In most cases, thediscipline is self-governed by the entities which require theProgramming, and sometimes very strict environments aredefined (e.g. United States Air Force use of AdaCore and securityclearance). However, representing oneself as a "ProfessionalSoftware Engineer" without a license from an accreditedinstitution is illegal in many parts of the world. http://eglobiotraining.com 7
  8. 8. Another ongoing debate is the extent to which the Programminglanguage used in writing computer programs affects the form thatthe final program takes. This debate is analogous to thatsurrounding the Sapir–Whorf hypothesis inlinguistics and cognitive science, which postulates that aparticular spoken languages nature influences the habitualthought of its speakers. Different language patterns yield differentpatterns of thought. This idea challenges the possibility ofrepresenting the world perfectly with language, because itacknowledges that the mechanisms of any language conditionthe thoughts of its speaker community. http://eglobiotraining.com 8
  9. 9. Switch CaseSwitch case statements are a substitute for long if statements thatcompare a variable to several "integral" values ("integral" values aresimply values that can be expressed as an integer, such as the value of achar). but there is really very little left to know about Programming itself. Most of the rest of C is concerned with making the business of Programming simpler. A good example of this is the switch construction. http://eglobiotraining.com 9
  10. 10. basic format for using switch caseswitch ( <variable> ) {case this-value: Code to execute if <variable> == this-value break;case that-value: Code to execute if <variable> == that-value break;...default: Code to execute if <variable> does not equal the value following any ofthe cases break;}The value of the variable given into switch is compared to the valuefollowing each of the cases, and when one value matches the valueof the variable, the computer continues executing the program fromthat point. http://eglobiotraining.com 10
  11. 11. The condition of a switch statement is avalue. The case says that if it has the valueof whatever is after that case then dowhatever follows the colon. The break is used to break out of the case statements. An important thing to note about the switch statement is that the case values may only be constant integral expressions. http://eglobiotraining.com 11
  12. 12. Break is a keyword that breaks out of the codeblock, usually surrounded by braces, which it is in.In this case, break prevents the program from fallingthrough and executing the code in all the other casestatements. The default case is optional, but it is wise to include it as it handles any unexpected cases. Switch statements serves as a simple way to write long if statements when the requirements are met. Often it can be used to process input from a user. http://eglobiotraining.com 12
  13. 13. This shows how would you use a Switch in a Program#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; } cin.get();} http://eglobiotraining.com 13
  14. 14. That program will compile, but cannot be run until the undefinedfunctions are given bodies, but it serves as a model (albeitsimple) for processing input. If you do not understand this then trymentally putting in if statements for the case statements. Defaultsimply skips out of the switch case construction and allows theprogram to terminate naturally. If you do not like that, then you canmake a loop around the whole thing to have it wait for valid input.You could easily make a few small functions if you wish to test thecode.but there is really very little left to know about Programming itself.Most of the rest of C is concerned with making the business ofProgramming simpler. A good example of this isthe switch construction. http://eglobiotraining.com 14
  15. 15. LoopingLoops are used to repeat a block of code. Being able to have yourprogram repeatedly execute a block of code is one of the most basicbut useful tasks in Programming -- many programs or websites thatproduce extremely complex output (such as a message board) arereally only executing a single task many times. In a loop structure, the program asks a question, and if the answer requires an action, it is performed and the original question is asked again until the answer is such that the action is no longer required.In a loop structure, the program asks a question, and ifthe answer requires an action, it is performed and theoriginal question is asked again until the answer is suchthat the action is no longer required. http://eglobiotraining.com 15
  16. 16. (They may be executing a small number of tasks, but inprinciple, to produce a list of messages only requiresrepeating the operation of reading in some data anddisplaying it.) Now, think about what this means: a loop letsyou write a very simple statement to produce a significantlygreater result simply by repetition. One Caveat: before going further, you should understand the concept of C++s true and false, because it will be necessary when working with loops (the conditions are the same as with if statements). Three types of Loops: for, while, and do.. http://eglobiotraining.com 16
  17. 17. FORFor ( variable initialization; condition; variable update ) { Code to execute while the condition is true} http://eglobiotraining.com 17
  18. 18. The variable initialization allows you to either declare avariable and give it a value or give a value to an alreadyexisting variable. Second, the condition tells the program thatwhile the conditional expression is true the loop shouldcontinue to repeat itself. The variable update section is theeasiest way for a for loop to handle changing of the variable.It is possible to do things like x++, x = x + 10, or even x =random ( 5 ), and if you really wanted to, you could call otherfunctions that do nothing to the variable but still have a usefuleffect on the code. Notice that a semicolon separates each ofthese sections, that is important. Also note that every singleone of the sections may be empty, though the semicolons stillhave to be there. If the condition is empty, it is evaluatedas true and the loop will repeat until something elsestops it. http://eglobiotraining.com 18
  19. 19. #include <iostream>using namespace std; // So the program can see cout and endlint main(){ // The loop goes while x < 10, and x increases by one every loop for ( int x = 0; x < 10; x++ ) { // Keep in mind that the loop condition checks // the conditional statement before it loops again. // consequently, when x equals 10 the loop breaks. // x is updated before the condition is checked. cout<< x <<endl; } cin.get();}This program is a very simple example of a for loop. x is set to zero,while x is less than 10 it calls cout<< x <<endl; and it adds 1 to x untilthe condition is met. Keep in mind also that the variable is incrementedafter the code in the loop is run for the first time. http://eglobiotraining.com 19
  20. 20. WHILEThe basic structure: While ( condition ) { Code to execute while the condition is true } The true represents a boolean expression which could be x == 1 or while ( x != 7 ) (x does not equal 7). It can be any combination of boolean statements that are legal. Even, (while x ==5 || v == 7) which says execute the code while x equals five or while v equals 7. Notice that a while loop is the same as a for loop without the initialization and update sections. However, an empty condition is not legal for a while loop as it is with a for loop. http://eglobiotraining.com 20
  21. 21. #include <iostream>using namespace std; // So we can see cout and endlint main(){ int x = 0; // Dont forget to declare variables while ( x < 10 ) { // While x is less than 10 cout<< x <<endl; x++; // Update x so the condition can be met eventually } cin.get();}The easiest way to think of the loop is that when it reaches the brace atthe end it jumps back up to the beginning of the loop, which checks thecondition again and decides whether to repeat the block another time, orstop and move to the next statement after the block. http://eglobiotraining.com 21
  22. 22. DO.. WHILE The Structure: do { } while ( condition ) ; http://eglobiotraining.com 22
  23. 23. The condition is tested at the end of the block instead ofthe beginning, so the block will be executed at least once.If the condition is true, we jump back to the beginning ofthe block and execute it again. A do.. while loop is basically a reversed while loop. A while loop says "Loop while the condition is true, and execute this block of code", a do.. while loop says "Execute this block of code, and loop while the condition is true". http://eglobiotraining.com 23
  24. 24. #include <iostream>using namespace std;int main(){ int x; x = 0; do { // "Hello, world!" is printed at least one time // even though the condition is false cout<<"Hello, world!n"; } while ( x != 0 ); cin.get();}Keep in mind that you must include a trailing semi-colon after thewhile in the above example. A common error is to forget that ado..while loop must be terminated with a semicolon (the other loopsshould not be terminated with a semicolon, adding to theconfusion). Notice that this loop will execute once, because itautomatically executes before checking the condition. http://eglobiotraining.com 24
  25. 25. Condition andExplanation of thePrograms that havebeen tested http://eglobiotraining.com 25
  26. 26. Switch case 1 #include <stdlib.h> #include <stdio.h> int main(void) { int n; printf("Please enter a number: "); scanf("%d", &n); switch (n) { case 1: { printf("n is equal to 1!n"); break; } case 2: { printf("n is equal to 2!n"); break; } case 3: { printf("n is equal to 3!n"); break; } default: { printf("n isnt equal to 1, 2, or 3.n"); break; } } system("PAUSE"); return 0; } http://eglobiotraining.com 26
  27. 27. Switch case 2 #include <stdio.h> main() { int grade; printf ("Input grade :"); scanf("%d", & grade); switch (grade) { case 1: printf("Fall (F)n");break; case 2: printf("Bad (D)n");break; case 3: printf("Good (C)n");break; case 4: printf("Very Good (B)n");break; case 5: printf("Excellent (A)n");break; default: printf("You have inputted false graden"); break; // break isn’t necessary here } } http://eglobiotraining.com 27
  28. 28. #include <iostream>Switch case 3 using namespace std; int main () { int score; cout << "What was your score?"; cin >> score; if (score <= 25) { cout << "nOuch, less than 25...!"; } else if (score <= 50) { cout << "nYou score aint great mate.."; } else if (score <= 75) { cout << "nYour pretty good, wel done man!"; } else if (score <= 100) { cout << "nYou got to the top!!!"; } else { cout << "nYou cant score higher than 100!!! Cheater!!!!"; } cin.ignore(); cin.get(); return 0; } http://eglobiotraining.com 28
  29. 29. Switch case 4 #include <iostream> using namespace std; int main(void) { char grade; cout << "Enter your grade: "; cin >> grade; switch (grade) { case A: cout << "Your average must be between 90 - 100" << endl; break; case B: cout << "Your average must be between 80 - 89" << endl; break; case C: cout << "Your average must be between 70 - 79" << endl; break; case D: cout << "Your average must be between 60 - 69" << endl; break; default: cout << "Your average must be below 60" << endl; } return 0; } http://eglobiotraining.com 29
  30. 30. Switch case 5 #include <stdio.h> #include <math.h> main() { int i, n, prime=1; // prime is true printf("Input natural number :"); scanf("%d", &n); for( i=2; i<= n-1; i++) { if( n % i == 0 ) { // also possible to state if(!(n % i)) prime =0; // prime is now false break; } } if( prime ) printf("%d is prime number !n", n); else printf("%d isn’t prime number!n", n); } http://eglobiotraining.com 30
  31. 31. Looping Statement 1 #include <iostream> using namespace std; // So the program can see cout and endl int main() { // The loop goes while x < 10, and x increases by one every loop for ( int x = 0; x < 10; x++ ) { // Keep in mind that the loop condition checks // the conditional statement before it loops again. // consequently, when x equals 10 the loop breaks. // x is updated before the condition is checked. cout<< x <<endl; } cin.get(); } http://eglobiotraining.com 31
  32. 32. Looping Statement 2 #include <stdio.h> main() { float price; short quantity; char answer; do { printf("Enter price quantity: "); scanf("%f %hi", &price, &quantity); printf("The total for this item is $%6.2f.n", price * quantity); printf("Another (Y/N)? "); scanf(" %c", &answer); }while ("answer == Y | | answer == y"); printf("Thank you for your patronage.n"); } http://eglobiotraining.com 32
  33. 33. Looping Statement 3 #include <stdio.h> main() { float price; short quantity; char answer; printf("Do you wish to enter a purchase (Y/N)? "); scanf(" %c", &answer); while ("answer == Y | | answer == y") { printf("Enter price quantity: "); scanf("%f %hi", &price, &quantity); printf("The total for this item is $%6.2f.n", price * quantity); printf("Another (Y/N)? "); scanf(" %c", &answer); } printf("Thank you for your patronage.n"); } http://eglobiotraining.com 33
  34. 34. Looping Statement 4 #include<iostream> using namespace std; int main() { int n; cout<<"Enter the starting number>"; cin>>n; while(n>0){ cout<<n<<","; --n; } cout<<"FIRE!n"; return 0; } http://eglobiotraining.com 34
  35. 35. Looping Statement 5 // // Demonstrates do while #include <iostream.h> int main() { int counter; cout << "How many hellos? "; cin >> counter; do { cout << "Hellon"; counter--; } while (counter >0 ); cout << "Counter is: " << counter << endl; return 0; } http://eglobiotraining.com 35
  36. 36. An OutputProgram usingDev C++ http://eglobiotraining.com 36
  37. 37. Because of so many experiences I had before this program run,I found Programming is also interesting for the more you arepracticing to make a program run, the more questions that cameup in my mind and try something that will fit to this or enteringnew codes to make matrix etc… that I know is possible. http://eglobiotraining.com 37
  38. 38. In this switch case missing out a break statement causes control tofall through to the next case label. Switches can always be replacedby nested if-else statements, but in some cases this may be moreclumsy. Each break statement terminates theenclosing switch statement. Control flow continues with the firststatement http://eglobiotraining.com 38
  39. 39. The switch statement can include any number of case instances, butno two case constants within the same switch statement can have thesame value. Execution of the statement body begins at the selectedstatement and proceeds until the jump-statement transfers control outof the case body. http://eglobiotraining.com 39
  40. 40. Unlike if-then and if-then-else statements, the switch statement can havea number of possible execution paths, A switch works withthe byte, short, char, and int primitive data types. http://eglobiotraining.com 40
  41. 41. Switch case is substitute for long if statements that compare a variableto several "integral" values that can be expressed as an integer, http://eglobiotraining.com 41
  42. 42. When I learned that Programming is very sensitive and at the same timevery detailed when it comes to entering codes, I make sure that it isclear means that I put everything important codes in it so that theprogram would run. http://eglobiotraining.com 42
  43. 43. I noticed that sometimes if the program does not run, it is becausesome braces are not included and I accidentally put braces on thesame line and it causes the program not to read its contents.Programming is sensitive, when there is missing variable or braces orsome words it does not run. http://eglobiotraining.com 43
  44. 44. Being able to have your program repeatedly execute a block ofcode is one of the most basic but useful tasks in Programming http://eglobiotraining.com 44
  45. 45. I have came up with this by just starting to write this code: #include<iostream> and then enter the succeeding codes, compiled and run. http://eglobiotraining.com 45
  46. 46. The do...while loop executes the body of the loop before its conditionis tested and ensures that the body always executes at least one time.What if you want to ensure that Hello is always printed at least once?The while loop cant accomplish this, because the if condition is testedbefore any printing is done. You can force the issue withan if statement just before entering the while: http://eglobiotraining.com 46
  47. 47. Submitted to: Professor. Erwin GlobioOfficial Website: http://eglobiotraining.com/ http://eglobiotraining.com 47

×