Control Structures Selection: else / if and switch Dr. Ahmed Telba.

Slides:



Advertisements
Similar presentations
More on Algorithms and Problem Solving
Advertisements

True or false A variable of type char can hold the value 301. ( F )
Computer Science 1620 Loops.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Chapter 3 - Structured Program Development
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control.
Structured Program Development in C
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
PRINCIPLES OF PROGRAMMING Revision. A Computer  A useful tool for solving a great variety of problems.  To make a computer do anything (i.e. solve.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Structural Program Development: If, If-Else Outline.
Selection Structures (if & switch statements) (CS1123)
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Chapter 4 Selection Structures: Making Decisions.
Structured Program Development Outline 2.1Introduction 2.2Algorithms 2.3Pseudo code 2.4Control Structures 2.5The If Selection Structure 2.6The If/Else.
CONTROLLING PROGRAM FLOW
Lecture 2: Logical Problems with Choices. Problem Solving Before writing a program Have a thorough understanding of the problem Carefully plan an approach.
Pseudocode When designing an ALGORITHM to solve a problem, Pseudocode, can be used. –Artificial, informal language used to develop algorithms –Similar.
C Lecture Notes 1 Structured Program Development.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Selection. Flow Chart If selection If/else selection Compound statement Switch.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
PROGRAM FLOW CHAPTER3 PART1. Objectives By the end of this section you should be able to: Differentiate between sequence, selection, and repetition structure.
Dale Roberts 1 Program Control - Algorithms Department of Computer and Information Science, School of Science, IUPUI CSCI N305.
Chapter 3 - Structured Program Development Outline 3.1Introduction 3.2Algorithms 3.3Pseudocode 3.4Control Structures 3.5The If Selection Structure 3.6The.
1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.
Lecture 2 Control Structure. Relational Operators -- From the previous lecture Relational Operator Meaning == is equal to < is less than > is greater.
Control structures Algorithm Development Conditional Expressions Selection Statements 1.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
CHAPTER#3 PART1 STRUCTURED PROGRAM DEVELOPMENT IN C++ 2 nd semester King Saud University College of Applied studies and Community Service Csc.
Structured Program Development Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010.
1 Lecture 3 Control Structures else/if and while.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Chapter#3 Part1 Structured Program Development in C++
1 Lecture 2 Control Structures: Part 1 Selection: else / if and switch.
COMP Loop Statements Yi Hong May 21, 2015.
Lecture 7 Computer Programming -1-. Conditional Statements 1- if Statement. 2- if ….. else Statement. 3- switch.
C++ Programming Lecture 5 Control Structure I (Selection) – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
STRUCTURED PROGRAMMING Selection Statements. Content 2  Control structures  Types of selection statements  if single-selection statement  if..else.
 2003 Prentice Hall, Inc. All rights reserved. 1 Basic C++ Programming.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
LECTURE # 7 : STRUCTURED PROGRAMMING Selection Statements Tr.Hadeel.
Lecture #8 SWITCH STATEMENT By Shahid Naseem (Lecturer)
Computer Programming -1-
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
1 Chapter 4 - Control Statements: Part 1 Outline 4.1 Introduction 4.4 Control Structures 4.5 if Selection Structure 4.6 if/else Selection Structure 4.7.
Branching statements.
Introduction to Computer Programming
The if…else Selection Statement
Data Types and Expressions
REPETITION CONTROL STRUCTURE
Engineering Problem Solving with C++, Etter/Ingber
Chapter 2.1 Control Structures (Selection)
CSC113: Computer Programming (Theory = 03, Lab = 01)
Programming Fundamentals
Programming Fundamentals
Lecture 2: Logical Problems with Choices
Structured Program
Chapter 3 - Structured Program Development
3 Control Statements:.
Chapter 3 - Structured Program Development
2.6 The if/else Selection Structure
Branching statements Kingdom of Saudi Arabia
Structural Program Development: If, If-Else
Presentation transcript:

Control Structures Selection: else / if and switch Dr. Ahmed Telba

Primitive Built-in Types: C++ offer the programmer a rich assortment of built-in as well as user defined data types. Following table lists down seven basic C++ data types: TypeKeyword Booleanbool Characterchar Integerint Floating pointfloat Double floating pointdouble Valuelessvoid

Constant /*const float pi = ; const char tab = '\t' ; #define pi */ #include using namespace std; #define LENGTH 10 #define WIDTH 5 #define NEWLINE '\n' int main() { int area; area = LENGTH * WIDTH; cout << area; cout << NEWLINE; return 0; }

Assume variable A holds 10 and variable B holds 20, then: Arithmetic Operators: Op erat or DescriptionExample +Adds two operandsA + B will give 30 -Subtracts second operand from the first A - B will give -10 *Multiplies both operands A * B will give 200 /Divides numerator by de-numerator B / A will give 2 %Modulus Operator and remainder of after an integer division B % A will give 0 ++Increment operatorIncrement operator, increases integer value by one A++ will give 11 --Decrement operatorDecrement operator, decreases integer value by one A-- will give 9

Relational Operators: There are following relational operators supported by C++ language Assume variable A holds 10 and variable B holds 20, then: OperatorDescriptionExample == Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

Logical Operators: There are following logical operators supported by C++ language Assume variable A holds 1 and variable B holds 0, then: Opera tor DescriptionExample &&Called Logical AND operator. If both the operands are non- zero, then condition becomes true. (A && B) is false. ||Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true. !Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. !(A && B) is true.

7 2.4Control Structures Sequential execution  Statements executed in order Transfer of control  Next statement executed not next one in sequence 3 control structures  Sequence structure Programs executed sequentially by default  Selection structures if, if/else, switch  Repetition structures while, do/while, for

8 2.4Control Structures Flowchart  Graphical representation of an algorithm  Special-purpose symbols connected by arrows (flowlines)  Rectangle symbol (action symbol) Any type of action  Oval symbol Beginning or end of a program, or a section of code (circles) Single-entry/single-exit control structures  Connect exit point of one to entry point of the next  Control structure stacking

9 2.5if Selection Structure Selection structure  Choose among alternative courses of action  Pseudocode example: If student’s grade is greater than or equal to 60 Print “Passed”  If the condition is true Print statement executed, program continues to next statement  If the condition is false Print statement ignored, program continues  Indenting makes programs easier to read C++ ignores whitespace characters (tabs, spaces, etc.)

10 2.5if Selection Structure Translation into C++ If student’s grade is greater than or equal to 60 Print “Passed” if ( grade >= 60 ) cout << "Passed"; Diamond symbol (decision symbol)  Indicates decision is to be made  Contains an expression that can be true or false Test condition, follow path if structure  Single-entry/single-exit

11 2.5if Selection Structure Flowchart of pseudocode statement true false grade >= 60 print “Passed” A decision can be made on any expression. zero - false nonzero - true Example: is true

12 if/else Selection Structure if  Performs action if condition true if/else  Different actions if conditions true or false Pseudocode if student’s grade is greater than or equal to 60 print “Passed” else print “Failed” C++ code if ( grade >= 60 ) cout << "Passed"; else cout << "Failed";

if/else Selection Structure Nested if/else structures  One inside another, test for multiple cases  Once condition met, other statements skipped if student’s grade is greater than or equal to 90 Print “A” else if student’s grade is greater than or equal to 80 Print “B” else if student’s grade is greater than or equal to 70 Print “C” else if student’s grade is greater than or equal to 60 Print “D” else Print “F”

14 #include using namespace std; int main () { int score; cout << "Enter the grade is=\t"; cin>> score; if (score >= 90) cout << "The grade is A." << endl; else if (score >= 80) cout << "The grade is B." << endl; else if (score >= 70) cout << "The grade is C." << endl; else if (score >= 60) cout << "The grade is D." << endl; else cout << "The grade is F." << endl; }

15 boolean Operators Combines multiple boolean expressions If person’s age greater than or equal to 13 and less than 17, he can go to G and PG-13 rated movies, but not R rated movies if (age >= 13 && age < 17) cout << “You can go to G and PG-13” << “ rated movies, but not R” + << “ rated movies.”) << endl; boolean operators  and - && (true if all conditions are true)  or - || (true if one condition is true)  not - ! (true if conditions is false)

16 Expression Combinations operand1operand2operand1 && operand2 true false truefalse if (age >= 13 && age < 17) cout << “You can go to G and PG-13” << “ rated movies, but not R” + << “ rated movies.” << endl; Let age = 12 Let age = 16 Let age = 17 The && (and) operator

17 Expression Combinations operand1operand2operand1 || operand2 true falsetrue falsetrue false The || (or) operator operand!operand truefalse true The ! (not) operator Example if ( !( grade == sentinelValue ) ) cout << "The next grade is " << grade << endl; Alternative: if ( grade != sentinelValue ) cout << "The next grade is " << grade << endl;

switch Multiple-Selection Structure true false case a case a action(s)break case b case b action(s)break false case z case z action(s)break true default action(s)

19 Converting if / else to a switch if (rank == JACK) cout << "Jack"; else if (rank == QUEEN) cout << "Queen"; else if (rank == KING; cout << "King"; else if (rank == ACE) cout << "Ace"; else cout << rank; switch (rank) { case JACK: cout << "Jack"; break; case QUEEN: cout << "Queen"; break; case KING: cout << "King"; break; case ACE: cout << "Ace"; break; default: cout << rank; }

# include using namespace std; int main() { int x=100; if (x == 100) { cout << "x is 100"; }

# include using namespace std; int main( ) { int a; cout<<"enter the value of a\n"; cin>>a; if ( a>5 ) {cout<<"is greter than 5\n"; cout<<"is greter than 5*******\n"; } a=a+2; cout<<"a="<<a ; }

# include using namespace std; int main() { int a,b; cout<<"enter value of a then b\n"; cin>>a>>b; if ( a>b ) cout<<"a is large than b"; if ( a>=b ) cout<<"\na is large than or equal b"; if ( a<b ) cout<<"\na is less than b"; if ( a<=b ) cout<<"\na is less than or equal b"; if ( a==b ) cout<<"\na is equal than b"; if ( a!=b ) cout<<"\na is not equal than b";}

# include using namespace std; int main() { int a; cout<<"enter the number of a"; cin>>a; if ( ( a>5 )&&(a<100) ) cout<<"the number in this range"; }

loops or repetition structures(while) // custom countdown using while #include using namespace std; int main () { int n = 10 ; while (n>0) { cout<< n << ", "; n--; } cout<< "FIRE!"; return 0; }

do statements while (condition) #include using namespace std; int main() { int n = 10 ; do { cout << n << ", "; n--; } while (n>0); cout << "FIRE!"; return 0; }

For loop

for (initialization ; condition ; increase) #include using namespace std; int main () { for ( int n=10 ; n>0 ; n-- ) { cout << n << ", "; } cout << "Fire!"; return 0; }

#include using namespace std; int main() { for (int n=10; n>0;n--) { if (n==5) continue; cout << n << ", "; } cout << "FIRE!\n"; return 0; }

#include using namespace std; int main() { unsigned short dnum ; cout<< "Enter number of day(1-7): "; cin>> dnum; cout<< "\n"; if(dnum == 1) cout << "the day is Friday"; else if(dnum == 2) cout << "the day is Saturday"; else if(dnum == 3) cout << "the day is Sunday"; else if(dnum == 4) cout << "the day is Monday"; else if(dnum == 5) cout << "the day is Tuesday"; else if(dnum == 6) cout << "the day is Tuesday"; else if(dnum == 7) cout << "the day is Thursday"; else cout << "Sorry we're closed "; cout<<'\n'; return 0; } 30

#include using namespace std; int main() { unsigned short dnum ; cout<< "Enter number of day(1-7): "; cin>> dnum; cout<< "\n"; switch(dnum){ case 1: // if dnum = 1 cout << "the day is Friday"; break; case 2: // if dnum = 2 cout << "the day is Saturday"; break; case 3: // if dnum = 3 cout << "the day is Sunday"; break; case 4: // if dnum = 4 cout << "the day is Monday"; break; case 5: // if dnum = 5 cout << "the day is Tuesday"; break; case 6: // if dnum = 6 cout << "the day is Wednesday"; break; case 7: // if dnum = 7 cout << "the day is Thursday"; break; default: // if dnum 7 cout << "Sorry we're closed "; break; } cout<< "\n"; return 0; } 31

#include using namespace std; int main( ) { double fuel_gauge_reading; cout << "Enter fuel gauge reading: "; cin >> fuel_gauge_reading; cout << "First with braces:\n"; if (fuel_gauge_reading < 0.75) { if (fuel_gauge_reading < 0.25) cout << "Fuel very low. Caution!\n"; } else { cout << "Fuel over 3/4. Dont stop now!\n"; } cout << "Now without braces:\n"; if (fuel_gauge_reading < 0.75) if (fuel_gauge_reading < 0.25) cout << "Fuel very low. Caution!\n"; else cout << "Fuel over 3/4. Don't stop now!\n"; return 0; }

#include using namespace std; int main( ) { int net_income; double tax_bill; double five_percent_tax, ten_percent_tax; cout << "Enter net income (rounded to whole dollars) $"; cin >> net_income; if (net_income <= 15000) tax_bill = 0; else if ((net_income > 15000) && (net_income <= 25000)) //5% of amount over $15,000 tax_bill = (0.05*(net_income )); else //net_income > $25,000 { //five_percent_tax = 5% of income from $15,000 to $25,000. five_percent_tax = 0.05*10000; //ten_percent_tax = 10% of income over $25,000. ten_percent_tax = 0.10*(net_income ); tax_bill = (five_percent_tax + ten_percent_tax); } cout << "Net income = $" << net_income << endl << "Tax bill = $" << tax_bill << endl; return 0; }

/*write a program to input 3 integers and determine which of them is biggest:-*/ #include using namespace std; int main( ) { int a,b,c; cout<<"enter a, b and c one after another"<<endl; cin>>a>>b>>c; if ((a>b)&&(a>c)) //take care of (( )) important. cout<<"first number is bigger="<<a<<endl; if ((b>a)&&(b>c)) cout<<"the second number is bigger="<<b<<endl; if ((c>a)&&(c>b)) cout<<"the last number is bigger="<<c<<endl; if((a==c)&&(c==b)) cout<<"all the numbers are equal"<<endl; }

#include using namespace std; int main() { int a; cout<<" Enter the value == of a as number\n"; cin>>a; if(a>=0) cout<<"a is positive number\n"; if(a%2==0) cout<<" a is even \n"; if(a%2!=0) cout<<"a is odd number"<<endl; if(a<0) cout<<"a is a negative number\n"; }

#include using namespace std; int main( ) { double fuel_gauge_reading; cout << "Enter fuel gauge reading: "; cin >> fuel_gauge_reading; cout << "First with braces:\n"; if (fuel_gauge_reading < 0.75) { if (fuel_gauge_reading < 0.25) cout << "Fuel very low. Caution!\n"; } else { cout << "Fuel over 3/4. Dont stop now!\n"; } cout << "Now without braces:\n"; if (fuel_gauge_reading < 0.75) if (fuel_gauge_reading < 0.25) cout << "Fuel very low. Caution!\n"; else cout << "Fuel over 3/4. Don't stop now!\n"; return 0; }

Loops in c++

//C++ Program to find factorial of a number (Note: Factorial of positive integer n = 1*2*3*...*n) #include using namespace std; int main() { int i, n, factorial = 1; cout<<"Enter a positive integer: "; cin>>n; for (i = 1; i <= n; ++i) { factorial *= i; // factorial = factorial * i; } cout<< "Factorial of "<<n<<" = "<<factorial; return 0; }

Loop Contents if Statement if...else Statement Nested if...else Statement Conditional Operator

#include using namespace std; int main() { int number; cout<< "Enter an integer: "; cin>> number; if ( number > 0) { // Checking whether an integer is positive or not. cout << "You entered a positive integer: "<<number<<endl; } cout<<"This statement is always executed because it's outside if statement."; return 0; }

C++ if...else The if...else executes body of if when the test expression is true and executes the body of else if test expression is false. Working of if...else Statement

Flowchart of if...else

Example 2: C++ if...else Statement //C++ Program to check whether integer entered by user is positive or negative (Considering 0 as positive) #include using namespace std; int main() { int number; cout<< "Enter an integer: "; cin>> number; if ( number >= 0) { cout << "You entered a positive integer: "<<number<<endl; } else { cout<<"You entered a negative integer: "<<number<<endl; } cout<<"This statement is always executed because it's outside if...else statement."; return 0; }

Syntax of Nested if...else if (test expression1){ statement/s to be executed if test expression1 is true; } else if(test expression2) { statement/s to be executed if test expression1 is false and 2 is true; } else if (test expression 3) { statement/s to be executed if text expression1 and 2 are false and 3 is true; }. else { statements to be executed if all test expressions are false; }

#include using namespace std; int main() // Most important part of the program! { int age; // Need a variable... cout<<"Please input your age: "; // Asks for age cin>> age; // The input is put in age if ( age < 50 ) { // If the age is less than 100 cout<<"You are pretty young!\n"; // Just to show you it works... } else if ( age == 50 ) { // I use else just to show an example cout<<"You are old\n"; // Just to show you it works... } else { cout<<"You are really old\n"; // Executed if no other statement is }

grading of student #include //grading student using namespace std; int main( ) { int grade; cout <<"Enter the grade:" ; cin >> grade; if(grade>= 90) cout<<'A'<< endl; else if(grade>= 80) cout<<'B'<< endl; else if(grade>= 70) cout<<'C'<< endl; else if(grade>= 60) cout<<'D'<< endl; else cout<<"fail"<<endl; return 0; }

C++ for Loop Syntax for(initialization statement; test expression; update statement) { code/s to be executed; } #include using namespace std; int main () { // for loop execution for( int a = 10; a < 20; a = a + 1 ) { cout << "value of a: " << a << endl; } return 0; }

C++ while and do...while Loop In computer programming, loop cause a certain piece of program to be executed a certain number of times. Consider these scenarios: You want to execute some code/s certain number of time. You want to execute some code/s certain number of times depending upon input from user. These types of task can be solved in programming using loops. There are 3 types of loops in C++ Programming: for Loop while Loop do...while Loop C++ while Loop Syntax of while Loop while (test expression) { statement/s to be executed. }

#include using namespace std; int main() { int i, n, factorial = 1; cout<<"Enter a positive integer: "; cin>>n; for (i = 1; i <= n; ++i) { factorial *= i; // factorial = factorial * i; } cout<< "Factorial of "<<n<<" = "<<factorial; return 0; }

#include using namespace std; // So we can see cout and endl int main() { int x = 0; // Don't forget to declare variables while ( x < 10 ) { // While x is less than 10 cout<< x <<endl; x++; // Update x so the condition can be met eventually }

do { } while ( condition ); #include using namespace std; int main() { int x; x = 0; do { // "Hello, world!" is printed at least one time // even though the condition is false cout<<"Hello, world!\n"; } while ( x != 1 );// orgnal 0 cin.get(); }

#include using namespace std; int main() { int x; x = 0; do { // "Hello, world!" is printed at least one time // even though the condition is false cout<<"Hello, world!\n"; } while ( x != 0 ); cin.get(); }

#include using namespace std; int main() { int number, i = 1, factorial = 1; cout<< "Enter a positive integer: "; cin >> number; while ( i <= number) { factorial *= i; //factorial = factorial * i; ++i; } cout<<"Factorial of "<<number<<" = "<<factorial; return 0; }

Syntax of do...while Loop do { statement/s; } while (test expression);

//C++ program to add numbers entered by user until user enters 0. #include using namespace std; int main() { float number, sum = 0.0; do { cout<<"Enter a number: "; cin>>number; sum += number; } while(number != 0.0); // stop when 0 is entered cout<<"Total sum = "<<sum; return 0; }

//C++ if Statement #include using namespace std; int main() { int number; cout<< "Enter an integer: "; cin>> number; if ( number > 0) { // Checking whether an integer is positive or not. cout << "You entered a positive integer: "<<number<<endl; } cout<<"This statement is always executed because it's outside if statement."; return 0; }

Example 2: C++ if...else Statement C++ Program to check whether integer entered by user is positive or negative (Considering 0 as positive) #include using namespace std; int main() { int number; cout<< "Enter an integer: "; cin>> number; if ( number >= 0) { cout << "You entered a positive integer: "<<number<<endl; } else { cout<<"You entered a negative integer: "<<number<<endl; } cout<<"This statement is always executed because it's outside if...else statement."; return 0; }

C++ Nested if...else Nested if...else are used if there are more than one test expression. Syntax of Nested if...else if (test expression1){ statement/s to be executed if test expression1 is true; } else if(test expression2) { statement/s to be executed if test expression1 is false and 2 is true; } else if (test expression 3) { statement/s to be executed if text expression1 and 2 are false and 3 is true; }. else { statements to be executed if all test expressions are false; }

Example 3: C++ Nested if...else Statement C++ Program to check whether the integer entered by user is positive, negative or zero. #include using namespace std; int main() { int number; cout<< "Enter an integer: "; cin>> number; if ( number > 0) { cout << "You entered a positive integer: "<<number<<endl; } else if (number < 0){ cout<<"You entered a negative integer: "<<number<<endl; } else { cout<<"You entered 0."<<endl; } cout<<"This statement is always executed because it's outside nested if..else statement."; return 0; }

Syntax of switch switch (n) { case constant1: code/s to be executed if n equals to constant1; break; case constant2: code/s to be executed if n equals to constant2; break;. default: code/s to be executed if n doesn't match to any cases; }

C++ switch Statement Syntax of switch switch (n) { case constant1: code/s to be executed if n equals to constant1; break; case constant2: code/s to be executed if n equals to constant2; break;. default: code/s to be executed if n doesn't match to any cases; }

Example 1: C++ switch Statement /* C++ program to demonstrate working of switch Statement */ /* C++ program to built simple calculator using switch Statement */ #include using namespace std; int main() { char o; float num1,num2; cout<<"Select an operator either + or - or * or / \n"; cin>>o; cout<<"Enter two operands: "; cin>>num1>>num2; switch(o) { case '+': cout<<num1<<" + "<<num2<<" = "<<num1+num2; break; case '-': cout<<num1<<" - "<<num2<<" = "<<num1-num2; break; case '*': cout<<num1<<" * "<<num2<<" = "<<num1*num2; break; case '/': cout<<num1<<" / "<<num2<<" = "<<num1/num2; break; default: /* If operator is other than +, -, * or /, error message is shown */ printf("Error! operator is not correct"); break; } return 0; }

C++ break and continue Statement

// C++ Program to demonstrate working of break statement #include using namespace std; int main() { float number, sum = 0.0; while (true) { // test expression is always true cout<<"Enter a number: "; cin>>number; if (number != 0.0) { sum += number; } else { break; // terminating the loop if number equals to 0.0 } cout<<"Sum = "<<sum; return 0; }

#include using namespace std; int main( ) { int Grade = 'A'; switch( Grade ) { case 'A' : cout<< "Excellent\n" ; break; case 'B' : cout<< "Good\n" ; break; case 'C' : cout<< "OK\n" ; break; case 'D' : cout<< "Mmmmm....\n" ; break; case 'F' : cout<< "You must do better than this\n"; break; default :cout<< "What is your grade anyway?\n"; }

#include using namespace std; // So the program can see cout and endl int main() { // The loop goes while x < 10, and x increases by one every loop for ( int x = 0; x < 10; x++ ) { // Keep in mind that the loop condition checks // the conditional statement before it loops again. // consequently, when x equals 10 the loop breaks. // x is updated before the condition is checked. cout<< x <<endl; } cin.get(); }

Loop in c++ Dr. Ahmed Telba

#include using namespace std; int main() { cout << "Hello World"; return 0; }

#include using namespace std; // main() is where program execution begins. int main() { cout << "Hello World"; // prints Hello World return 0; }

Comment in c++ C++ comments start with /* and end with */. For example: // next type of comment /* This is a comment */ /* C++ comments can also * span multiple lines */

Primitive Built-in Types: C++ offer the programmer a rich assortment of built-in as well as user defined data types. Following table lists down seven basic C++ data types: TypeKeyword Booleanbool Characterchar Integerint Floating pointfloat Double floating pointdouble Valuelessvoid

Local Variables: #include using namespace std; int main () { // Local variable declaration: int a, b; int c; // actual initialization a = 10; b = 20; c = a + b; cout << c; return 0; }

Global Variables: #include using namespace std; // Global variable declaration: int g; int main () { // Local variable declaration: int a, b; // actual initialization a = 10; b = 20; g = a + b; cout << g; return 0; }

Constant #include using namespace std; #define LENGTH 10 #define WIDTH 5 #define NEWLINE '\n' int main() { int area; area = LENGTH * WIDTH; cout << area; cout << NEWLINE; return 0; }

#include using namespace std; /* This program shows the difference between * signed and unsigned integers. */ int main() { short int i; // a signed short integer short unsigned int j; // an unsigned short integer j = 50000; i = j; cout << i << " " << j; return 0; }

Assume variable A holds 10 and variable B holds 20, then: Arithmetic Operators: Op erat or DescriptionExample +Adds two operandsA + B will give 30 -Subtracts second operand from the first A - B will give -10 *Multiplies both operands A * B will give 200 /Divides numerator by de-numerator B / A will give 2 %Modulus Operator and remainder of after an integer division B % A will give 0 ++Increment operatorIncrement operator, increases integer value by one A++ will give 11 --Decrement operatorDecrement operator, decreases integer value by one A-- will give 9

Relational Operators: There are following relational operators supported by C++ language Assume variable A holds 10 and variable B holds 20, then: OperatorDescriptionExample == Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

Logical Operators: There are following logical operators supported by C++ language Assume variable A holds 1 and variable B holds 0, then: Op erat or DescriptionExample &&Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false. ||Called Logical OR Operator. If any of the two operands is non- zero, then condition becomes true. (A || B) is true. !Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. !(A && B) is true.

C++ provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching: Branching is so called because the program chooses to follow one branch or another. if statement This is the most simple form of the branching statements. It takes an expression in parenthesis and an statement or block of statements. if the expression is true then the statement or block of statements gets executed otherwise these statements are skipped. NOTE: Expression will be assumed to be true if its evaluated values is non-zero. if statements take the following form:

if (expression) statement; or if (expression) { Block of statements; } or if (expression) { Block of statements; } else { Block of statements; } or if (expression) { Block of statements; } else if(expression) { Block of statements; } else { Block of statements; }

# include using namespace std; int main() { int x=100; if (x == 100) { cout << "x is 100"; }

/*const float pi = ; const char tab = '\t' ; #define pi */ # include using namespace std; int main() { int a; cout<<"enter the number of a"; cin>>a; if ( ( a>5 )&&(a<100) ) cout<<"the number in this range"; } */

# include using namespace std; int main( ) { int a; cin>>a; if ( a>5 ) {cout<<"is greter than 5\n"; cout<<"is greter than 5*******\n"; } a=a+2; cout<<"a="<<a ; }

# include using namespace std; int main() { int a,b; cout<<"enter value of a then b\n"; cin>>a>>b; if ( a>b ) cout<<"a is large than b"; if ( a>=b ) cout<<"\na is large than or equal b"; if ( a<b ) cout<<"\na is less than b"; if ( a<=b ) cout<<"\na is less than or equal b"; if ( a==b ) cout<<"\na is equal than b"; if ( a!=b ) cout<<"\na is not equal than b";}

# include using namespace std; int main() { int a; cout<<“enter the number of a"; cin>>a; if ( ( a>5 )&&(a<100) ) cout<<"the number in this range"; }

# include using namespace std; int main() { int x; cin >>x; if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else cout << "x is 0";} 88