SlideShare une entreprise Scribd logo
1  sur  23
PROGRAMMING



  http://eglobiotraining.com
Switch case
Looping




          http://eglobiotraining.com
   In programming, a switch, case, select or inspect stat
    ement is a type of selection control mechanism that exis
    ts in most imperative programming languages such a
    s Pascal, Ada, C/C++, C#, Java, and so on. It is also inc
    luded in several other types of Programming languages.
    Its purpose is to allow the value of a variable or express
    ion to control the flow of program execution via a multw
    ay branch (or "go to", one of several labels). The main r
    easons for using a switch include improving clarity, by r
    educing otherwise repetitive coding, and (if the heuristic
    s permit) also offering the potential for faster execution t
    hrough easier compiler optimization in many cases.




                        http://eglobiotraining.com
   Switch case statements are a substitute for long if statements
    that compare a variable to several "integral" values ("integral"
    values are simply values that can be expressed as an integer
    , such as the value of a char). The basic format for using the s
    witch case in the programming is outlined below. The value of
    the variable given into switch is compared to the value followi
    ng each of the cases, and when one value matches the value
    of the variable, the computer continues executing the program
    from that point.
   The switch-case statement is a multi-way decision statement
    . Unlike the multiple decision statement that can be created us
    ing if-else, the switch statement evaluates the conditional exp
    ression and tests it against numerous constant values. The br
    anch corresponding to the value that the expression matches i
    s taken during execution.


                           http://eglobiotraining.com
   Switch is used to choose a fragment of template d
    epending on the value of an expression
   This has a similar function as the If condition - but i
    t is more useful in situations when there is many p
    ossible values for the variable. Switch will evaluate
    one of several statements, depending on the value
    of a given variable. If no given value matches the v
    ariable, the default statement is executed.
   The value of the expressions in a switch-case stat
    ement must be an ordinal type i.e. integer, char, sh
    ort, long, etc. Float and double are not allowed.

                        http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
#include <iostream>                                                                     // switch statement based on the choice variable
#include <stdlib.h>
using namespace std;
                                                                                         switch (choice) // notice no semicolon
void welcome();                                                                          {
char getChar();                                                                             case 'A': // choice was the letter A
void displayResponse(char choice);                                                          case 'a': // choice was the letter a
int main(int argc, char *argv[])
{
                                                                                             cout << "your awesome dude.nn";
  char choice; // declares the choice variable                                               break; // this ends the statements for case A/a
  welcome(); // This calls the welcome function                                             case 'B': // choice was the letter b
  choice = getChar(); // calls getChar and returns the value for choice                     case 'b': // choice was the letter b
  displayResponse(choice); // passes choice to displayResponse function
                                                                                             cout << "you will find your lovelife.nn";
  system("PAUSE");                                                                           break; // this ends the statements for case B/b
  return 0;                                                                                 case 'C': // choice was the letter C
} // end main                                                                               case 'c': // choice was the letter c
// welcome function displays an opening message to
// explain the program to the user
                                                                                             cout << "your will won the lottery.nn";
void welcome()                                                                               break; // this ends the statements for case C/c
{                                                                                             case 'D': // choice was the letter D
  cout << "This program displays different messages dependingn";                           case 'd': // choice was the letter d
  cout << "on which letter is entered by the user.n";
  cout << "Pick a letter a, b, c or d to see whatn";
                                                                                             cout << "your so ugly!!.nn";
  cout << "the program will say.nn";                                                       break; // this ends the statements for case D/d
} // end of welcome function                                                                default: // used when choice falls out of the cases
// getChar asks the user for a letter a, b or c.                                       covered above
// The character is returned to where the function was called.                               cout << "You didn't pick a letter a, b or c.nn";
char getChar()
{
                                                                                             again = getChar(); // gives the user another try
    char response; // declares variable called response                                      displayResponse(again); // recalls
  cout << "Please type a letter a, b, c and d: "; // prompt for letter                 displayResponse with new character
  cin >> response; // gets input from user and assigns it to response                        break;
  return response; // sends back the response value                                      } // end of switch statement
} // end getChar function
// displayResponse function takes the char variable and uses it
                                                                                       } // end displayResponse function
// to determine which set of tasks will be performed.
void displayResponse(char choice)
{
  char again;


                                                                          http://eglobiotraining.com
http://eglobiotraining.com
There may be a situation when you need to execute a block
of code several number of times. In general statements are
executed sequentially: The first statement in a function is
executed first, followed by the second, and so on.

Programming languages provide various control structures
that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group
of statements multiple times and following is the general from
of a loop statement in most of the programming languages.



                       http://eglobiotraining.com
C++ programming language provides
following types of loop to handle
looping requirements:

               WHILE                       DO
   FOR                                    WHILE
               LOOP
   LOOP                                   LOOP


             http://eglobiotraining.com
   A for loop is a repetition control structure that
    allows you to efficiently write a loop that need
    s to execute a specific number of times.
   The statements in the for loop repeat continu
    ously for a specific number of times. The wh
    ile and do-while loops repeat until a certain c
    ondition is met. The for loop repeats until a s
    pecific count is met. Use a for loop when the
    number of repetition is know, or can be suppli
    ed by the user.

                    http://eglobiotraining.com
#include <iostream>                                                       }
#include <cmath>
using namespace std;                                                      cout <<"nSeconds
                                                                          falling distancen";
                                                                          cout <<"---------------------------------------n";
//prototype
int fallingdistance();                                                     for ( count = 1; count <= time; count++)
                                                                           {
//main function                                                                           distance = .5 * 9.8 *
int main()                                                   pow(time, 2.0);
                                                                                          cout << count << "
{                                                            " << distance <<" meters"<< endl;
            int count = 1 ;
            int time;                                                    }
            double distance ;                                  system ("pause");
            cout << "Please enter time in 1                              return 0;
through 10 seconds.nn";                                }
                                                         // falling distance function for a return value in seconds
                                                         transfer to time
  time = fallingdistance();                              int fallingdistance ()
                                                         {
            while ( time < 1 || time > 10)                               int seconds;
            { cout << "Must enter between 1 and                          cin >> seconds;
10 seconds, please re-enter.n";                                         return seconds;
                                                         }
               time = fallingdistance();   http://eglobiotraining.com
http://eglobiotraining.com
 The while loop allows programs to repeat
  a statement or series of statements, over a
  nd over, as long as a certain test condition
  is true.
 The while loop can be used if you don’t kn
  ow how many times a loop must run.
 A while loop statement repeatedly execute
  s a target statement as long as a given co
  ndition is true.

                 http://eglobiotraining.com
#include <iostream.h>

int main(void) {
    int x = 0;
    int y = 0;
    bool validNumber = false;

    while (validNumber == false) {
        cout << "Please enter an integer between 1 and 10: ";
        cin >> x;
        cout << "You entered: " << x << endl << endl;

        if ((x < 1) || (x > 10)) {
             cout << "Your value for x is not between 1 and 10!"
              << endl;
             cout << "Please re-enter the number!" << endl << endl;
        }
        else
             validNumber = true;
    }

    cout << "Thank you for entering a valid number!" << endl;

    return 0;
     }
                                                      http://eglobiotraining.com
http://eglobiotraining.com
   In most computer programming languages, a do while
    loop, sometimes just called a while loop, is a control f
    low statement that allows code to be executed once b
    ased on a given Boolean condition.
   The do while construct consists of a process symbol a
    nd a condition. First, the code within the block is execu
    ted, and then the condition is evaluated. If the conditio
    n is true the code within the block is executed again. T
    his repeats until the condition becomes false. Because
    do while loops check the condition after the block is ex
    ecuted, the control structure is often also known as a p
    ost-test loop. Contrast with the while loop, which test
    s the condition before the code within the block is exec
    uted.

                        http://eglobiotraining.com
   Unlike for and while loops, which test the loop co
    ndition at the top of the loop, the do...while loop c
    hecks its condition at the bottom of the loop.
   A do...while loop is similar to a while loop, except
    that a do...while loop is guaranteed to execute at l
    east one time.
   The do-while loop is similar to the while loop, exc
    ept that the test condition occurs at the end of the
    loop. Having the test condition at the end, guarant
    ees that the body of the loop always executes at le
    ast one time.

                       http://eglobiotraining.com
   #include <iostream>
   using namespace std;
   main()
   { int num1, num2;
   char again = 'y';

   while (again == 'y' || again == 'Y') {
   cout << "Enter a number: ";
   cin >> num1;
   cout << "Enter another number: ";
   cin >> num2;
   cout << "Their sum is " << (num1 + num2) << endl;
   cout << "Do you want to do this again? ";
   cin >> again; }
   return 0;
   }

                               http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com

Contenu connexe

Tendances (19)

[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
Ref cursor
Ref cursorRef cursor
Ref cursor
 
Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)Final project powerpoint template (fndprg) (1)
Final project powerpoint template (fndprg) (1)
 
Final exam
Final examFinal exam
Final exam
 
Perl_Part2
Perl_Part2Perl_Part2
Perl_Part2
 
Lazy Data Using Perl
Lazy Data Using PerlLazy Data Using Perl
Lazy Data Using Perl
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scope
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
 
Unit 2.5
Unit 2.5Unit 2.5
Unit 2.5
 
C if else
C if elseC if else
C if else
 
C operators
C operatorsC operators
C operators
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
Presentation 2
Presentation 2Presentation 2
Presentation 2
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
1584503386 1st chap
1584503386 1st chap1584503386 1st chap
1584503386 1st chap
 
Module Magic
Module MagicModule Magic
Module Magic
 
A Spin-off: Firebird Checked by PVS-Studio
A Spin-off: Firebird Checked by PVS-StudioA Spin-off: Firebird Checked by PVS-Studio
A Spin-off: Firebird Checked by PVS-Studio
 
Elements of c program....by thanveer danish
Elements of c program....by thanveer danishElements of c program....by thanveer danish
Elements of c program....by thanveer danish
 

En vedette

Ulyanovsk presentation
Ulyanovsk presentationUlyanovsk presentation
Ulyanovsk presentationgoogle_mazanov
 
Go kostroma presentation
Go kostroma presentationGo kostroma presentation
Go kostroma presentationgoogle_mazanov
 
Business case channel financing ver 1.5
Business case   channel financing ver 1.5Business case   channel financing ver 1.5
Business case channel financing ver 1.5Partho Chakraborty
 
Regulatory reporting by banks to rbi
Regulatory reporting by banks to rbiRegulatory reporting by banks to rbi
Regulatory reporting by banks to rbiPartho Chakraborty
 
Global remittances product writeup
Global remittances   product writeupGlobal remittances   product writeup
Global remittances product writeupPartho Chakraborty
 
Smart entry for master
Smart entry for masterSmart entry for master
Smart entry for masterShalman Farisy
 

En vedette (7)

Sls backed mtn ver 1.0
Sls backed mtn ver 1.0Sls backed mtn ver 1.0
Sls backed mtn ver 1.0
 
Ulyanovsk presentation
Ulyanovsk presentationUlyanovsk presentation
Ulyanovsk presentation
 
Go kostroma presentation
Go kostroma presentationGo kostroma presentation
Go kostroma presentation
 
Business case channel financing ver 1.5
Business case   channel financing ver 1.5Business case   channel financing ver 1.5
Business case channel financing ver 1.5
 
Regulatory reporting by banks to rbi
Regulatory reporting by banks to rbiRegulatory reporting by banks to rbi
Regulatory reporting by banks to rbi
 
Global remittances product writeup
Global remittances   product writeupGlobal remittances   product writeup
Global remittances product writeup
 
Smart entry for master
Smart entry for masterSmart entry for master
Smart entry for master
 

Similaire à Jangsehyun final requirement

Final requirement in programming vinson
Final requirement in programming  vinsonFinal requirement in programming  vinson
Final requirement in programming vinsonmonstergeorge
 
My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)aeden_brines
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
 
presentation_functions_1443207686_140676.ppt
presentation_functions_1443207686_140676.pptpresentation_functions_1443207686_140676.ppt
presentation_functions_1443207686_140676.pptSandipPradhan23
 
Final requirement in programming niperos
Final requirement in programming   niperosFinal requirement in programming   niperos
Final requirement in programming niperosmarkings17
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupSyedHaroonShah4
 
Fundamentals of programming angeli
Fundamentals of programming angeliFundamentals of programming angeli
Fundamentals of programming angelibergonio11339481
 
Lecture#4 Algorithm and computing
Lecture#4 Algorithm and computingLecture#4 Algorithm and computing
Lecture#4 Algorithm and computingNUST Stuff
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functionsmussawir20
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingChaAstillas
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operatorSAFFI Ud Din Ahmad
 

Similaire à Jangsehyun final requirement (20)

Final requirement in programming vinson
Final requirement in programming  vinsonFinal requirement in programming  vinson
Final requirement in programming vinson
 
My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
presentation_functions_1443207686_140676.ppt
presentation_functions_1443207686_140676.pptpresentation_functions_1443207686_140676.ppt
presentation_functions_1443207686_140676.ppt
 
C++ theory
C++ theoryC++ theory
C++ theory
 
Final requirement in programming niperos
Final requirement in programming   niperosFinal requirement in programming   niperos
Final requirement in programming niperos
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
Pl sql programme
Pl sql programmePl sql programme
Pl sql programme
 
Pl sql programme
Pl sql programmePl sql programme
Pl sql programme
 
Fundamentals of programming angeli
Fundamentals of programming angeliFundamentals of programming angeli
Fundamentals of programming angeli
 
Lecture#4 Algorithm and computing
Lecture#4 Algorithm and computingLecture#4 Algorithm and computing
Lecture#4 Algorithm and computing
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Final requirement
Final requirementFinal requirement
Final requirement
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Php Reusing Code And Writing Functions
Php Reusing Code And Writing FunctionsPhp Reusing Code And Writing Functions
Php Reusing Code And Writing Functions
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
API
APIAPI
API
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
 
Looping statements
Looping statementsLooping statements
Looping statements
 

Jangsehyun final requirement

  • 2. Switch case Looping http://eglobiotraining.com
  • 3. In programming, a switch, case, select or inspect stat ement is a type of selection control mechanism that exis ts in most imperative programming languages such a s Pascal, Ada, C/C++, C#, Java, and so on. It is also inc luded in several other types of Programming languages. Its purpose is to allow the value of a variable or express ion to control the flow of program execution via a multw ay branch (or "go to", one of several labels). The main r easons for using a switch include improving clarity, by r educing otherwise repetitive coding, and (if the heuristic s permit) also offering the potential for faster execution t hrough easier compiler optimization in many cases. http://eglobiotraining.com
  • 4. Switch case statements are a substitute for long if statements that compare a variable to several "integral" values ("integral" values are simply values that can be expressed as an integer , such as the value of a char). The basic format for using the s witch case in the programming is outlined below. The value of the variable given into switch is compared to the value followi ng each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point.  The switch-case statement is a multi-way decision statement . Unlike the multiple decision statement that can be created us ing if-else, the switch statement evaluates the conditional exp ression and tests it against numerous constant values. The br anch corresponding to the value that the expression matches i s taken during execution. http://eglobiotraining.com
  • 5. Switch is used to choose a fragment of template d epending on the value of an expression  This has a similar function as the If condition - but i t is more useful in situations when there is many p ossible values for the variable. Switch will evaluate one of several statements, depending on the value of a given variable. If no given value matches the v ariable, the default statement is executed.  The value of the expressions in a switch-case stat ement must be an ordinal type i.e. integer, char, sh ort, long, etc. Float and double are not allowed. http://eglobiotraining.com
  • 8. #include <iostream> // switch statement based on the choice variable #include <stdlib.h> using namespace std; switch (choice) // notice no semicolon void welcome(); { char getChar(); case 'A': // choice was the letter A void displayResponse(char choice); case 'a': // choice was the letter a int main(int argc, char *argv[]) { cout << "your awesome dude.nn"; char choice; // declares the choice variable break; // this ends the statements for case A/a welcome(); // This calls the welcome function case 'B': // choice was the letter b choice = getChar(); // calls getChar and returns the value for choice case 'b': // choice was the letter b displayResponse(choice); // passes choice to displayResponse function cout << "you will find your lovelife.nn"; system("PAUSE"); break; // this ends the statements for case B/b return 0; case 'C': // choice was the letter C } // end main case 'c': // choice was the letter c // welcome function displays an opening message to // explain the program to the user cout << "your will won the lottery.nn"; void welcome() break; // this ends the statements for case C/c { case 'D': // choice was the letter D cout << "This program displays different messages dependingn"; case 'd': // choice was the letter d cout << "on which letter is entered by the user.n"; cout << "Pick a letter a, b, c or d to see whatn"; cout << "your so ugly!!.nn"; cout << "the program will say.nn"; break; // this ends the statements for case D/d } // end of welcome function default: // used when choice falls out of the cases // getChar asks the user for a letter a, b or c. covered above // The character is returned to where the function was called. cout << "You didn't pick a letter a, b or c.nn"; char getChar() { again = getChar(); // gives the user another try char response; // declares variable called response displayResponse(again); // recalls cout << "Please type a letter a, b, c and d: "; // prompt for letter displayResponse with new character cin >> response; // gets input from user and assigns it to response break; return response; // sends back the response value } // end of switch statement } // end getChar function // displayResponse function takes the char variable and uses it } // end displayResponse function // to determine which set of tasks will be performed. void displayResponse(char choice) { char again; http://eglobiotraining.com
  • 10. There may be a situation when you need to execute a block of code several number of times. In general statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages. http://eglobiotraining.com
  • 11. C++ programming language provides following types of loop to handle looping requirements: WHILE DO FOR WHILE LOOP LOOP LOOP http://eglobiotraining.com
  • 12. A for loop is a repetition control structure that allows you to efficiently write a loop that need s to execute a specific number of times.  The statements in the for loop repeat continu ously for a specific number of times. The wh ile and do-while loops repeat until a certain c ondition is met. The for loop repeats until a s pecific count is met. Use a for loop when the number of repetition is know, or can be suppli ed by the user. http://eglobiotraining.com
  • 13. #include <iostream> } #include <cmath> using namespace std; cout <<"nSeconds falling distancen"; cout <<"---------------------------------------n"; //prototype int fallingdistance(); for ( count = 1; count <= time; count++) { //main function distance = .5 * 9.8 * int main() pow(time, 2.0); cout << count << " { " << distance <<" meters"<< endl; int count = 1 ; int time; } double distance ; system ("pause"); cout << "Please enter time in 1 return 0; through 10 seconds.nn"; } // falling distance function for a return value in seconds transfer to time time = fallingdistance(); int fallingdistance () { while ( time < 1 || time > 10) int seconds; { cout << "Must enter between 1 and cin >> seconds; 10 seconds, please re-enter.n"; return seconds; } time = fallingdistance(); http://eglobiotraining.com
  • 15.  The while loop allows programs to repeat a statement or series of statements, over a nd over, as long as a certain test condition is true.  The while loop can be used if you don’t kn ow how many times a loop must run.  A while loop statement repeatedly execute s a target statement as long as a given co ndition is true. http://eglobiotraining.com
  • 16. #include <iostream.h> int main(void) { int x = 0; int y = 0; bool validNumber = false; while (validNumber == false) { cout << "Please enter an integer between 1 and 10: "; cin >> x; cout << "You entered: " << x << endl << endl; if ((x < 1) || (x > 10)) { cout << "Your value for x is not between 1 and 10!" << endl; cout << "Please re-enter the number!" << endl << endl; } else validNumber = true; } cout << "Thank you for entering a valid number!" << endl; return 0;  } http://eglobiotraining.com
  • 18. In most computer programming languages, a do while loop, sometimes just called a while loop, is a control f low statement that allows code to be executed once b ased on a given Boolean condition.  The do while construct consists of a process symbol a nd a condition. First, the code within the block is execu ted, and then the condition is evaluated. If the conditio n is true the code within the block is executed again. T his repeats until the condition becomes false. Because do while loops check the condition after the block is ex ecuted, the control structure is often also known as a p ost-test loop. Contrast with the while loop, which test s the condition before the code within the block is exec uted. http://eglobiotraining.com
  • 19. Unlike for and while loops, which test the loop co ndition at the top of the loop, the do...while loop c hecks its condition at the bottom of the loop.  A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at l east one time.  The do-while loop is similar to the while loop, exc ept that the test condition occurs at the end of the loop. Having the test condition at the end, guarant ees that the body of the loop always executes at le ast one time. http://eglobiotraining.com
  • 20. #include <iostream>  using namespace std;  main()  { int num1, num2;  char again = 'y';  while (again == 'y' || again == 'Y') {  cout << "Enter a number: ";  cin >> num1;  cout << "Enter another number: ";  cin >> num2;  cout << "Their sum is " << (num1 + num2) << endl;  cout << "Do you want to do this again? ";  cin >> again; }  return 0;  } http://eglobiotraining.com