+ All Categories
Home > Documents > Switch case and looping statement

Switch case and looping statement

Date post: 09-Jun-2015
Category:
Upload: jenica
View: 489 times
Download: 1 times
Share this document with a friend
Popular Tags:
58
Switch Case and Looping Statement Final Requirement for Fundamentals of Programming http://eglobiotraining.com
Transcript
Page 1: Switch case and looping statement

Switch Case and Looping Statement

Final Requirement for Fundamentals of Programming

http://eglobiotraining.com

Page 2: Switch case and looping statement

What is computer program?• 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

Page 3: Switch case and looping statement

• 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

Page 4: Switch case and looping statement

Computer Programmer

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

Page 5: Switch case and looping statement

 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

Page 6: Switch case and looping statement

What is computer programming?

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

Page 7: Switch case and looping statement

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 Tasks2. Conceptual: It is a framework within which we organize our ideas about things and processes.

http://eglobiotraining.com

Page 8: Switch case and looping statement

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

Page 9: Switch case and looping statement

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

Page 10: Switch case and looping statement

• 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

Page 11: Switch case and looping statement

Switch Case

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

Page 12: Switch case and looping statement

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

Page 13: Switch case and looping statement

http://eglobiotraining.com

In programming,a switch, case, select or inspect statement 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.

Page 14: Switch case and looping statement

The general form of the switch statement is:

switch (expression){case constant1:statement sequencebreak;case constant2:statement sequencebreak;case constant3:statement sequencebreak;

defaultstatement sequence}

http://eglobiotraining.com

Page 15: Switch case and looping statement

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

Page 16: Switch case and looping statement

There are three important things to know about the switch statement:

• 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

Page 17: Switch case and looping statement

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

Page 18: Switch case and looping statement

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

Page 19: Switch case and looping 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.

Page 20: Switch case and looping statement

Example :// 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: %d\nLowercase a: %d\nTotal: %d\n", capa, lettera, (capa + lettera + nota) ); }

http://eglobiotraining.com

Page 21: Switch case and looping statement

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.

Page 22: Switch case and looping statement

http://eglobiotraining.com

Looping Statement 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.

Page 23: Switch case and looping statement

http://eglobiotraining.com

While Statement

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.

Page 24: Switch case and looping statement

While Statement

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

Page 25: Switch case and looping statement

While Statement 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

Page 26: Switch case and looping statement

For Statement

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

Page 27: Switch case and looping statement

For Statement 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

Page 28: Switch case and looping statement

Do…While Statement

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

Page 29: Switch case and looping statement

Do …While Statement // 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

Page 30: Switch case and looping statement

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

Page 31: Switch case and looping statement

Codes and Explanation of the Program that is being

tested

http://eglobiotraining.com

Page 32: Switch case and looping statement

Switch Case 1#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 color\n"); break; case 2: printf("you chose green color\n"); break; case 3: printf("you chose blue color\n"); break; default: printf("you did not choose any color\n"); } return 0;}

http://eglobiotraining.com

Page 33: Switch case and looping statement

Switch Case 2

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 game\n"; cout<<"2. Load game\n"; cout<<"3. Play multiplayer\n"; cout<<"4. Exit\n"; 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, quitting\n"; break; } cin.get();}

Page 34: Switch case and looping statement

Switch Case 3 #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 << "\n\n"; return 0; }

http://eglobiotraining.com

Page 35: Switch case and looping statement

Switch Case 5#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

Page 36: Switch case and looping statement

Switch Case 4

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

Page 37: Switch case and looping statement

Switch Case 5 #include <stdio.h>#include <iostream>using namespace std;

int main(){

int nr = 0;char ch = 0;

//This uses numberscout << "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

Page 38: Switch case and looping statement

Switch Case 5 //This uses lowercase characters onlycout << "\n\n 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 characterscout << "\n\nType 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

Page 39: Switch case and looping statement

Looping Statement 1 #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

Page 40: Switch case and looping statement

Looping Statement #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

Page 41: Switch case and looping statement

Looping Statement 3 int main(){ int x = 0; /* Don't forget to declare variables */ while ( x < 16 ) { /* While x is less than 16*/ printf( "%d\n", x ); x++; /* Update x so the condition can be met eventually */ } getchar();}

http://eglobiotraining.com

Page 42: Switch case and looping statement

Looping Statement 4

#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

Page 43: Switch case and looping statement

Looping Statement 5

#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

Page 44: Switch case and looping statement

Output Program Using Dev C ++

http://eglobiotraining.com

Page 45: Switch case and looping statement

Switch Case 1

http://eglobiotraining.com

Page 46: Switch case and looping statement

Switch Case 2

http://eglobiotraining.com

Page 47: Switch case and looping statement

Switch Case 3

http://eglobiotraining.com

Page 48: Switch case and looping statement

Switch Case 4

http://eglobiotraining.com

Page 49: Switch case and looping statement

Switch Case 5

http://eglobiotraining.com

Page 50: Switch case and looping statement

Looping Statement 1

http://eglobiotraining.com

Page 51: Switch case and looping statement

Looping Statement 2

http://eglobiotraining.com

Page 52: Switch case and looping statement

Looping Statement 3

http://eglobiotraining.com

Page 53: Switch case and looping statement

Looping Statement 4

http://eglobiotraining.com

Page 54: Switch case and looping statement

Looping Statement 5

http://eglobiotraining.com

Page 55: Switch case and looping statement

Explanations: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

Page 56: Switch case and looping statement

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

Page 57: Switch case and looping statement

Looping Statement

• 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

Page 58: Switch case and looping statement

Submitted to:Prof. Erwin Globio http://eglobiotraining.com

Submitted by: Jenica H. Tubungbanua BM10203

http://eglobiotraining.com


Recommended