Introduction to High Level Programming Language C++Language Translators : - • Compiler - software...
Transcript of Introduction to High Level Programming Language C++Language Translators : - • Compiler - software...
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 1
Introduction to High Level Programming Language
C++
What is C++
• C++ is a high level programming language designed to making programming more
enjoyable for the serious programmer.
• In the 1990s it became one of the most popular programming languages in the world.
Development
• C++, designed by AT&T Bell Lab’s Bjarne Stroustup, was developed as an
enhancement to the C programming language.
Program or an algorithm
• Program is a set of instructions to perform a specific task. It is A step by step ordered procedure that solves
a problem in a finite number of precise steps
• Stored in main memory
• Instructions are stored sequentially
• Instructions are in machine language (binary)
Example (Program or an algorithm)
• Display on screen: “how many hours did you work?”
• Wait for user to enter number, store in memory
• Display on screen: “what is your pay rate (per hour)?”
• Wait for user to enter rate, store in memory
• Multiply hours by rate, store in memory
• Display on screen: “you have earned $xx.xx” where xx.xx is result of previous step
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 2
Language Translators : -
• Compiler - software that translates a program written in a high-level language into binary
machine language instructions so that the program can be executed (later) on a computer.
( C , C++, Java , Cobol )
Translation Process
▪ Source Code File → [Preprocessor] →
▪ Modified Source Code → [Compiler] →
▪ Object Code →[Linker] →
▪ Executable Code File
▪ Usually don't see intermediate files
▪ Using an “Integrated Development Environment” (like Eclipse) you may only see the source, and
▪ result of running the executable file.
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 3
CodeBlocks – Installation
Go to http://codeblocks.org
Click on downloads
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 4
Click on Binaries
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 5
Select and download
codeblocks-17.12mingw-setup.exe
Double click on the downloaded file
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 6
Click on next
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 7
Click on I agree
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 8
Click on Next
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 9
Click on Install
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 10
Click on Yes
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 11
Click on OK
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 12
Select No, leave everything as it is
Click on OK
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 13
Select finish
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 14
CodeBlocks
Double click on the CodeBlocks short cut
First , you need to create a project as follows :-
File ----------> New ------------ > Project --- > enter
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 15
Select Console application
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 16
Then Select C++ --- > next
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 17
Type in Project title and chose to folder to create the project in the --- > next
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 18
Press on Finish
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 19
A projects and its main program will be created as
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 20
First , make sure that you rename the .cpp file from main.cpp to the
name that is given in the assignment then click ok.
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 21
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 22
Select Build . Fix all syntax errors if any then re-build
Select Run. Fix all logical errors if any.
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 23
Example
#include <iostream>
using namespace std;
int main()
{
double hours, rate, pay;
// Get the number of hours worked
cout << “How many hours did you work? ” ;
cin >> hours;
// Get the hourly pay rate
cout << “How much do you get paid per hour? ”;
cin >> rate;
// Calculate the pay
pay = hours * rate;
// Display the pay
cout << “You have earned $” << pay << endl;
return 0;
}
Categories of Instructions
▪ Input
▪ cin >> hours
▪ gathers info from “outside world”
▪ Processing
▪ pay = hours * rate;
▪ computation
▪ Output
• cout << “How many hours did you work? “;
• sends info to “outside world”
Language Elements Reserve Words or Key Words : have special meaning
(lowercase)
Programmer Defined Identifiers : names made by
programmer
Operators : instruction to manipulate data ( * , + … )
Punctuation : special meaning to compiler ( ; \ … )
Statement : complete instruction to computer to perform
an action.
Variables : named storage location in memory for holding
a piece of information.
Variable Definition : instruction to set up variable
requires :
data type information (numbers, characters , … )
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 24
Programming Process
1. Clearly define the problem
2. Visualize output of program
3. Make a model of the program
# hierarchy chart
# flowcharts
# pseudocode
4. Translate to C++ code (type it into a file)
5. Compile, fix syntax errors, repeat
6. Test the program (execute it with data)
7. Correct errors, go to step 5. If no errors, quit.
What is Software Engineering?
Software Engineering is a branch of computer science. It deals with entire process of developing and
maintaining computer software :-
a. Analysis
b. Designing
c. Writing Code
d. Testing
e. Debugging
f. Documenting
g. Modifying (updating)
h. Maintaining (fixing bugs reported by users)
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 25
Part of C++ Program
C++ programs have parts and components that serve specific purposes.
// A simple C++ program
/* This is Just An Example
of a Simple C++ Program */
#include <iostream>
using namespace std;
int main ()
{
cout << " Programming is Fun !!! ";
return 0;
}
The output of this program is :
Programming is Fun !!!
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 26
Parts of a C++ Program
Comment: //...
• ignored by compiler
• notes to human reader
• /*...*/
• mark the beginning and end of a comment with multiple
lines
Preprocessor Directive: #include …
• Read the program before it is compiled.
• It sets up your code.
• Preprocessor inserts contents of file here using namespace std;
• Every name in iostream is part of std namespace.
• ( Note: There is no semicolon at the end of a preprocessor directive.)
iostream : Name of the file that is going to be included in your program is
placed in this area. It is called file header.
Opening/Closing angle brackets < >
• Encloses the filename when used in a preprocessor directive
using namespace std;
• Declares that a program will be accessing entities whose names are part of the namespace called std
• e.g. every name created by the iostream file is part of the namespace std
int
• Short for integer – it indicates that the function main will send and integer value back to Operating System ( OS ) when it is completed execution.
main()
• Start of function main . Function is a group of one or more programming statement. named main
• The starting point of the program
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 27
{ } - Contains the body of the function
cout << " Programming is Fun !!! ";
• Short for “ console output “.
• Statement that displays message on screen
return 0 ; : Sends value of 0 to OS (means success! Or normal program
termination)
; Semicolon : Marks the end of a complete programming statement
The cout object
cout : Short for “Console Output” (represents the screen)
• A stream object: works on a sequence of data
• << : the stream insertion operator
• Sends value on right-hand side (rhs) to stream on left hand side (lhs)
• cout << " This is an example. " ;
• endl : short for “end line”. It is a stream manipulator. It Advances output to start of next line
NOTE : C++ is case-sensitive Programming Language.
Special characters used within cout statements
• Newline: \n or endl
• Horizontal tab : \t causes the cursor to skip over to the next tab stop.
• Single quote: \' - causes a single quotation mark to be printed
• Double quote: \" – causes a double quotation mark to be printed.
• Double backslash: \\ - causes a single backslash mark to be printed
• These can occur in strings: o "hello\nthere" o "she said \" boo \" very quietly"
• See textbook for more ( ; < > …..etc )
It's a backslash (\), not a forward slash (/)
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 28
Examples with the cout statement
cout << "This is an example. ";
cout << "This is" << " an example. ";
cout << "This is";
cout << " an example";
cout << "The best selling book on Amazon";
cout << " is \"The Help\" ";
cout << "The best selling book on Amazon" << endl;
cout << " is \" The Help\" ";
cout << "The best selling book on Amazon \n is \" The Help \" ";
cout<<"Programming is \' Fun\' "<<endl<<endl;
cout<<"Programming\n"<<" is\n"<<" Fun "<<endl<<endl;
cout<<"Programming is \\ Fun \\ "<<endl<<endl;
cout<<" Programming is \t\t\t Fun "<<endl;
Literals
A literal represents a constant value from a given data type. It is used in a program statement.
• Numbers : 0, 34, 3.14159, -1.8e12, etc.
• Characters : 'A', 'z', '!', '5', etc.
• Strings (sequence of characters) : "Hello", "This is a string" "100 years", "100", "Y" etc.
NOTE: These are all different: 5, '5', "5"
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 29
Identifiers
• An identifier is a name for some program element ( Like a variable )
• Rules: a) May not be a keyword (see p. 41 for complete list) b) The first character must be a letter or underscore c) Following characters must be letters, numbers or underscores only.
• Identifiers are case-sensitive:
o myVariable is not the same as MyVariable
Examples : dayOfweek , _legal , May2012
What about This group : _employee_name , 3C, C#
Variables
• Variable : named location in main memory
• Variable definition in a program: o <datatype> <identifier name>; // pay attention to identifier rules.
examples:
o int someNumber; o char firstLetter;
What about the following : int int , int Int , int _main , int include# ,
int namespaces.
Note : Variables must be defined before it can be used.
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 30
Variable Assignment
• An assignment statement uses the = operator to store a value in an already defined variable.
o someNumber = 12;
• When this statement is executed, the computer stores the value 12 in memory, in the location named “someNumber”.
• The variable receiving the value must be on the left side of the = (the following does NOT work):
o 12 = someNumber; // This is an ERROR
Variable Initialization
• To initialize a variable means to assign it a value when it is defined:
o int length = 12;
• You can define and initialize multiple variables at once (and change them later) :
int length = 12, width = 5, area;
area = 35;
length = 10;
area =40;
Program with a variable
#include <iostream>
using namespace std;
int main()
{
int number;
number = 100;
cout << "The value of the number is " << number << endl;
number = 50;
cout << "The value of the number is " << number << endl;
cout << "The value of the number is " << " number " << endl;
return 0;
What is the output of this program ??
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 31
}
Example of C++ Reserved words Reference List and
Keyword Description
---------------------------------------
bool declare a boolean variable
break break out of a loop
case a block of code in a switch statement
catch handles exceptions from throw
char declare a character variable
class declare a class
const declare immutable data or functions that do not change data
const_cast cast from const variables
continue bypass iterations of a loop
default default handler in a case statement
do looping construct
double declare a double precision floating-point variable
else alternate case for an if statement
float declare a floating-point variable
for looping construct
if execute code based off of the result of a test
int declare a integer variable
long declare a long integer variable
namespace partition the global namespace by defining a scope
return return from a function
short declare a short integer variable
signed modify variable type declarations
sizeof return the size of a variable or type
static create permanent storage for a variable
static_cast perform a nonpolymorphic cast
struct define a new structure
switch execute code based off of different possible values for a variable
true the boolean value of true
unsigned declare an unsigned integer variable
using import complete or partial namespaces into the current scope
void declare functions or data with no associated data type
while looping construct
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 32
Data Types • Variables are classified according to their data type.
• The data type determines the kind of information that may be stored in the variable.
• A data type is a set of values.
• Generally two main (types of) data types: a. Numeric ( integers such as 3, 157 , -47 and floating points such 23.7 , 0.94 ) b. Character
• Primary Consideration for selecting a numeric data type are :-
a. The largest and the smallest numbers that may be stored in the variable.
b. How much memory the variable uses.
c. Whether the variable stores signed or unsigned numbers
d. The number of decimal places of precision the variable has.
Data Types
Data Type Represents int, short, long whole numbers ( integers ) float, double real numbers ( fractional , decimal ) bool logical values : true, false
char a single character string sequence of chars.
Integer Data Types int, short int , long int
• Whole numbers 2 , 1000 , -900
• May be signed or unsigned
• Typical sizes and ranges (may vary depending on the system)
• Literals ( are int by default)
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 33
Integer Data Types
Data Type Size Range Short int 2 bytes -32,768 to 32,767
unsigned short int 2 bytes 0 to 65,535
int 4 bytes -2,147,483,648 to
2,147,483,647
unsigned int 4 bytes 0 to 4,294,967,295
Long int 4 bytes -2,147,483,648 to
2,147,483,647
unsigned long int 4 bytes 0 to 4,294,967,295
Long long int 8 bytes -9,223,372,036,854,775,808
to
9,223,372,036,854,775,808
unsigned long long int 8 bytes 0 to
18,446,744,073,709,551,615
Example of Variable Definitions:
short dayOfWeek; unsigned long distance; int xCoordinate = 10; long deficit = 1500;
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 34
Floating-Point Data Types
• Used to hold real numbers such as 2.5 , -7.8
• Typical sizes and ranges (may vary depending on the system): Single Precision float 4 bytes +/- 3.4e +/- 38 (~7 digits) Double Precision double 8 bytes +/- 1.7e +/- 308 (~15 digits) Long Double Precision long double 8 bytes* +/- 1.7e +/- 308 (~15 digits)
Floating-Point Data Types
float distance, time; double mass; distance = 1.495979E11; // how far away the sun is (in meters) mass = 1.989E30; // how much the sun weighs (in kilograms) time = 12.816; // hours of daylight in San Marcos today, 8/31
Converting between floating-points and integers: int i; float f; f = 8.9; i = 8.9; // stores 8 in i ( truncates, does not round ) i = 8; f = 8; // stores 8.0 in f f = 7.9; i = f; // stores 7 in i
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 35
The bool Data Type
• Defined as bool
• Literals: the values are true or false
bool boolValue; boolValue = true; cout << boolValue << endl; boolValue = false; cout << boolValue << endl;
Output: 1 0
• bool is a numeric type:
• true is 1 and false is 0
The char Data Type • char
• Literals: All the keyboard and printable symbols such as 'A' '3' '!' '\n' 'n'.
• Numeric value of character from the ASCII character set is stored in memory: char letter; letter = 'A'; // 65 is stored in memory cout << letter << endl; letter = '!'; cout << letter << endl;
Output: A !
• char is really a numeric type also!
• Note: 65 is the ASCII code for 'A'
char letter; letter = 65; cout << letter << endl; letter = 66;
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 36
cout << letter << endl;
Output: A B
The string Data Type
• A string is a sequence of characters.
• Requires the string header file: #include <string>
• Literals: “Hello again” “Over\nThere” “Y”
• A string is stored sequentially in memory, with the null character ('\0') at the end.
• The null character is not displayed.
• To define string variables in programs:
string firstName , lastName;
• To assign literals to variables :
firstName = "George"; lastName = "Washington";
• To display via cout :
cout << firstName << " " << lastName;
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 37
Arithmetic Operators • An operator is a symbol that tells the computer to perform specific mathematical or
logical manipulations
• An operand is a value used in an operation.
• C++ has Unary operators : unary operators have one operand / argument:
▪ -5 ▪ +9 ▪ -x
• minus sign (unary op) is called the negation operator - (negation)
e.g. -5
• C++ also has Binary operators : binary operators have two operands:
+ addition x + y
- subtraction index - 1
* multiplication hours * rate
/ division total / count
% modulus count % 3
• from integer division.
• % requires integers for both operands
cout << 13 % 5.0 ; // ERROR
• There is no operator for exponentiation in C++
• There IS a library function called "pow ".
• The expression is a call to the pow function with
arguments x and 3.0.
• Arguments should have type double and the
result is a double.
• If x is 2.0, the result is 8.0.
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 38
Note : #include <cmath> is required to use pow.
Example :
cout<<"The power of 3 is "<< pow(3,2.0);
Precedence rules ( order of operations )
• Which operation gets done first ???
• ( ) parentheses/
• unary minus (an operator that has only one operand) e.g. -5 evaluate right to left.
• * / % (binary operators have two operands) evaluate left to right.
• + - (binary operators) evaluate left to right.
• If the expression has multiple operators from the same level, they associate left to right or right to left.
• You can use parentheses to override the precedence or associatively rules
Examples :
cout<< 2.5 + 3.0 / 1.5 <<endl;
cout << 6 – 3 * 5 / 2 - 1 << endl ;
cout<< 1- (2 + 1) % 2 * 4 << endl;
cout<< 20%(3*(4/2))-2*((3+1)+3) << endl;
• If both operands are integers, / (division) operator always performs integer division.
The fractional part is lost!!
• If either operand is floating point, the result is floating point.
21 / 5 //value is: 4 ( integer division )
21.0 / 5 //value is: 4.2 ( float )
21 / 5.0 //value is: 4.2 ( float )
21 % 5 //value is: 1
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 39
Computational Shortcuts
int x = 10;
x++; // same as x = x + 1 ---> x has value 11
x -= 10; // same as x = x – 10 ---> x has value 1;
x *= 5; // same as x = x * 5 ---> x has value 5;
Example
/* This Program is written By Husain Gholoom
* CS1428
* This is A Sample Program
*
* Find all Syntax Errors in This Program
*\
using namespace std,
intt main();
[
long double X# = 0.254;
int X = 0;
int y = 1234567891
cout<<x<<endl;
cout<<y<endl;
cout<<20%(3*(4/2))-2\((3+1)+3)<<endl;
cout<< (4/2))-2*((3+1)+3)<<endl;
cout<< ((4/2))-2//((3+1)+3)<<endl;
retrn 0;
}
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 40
Example
// This program calculates hourly wages, including overtime.
#include <iostream>
using namespace std;
int main()
{
double regularWages, // To hold regular wages
basePayRate = 18.25, // Base pay rate
regularHours = 40.0, // Hours worked less overtime
overtimeWages, // To hold overtime wages
overtimePayRate = 27.78, // Overtime pay rate
overtimeHours = 10, // Overtime hours worked
totalWages; // To hold total wages
// Calculate the regular wages.
regularWages = basePayRate * regularHours;
// Calculate the overtime wages.
overtimeWages = overtimePayRate * overtimeHours;
// Calculate the total wages.
totalWages = regularWages + overtimeWages;
// Display the total wages.
cout << "Wages for this week are $" << totalWages << endl;
return 0;
}
Sample Output
Wages for this week are $1007.8
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 41
The cin Object
• Short for console input . It is used to read data typed at the keyboard.
• Must include the iostream library.
• When this instruction is executed, it waits for the user to type, it reads the characters until space or enter (newline) is typed, then it stores the value in the variable.
• >> the stream extraction operator use it to read data from cin (entered via the keyboard)
• right-hand operand MUST be a variable.
Example : int length, width, area; cout << "This program calculates the area of a rectangle.\n "; cout << "What is the length of the rectangle? "; cin >> length; cout << "What is the width of the rectangle? "; cin >> width; area = length * width; cout << "The area of the rectangle is " << area << ".\n";
Entering Multiple Values
cout << "Enter the length and the width of the rectangle? "; cin >> length >> width; area = length * width; cout << "The area of the rectangle is " << area << ".\n";
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 42
Reading a Character
int number; char letter;
cout << "Enter an integer, and a character: ";
cin >> number >> letter;
Mathematical Expressions
• An expression is a program component that evaluates to a value.
• An expression can be : – a literal,. – a variable, or – a combination of these using operators and parentheses.
Examples:
x + 5 x * y / z
num 'A'
4 -15e10
8 * x * x – 16 * x + 3
Each expression has a type, which is the type of the result value.
Where can expressions occur? Expressions can occur in the rhs of an assignment statement.
Examples :-
x = y * 10 / 3;
y = 8;
num = num + 1;
aLetter = 'W';
x = y;
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 43
Expressions can also occur in the rhs of a stream insertion operator (<<) ( cout ) :
cout << "The pay for the week is "<< hours * rate << endl;
cout << num;
cout << 25 / y;
Type Conversion Rules
Binary operations convert lower ranking value to the type of the other expression / value. The rhs of assignment operator is converted to the type of the variable on the lhs.
Example :
int years;
float interestRate;
int result = years * interestRate;
// years is converted to float before being multiplied
int x, y = 4;
float z = 2.7;
x = y * z;
// y is converted to float, 10.8 is converted to int (10)
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 44
Integer Division
When an integer is divided by an integer the result is an integer. The remainder/fractional part is discarded, NO ROUNDING.
Example :
double result;
result = 15 / 6; // 2.5 ==> 2
result = 15.0 / 6; // 6 ==> 6.0, result is 2.5
How About This
cout<<15/6<<endl;
cout<<15.0/6<<endl;
int result1;
result1 = 15 / 6;
cout<<result1<<endl;
result1 = 15.0 / 6;
cout<<result1<<endl;
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 45
Hand Tracing a Program
You be the computer. Track the values of the variables as the program executes.
Example
double num1, num2, num3, avg;
cout << "Enter first number";
cin >> num1;
cout << "Enter second number";
cin >> num2;
cout << "Enter third number";
cin >> num3;
avg = num1 + num2 + num3 / 3;
cout << "The average is " << avg << endl;
What is the Output of the above code fragment ???
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 46
Making Decisions
Three ways a computer processes statements:
o Sequentially o Selection o Repetition
Straight-line code
• So far all of our programs have followed this basic format: o Input some values o Do some computations o Output the results
• The statements are executed in a sequence, first to last.
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 47
Decisions
• Sometimes we want to be able to decide NOT to execute certain statements:
Relational Expressions
• Making decisions require being able to ask “Yes” or “No” questions.
• Relational expressions evaluate to true or false.
• Also called o logical expressions o conditional expressions o boolean expressions
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 48
Relational Expressions
• Boolean literals have two values : o true o false
Boolean variables:
bool isPositive;
bool found;
isPositive = true; // isPositive evaluates to true
found = false; // found evaluates to false
Relational Operators
• Express conditions
• Make comparisons to make decisions
• Logical (Boolean) expression: has a value of either true or false
• Relational operator: allows comparisons in a program
• All Relational operators are binary o Binary operators require two operands o Result of comparison is true or false
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 49
Thus, Binary operators that are used to compare numbers are :
Expression Meaning Value
8 < 15 8 less than 15 True
6 != 6 6 not equal to 6 False
2.5 > 5.8 2.5 greater than 5.8 False
5.9 <= 7.5 5.9 less than or equal to 7.5 True
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 50
Comparing Characters
• Expression using relational operators evaluates to true or false based on collating sequence
• Example: 'R' > 'T'
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 51
Relational Operators
• Examples : Indicate T or F ( 1 or 0 ) for each of the following :
int x=6;
int y=10;
a. x == 5
b. 7 <= x + 2
c. y = 3 > x
d. x != y
e. true
• We Can assign relational exprs to variables:
bool isPositive, found;
int x;
cin >> x;
isPositive = x > 0;
found = x == 100;
• Relational ops have higher precedence than =
Precedence and Relational Operators
• Relational operators are lower than arithmetic operators :
int x, y;
... x < y -10 ... // minus happens first
... x * 5 >= y + 10 ... // mult, then plus, then >=
• Relational operators are higher than assignment :
int x, y;
...
bool t1 = x > 7; // > then =
bool t2 = x * 5 >= y + 10; // *, +, >=, =
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 52
if-else statement
• if-else statement is used to express decisions
if (expression)
statement1
else
statement2
• The expression is evaluated: o If it is true, then statement1 is executed.
(statement2 is skipped). o If it is false, then statement2 is executed
(statement1 is skipped).
if-else example
double rate; double monthlySales; cout << "Enter monthly sales last month: " ; cin >> monthlySales; if (monthlySales > 3000) rate = .025; else rate = .029; double price; cout << "Enter selling price of item: " ; cin >> price; double commission = (price + 3.99) * rate; cout << "Commission: $" << commission << endl;
Sample Output Enter monthly sales last month: 5430 Enter selling price of item: 175 Commission: $4.47475
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 53
Notice that :
if (monthlySales > 3000)
rate = .025;
else
rate = .029;
• Relational expression in parentheses
• NO semi-colon after expression, nor else
• Good style: indent the statements
• The semi-colons belong to the statements, not to the if-else
The block statement
• a block (or a compound statement) is a set of statements inside braces:
{
int x;
cout << "Enter a value for x: " << endl;
cin >> x;
cout << "Thank You " << endl;
}
• This allows us to use multiple statements when by rule only one is allowed.
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 54
if-else with blocks
• We can use blocks to put more than one statement in the branches of the if-else:
int number; cout << "Enter a Number : " << endl; cin >> number; if (number % 2 == 0) {
number = number / 2; cout << "Even" << endl;
} else {
number = (number – 1) / 2; cout << "Odd " << endl; }
if statement
• The else part is optional: if (expression)
statement1
• Expression is evaluated: o If it is true, then statement1 is executed. o If it is false, then statement1 is skipped.
if statement example
• Example : Input Validation cout << "Enter a positive number: ";
cin >> x; if (x < 0) { cout << "That number is negative. " << "Please enter a positive number: "; cin >> x;
} //do something with x here
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 55
Watch out
• What is output of the following code segment ?
int x; x = 13;
if (x==10) x = 17;
cout << x << endl;
cout << "Done !" << endl;
• What is output of the following code segment ?
char babyGender; cin >> babyGender;
if (babyGender == 'M') cout << "It's a boy!" << endl;
cout << "It's a girl!" << endl;
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 56
Nested If statements
• if-else is a statement. It can occur as a branch of an if-else statement.
Example : Nested if statements
char bornInUSA; int age; cout << " Were you born in USA ( Y / N ) " ; cin >> bornInUSA; cout << " What is your age; "; cin >> age; if (bornInUSA == 'Y') if (age >= 35) cout << "You qualify to run for President" << endl; else
cout << "You are too young to run for President" << endl; else cout << "You must have been born in the US in order " << "to run for President" << endl;
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 57
Dangling Else Problem
• Combining an if with an if-else : if (a > 0)
if (b > 0) cout << "*****" << endl;
else cout << "-----" << endl;
• Or is it:
if (a > 0)
if (b > 0) cout << "*****" << endl;
else cout << "-----" << endl;
• It's the first one. The else is paired with the closest if.
To override the dangling else convention
• Add braces : if (a > 0)
{
if (b > 0)
cout << "*****" << endl;
}
else
cout << "-----" << endl;
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 58
Common nested if pattern
• Determine letter grade from testScore :
if (testScore < 60)
grade = 'F';
else {
if (testScore < 70)
grade = 'D';
else {
if (testScore < 80)
grade = 'C';
else {
if (testScore < 90)
grade = 'B';
else
grade = 'A';
}
}
}
• Note that braces are actually optional here
if-else if ( .. else-if)
• Not really a different statement, just a different way of indenting the previous nested if statement :
if (testScore < 60)
grade = 'F';
else if (testScore < 70)
grade = 'D';
else if (testScore < 80)
grade = 'C';
else if (testScore < 90)
grade = 'B';
else
grade = 'A';
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 59
Comparing Floating-Point Numbers when using ==
Because of the nature of the floating points and the way they are stored in memory, rounding errors sometimes occur. That is because some of the fraction numbers can not be exactly represented using binary .
double a = 1.5 ; // a = 1.5 double b = 1.5 ; // b = 1.5 a += 0.0000000000000001; // Adding a little bit value if ( a == b )
cout << "Both a and b are equal "; else cout << " a and b are not equal";
Try to stay with greater than or less than comparison with the floating-point numbers.
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 60
Logical (Boolean) Operators and Logical Expressions :
• Logical (Boolean) operators enable you to combine logical expressions
• Logical operators take logical values as operands
• Binary operators: && and || or
• Unary operator: !
Logical Operators :-
Logical Operator Meaning Evaluates
&& AND Both conditions must be true for the entire
condition to be true
| | OR Either condition or both conditions must
be true for the entire condition to be true
! NOT Reverse the truth condition
Logical Operators Table ( and && )
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 61
Logical Operators Table ( or | | )
Logical Operators : Examples :
/*
* Author: Husain Gholoom
* Example : Logical Operators
*
*/
#include<iostream>
using namespace std;
int main()
{
bool found = true;
bool flag = false;
double x = 5.2, num1=2567.58,num2=2567.58;double y = 3.4;
int a = 5; int b = 8; int n = 20;
char ch = 'B';
cout<< "!found evaluates to " << !found <<endl;
cout<< "x > 4.0 evaluates to " << (x > 4.0) <<endl;
cout<<"!found && (x >= 0) evaluates to "<<(!found && (x >= 0))<<endl;
cout<<"!(found && (x >= 0)) evaluates to "<< !(found && (x >= 0))<<endl;
cout<<"x + y <= 20.5 evaluates to " << (x + y <= 20.5)<<endl;
cout<<"(n >= 0) && <<n <= 100) evaluates to " <<((n >= 0) && (n <= 100))<<endl;
cout<<"('A' <= ch && ch <= 'Z') evaluates to " <<('A' <= ch && ch <= 'Z')<<endl;
cout<<"(a + 2 <= b) && !flag evaluates to "<<((a + 2 <= b) && !flag)<<endl;
cout<<"The value of num1 == num2 is " <<( num1 == num2)<<endl;
return 0;
}
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 62
Precedence and Logical Operators
• ! is higher than most operators, so use parentheses: int x;
... !(x < 0 && x > -10) ...
• && is higher than ||
• int x, y;
...
... flag || x * 5 >= y + 10 && x == 5
// which op is first? second? etc?
• ! && and || are lower than arithmetic + relational Operators : parens not usually needed
Precedence Symbols
Highest * / %
+ -
> >= < <=
= = !=
&&
| |
Lowest =
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 63
Checking Numeric Ranges
• Want x to be in the range from 1 to 10 (inclusive)
a. if (1 <= x <= 10)
cout << "YES" << endl;
//NO, which op is done first? second?
b. if (1 <= x && x <= 10)
cout << "YES" << endl;
- check: x=0?
- check: x=5?
- check: x=100?
Short Circuit Evaluation
• What is the value of : x != x && y > 10 o true o false o don't have enough information to determine
• Actually it is false.
o x != x is always false. o false && ?? is always false
▪ false && false is false ▪ false && true is false
• If expression on the left of && is false, the expression on the right is not evaluated, the result is false.
• If expression on the left of || is true, the expression on the right is not evaluated, the result is true.
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 64
Watch out
• What is output?
int x=10, y=15;
if (x+y)
cout << "x+y is true. " << endl;
o anything not 0 (zero) is true. o 0 (zero) is false.
• What is output?
int x;
cin >> x;
if (x = 5)
cout << x << endl;
• It always outputs : 5. Why ??
• What is output?
double x = 1.0/9.0;
if (x+x+x + x+x+x + x+x+x == 1.0)
cout << "Nine ninths is one" << endl;
else
cout << "Uh Oh" << endl;
• Some fractional numbers cannot be stored exactly using binary (round-off errors)
• Computation can compound these errors.
• Don't test floating point values using equality
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 65
Compare using else-if to a series of if statements.
if ( month == 1 ) cout << "Jan"; else if ( month == 2 ) cout << "Feb"; else if ( month == 3 ) cout << "Mar";
VS
if ( month == 1 ) cout << "Jan"; if ( month == 2 ) cout << "Feb"; if ( month == 3 ) cout << "Mar";
Does Order Matter ??
if ( average >= 89.5 ) ltr_grd = 'A' ; else if ( average >= 79.5 ) ltr_grd = 'B'; else if ( average >= 69.5 ) ltr_grd = 'C'; else if ( average >= 59.5 ) ltr_grd = 'D'; else ltr_grd = 'F';
VS
if ( average >= 69.5 ) ltr_grd = 'C' ; else if ( average >= 79.5 ) ltr_grd = 'B'; else if ( average >= 89.5 ) ltr_grd = 'A'; else if ( average >= 59.5 ) ltr_grd = 'D'; else ltr_grd = 'F';
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 66
1. What is the output of the following segment of code if the input value is 20?
cin >> someInt;
if (someInt > 30)
cout << "Moe ";
cout << "Larry ";
cout << "Curley ";
a. Curley b. Moe Larry Curley c. Larry Curley
d. There is no output, there is a compile-time error
e. There is no output, there is a run-time error
2. After execution of the following code, what will be the value of angle if the input value
is 0?
cin >> angle;
if (angle>5)
angle = angle + 5;
else if (angle > 2)
angle = angle + 10;
else
angle = angle + 15;
a. 15 b. 10 c. 25 d. 0 e. 5
3. What will be the output given the segment of code, if a 0 is entered from the keyboard?
int x = -1;
cout << " Enter a 0 or a 1 from the keyboard: ";
cin >> x;
if (x)
cout << x;
a. the output will be a 0 b. nothing will be output
c. x will be outputted d. a –1 will be outputted
e. I do not know so cout it wrong!
CS1319 - Introduction to C++
Husain Gholoom – Lecturer in Computer Science Page 67
4. What will be outputted given the segment of code, if a 0 is entered from the keyboard?
int number;
cin << number;
if (number = 0);
cout << "Moe" << endl;
else
cout << "Larry" << endl;
cout << "Curly"<< endl;
a. Moe b. Larry
Curley Curley
c. Moe Curley d. Larry Curley
e. Nothing, a compiler syntax error exists
5. What will be the output given the coding segment below?
int x=1, y=0;
if (x == 1)
cout << "Moe ";
if (y = 1)
cout << "Larry ";
cout << "Curley ";
a. Moe Larry Curley b. Larry Curley c. Curley
d. Moe Curley e. None of these
Program Problem 1: Assume that we Have 3 variables a, b, c. Write IF-Statements that
find the variable that has the highest value and sets another variable, max to that value.
Program Problem 2 : Assume that we Have 3 variables a, b, c. Write an IF-Statement that
sort them in an ascending order from highest to lowest.