Switch case looping
Upcoming SlideShare
Loading in...5
×
 

Switch case looping

on

  • 319 views

Sir, I'm sorry for passing late. I have to undergo medication Please accept my project. I am really sorry

Sir, I'm sorry for passing late. I have to undergo medication Please accept my project. I am really sorry

Statistics

Views

Total Views
319
Views on SlideShare
319
Embed Views
0

Actions

Likes
0
Downloads
3
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Switch case looping Switch case looping Presentation Transcript

    • http://eglobiotraining.com
    • We first define the word “programming”, it is acomputer language programmers use to developapplications, scripts, or other set of instructions for acomputer to execute. 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:  Technical: It is a means for instructing a Computer to perform Tasks  Conceptual: It is a framework within which we organize our ideas about things and processes. http://eglobiotraining.com
    • As an individual, I have learned thatprogramming is a very broad because it composesmany scripts, applications and can be used to run aprogram that has been part of the programminglanguage. A programming language should bothprovide means to describe primitive data andprocedures and means to combine and abstractthose into more complex ones. http://eglobiotraining.com
    • The distinction between data andprocedures is not that clear cut. In manyprogramming languages, procedures can bepassed as data (to be applied to ``real data)and sometimes processed like ``ordinary data.Conversely ``ordinary data can be turned intoprocedures by an evaluation mechanism. http://eglobiotraining.com
    • At first, programming is confusing becauseyou have so much to understand about codes thatwill enable to run a program. Programming hasapplications and program development, the bestexample for this is the Internet bowser… Programming is a creative process done byprogrammers to instruct a computer on how to doa task. Programming languages let you use them indifferent ways, e.g adding numbers, etc… orstoring data on disk for later retrieval. http://eglobiotraining.com
    • You have to consider languages to run or writeyour own program, most demanded language inprogramming is the DEV C++ (a full-featured IntegratedDevelopment Environment (IDE)). C++ is one of the most used programminglanguages in the world. Also known as "C with Classes".New to programming or thinking about it? It mightsurprise you to know that there are many programmerswho program just for fun and it can lead to a job. http://eglobiotraining.com
    • http://eglobiotraining.com
    • Switch case statements are a substitute for long ifstatements that compare a variable to several "integral"values ("integral" values are simply values that can beexpressed as an integer, such as the value of a char). –A switch, case, select or inspect statement is a type ofselection control mechanism that exists inmost imperative programming languages such as Pascal,Ada, C/C++, C#, Java, and so on. It is also included inseveral other types of languages. Its purpose is to allowthe value of a variable or expression to control the flow ofprogram execution via a multiway branch (or "goto", oneof several labels). http://eglobiotraining.com
    •  - To improve clarity, by reducing otherwise repetitive coding, and (if the heuristics permit) also offering the potential for faster execution through easier compiler optimization in many cases. http://eglobiotraining.com
    • 1. The If – else Statement-The if statement allows the programmer to make decisions within a program. - The general format of an if statement is: If (expression) statement -Where expression represents a relational, equality, or logical expression ( conditional expression) . http://eglobiotraining.com
    • If statement (two alternatives) Form: If (condition) Note: if condition evaluates to true, then statement is statement; executed and statement is skipped; otherwise, statement is else skipped and statement is executed statement;If statement (One-Alternatives) Form: If (condition) Note: if condition evaluates to true, then statement is statement; executed and statement is skippedFormat of the if statement- All if statement examples in this text indent statements. The word elseIs typed without indention on a separate line. The format of the if statementmakes its meaning apparent and is used solely to improve program readability;The format makes no difference to the computer http://eglobiotraining.com
    •  If we know how to write a C expression that is equivalent of a question such as “Is resting the value of expression to select a course of action. In C, the statement is the primary selection control structure Me: it’s hard to write c expression. So, I just copy and paste it into internet. A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely. http://eglobiotraining.com
    •  1. Open Dev C++ 2. Click File and choose New 3. Post your Statements 4. after you post your statement 5. Save it .choose file and save or 6. click f9 or you can see it shaped like a square http://eglobiotraining.com http://eglobiotraining.com/
    • basic format for using switch case: switch ( <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 of the cases break; } The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point. http://eglobiotraining.com
    • The condition of a switch statement is avalue. The case says that if it has the value ofwhatever is after that case then do whatever followsthe colon. http://eglobiotraining.com
    • The break is used to break out of the casestatements. An important thing to note about theswitch statement is that the case values may only beconstant integral expressions. http://eglobiotraining.com
    • Break is a keyword that breaks out of thecode block, usually surrounded by braces, whichit is in. In this case, break prevents the programfrom falling through and executing the code inall the other case statements. http://eglobiotraining.com
    • The default case is optional, but it is wise toinclude it as it handles any unexpected cases. Switchstatements serves as a simple way to write long ifstatements when the requirements are met. Oftenit can be used to process input from a user. http://eglobiotraining.com
    • 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
    • That program will compile, but cannot be run until theundefined functions are given bodies, but it serves as amodel (albeit simple) for processing input. If you do notunderstand this then try mentally putting in if statements forthe case statements. Default simply skips out of the switchcase construction and allows the program to terminatenaturally. If you do not like that, then you can make a looparound the whole thing to have it wait for valid input. Youcould easily make a few small functions if you wish to testthe code. http://eglobiotraining.com
    • Loops are used to repeat a block of code.Being able to have your program repeatedlyexecute a block of code is one of the most basicbut useful tasks in programming -- manyprograms or websites that produce extremelycomplex output (such as a message board) arereally only executing a single task many times. http://eglobiotraining.com
    • (They may be executing a small number oftasks, but in principle, to produce a list ofmessages only requires repeating the operationof reading in some data and displaying it.) Now,think about what this means: a loop lets youwrite a very simple statement to produce asignificantly greater result simply by repetition. http://eglobiotraining.com
    • One Caveat: before going further, you should understandthe concept of C++s true and false, because it will benecessary when working with loops (the conditions are thesame as with if statements). Three types of Loops: for, while, and do.. http://eglobiotraining.com
    • FORFor ( variable initialization; condition; variable update ) { Code to execute while the condition is true} http://eglobiotraining.com
    • The variable initialization allows you to either declare avariable and give it a value or give a value to an already existingvariable. Second, the condition tells the program that while theconditional expression is true the loop should continue to repeatitself. The variable update section is the easiest way for a for loopto handle changing of the variable. It is possible to do things likex++, x = x + 10, or even x = random ( 5 ), and if you really wanted to,you could call other functions that do nothing to the variable butstill have a useful effect on the code. Notice that a semicolon separates each of these sections, that isimportant. Also note that every single one of the sections may beempty, though the semicolons still have to be there. If thecondition is empty, it is evaluated as true and the loop will repeatuntil something else stops it. http://eglobiotraining.com
    • Example: #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(); } 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 until the condition is met. Keep in mind also that the variable is incremented after the code in the loop is run for the first time. http://eglobiotraining.com
    • 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
    • Example: #include <iostream> using namespace std; // So we can see cout and endl int 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 at the end it jumps back up to the beginning of the loop, which checks the condition again and decides whether to repeat the block another time, or stop and move to the next statement after the block. http://eglobiotraining.com
    • DO..WHILE are useful for things that want to loop at least once.The Structure: do { } while ( condition ) ; http://eglobiotraining.com
    • Notice that the condition is tested at the end of the blockinstead of the beginning, so the block will be executed atleast once. If the condition is true, we jump back to thebeginning of the block and execute it again. A do..while loopis basically a reversed while loop. A while loop says "Loopwhile the condition is true, and execute this block of code", ado..while loop says "Execute this block of code, and loopwhile the condition is true". http://eglobiotraining.com
    • Example: #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 the while in the above example. A common error is to forget that a do..while loop must be terminated with a semicolon (the other loops should not be terminated with a semicolon, adding to the confusion). Notice that this loop will execute once, because it automatically executes before checking the condition. http://eglobiotraining.com
    • http://eglobiotraining.com
    • LOOPING STATEMENT 1#include <iostream>int main(){ using namespace std; // nSelection must be declared outside do/while loop int nSelection; do { cout << "Please make a selection: " << endl; cout << "1) Addition" << endl; cout << "2) Subtraction" << endl; cout << "3) Multiplication" << endl; cout << "4) Division" << endl; cin >> nSelection; } while (nSelection != 1 && nSelection != 2 && nSelection != 3 && nSelection != 4); // do something with nSelection here // such as a switch statement return 0;} http://eglobiotraining.com
    • LOOPING STAEMENT 2 #include <iostream> using namespace std; int main() { int nSelection; double var1, var2; do { cout << "Please make a selection: " << endl; cout << "1) Addition" << endl; cout << "2) Subtraction" << endl; cout << "3) Multiplication" << endl; cout << "4) Division" << endl; cin >> nSelection; } while (nSelection != 1 && nSelection != 2 && nSelection != 3 && nSelection != 4); if (nSelection == 1) { cout << "Please enter the first whole number "; cin >> var1; cout << "Please enter the second whole number "; cin >> var2; cout << "The result is " << (var1+var2) << endl; } http://eglobiotraining.com
    • LOOPING STATEMENT 3 if (nSelection == 2) { cout << "Please enter the first whole number "; cin >> var1; cout << "Please enter the second whole number "; cin >> var2; cout << "The result is " << (var1-var2) << endl; } if (nSelection == 3) { cout << "Please enter the first whole number "; cin >> var1; cout << "Please enter the second whole number "; cin >> var2; cout << "The result is " << (var1*var2) << endl; } if (nSelection == 4) { cout << "Please enter the first whole number "; cin >> var1; cout << "Please enter the second whole number "; cin >> var2; cout << "The result is " << (var1/var2) << endl; } return 0; } http://eglobiotraining.com
    • LOOPING STATEMENT 3 #include <iostream> using namespace std; int main() { int nSelection; double var1, var2; while (1) { do { cout << "Please make a selection: " << endl; cout << "1) Addition" << endl; cout << "2) Subtraction" << endl; cout << "3) Multiplication" << endl; cout << "4) Division" << endl; cout << "5) Exit" << endl; cin >> nSelection; } while (nSelection != 1 && nSelection != 2 && nSelection != 3 && nSelection != 4 && nSelection != 5); if (nSelection == 1) { cout << "Please enter the first whole number "; cin >> var1; cout << "Please enter the second whole number "; cin >> var2; cout << "The result is " << (var1+var2) << endl; } http://eglobiotraining.com
    • LOOPING STATEMENT 4 else if (nSelection == 2) { cout << "Please enter the first whole number "; cin >> var1; cout << "Please enter the second whole number "; cin >> var2; cout << "The result is " << (var1-var2) << endl; } else if (nSelection == 3) { cout << "Please enter the first whole number "; cin >> var1; cout << "Please enter the second whole number "; cin >> var2; cout << "The result is " << (var1*var2) << endl; } else if (nSelection == 4) { cout << "Please enter the first whole number "; cin >> var1; cout << "Please enter the second whole number "; cin >> var2; cout << "The result is " << (var1/var2) << endl; }else { return 0; } }} http://eglobiotraining.com
    • LOOPING STATEMENT 5 #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
    • LOOPING STATEMENT 6#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();} http://eglobiotraining.com
    • LOOPING STATEMENT 7#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
    • SWITCH CASE 1 SWITCH CASE #include <iostream> using namespace std; int main () { int score; cout << "What was your score?"; cin >> score; if (score <= 25) { cout << "nOuch, less than 25...!"; } http://eglobiotraining.com
    • SWITCH CASE 2else 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!!!"; } http://eglobiotraining.com
    • SWITCH CASE 3 else { cout << "nYou cant score higher than 100!!! Cheater!!!!"; } cin.ignore(); cin.get(); return 0;} http://eglobiotraining.com
    • SWITCH CASE 4#include <iostream>using namespace std;int main(){cout << "Enter a number between 1 and 5!" << endl;int number;cin >> number;if(number == 1){cout << "one";}else if(number == 2){cout << "two";}else if(number == 3){cout << "three";}else if(number == 4){cout << "four";}else if(number == 5){cout << "five";}else{cout << number << " is not between 1 and 5!";}cout << endl;system("pause");} http://eglobiotraining.com
    • SWITCH CASE 5#include <iostream>using namespace std;int main(){int price_before_discount, RM, dozen, total_price;cout<< "How much is the price before discount for 1 dozen boxes of tissue?n";cout<<"RM ";cin>>price_before_discount;cout<<"nn";cout<< "How many dozen boxes of tissue you buy?n";cin>>dozen;cout<<"nn";switch (dozen){total_price = ((price_before_discount*dozen) * (95/100));case 1: cout<< "Total price is RM ";cout<<RM;cout<<"nn";break;total_price = ((price_before_discount*dozen) * (88/100));case 2: cout<< "Total price is RM ";cout<<RM;cout<<"nn";break;total_price = ((price_before_discount*dozen) * (75/100));case 3: cout<< "Total price is RM ";cout<<RM;cout<<"nn";break;total_price = ((price_before_discount*dozen) * (60/100));case 4 : cout<< "Total price is RM ";cout<<RM;cout<<"nn";break;total_price = ((price_before_discount*dozen) * (40/100));default : cout<< "Total price is RM ";cout<<RM;cout<<"nn";}return 0;} http://eglobiotraining.com
    • SWITCH CASE 6#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
    • SWITCH CASE 7#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
    • http://eglobiotraining.com
    • In this looping statement, I used “while” looping, and I choose to show MDASjust as an example for the program to run. If logical Expression evaluatesto true, the statement executes. The logical Expression is reevaluated. Thebody of the loop continues to execute until the logicalExpression is false http://eglobiotraining.com
    • 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
    • I noticed that sometimes if the program does not run, it is becausesome braces are not included and I accidentally put braces on the sameline and it causes the program not to read its contents. Programming issensitive, when there is missing variable or braces or some words itdoes not run. http://eglobiotraining.com
    • When I learned that programming is very sensitive and at the sametime very detailed when it comes to entering codes, I make surethat it is clear means that I put everything important codes in it sothat the program would run. http://eglobiotraining.com
    • So much codes that should be entered that even the spaces are neededprogramming is very specific that whatever you have entered in to it youshould specify because when the statement is false it wouldn’t let you runthe program, I have experienced it before I arrived at this result. http://eglobiotraining.com
    • Because of so many experiences I had before this program run, I foundprogramming is also interesting for the more you are practicing tomake a program run, the more questions that came up in my mind andtry something that will fit to this or entering new codes to make matrixetc… that I know is possible. http://eglobiotraining.com
    • In this switch case missing out a break statement causes control to fallthrough to the next case label. Switches can always be replaced bynested if-else statements, but in some cases this may be more clumsy.Each break statement terminates the enclosing switch statement. Controlflow continues with the first statement http://eglobiotraining.com
    • Unlike if-then and if-then-else statements, the switch statement can have anumber of possible execution paths, A switch works with the byte, short,char, and int primitive data types. http://eglobiotraining.com
    • The switch statement evaluates its expression, then executes allstatements that follow the matching case label. http://eglobiotraining.com
    • The switch statement can include any number of case instances, but notwo case constants within the same switch statement can have the samevalue. Execution of the statement body begins at the selected statementand proceeds until the jump-statement transfers control out ofthe case body. http://eglobiotraining.com
    • USERNAME : Chem Batallones http://eglobiotraining.com
    • Submitted by:Batallones, Cherimay C. BM10203 http://eglobiotraining.com