Basic Of Computer Science

Slides:



Advertisements
Similar presentations
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Advertisements

Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
If Statements & Relational Operators Programming.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
1 9/26/08CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
Programming Switch command. COMP102 Prog. Fundamentals: Switch command / Slide 2 Multiple Selection: The switch Statement value1 action 1 value2 action.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
true (any other value but zero) false (zero) expression Statement 2
1 CS 105 Lecture 4 Selection Statements Wed, Jan 26, 2011, 6:05 pm.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
CS 1400 Jan 2007 Chapter 4, sections Relational operators Less than< Greater than> Less than or equal= Equal== Not equal!=
1 Midterm Review COMP 102. Tips l Eat a light meal before the exam l NO electronic devices (including calculators, dictionaries, phones, pagers, etc.)
C++ Programming, Namiq Sultan1 Chapter 4 Making Decisions Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:
C++ for Engineers and Scientists Third Edition
1 9/28/07CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
Administrative MUST GO TO CORRECT LAB SECTION! Homework due 11:59pm on Tuesday. 25 points off if late (up to 24 hours) Cannot submit after 11:59pm on Wednesday.
1 CS 105 Lecture 5 Logical Operators; Switch Statement Wed, Feb 16, 2011, 5:11 pm.
If Statements & Relational Operators, Part 2 Programming.
Quiz 1 Exam 1 Next Week. Nested if Statements if (myGrade >= 80) if (myGrade >= 90) cout
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
CHAPTER#3 STRUCTURED PROGRAM DEVELOPMENT IN C++ 1 st semester King Saud University College of Applied studies and Community Service Csc 1101.
Control Structures I (Selection)
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 1: Selection statements: if, if…else, switch.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 C++ Control Statements ~ Selection and Iteration.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
CPS120: Introduction to Computer Science Decision Making in Programs.
Selection Structures (if & switch statements) (CS1123)
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Flow of Control Part 1: Selection
PROBLEM SOLVING & ALGORITHMS CHAPTER 5: CONTROL STRUCTURES - SELECTION.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
1 Compound Assignment C++ has a large set of operators for applying an operation to an object and then storing the result back into the object Examples.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
CCSA 221 Programming in C CHAPTER 6 MAKING DECISIONS 1.
Chapter 4 Selection: the if-else and switch-case instructions.
1 Chapter 4, Part 1 If Control Construct A mechanism for deciding whether an action should be taken JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Programming Fundamentals1 Chapter 4 SELECTION STRUCTURES.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
Control statements Mostafa Abdallah
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
CPS120: Introduction to Computer Science Decision Making in Programs.
Lecture 7 Computer Programming -1-. Conditional Statements 1- if Statement. 2- if ….. else Statement. 3- switch.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 15, 2004 Lecture Number: 11.
C++ Programming Control Structures I (Selection).
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
 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.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Branching statements.
Chapter 3 Control Statements
Selection (also known as Branching) Jumail Bin Taliba by
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
A mechanism for deciding whether an action should be taken
Chapter 7 Conditional Statements
Summary Two basic concepts: variables and assignments Basic types:
Chapter 4: Control Structures I (Selection)
Structured Program Development in C++
Presentation transcript:

Basic Of Computer Science Dr. Mohamed Khafagy

Conditional Statements A conditional statement allows us to control whether a program segment is executed or not. Two constructs if statement if if-else if-else-if switch statement

The Basic if Statement Syntax if(condition) action if the condition is true then execute the action. action is either a single statement or a group of statements within braces. condition false true action

Choice (if) Put multiple action statements within braces if (it's raining){ <take umbrella> <wear raincoat> }

Absolute Value // program to read number & print its absolute value #include <iostream> using namespace std; int main(){ int value; cout << "Enter integer: "; cin >> value; if(value < 0) value = -value; cout << "The absolute value is " << value << endl; return 0; }

Relational Operators Relational operators are used to compare two values to form a condition. Math C++ Plain English = == equals [example: if(a==b) ] [ (a=b) means put the value of b into a ] < < less than  <= less than or equal to > > greater than  >= greater than or equal to  != not equal to

Operator Precedence Answer: Which comes first? * / % + - * / % + - < <= >= > == != = Answer:

The Boolean Type C++ contains a type named bool for conditions. A condition can have one of two values: true (corresponds to a non-zero value) false (corresponds to zero value) Boolean operators can be used to form more complex conditional expressions. The and operator is && The or operator is || The not operator is !

The Boolean Type Truth table for "&&" (AND): Operand1 Operand2 true false

The Boolean Type Truth table for “||" (OR): Operand1 Operand2 true false

The Boolean Type Truth table for "!" (NOT): Operand !Operand true false

A Boolean Type Assignments to bool type variables bool P = true; bool Q = false; bool R = true; bool S = P && Q; bool T = !Q || R; bool U = !(R && !Q);

Sorting Two Numbers int value1; int value2; int temp; cout << "Enter two integers: "; cin >> value1 >> value2; if(value1 > value2){ temp = value1; value1 = value2; value2 = temp; } cout << "The input in sorted order: " << value1 << " " << value2 << endl;

The if-else Statement Syntax if (condition) Action_A else Action_B if the condition is true then execute Action_A else execute Action_B Example: if(value == 0) cout << "value is 0"; else cout << "value is not 0"; condition false true Action_A Action_B

Choice (if and else) <go to beach> <take umbrella> if <it's sunny>{ <go to beach> } else{ <take umbrella>

Finding the Big One int value1; int value2; int larger; cout << "Enter two integers: "; cin >> value1 >> value2; if(value1 > value2) larger = value1; else larger = value2; cout << "Larger of inputs is: " << larger << endl;

Area of the circle const double PI = 3.1415926; int radius; double area; cout << "Enter the radius of the circle: "; cin >> radius; if(radius > 0){ area = radius * radius * PI; cout << "The area of the circle is: " << area; } else cout << "The radius has to be positive " << endl;

Even or Odd int value1; bool even; cout << "Enter a integer : "; cin >> value; if(value%2 == 0) even = true; else even = false; // even = !(value%2);

if-else-if Statements if <condition 1 exists>{ <do Q> } else if <condition 2 exists>{ <do R> else if <condition 3 exists>{ <do S> else{ <do T> Q R S T

if-else-if Statement int people, apples, difference; cout << "How many people do you have?\n"; cin >> people; cout << "How many apples do you have?\n"; cin >> apples; if(apples == people) cout << "Everybody gets one apple.\n"; else if(apples > people){ difference = apples - people; cout << "Everybody gets one apple, & there are " << difference << " extra apples.\n";} else{ difference = people - apples; cout << "Buy " << difference << " more apples so that everyone gets one apple.\n";}

if-else-if Example if (score >= 90) int score; cout << "Please enter a score: "; cin >> score; if (score >= 90) cout << "Grade = A" << endl; else if (score >= 80) cout << "Grade = B" << endl; else if (score >= 70) cout << "Grade = C" << endl; else if (score >= 60) cout << "Grade = D" << endl; else // totalscore < 59 cout << "Grade = F" << endl;

Nested if Statements Nested means that one complete statement is inside another if <condition 1 exists>{ if <condition 2 exists>{ if <condition 3 exists>{ <do A> } <do B> <do C: sleep>

Nested if Statements Example: if <it's Monday>{ <go to HKUST> if <it's time for class>{ if <it's raining>{ <bring umbrella> } <go to COMP 102>

Nested if Statements if the customer is a member, then Consider the following example: if the customer is a member, then { If the customer is under 18, then the entrance fee is half the full fee. If the customer is 18 or older, then the entrance fee is 80% of the full fee. } The if statements deciding whether to charge half fee to someone under 18 or whether to charge 80% to someone over 18 are only executed if the outer if statement is true, i.e. the customer is a member. Non-members, no matter what their age, are charged full fee.

Nested if Statements Consider a variant of the previous example: if the customer is a member, then { If the customer is under 18, then the entrance fee is half the full fee. } If the customer is 18 or older, then the entrance fee is 80% of the full fee. Here, member customers under 18 will be charged half fee and all other customers over 18 will be charged 80% of the full fee.

Nested if Statements If (member) { if (age < 18) fee = fee * 0.5; }

“Dangling Else” Problem Always pair an else with the most recent unpaired if in the current block. Use extra brackets { } to clarify the intended meaning, even if not necessary. For example, what is the value of c in the following code? int a = -1, b = 1, c = 1; if( a > 0 ) if( b > 0 ) c = 2; else c = 3;

“Dangling Else” Problem (A) int a = -1, b = 1, c = 1; if (a > 0) { if (b > 0) c = 2; else c = 3; } (B) int a = -1, b = 1, c = 1; (A) is the correct interpretation. To enforce (B), braces have to be explicitly used, as above.

Short-circuit Evaluation If the first operand of a logical and expression is false, the second operand is not evaluated because the result must be false. If the first operand of a logical or expression is true, the second operand is not evaluated because the result must be true.

Multiple Selection: The switch Statement multiway expression value1 action 1 value2 action 2 value3 action 3 value4 action 4

Multiple Selection: The switch Statement Syntax: switch (<selector expression>) { case <label1> : <sequence of statements>; break; case <label2> : <sequence of statements>; case <labeln> : <sequence of statements>; default : <sequence of statements>; }

Multiple Selection: The switch Statement Meaning: Evaluate selector expression. The selector expression can only be: a bool, an integer, an enum constant, or a char. Match case label. Execute sequence of statements of matching label. If break encountered, go to end of the switch statement. Otherwise continue execution.

Multiple Selection: The switch Statement case 1 action case 2 action case 3 action default action

switch Statement: Example 1 If you have a 95, what grade will you get? switch(int(score)/10){ case 10: case 9: cout << "Grade = A" << endl; case 8: cout << "Grade = B" << endl; case 7: cout << "Grade = C" << endl; case 6: cout << "Grade = D" << endl; default:cout << "Grade = F" << endl; }

switch Statement: Example 2 switch(int(score)/10){ case 10: case 9: cout << "Grade = A" << endl; break; case 8: cout << "Grade = B" << endl; case 7: cout << "Grade = C" << endl; case 6: cout << "Grade = D" << endl; default:cout << "Grade = F" << endl; }

switch Statement: Example 2 is equivalent to: if (score >= 90) cout << "Grade = A" << endl; else if (score >= 80) cout << "Grade = B" << endl; else if (score >= 70) cout << "Grade = C" << endl; else if (score >= 60) cout << "Grade = D" << endl; else // score < 59 cout << "Grade = F" << endl;

switch Statement: Example 2 #include <iostream> using namespace std; int main() { char answer; cout << "Is comp102 an easy course? (y/n): "; cin >> answer; switch (answer){ case 'Y': case 'y': cout << "I think so too!" << endl; break; case 'N': case 'n': cout << "Are you kidding?" << endl; default: cout << "Is that a yes or no?" << endl; } return 0;

switch Statement with Multiple Labels: Example 3 switch (watts) { case 25 : lifespan = 2500; break; case 40 : case 60 : lifespan = 1000; case 75 : lifespan = 750; default : lifespan = 0; } // end switch

Points to Remember The expression followed by each case label must be a constant expression. No two case labels may have the same value. Two case labels may be associated with the same statements. The default label is not required. There can be only one default label, and it is usually last.

Problem 1 Write a program that reports the contents of a compressed-gas cylinder based on the first letter of the cylinder’s color. The program input is a character representing the observed color of the cylinder: ‘Y’ or ‘y’ for yellow, ‘O’ or ‘o’ for orange, and so on. Cylinder colors and associated contents are as follows: orange -> ammonia brown -> carbon monoxide yellow -> hydrogen green -> oxygen Your program should respond to input of a letter other than the first letters of the given colors with the message “Contents unknown”.

Input(s) color char

Output(s) content

brown -> carbon monoxide yellow -> hydrogen green -> oxygen Relevant Formula orange -> ammonia brown -> carbon monoxide yellow -> hydrogen green -> oxygen

ALTERNATIVE SOLUTION #include <iostream.h> int main() { char color; cout<<"Please enter the first letter of the cylinder's color : “; cin>>color ; if (color == 'O' || color == 'o') cout<<“The contents of the compressed-gas cylinder is Ammonia”<<endl; else if (color == 'B' || color == 'b') cout<<"The contents of the compressed-gas cylinder is Carbon monoxide\n“; else if (color == 'Y' || color == 'y') cout<<"The contents of the compressed-gas cylinder is Hydrogen\n“; else if (color == 'G' || color == 'g') cout<<"The contents of the compressed-gas cylinder is Oxygen\n“; else cout<<"Contents unknown\n"; return 0; }

Exercise: Instead of using both uppercase and lowercase letters of the given character in every if-condition or in switch-cases, convert the character given by the user into uppercase or lowercase and use only this character in if-conditions and switch-cases.

Problem 2 The National Earthquake Information Center has asked you to write a program implementing the following decision table to characterize an earthquake based on its Richter scale number. Richter Scale Number (n) Characterization n < 5.0 Little or no damage 5.0 <= n < 5.5 Some damage 5.5 <= n < 6.5 Serious damage 6.5 <= n < 7.5 Disaster higher Catastrophe

Input(s) n double

Output(s) characterization

Richter Scale Number (n) Characterization Relevant Formula Richter Scale Number (n) Characterization n < 5.0 Little or no damage 5.0 <= n < 5.5 Some damage 5.5 <= n < 6.5 Serious damage 6.5 <= n < 7.5 Disaster higher Catastrophe

#include <iostram.h> int main() { double n; cout<<"Please enter Richter Scale Number : “; cin>>n; if (n < 5.0) cout<<"\nLittle or no damage\n”; else if (5.0 <= n && n < 5.5) /* else if (n < 5.5) */ cout<<"\nSome damage\n”; else if (5.5 <= n && n < 6.5) /* else if (n < 6.5) */ cout<<"\nSerious damage\n”; else if (6.5 <= n && n < 7.5) /* else if (n < 7.5) */ cout"\nDisaster\n”; else cout<<"\nCatastrophe\n”; return 0; }

Problem 1 Write a program that reports the contents of a compressed-gas cylinder based on the first letter of the cylinder’s color. The program input is a character representing the observed color of the cylinder: ‘Y’ or ‘y’ for yellow, ‘O’ or ‘o’ for orange, and so on. Cylinder colors and associated contents are as follows: orange -> ammonia brown -> carbon monoxide yellow -> hydrogen green -> oxygen Your program should respond to input of a letter other than the first letters of the given colors with the message “Contents unknown”.

Input(s) color char

Output(s) content

brown -> carbon monoxide yellow -> hydrogen green -> oxygen Relevant Formula orange -> ammonia brown -> carbon monoxide yellow -> hydrogen green -> oxygen

default: cout<<"\nContents unknown\n“; } #include <iostream.h> int main() { char color; cout<<"Please enter the first letter of the cylinder's color : “; cin>>color ; switch (color) { case 'O': case 'o':cout<<"\nThe contents of the compressed-gas cylinder is Ammonia\n“; break; case 'B': case 'b':cout<<"\nThe contents of the compressed-gas cylinder is Carbon monoxide\n"; case 'Y': case 'y':cout<<"\nThe contents of the compressed-gas cylinder is Hydrogen\n"; case 'G': case 'g':cout<<"\nThe contents of the compressed-gas cylinder is Oxygen\n“; default: cout<<"\nContents unknown\n“; } return 0; }