SlideShare a Scribd company logo
1 of 58
Final Requirement for Fundamentals of
                        Programming




            http://eglobiotraining.com
• A program is a sequence of instruction written to
perform a specified task with a computer. A computer
requires programs to function, typically executing the
program's instructions in central processor. The
program has an executable form that the computer can
use directly to execute the instructions. The same
program in its human-readable source code form, from
which executable programs are derived (e.g.,
compiled), enables a programmer to study and develop
its algorithms.

                    http://eglobiotraining.com
• Computer source code is often written
by computer programmers. Source code is written
in a programming language that usually follows
one of two main paradigms: imperative
programming or declarative programming. Source
code may be converted into an executable
file (sometimes called an executable program or a
binary) by a compiler and later executed by a
central processing unit.



                  http://eglobiotraining.com
A computer programmer is a person who
writes computer software. The term computer
programmer can refer to a specialist in one area
of computer programming or to a generalist who writes
code for many kinds of software. One who practices or
professes a formal approach to programming may also
be known as a programmer analyst.




                    http://eglobiotraining.com
Programmers are people who design the program
of events that turns input data into output data. It
has been proved that such a program of events can
be designed using a structure composed of
sequences, iterations and selections. Code is
merely the way that the program is described.




                   http://eglobiotraining.com
Programming is the iterative process of writing
or editing source code. Editing source code involves testing,
analyzing, and refining, and sometimes coordinating with
other programmers on a jointly developed program. A
person who practices this skill is referred to as a
computer programmer, software developer or coder. The
sometimes lengthy process of computer programming is
usually referred to as software development. The
term software engineering is becoming popular as the
process is seen as an engineering discipline.


                      http://eglobiotraining.com
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:
1. Technical: It is a means for instructing a Computer to
perform Tasks
2. Conceptual: It is a framework within which we
organize our ideas about things and processes.



                     http://eglobiotraining.com
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 many programming 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
In practicing programming one must know the basic
program a programmer use. Dev C++ can help us on
computing grades, making test questionnaires and
many more things a teacher and a student can do.
Programming is a an act of formulating a program for a
definite course of action; "the planning was more fun
than the trip itself“.




                    http://eglobiotraining.com
• C++ is a statically typed, free-form, multi-
paradigm, compiled, general-purpose programming language. It
is regarded as an intermediate-level language, as it comprises a
combination of both high-level and low-level language features.

• C++ is one of the most popular programming languages and is
implemented on a wide variety of hardware and operating
system platforms.

 • C++ has greatly influenced many other popular programming
languages, most notably C# and Java. Other successful languages
such as Objective-C use a very different syntax and approach to
adding classes to C.


                        http://eglobiotraining.com
C/C++ has a built-in multiple-branch selection
statement, called switch, which successively tests the
value of an expression against a list of integer
or character constants. When a match is found, the
statements associated with that constant are executed.




                   http://eglobiotraining.com
Programs have a need to do different things depending
on user input or based on the flow of the program itself. If
statements can do this work, but sometimes it is much
easier to use other forms that might work more easily for
menu items or what to do with different rolls of a die. The
switch statement can be very helpful in handling multiple
choices in programming.

    This program will ask the user to select a number from
a predetermined set of numbers. Then the program will
print different things on the screen depending on which
number the user chose
                       http://eglobiotraining.com
In programming,a switch, case, select or inspect sta
tement is a type of selection control mechanism that exists in
most imperative programming languages such
as Pascal, Ada, C/C++,C#, Java, and so on. It is also included
in several other types of languages. Its purpose is to allow the
value of a variable or expression to control the flow of
program execution via a multi way branch(or "goto", one of
several labels). The main reasons for using a switch include
improving 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
switch (expression)
{
case constant1
:statement sequence
break;
case constant2
:statement sequence
break;
case constant3
:statement sequence
break;


default
statement sequence
}

                      http://eglobiotraining.com
The expression must evaluate to a character or integer
value. Floating-point expressions, for example, are not
allowed. The value of expression is tested, in order,
against the values of the constants specified in the case
statements. When a match is found, the statement
sequence associated with that case is executed until the
break statement or the end of the switch statement is
reached. The default statement is executed if no matches
are found. The default is optional and, if it is not present,
no action takes place if all matches fail.

                      http://eglobiotraining.com
• The switch differs from the if in that switch can only
test for equality, whereas if can evaluate any type of
relational or logical expression.
• No two case constants in the same switch can have
identical values. Of course, a switch statement
enclosed by an outer switch may have
case constants that are the same.
• If character constants are used in the switch
statement, they are automatically converted to integers


                     http://eglobiotraining.com
In programming switch case statement body consists a
series of case labels and an optional default label. No
two constant expressions in case statements can
evaluate to the same value.




                     http://eglobiotraining.com
The default label can appear only once. The labeled
statements are not syntactic requirements, but
the switch statement is meaningless without them. The
default statement need not come at the end; it can appear
anywhere in the body of the switch statement. A case or
default label can only appear inside a switch statement.




                       http://eglobiotraining.com
The constant-expression in each case label is
converted to the type of expression and compared
with expression for equality. Control passes to the
statement whose case constant-expression matches the
value of expression. If a matching expression is
found, control is not impeded by
subsequent case or default labels. The ”break ”statement
is used to stop execution and transfer control to the
statement after the switch statement. Without
a break statement, every statement from the matched
case label to the end of the switch, including
the default, is executed.



                      http://eglobiotraining.com
// switch_statement1.cpp
#include <stdio.h>
 int main()
{ char *buffer = "Any character stream";
int capa, lettera, nota;
char c;
capa = lettera = nota = 0;
while ( c = *buffer++ ) // Walks buffer until NULL
 {
switch ( c )
{
case 'A':
 capa++;
 break;
case 'a':
 lettera++;
break;
default:
 nota++;
 }
 }
printf_s( "nUppercase a: %dnLowercase a: %dnTotal: %dn",
capa, lettera, (capa + lettera + nota) );
}




                                            http://eglobiotraining.com
On the example given , capa is incremented if c is an
uppercase A. The break statement after capa++ terminates
execution of the switch statement body and control passes
to the while loop. Without the break statement, letter
a and nota would also be incremented. A similar purpose is
served by the break statement for case 'a'. If c is a
lowercase a, letter a is incremented and
the break statement terminates the switch statement body.
If c is not an a or A, the default statement is executed.



                      http://eglobiotraining.com
In the series of the Programming language a loop statements
have an optional LABEL in their formal syntax. (You can put a
label on any statement, but it has a special meaning to a loop.) If
present, the label consists of an identifier followed by a colon. It's
customary to make the label uppercase to avoid potential
confusion with reserved words, and so it stands out better. And
although Perl won't get confused if you use a label that already
has a meaning like if or open, your readers might.




                           http://eglobiotraining.com
The ”while” statement in programming repeatedly executes the
block as long as EXPR is true. If the word while is replaced by the
word until, the sense of the test is reversed; that is, it executes
the block only as long as EXPR remains false. The conditional is
still tested before the first iteration, though.




                          http://eglobiotraining.com
The while or until statement can have an optional extra
block: the continue block. This block is executed every
time the block is continued, either by falling off the
end 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 it's
in here so we can define the for loop rigorously in the
next section

                      http://eglobiotraining.com
while (my $line = <STDIN>) {

$line = lc $line;

}

continue {

print $line; # still visible
}
# $line now out of scope here


Here the scope of $line extends from its declaration in the control expression throughout
the rest of the loop construct, including the continue block, but not beyond. If you want
the scope to extend further, declare the variable before the loop.




                                   http://eglobiotraining.com
The ”for ” loop has three semicolon-separated
expressions within its parentheses. These expressions
function respectively as the initialization, the
condition, and the re-initialization expressions of the
loop. All three expressions are optional (but not the
semicolons); if omitted, the condition is always true




                      http://eglobiotraining.com
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” is
limited thus , the three-part for loop can be defined in terms of the
corresponding while loop.


                                     http://eglobiotraining.com
A do-while loop in programming executes one or
more times, depending on the value of the termination
expression. The do-while statement can also
terminate when a break, go to, or return statement is
executed within the statement body.




                   http://eglobiotraining.com
// 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 to
the next statement in the program. If expression is true (nonzero), the process
is repeated, beginning with step 1.




                                           http://eglobiotraining.com
Iteration statements cause statements (or
compound statements) to be executed zero or more times,
subject to some loop-termination criteria. When these
statements are compound statements, they are executed in
order, except when either the break statement or
the continue statement is encountered.
        C++ program provides four iteration statements —
 while, do, for, and range-based for. Each of these iterates
until its termination on the programming expression
evaluates to zero (false), or until loop termination is forced
with a break statement. The following table summarizes
these statements and their actions; each is discussed in
detail in the sections that follow.


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

int main() {
  int color = 1;
  printf("Please choose a color(1: red,2: green,3: blue):n");
  scanf("%d", &color);

    switch (color) {
      case 1:
         printf("you chose red colorn");
         break;
      case 2:
         printf("you chose green colorn");
         break;
      case 3:
         printf("you chose blue colorn");
         break;
      default:
         printf("you did not choose any colorn");
    }
    return 0;
}



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

using namespace std;

void playgame()
{
  cout << "Play game called";
}
void loadgame()
{
  cout << "Load game called";
}
void playmultiplayer()
{
  cout << "Play multiplayer game called";
}

int main()
{
  int input;

 cout<<"1. Play gamen";
 cout<<"2. Load gamen";
 cout<<"3. Play multiplayern";
 cout<<"4. Exitn";
 cout<<"Selection: ";
 cin>> input;
 switch ( input ) {
 case 1:      // Note the colon, not a semicolon
   playgame();
   break;
 case 2:       // Note the colon, not a semicolon
   loadgame();
   break;
 case 3:       // Note the colon, not a semicolon
   playmultiplayer();
   break;
 case 4:       // Note the colon, not a semicolon
   cout<<"Thank you for playing!n";
   break;
 default:       // Note the colon, not a semicolon
   cout<<"Error, bad input, quittingn";             http://eglobiotraining.com
   break;
 }
#include <iostream.h>

int main()
{
  unsigned short int day;
  cout << "What's your favorite day of the week? ";
  cin >> day;
  switch (day)
{
 case 1 : cout << "Sunday";
       break;
 case 2 : cout << "Monday";
       break;
 case 3 : cout << "Tuesday";
       break;
 case 4 : cout << "Wednesday";
       break;
 case 5 : cout << "Thursday";
       break;
 case 6 : cout << "Friday";
       break;
 case 7 : cout << "Saturday";
       break;
default : cout << "Not an allowable day number";
       break;

    }
    cout << "nn";
     return 0;
}                                                     http://eglobiotraining.com
#include <iostream>
#include <math.h>
#include<stdio.h>
using namespace std;

int main()
{
    int number1;
    int number2;
    int number3;
    int number4;
   float Circle;
   float Rectangle;
   float Triangle;
   int choice;
   double pi;
   float length;
   float width;
    float base;
    float height;
    float radius;

number1 = 1;
number2 = 2;
number3 = 3;
number4 = 4;
pi = 3.14159;
Circle = pi * radius * radius;
Rectangle = length * width;
Triangle = base * height * .5;



                                 http://eglobiotraining.com
cout << "Geometry Calculator" << endl;

cout << "1. Calculate the Area of a Circle" << endl;
cout << "2. Calculate the Area of a Rectangle" << endl;
cout << "3. Calculate the Area of a Triangle" << endl;
cout << "4. Quit" << endl << endl;

cout << "Enter your choice (1-4):" << endl;
cin >> choice;

switch(choice)
{
    case 1 : cout << "Enter the radius of the circle:" << endl;
    cin >> radius;
    case 2 : cout << "Enter the length of the rectangle:" << endl;
   cin >> length;
   cout << "Enter the width of the rectangle:" << endl;
   cin >> width;
   case 3 : cout << "Enter the height of the triangle:" << endl;
   cin >> height;
   case 4 : cout << "Goodbye!" << endl;
   default: cout << "5 is not a valid entry." << endl;
}
return 0;
}




                                                 http://eglobiotraining.com
#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 didn't type in 1 or 2!n";
                                                break;

               }




                                                     http://eglobiotraining.com
//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 didn't 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 didn't type in a or b!n";
                                                                 break;
                     }

                     getchar();           // wait for a key to be pressed.

                     return 0;
}




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

using namespace std;

int main(){

string choice = "y";

while ( choice == "y" ){

cout << "Say something about this" << endl;

cout << "Leave your comments." << endl;
cin >> choice;

}

cout << "You exited the loop" << endl;

}




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

using namespace std;

int main(){

          int a;

          cout << "How long do you want this program to run? ";
          cin >> a;

          while (a){
                       cout << a << "n";
                       --a;
          }

          return 0;

}




                                    http://eglobiotraining.com
int main()
{
  int x = 0; /* Don't forget to declare variables */

    while ( x < 16 ) { /* While x is less than 16*/
      printf( "%dn", x );
      x++;          /* Update x so the condition can be met eventually */
    }
    getchar();
}




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

int main()
{
  int x;

    x = 0;
    do {
      /* "He who hesitates is lost.-Proverb" is printed at least one time
       even though the condition is false */
       printf( "He who hesitates is lost.-Proverb" );
    } while ( x != 0 );
    getchar();
}




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

int main()
{
    int i, count;
    printf("Enter the number of the item: ");
    scanf("%d", &count, 1);
    for(i = 1; i <= count; i = i + 1)
        printf(" %d", i);
    printf("n");
     return 0;
}



                         http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
http://eglobiotraining.com
Switch Statement:
•     The first line contains the basic keyword,
usually switch, case or select, followed by an
expression which is often referred to as the control
expression or control variable of the switch statement.

•      Subsequent lines define the actual cases (the
values) with corresponding sequences of statements
that should be executed when a match occurs.


                     http://eglobiotraining.com
Each alternative begins with the particular value, or
list of values (see below), that the control variable may
match and which will cause the control to go to the
corresponding sequence of statements. The value (or
list/range of values) is usually separated from the
corresponding statement sequence by a colon or an
implication arrow. In many programming languages, every
case must also be preceded by a keyword such
as case or when. An optional default case is typically also
allowed, specified by a default or else keyword; this is
executed when none of the other cases matches the control
expression.

                       http://eglobiotraining.com
•      When the program starts the user is prompted
to insert a starting number for the countdown. Then
the while loop begins, if the value entered by the user
fulfills the condition n>0 (that n is greater than zero)
the block that follows the condition will be executed
and repeated while the condition (n>0) remains being
true.

•      The easiest way to think of the loop in the
programming is 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
Submitted by:
Jenica H. Tubungbanua
BM10203




             http://eglobiotraining.com

More Related Content

What's hot

Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c languagetanmaymodi4
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language Mohamed Loey
 
C programming - String
C programming - StringC programming - String
C programming - StringAchyut Devkota
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in CRAJ KUMAR
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming LanguageAhmad Idrees
 
Loops in c programming
Loops in c programmingLoops in c programming
Loops in c programmingCHANDAN KUMAR
 
Looping statement
Looping statementLooping statement
Looping statementilakkiya
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements Tarun Sharma
 

What's hot (20)

Operators and expressions in c language
Operators and expressions in c languageOperators and expressions in c language
Operators and expressions in c language
 
Types of Compilers
Types of CompilersTypes of Compilers
Types of Compilers
 
If-else and switch-case
If-else and switch-caseIf-else and switch-case
If-else and switch-case
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
C programming - String
C programming - StringC programming - String
C programming - String
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in C
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
 
SPL 9 | Scope of Variables in C
SPL 9 | Scope of Variables in CSPL 9 | Scope of Variables in C
SPL 9 | Scope of Variables in C
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
SWITCH CASE STATEMENT IN C
SWITCH CASE STATEMENT IN CSWITCH CASE STATEMENT IN C
SWITCH CASE STATEMENT IN C
 
Dart ppt
Dart pptDart ppt
Dart ppt
 
Loops in c programming
Loops in c programmingLoops in c programming
Loops in c programming
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
 
Learning typescript
Learning typescriptLearning typescript
Learning typescript
 
Looping statement
Looping statementLooping statement
Looping statement
 
Control Flow Statements
Control Flow Statements Control Flow Statements
Control Flow Statements
 
Preprocessors
Preprocessors Preprocessors
Preprocessors
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Loops
LoopsLoops
Loops
 

Viewers also liked

10. switch case
10. switch case10. switch case
10. switch caseWay2itech
 
Switch statement, break statement, go to statement
Switch statement, break statement, go to statementSwitch statement, break statement, go to statement
Switch statement, break statement, go to statementRaj Parekh
 
Chapter 05 looping
Chapter 05   loopingChapter 05   looping
Chapter 05 loopingDhani Ahmad
 
C Language - Switch and For Loop
C Language - Switch and For LoopC Language - Switch and For Loop
C Language - Switch and For LoopSukrit Gupta
 
Do...while loop structure
Do...while loop structureDo...while loop structure
Do...while loop structureJd Mercado
 
Looping and switch cases
Looping and switch casesLooping and switch cases
Looping and switch casesMeoRamos
 
Do While and While Loop
Do While and While LoopDo While and While Loop
Do While and While LoopHock Leng PUAH
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While LoopAbhishek Choksi
 
Presentation on nesting of loops
Presentation on nesting of loopsPresentation on nesting of loops
Presentation on nesting of loopsbsdeol28
 
Loops in C Programming
Loops in C ProgrammingLoops in C Programming
Loops in C ProgrammingHimanshu Negi
 
C language in hindi (cलेग्वेज इन हिंदी )
C language  in hindi (cलेग्वेज इन हिंदी )C language  in hindi (cलेग्वेज इन हिंदी )
C language in hindi (cलेग्वेज इन हिंदी )Chand Rook
 
Overview of c language
Overview of c languageOverview of c language
Overview of c languageshalini392
 

Viewers also liked (20)

10. switch case
10. switch case10. switch case
10. switch case
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
Switch statement, break statement, go to statement
Switch statement, break statement, go to statementSwitch statement, break statement, go to statement
Switch statement, break statement, go to statement
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
 
Chapter 05 looping
Chapter 05   loopingChapter 05   looping
Chapter 05 looping
 
C Language - Switch and For Loop
C Language - Switch and For LoopC Language - Switch and For Loop
C Language - Switch and For Loop
 
Do...while loop structure
Do...while loop structureDo...while loop structure
Do...while loop structure
 
Loops in C
Loops in CLoops in C
Loops in C
 
Looping and switch cases
Looping and switch casesLooping and switch cases
Looping and switch cases
 
The Loops
The LoopsThe Loops
The Loops
 
Do While and While Loop
Do While and While LoopDo While and While Loop
Do While and While Loop
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 
Presentation on nesting of loops
Presentation on nesting of loopsPresentation on nesting of loops
Presentation on nesting of loops
 
Loops
LoopsLoops
Loops
 
C++ loop
C++ loop C++ loop
C++ loop
 
Loops c++
Loops c++Loops c++
Loops c++
 
Loops in C Programming
Loops in C ProgrammingLoops in C Programming
Loops in C Programming
 
C language in hindi (cलेग्वेज इन हिंदी )
C language  in hindi (cलेग्वेज इन हिंदी )C language  in hindi (cलेग्वेज इन हिंदी )
C language in hindi (cलेग्वेज इन हिंदी )
 
Overview of c language
Overview of c languageOverview of c language
Overview of c language
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 

Similar to Switch case and looping statement

Margareth lota
Margareth lotaMargareth lota
Margareth lotamaggybells
 
Fundamentals of programming final
Fundamentals of programming finalFundamentals of programming final
Fundamentals of programming finalRicky Recto
 
Fundamentals of programming final santos
Fundamentals of programming final santosFundamentals of programming final santos
Fundamentals of programming final santosAbie Santos
 
Fundamentalsofprogrammingfinal 121011003536-phpapp02
Fundamentalsofprogrammingfinal 121011003536-phpapp02Fundamentalsofprogrammingfinal 121011003536-phpapp02
Fundamentalsofprogrammingfinal 121011003536-phpapp02thinesonsing
 
Mark asoi ppt
Mark asoi pptMark asoi ppt
Mark asoi pptmark-asoi
 
Fundamentals of programming
Fundamentals of programmingFundamentals of programming
Fundamentals of programmingKaycee Parcon
 
Fundamentals of prog. by rubferd medina
Fundamentals of prog. by rubferd medinaFundamentals of prog. by rubferd medina
Fundamentals of prog. by rubferd medinarurumedina
 
Final requirement for programming-Bonifacio, Mary Clemence
Final requirement for programming-Bonifacio, Mary ClemenceFinal requirement for programming-Bonifacio, Mary Clemence
Final requirement for programming-Bonifacio, Mary Clemenceclemencebonifacio
 
Deguzmanpresentationprogramming
DeguzmanpresentationprogrammingDeguzmanpresentationprogramming
Deguzmanpresentationprogrammingdeguzmantrisha
 
Fundamentals of programming finals.ajang
Fundamentals of programming finals.ajangFundamentals of programming finals.ajang
Fundamentals of programming finals.ajangJaricka Angelyd Marquez
 
Password protected diary
Password protected diaryPassword protected diary
Password protected diarySHARDA SHARAN
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!olracoatalub
 

Similar to Switch case and looping statement (20)

Survelaine murillo ppt
Survelaine murillo pptSurvelaine murillo ppt
Survelaine murillo ppt
 
Switch case looping
Switch case loopingSwitch case looping
Switch case looping
 
Margareth lota
Margareth lotaMargareth lota
Margareth lota
 
Fundamentals of programming final
Fundamentals of programming finalFundamentals of programming final
Fundamentals of programming final
 
Fundamentals of programming final santos
Fundamentals of programming final santosFundamentals of programming final santos
Fundamentals of programming final santos
 
Fundamentalsofprogrammingfinal 121011003536-phpapp02
Fundamentalsofprogrammingfinal 121011003536-phpapp02Fundamentalsofprogrammingfinal 121011003536-phpapp02
Fundamentalsofprogrammingfinal 121011003536-phpapp02
 
How a Compiler Works ?
How a Compiler Works ?How a Compiler Works ?
How a Compiler Works ?
 
Final requirement
Final requirementFinal requirement
Final requirement
 
Mark asoi ppt
Mark asoi pptMark asoi ppt
Mark asoi ppt
 
Fundamentals of programming
Fundamentals of programmingFundamentals of programming
Fundamentals of programming
 
Fundamentals of prog. by rubferd medina
Fundamentals of prog. by rubferd medinaFundamentals of prog. by rubferd medina
Fundamentals of prog. by rubferd medina
 
Final requirement for programming-Bonifacio, Mary Clemence
Final requirement for programming-Bonifacio, Mary ClemenceFinal requirement for programming-Bonifacio, Mary Clemence
Final requirement for programming-Bonifacio, Mary Clemence
 
Project
ProjectProject
Project
 
Training 8051Report
Training 8051ReportTraining 8051Report
Training 8051Report
 
Deguzmanpresentationprogramming
DeguzmanpresentationprogrammingDeguzmanpresentationprogramming
Deguzmanpresentationprogramming
 
Fundamentals of programming finals.ajang
Fundamentals of programming finals.ajangFundamentals of programming finals.ajang
Fundamentals of programming finals.ajang
 
Password protected diary
Password protected diaryPassword protected diary
Password protected diary
 
My final requirement
My final requirementMy final requirement
My final requirement
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
 
Pc module1
Pc module1Pc module1
Pc module1
 

Switch case and looping statement

  • 1. Final Requirement for Fundamentals of Programming http://eglobiotraining.com
  • 2. • A program is a sequence of instruction written to perform a specified task with a computer. A computer requires programs to function, typically executing the program's instructions in central processor. The program has an executable form that the computer can use directly to execute the instructions. The same program in its human-readable source code form, from which executable programs are derived (e.g., compiled), enables a programmer to study and develop its algorithms. http://eglobiotraining.com
  • 3. • Computer source code is often written by computer programmers. Source code is written in a programming language that usually follows one of two main paradigms: imperative programming or declarative programming. Source code may be converted into an executable file (sometimes called an executable program or a binary) by a compiler and later executed by a central processing unit. http://eglobiotraining.com
  • 4. A computer programmer is a person who writes computer software. The term computer programmer can refer to a specialist in one area of computer programming or to a generalist who writes code for many kinds of software. One who practices or professes a formal approach to programming may also be known as a programmer analyst. http://eglobiotraining.com
  • 5. Programmers are people who design the program of events that turns input data into output data. It has been proved that such a program of events can be designed using a structure composed of sequences, iterations and selections. Code is merely the way that the program is described. http://eglobiotraining.com
  • 6. Programming is the iterative process of writing or editing source code. Editing source code involves testing, analyzing, and refining, and sometimes coordinating with other programmers on a jointly developed program. A person who practices this skill is referred to as a computer programmer, software developer or coder. The sometimes lengthy process of computer programming is usually referred to as software development. The term software engineering is becoming popular as the process is seen as an engineering discipline. http://eglobiotraining.com
  • 7. 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: 1. Technical: It is a means for instructing a Computer to perform Tasks 2. Conceptual: It is a framework within which we organize our ideas about things and processes. http://eglobiotraining.com
  • 8. 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 many programming 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
  • 9. In practicing programming one must know the basic program a programmer use. Dev C++ can help us on computing grades, making test questionnaires and many more things a teacher and a student can do. Programming is a an act of formulating a program for a definite course of action; "the planning was more fun than the trip itself“. http://eglobiotraining.com
  • 10. • C++ is a statically typed, free-form, multi- paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. • C++ is one of the most popular programming languages and is implemented on a wide variety of hardware and operating system platforms. • C++ has greatly influenced many other popular programming languages, most notably C# and Java. Other successful languages such as Objective-C use a very different syntax and approach to adding classes to C. http://eglobiotraining.com
  • 11. C/C++ has a built-in multiple-branch selection statement, called switch, which successively tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed. http://eglobiotraining.com
  • 12. Programs have a need to do different things depending on user input or based on the flow of the program itself. If statements can do this work, but sometimes it is much easier to use other forms that might work more easily for menu items or what to do with different rolls of a die. The switch statement can be very helpful in handling multiple choices in programming. This program will ask the user to select a number from a predetermined set of numbers. Then the program will print different things on the screen depending on which number the user chose http://eglobiotraining.com
  • 13. In programming,a switch, case, select or inspect sta tement is a type of selection control mechanism that exists in most imperative programming languages such as Pascal, Ada, C/C++,C#, Java, and so on. It is also included in several other types of languages. Its purpose is to allow the value of a variable or expression to control the flow of program execution via a multi way branch(or "goto", one of several labels). The main reasons for using a switch include improving 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
  • 14. switch (expression) { case constant1 :statement sequence break; case constant2 :statement sequence break; case constant3 :statement sequence break; default statement sequence } http://eglobiotraining.com
  • 15. The expression must evaluate to a character or integer value. Floating-point expressions, for example, are not allowed. The value of expression is tested, in order, against the values of the constants specified in the case statements. When a match is found, the statement sequence associated with that case is executed until the break statement or the end of the switch statement is reached. The default statement is executed if no matches are found. The default is optional and, if it is not present, no action takes place if all matches fail. http://eglobiotraining.com
  • 16. • The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of relational or logical expression. • No two case constants in the same switch can have identical values. Of course, a switch statement enclosed by an outer switch may have case constants that are the same. • If character constants are used in the switch statement, they are automatically converted to integers http://eglobiotraining.com
  • 17. In programming switch case statement body consists a series of case labels and an optional default label. No two constant expressions in case statements can evaluate to the same value. http://eglobiotraining.com
  • 18. The default label can appear only once. The labeled statements are not syntactic requirements, but the switch statement is meaningless without them. The default statement need not come at the end; it can appear anywhere in the body of the switch statement. A case or default label can only appear inside a switch statement. http://eglobiotraining.com
  • 19. The constant-expression in each case label is converted to the type of expression and compared with expression for equality. Control passes to the statement whose case constant-expression matches the value of expression. If a matching expression is found, control is not impeded by subsequent case or default labels. The ”break ”statement is used to stop execution and transfer control to the statement after the switch statement. Without a break statement, every statement from the matched case label to the end of the switch, including the default, is executed. http://eglobiotraining.com
  • 20. // switch_statement1.cpp #include <stdio.h> int main() { char *buffer = "Any character stream"; int capa, lettera, nota; char c; capa = lettera = nota = 0; while ( c = *buffer++ ) // Walks buffer until NULL { switch ( c ) { case 'A': capa++; break; case 'a': lettera++; break; default: nota++; } } printf_s( "nUppercase a: %dnLowercase a: %dnTotal: %dn", capa, lettera, (capa + lettera + nota) ); } http://eglobiotraining.com
  • 21. On the example given , capa is incremented if c is an uppercase A. The break statement after capa++ terminates execution of the switch statement body and control passes to the while loop. Without the break statement, letter a and nota would also be incremented. A similar purpose is served by the break statement for case 'a'. If c is a lowercase a, letter a is incremented and the break statement terminates the switch statement body. If c is not an a or A, the default statement is executed. http://eglobiotraining.com
  • 22. In the series of the Programming language a loop statements have an optional LABEL in their formal syntax. (You can put a label on any statement, but it has a special meaning to a loop.) If present, the label consists of an identifier followed by a colon. It's customary to make the label uppercase to avoid potential confusion with reserved words, and so it stands out better. And although Perl won't get confused if you use a label that already has a meaning like if or open, your readers might. http://eglobiotraining.com
  • 23. The ”while” statement in programming repeatedly executes the block as long as EXPR is true. If the word while is replaced by the word until, the sense of the test is reversed; that is, it executes the block only as long as EXPR remains false. The conditional is still tested before the first iteration, though. http://eglobiotraining.com
  • 24. The while or until statement can have an optional extra block: the continue block. This block is executed every time the block is continued, either by falling off the end 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 it's in here so we can define the for loop rigorously in the next section http://eglobiotraining.com
  • 25. while (my $line = <STDIN>) { $line = lc $line; } continue { print $line; # still visible } # $line now out of scope here Here the scope of $line extends from its declaration in the control expression throughout the rest of the loop construct, including the continue block, but not beyond. If you want the scope to extend further, declare the variable before the loop. http://eglobiotraining.com
  • 26. The ”for ” loop has three semicolon-separated expressions within its parentheses. These expressions function respectively as the initialization, the condition, and the re-initialization expressions of the loop. All three expressions are optional (but not the semicolons); if omitted, the condition is always true http://eglobiotraining.com
  • 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” is limited thus , the three-part for loop can be defined in terms of the corresponding while loop. http://eglobiotraining.com
  • 28. A do-while loop in programming executes one or more times, depending on the value of the termination expression. The do-while statement can also terminate when a break, go to, or return statement is executed within the statement body. http://eglobiotraining.com
  • 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 to the next statement in the program. If expression is true (nonzero), the process is repeated, beginning with step 1. http://eglobiotraining.com
  • 30. Iteration statements cause statements (or compound statements) to be executed zero or more times, subject to some loop-termination criteria. When these statements are compound statements, they are executed in order, except when either the break statement or the continue statement is encountered. C++ program provides four iteration statements — while, do, for, and range-based for. Each of these iterates until its termination on the programming expression evaluates to zero (false), or until loop termination is forced with a break statement. The following table summarizes these statements and their actions; each is discussed in detail in the sections that follow. http://eglobiotraining.com
  • 32. #include <stdio.h> int main() { int color = 1; printf("Please choose a color(1: red,2: green,3: blue):n"); scanf("%d", &color); switch (color) { case 1: printf("you chose red colorn"); break; case 2: printf("you chose green colorn"); break; case 3: printf("you chose blue colorn"); break; default: printf("you did not choose any colorn"); } return 0; } http://eglobiotraining.com
  • 33. #include <iostream> using namespace std; void playgame() { cout << "Play game called"; } void loadgame() { cout << "Load game called"; } void playmultiplayer() { cout << "Play multiplayer game called"; } int main() { int input; cout<<"1. Play gamen"; cout<<"2. Load gamen"; cout<<"3. Play multiplayern"; cout<<"4. Exitn"; cout<<"Selection: "; cin>> input; switch ( input ) { case 1: // Note the colon, not a semicolon playgame(); break; case 2: // Note the colon, not a semicolon loadgame(); break; case 3: // Note the colon, not a semicolon playmultiplayer(); break; case 4: // Note the colon, not a semicolon cout<<"Thank you for playing!n"; break; default: // Note the colon, not a semicolon cout<<"Error, bad input, quittingn"; http://eglobiotraining.com break; }
  • 34. #include <iostream.h> int main() { unsigned short int day; cout << "What's your favorite day of the week? "; cin >> day; switch (day) { case 1 : cout << "Sunday"; break; case 2 : cout << "Monday"; break; case 3 : cout << "Tuesday"; break; case 4 : cout << "Wednesday"; break; case 5 : cout << "Thursday"; break; case 6 : cout << "Friday"; break; case 7 : cout << "Saturday"; break; default : cout << "Not an allowable day number"; break; } cout << "nn"; return 0; } http://eglobiotraining.com
  • 35. #include <iostream> #include <math.h> #include<stdio.h> using namespace std; int main() { int number1; int number2; int number3; int number4; float Circle; float Rectangle; float Triangle; int choice; double pi; float length; float width; float base; float height; float radius; number1 = 1; number2 = 2; number3 = 3; number4 = 4; pi = 3.14159; Circle = pi * radius * radius; Rectangle = length * width; Triangle = base * height * .5; http://eglobiotraining.com
  • 36. cout << "Geometry Calculator" << endl; cout << "1. Calculate the Area of a Circle" << endl; cout << "2. Calculate the Area of a Rectangle" << endl; cout << "3. Calculate the Area of a Triangle" << endl; cout << "4. Quit" << endl << endl; cout << "Enter your choice (1-4):" << endl; cin >> choice; switch(choice) { case 1 : cout << "Enter the radius of the circle:" << endl; cin >> radius; case 2 : cout << "Enter the length of the rectangle:" << endl; cin >> length; cout << "Enter the width of the rectangle:" << endl; cin >> width; case 3 : cout << "Enter the height of the triangle:" << endl; cin >> height; case 4 : cout << "Goodbye!" << endl; default: cout << "5 is not a valid entry." << endl; } return 0; } http://eglobiotraining.com
  • 37. #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 didn't type in 1 or 2!n"; break; } http://eglobiotraining.com
  • 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 didn't 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 didn't type in a or b!n"; break; } getchar(); // wait for a key to be pressed. return 0; } http://eglobiotraining.com
  • 39. #include <iostream> #include <string> using namespace std; int main(){ string choice = "y"; while ( choice == "y" ){ cout << "Say something about this" << endl; cout << "Leave your comments." << endl; cin >> choice; } cout << "You exited the loop" << endl; } http://eglobiotraining.com
  • 40. #include <iostream> using namespace std; int main(){ int a; cout << "How long do you want this program to run? "; cin >> a; while (a){ cout << a << "n"; --a; } return 0; } http://eglobiotraining.com
  • 41. int main() { int x = 0; /* Don't forget to declare variables */ while ( x < 16 ) { /* While x is less than 16*/ printf( "%dn", x ); x++; /* Update x so the condition can be met eventually */ } getchar(); } http://eglobiotraining.com
  • 42. #include <stdio.h> int main() { int x; x = 0; do { /* "He who hesitates is lost.-Proverb" is printed at least one time even though the condition is false */ printf( "He who hesitates is lost.-Proverb" ); } while ( x != 0 ); getchar(); } http://eglobiotraining.com
  • 43. #include <stdio.h> int main() { int i, count; printf("Enter the number of the item: "); scanf("%d", &count, 1); for(i = 1; i <= count; i = i + 1) printf(" %d", i); printf("n"); return 0; } http://eglobiotraining.com
  • 55. Switch Statement: • The first line contains the basic keyword, usually switch, case or select, followed by an expression which is often referred to as the control expression or control variable of the switch statement. • Subsequent lines define the actual cases (the values) with corresponding sequences of statements that should be executed when a match occurs. http://eglobiotraining.com
  • 56. Each alternative begins with the particular value, or list of values (see below), that the control variable may match and which will cause the control to go to the corresponding sequence of statements. The value (or list/range of values) is usually separated from the corresponding statement sequence by a colon or an implication arrow. In many programming languages, every case must also be preceded by a keyword such as case or when. An optional default case is typically also allowed, specified by a default or else keyword; this is executed when none of the other cases matches the control expression. http://eglobiotraining.com
  • 57. When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true. • The easiest way to think of the loop in the programming is 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
  • 58. Submitted by: Jenica H. Tubungbanua BM10203 http://eglobiotraining.com