3 3 recap variables and data types functions control structures
Post on 20-Dec-2015
220 views
TRANSCRIPT
33Recap
Variables and Data typesFunctions
Control Structures
RECAP Wrote our first program in C++.
1 // Fig. 2.1: fig02_01.cpp
2 // Text-printing program.
3 #include <iostream> // allows program to output data to the screen
4
5 // function main begins program execution
6 int main()
7 {
8 std::cout << "Welcome to C++!\n"; // display message
9
10 return 0; // indicate that program ended successfully
11
12 } // end function main
Welcome to C++!
Function main part of every program
Body delimited by {}
Multiple ways to write comments in code
Writing Simple output statements using stream insertion
operator <<
Function main returning 0,
execution ends here
Begin with appropriate
include statements
Escape Characters, preceded by ‘\’
indicates special character output
Statements instruct a program to perform actionAll statements end with a
semicolon
Fig. 2.2 | Escape sequences.
Escape sequence
Description
\n Newline. Position the screen cursor to the beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
\r Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line.
\a Alert. Sound the system bell.
\\ Backslash. Used to print a backslash character.
\' Single quote. Use to print a single quote character.
\" Double quote. Used to print a double quote character.
Outline
fig02_03.cpp
(1 of 1)
fig02_03.cpp output (1 of 1)
1 // Fig. 2.3: fig02_03.cpp
2 // Printing a line of text with multiple statements.
3 #include <iostream> // allows program to output data to the screen
4
5 // function main begins program execution
6 int main()
7 {
8 std::cout << "Welcome ";
9 std::cout << "to C++!\n";
10
11 return 0; // indicate that program ended successfully
12
13 } // end function main
Welcome to C++!
Multiple stream insertion statements produce one line of output
Outline
fig02_04.cpp
(1 of 1)
fig02_04.cpp output (1 of 1)
1 // Fig. 2.4: fig02_04.cpp
2 // Printing multiple lines of text with a single statement.
3 #include <iostream> // allows program to output data to the screen
4
5 // function main begins program execution
6 int main()
7 {
8 std::cout << "Welcome\nto\n\nC++!\n";
9
10 return 0; // indicate that program ended successfully
11
12 } // end function main
Welcome to C++!
Use newline characters to print on multiple lines
RECAP
• Syntax errors– A syntax error occurs when the compiler encounters code
that violates C++’s language rules (i.e., its syntax). The compiler normally issues an error message to help the programmer locate and fix the incorrect code.
– C++ case sensitive
– Semicolon after each statement
– Syntax errors encountered in lab
1 // Fig. 2.5: fig02_05.cpp
2 // Addition program that displays the sum of two numbers.
3 #include <iostream> // allows program to perform input and output
4
5 // function main begins program execution
6 int main()
7 {
8 // variable declarations
9 int number1; // first integer to add
10 int number2; // second integer to add
11 int sum; // sum of number1 and number2
12
13 std::cout << "Enter first integer: "; // prompt user for data
14 std::cin >> number1; // read first integer from user into number1
15
16 std::cout << "Enter second integer: "; // prompt user for data
17 std::cin >> number2; // read second integer from user into number2
18
19 sum = number1 + number2; // add the numbers; store result in sum
20
21 std::cout << "Sum is " << sum << std::endl; // display sum; end line
22
23 return 0; // indicate that program ended successfully
24
25 } // end function main Enter first integer: 45 Enter second integer: 72 Sum is 117
How to Declare integer variables• Can declare several of them on one line, comma separated• Variable names can be any valid identifier, which is not a keyword• Series of characters (letters, digits, underscores)
• Cannot begin with digit
Use stream extraction operator with standard input stream to obtain user input• Input stream object
std::cin from <iostream>• Usually connected to keyboard• Stream extraction operator >>
• Waits for user to input value, press Enter (Return) key• Stores value in variable to right of operator
• Converts value to variable data typeConcatenating, chaining or cascading
stream insertion operations
Assignment operator =• Assigns value on left to variable on right
• Binary operator (two operands)• Add the values of variable1 and variable2• Store result in sum
Recap Variables and Memory
• Variable names– Correspond to actual locations in computer's memory
• Every variable has name, type, size and value
– When new value placed into variable, overwrites old value• Writing to memory is destructive
– Reading variables from memory nondestructive– Example
• sum = number1 + number2;– Value of sum is overwritten– Values of number1 and number2 remain intact
Memory locations after calculating and storing the sum of number1 and number2.
Recap Arithmetic
•Arithmetic operators–*
•Multiplication –/
•Division•Integer division truncates remainder
–7 / 5 evaluates to 1–%
•Modulus operator returns remainder –7 % 5 evaluates to 2
C++ operation C++ arithmetic operator
Algebraic expression
C++ expression
Addition + f + 7 f + 7
Subtraction - p – c p - c
Multiplication * bm or b· m b * m
Division / x / y or x
y or x ÷ y x / y
Modulus % r mod s r % s
Recap Arithmetic (Cont.)•Rules of operator precedence
–Operators in parentheses evaluated first•Nested/embedded parentheses
–Operators in innermost pair first
–Multiplication, division, modulus applied next•Operators applied from left to right
–Addition, subtraction applied last•Operators applied from left to right
Operator(s) Operation(s) Order of evaluation (precedence)
( ) Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.
*
/
%
Multiplication
Division
Modulus
Evaluated second. If there are several, they are evaluated left to right.
+ -
Addition
Subtraction Evaluated last. If there are several, they are evaluated left to right.
Recap: Decision Making
• Condition– Expression can be either true or false
– Can be formed using equality or relational operators
•if statement– Guards a block of statements
– If condition is true, body of the if statement executes
– If condition is false, body of the if statement does not execute
• ………..
• statement0;
• if ( condition )
• statement1;
• statement2;
• ……………..
Recap: Decision Making
Recap: Decision Making• Condition
– Expression can be either true or false
– Can be formed using equality or relational operators
• if statement– If condition is true, body of the if statement executes
– If condition is false, body of the if statement does not execute• if ( condition )
• {
• }
Fig. 2.12 | Equality and relational operators.
Standard algebraic equality or relational operator
C++ equality or relational operator
Sample C++ condition
Meaning of C++ condition
Relational operators
> x > y x is greater than y
< x < y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y
Equality operators
= == x == y x is equal to y
≠ != x != y x is not equal to y
1 // Fig. 2.13: fig02_13.cpp
2 // Comparing integers using if statements, relational operators
3 // and equality operators.
4 #include <iostream> // allows program to perform input and output
5
6 using std::cout; // program uses cout
7 using std::cin; // program uses cin
8 using std::endl; // program uses endl
9
10 // function main begins program execution
11 int main()
12 {
13 int number1; // first integer to compare
14 int number2; // second integer to compare
15
16 cout << "Enter two integers to compare: "; // prompt user for data
17 cin >> number1 >> number2; // read two integers from user
18
19 if ( number1 == number2 )
20 cout << number1 << " == " << number2 << endl;
21
22 if ( number1 != number2 )
23 cout << number1 << " != " << number2 << endl;
24
25 if ( number1 < number2 )
26 cout << number1 << " < " << number2 << endl;
27
28 if ( number1 > number2 )
29 cout << number1 << " > " << number2 << endl;
30
using declarations eliminate need for std:: prefix
Can write cout and cin without std:: prefix
Declare variables
if statement compares values of number1 and number2 to test for equality
If condition is true (i.e., values are equal), execute this statementif statement compares values
of number1 and number2 to test for inequality
If condition is true (i.e., values are not equal), execute this statement
Compares two numbers using relational operator < and >
Outline
fig02_13.cpp
(2 of 2)
fig02_13.cpp output (1 of 3)
(2 of 3)
(3 of 3)
31 if ( number1 <= number2 )
32 cout << number1 << " <= " << number2 << endl;
33
34 if ( number1 >= number2 )
35 cout << number1 << " >= " << number2 << endl;
36
37 return 0; // indicate that program ended successfully
38
39 } // end function main Enter two integers to compare: 3 7 3 != 7 3 < 7 3 <= 7 Enter two integers to compare: 22 12 22 != 12 22 > 12 22 >= 12 Enter two integers to compare: 7 7 7 == 7 7 <= 7 7 >= 7
Compares two numbers using relational operators <= and >=
Details of relational operatorsRelational (comparison) operators work as expected with int and double values, what about string and bool?
23 < 45 49.0 >= 7*7 "apple" < "berry"
Strings are compared alphabetically so that "ant" < "zebra" but (suprisingly?) "Ant" < "zebra"
How do lengths of strings compare?
Why does uppercase ‘A’ come before lowercase ‘z’?
Boolean values have numeric equivalents, 1 is true, 0 is false
cout << (23 < 45) << endl;
cout << ("guava" == "Guava") << endl;
ASCII
Details of relational operators
• What about true/false and numeric one/zero equivalent? if (3 + 4 – 7) { cout << "hi" << endl; }• Boolean expressions can be combined using logical operators: AND, OR, NOT C++ equivalents are &&, ||, and !, respectively
(standard requires and, or, not, most compilers don’t)
if (90 <= grade) {
if (grade < 95) {
cout << "that’s an A" << endl;}
}• What range of values generates ‘A’ message? Problems?
if (90 < grade && grade < 95) {
cout << "that’s an A" << endl; }
Write a program that prompts the user for a number in seconds and then determines how many hours, minutes and seconds does this represent
Example:Please Enter the number of seconds: 2000The number you entered represents5 Hours, 33 Minutes and 20 Seconds.
Using If statements, Only display hours and minutes if you have to. If the input number is less than an hour, only display minutes and seconds.
Example:Please Enter the number of seconds: 200The number you entered represents3 Minutes and 20 Seconds.
If input number is less than a minute, the answer should only display seconds
Example:Please Enter the number of seconds: 20The number you entered represents20 Seconds.
Variables and Data types
• Variable names– Correspond to actual locations in computer's memory
• Every variable has name, type, size and value
• Memory in computers is organized in bytes
• A byte is the minimum memory we can manage in C++
• A Byte can store one single character or small integer
• More complex data types come from grouping several bytes
• The size and ranges of data types is dependent on the system the program is compiled for
• Basic Fundamental Data types in C++
If Else statement• #include <iostream>• #include <string>• using namespace std;• // illustrates use of if-else statement• int main()• { • string response; • cout << "Do you like broccoli [yes/no]> "; • cin >> response; • if ("yes" == response) • { • cout << "Green vegetables are good for you" << endl; • cout << "Broccoli is good in stir-fry as well" << endl; • } • else • { • cout << "(There is no accounting for taste)" << endl; • } • return 0;• }
If Else statement• if (condition) statement1 else statement2• The if + else structures can be concatenated with the intention of verifying a range of values
• if (x > 0) • cout << "x is positive"; • else if (x < 0) • cout << "x is negative"; • else cout << "x is 0";
Nested If Else
• Nested if…else statements– One inside another, test for multiple cases – Once a condition met, other statements are skipped– Example
• 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”
Nested If Else
• Nested if…else statements (Cont.)
– Written In C++
• if ( studentGrade >= 90 ) cout << "A";else if (studentGrade >= 80 ) cout << "B"; else if (studentGrade >= 70 ) cout << "C"; else if ( studentGrade >= 60 ) cout << "D"; else cout << "F";
• A nested if...else statement can perform much faster than a series of single-selection if statements because of the possibility of early exit after one of the conditions is satisfied.
Nested If Else
• Dangling-else problem– Compiler associates else with the immediately
preceding if– Example
• if ( x > 5 ) if ( y > 5 ) cout << "x and y are > 5";else cout << "x is <= 5";
– Compiler interprets as• if ( x > 5 ) if ( y > 5 ) cout << "x and y are > 5"; else cout << "x is <= 5";
Nested If Else
• Dangling-else problem (Cont.)– Rewrite with braces ({})
• if ( x > 5 ){ if ( y > 5 ) cout << "x and y are > 5";}else cout << "x is <= 5";
– Braces indicate that the second if statement is in the body of the first and the else is associated with the first if statement
Compound Statement
• Compound statement– Also called a block
• Set of statements within a pair of braces• Used to include multiple statements in an if body
– Example• if ( studentGrade >= 60 )
cout << "Passed.\n";else { cout << "Failed.\n"; cout << "You must take this course again.\n";}
– Without braces,– cout << "You must take this course again.\n";
– always executes• A block can be placed anywhere in a program that a single statement can be
placed.
Good Programming practice
• Always putting the braces in an if...else statement (or any control statement) helps prevent their accidental omission, especially when adding statements to an if or else clause at a later time. To avoid omitting one or both of the braces, some programmers prefer to type the beginning and ending braces of blocks even before typing the individual statements within the braces.
Variables and Data typesName Description Size* Range*
char Character or small integer. 1byte signed: -128 to 127 unsigned: 0 to 255
short int (short) Short Integer. 2bytes
signed: -32768 to 32767 unsigned: 0 to 65535
int Integer. 4bytes signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295
long int (long) Long integer. 4bytes
signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295
bool Boolean value. I t can take one of two values: true or false.
1byte true or false
float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)
double Double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)
long double Long double precision floating point number.
8bytes +/- 1.7e +/- 308 (~15 digits)
Declaration of Variables
• Declare variables by specifying type• Followed by identifier or name of variable
• • integer datatypes char, short, int can either be signed or unsigned• if not specified, default is signed• signed types can represent both +ve and –ve numbers• Unsigned types can only represent +ve values or 0
int a;
float mynumber;
int c, d , e;
unsigned short int NumberOfsisters;
signed int myaccountbalance;
Declaration of Variables
• short and long can be used alone as type specifiers• In that case, they refer to their integer fundamental types
• signed and unsigned can be used similarly
short year;
short int Year;
unsigned NextYear;
unsigned int NextYear;
Scope of Variables
• Variables must be declared before use• Variable can either be local or global scope• Global variables can be referred from anywhere
in the code • Scope of local variables is limited by the block {}
in which they are declared• For example if they are declared at the beginning
of the body of a function their scope is limited to the end of the function
Scope of Variables
#include <iostream>using namespace std;void test () { int a=5; cout << “Value of ‘a’ in test =”<<a;}
int main (){ int a=10; cout << “Value of ‘a’ in main=”<<a<<endl; test(); return 0;}
Scope of Variables
Run:
SCOPE.exe
Initialization of Variables
• value of a local variable is undetermined by default
• can be given a value using assignment operator
• int a = 10;• constructor initialization can also be used• int a (0);• both ways are equivalent
Constants
• constants are expressions with fixed value
• Literal constants are used to express particular values within the source code of a program
• Literals can be Integer Numerals, Floating point numerals, Characters, Strings and boolean values
• Integers can be decimal, octal or hex• char enclosed in single quotes ‘’• strings enclosed in “”
75 // decimal;
0113 // Octal;
0x4b // hex;
75u // unsigned int;
75l // long;
3.14159 // 3.14159
6.02e23 // 6.02 x 10^23
1.6e-19 // 1.6 x 10^-19
3.0 // 3.0
'z' // character ‘z’
'p' // character ‘p’
"Hello world"
Constants
• can define own names for constants without memory consuming variable// defined constants: calculate circumference
#include <iostream>using namespace std;
#define PI 3.14159#define NEWLINE '\n'
int main (){ double r=5.0; // radius double circle; circle = 2 * PI * r; cout << circle; cout << NEWLINE; return 0;}
Constants
• const prefix can declare variables whose values cannot be modified once they are defined
const int pathwidth = 100; const char tabulator = '\t';
Strings
• Introduced in the lab• inherit from the string class• non-numerical values longer than one
character– example: string name, password;– can be initialized with any valid string literal
// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring;
mystring = "This is the initial string content";
cout << mystring << endl;
mystring = "This is a different string content";
cout << mystring << endl;
return 0;
}
Strings
Towards functions (Face1)
#include <iostream>
using namespace std;
int main()
{
cout << " |||||||||||||||| " << endl;
cout << " | | " << endl;
cout << " | o o | " << endl;
cout << " _| |_ " << endl;
cout << "|_ _|" << endl;
cout << " | |______| | " << endl;
cout << " | | " << endl;
return 0;
}• Prints head, but not as modular as program using functions
– Harder to modify to draw differently
Introduction to Functions (Face2)#include <iostream>
using namespace std;
// print a head, use of functions
void Head ()
{ cout << “ ////////|\\\\\\\\ “ << endl;cout << “ | | “ << endl;cout << “ | o o | “ << endl;cout << “ _| O |_ “ << endl;cout << “ |_| “=” |_| “ << endl;cout << “ | |_______| | “ << endl;cout << “ | | “ << endl;cout << “ | | “ << endl;cout << “ |---------------| “ << endl;
}
int main (){ Head (); return 0;}
Introduction to Functions#include <iostream>using namespace std;void Hair(){
cout << “ ////////|\\\\\\\\ “ << endl;}void side(){
cout << “ | | “ << endl;}void eyes(){
cout << “ | o o | “ << endl;}void nose(){
cout << “ _| O |_ “ << endl;}void moustache(){
cout << “ |_| “=” |_| “ << endl;}void mouth(){
cout << “ | |_______| | “ << endl;}void chin(){
cout << “ |---------------| “ << endl;}
Introduction to Functionsvoid Head(){
Hair();side{};eyes();nose();moustache();mouth();side();side();chin();
}int main(){ Head (); return 0;}
Function with parameters
• Using a calculator √100• 100 is the argument of the square root
function• Functions that take arguments are called
parameterized functions• Parameters are useful in making functions
more general• Functions that receive parameters must
receive the correct parameters
Happy Birthday#include <iostream>using namespace std;#include <string>
void Sing(string person){
cout << “ Happy Birthday to you ” << endl;cout << “ Happy Birthday to you ” << endl;cout << “ Happy Birthday dear ”<< person << endl;cout << “ Happy Birthday to you ” << endl;cout << endl;
}int main(){ Sing ( “Alice”); Sing ( “John”); Sing ( “Alan”); return 0;}
Happy Birthday• When Sing (“Alice”) is called when main is executed, Alice is passed to the function as ‘person’
• when cout << “ Happy Birthday” << person <<endl; is executed, person is replaced by ‘Alice’
• Each parameter passed to a function has a name and a type
• Functions can have several parameters
• Example int Addition (int x, int y), called as Addition (2,3)
• Will study passing arguments to functions in detail later
• What if we do Sing(1234)?
• Compiling...
• HappyBirthday.cpp
• C:\Program Files\Microsoft Visual Studio\MyProjects\HappyBirthday\HappyBirthday.cpp(23) : error C2664: 'Sing' : cannot convert parameter 1 from 'const int' to 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >'
• No constructor could take the source type, or constructor overload resolution was ambiguous
• Error executing cl.exe.
• HappyBirthday.exe - 1 error(s), 0 warning(s)
Function prototype• Functions have prototypes (or signatures) that indicate to both the compiler and the
programmer how to use the function– Later functions will return values, like square root
– For now, void means no value is returned
– Every function has a parameter list, but it’s possible to have no parameters• Hello(); colorOfAnimal(“crow”,”black”);
• What do prototypes look like for these calls?
• Cant use variables before they are defined
• Can use functions before they are defined – How?
– Add function prototype before the function is called
– The prototype shows the order and type of arguments for the function as well as return type
– Example?
Function prototype// order.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>#include <string>using namespace std;
// order of procedures is important
void Hi (string name){ cout << "Hi " << name << endl; Greetings();}
void Greetings(){ cout << "Things are happening inside this computer" << endl;}
int main(){ Hi("Fred"); return 0;}
Function prototypeCompiling...StdAfx.cppCompiling...order.cppC:\Program Files\Microsoft Visual Studio\MyProjects\order\order.cpp(15) : error C2065: 'Greetings' : undeclared identifierC:\Program Files\Microsoft Visual Studio\MyProjects\order\order.cpp(19) : error C2373: 'Greetings' : redefinition; different type modifiersError executing cl.exe.
order.exe - 2 error(s), 0 warning(s)
Function prototype#include "stdafx.h"#include <iostream>#include <string>using namespace std;
// illustrates function prototypesvoid Hi(string);void Greetings();
void Hi (string name){ cout << "Hi " << name << endl; Greetings();}
void Greetings(){ cout << "Things are happening inside this computer" << endl;}
int main(){ Hi("Fred"); return 0;}
Operators• Operators to operate on variables and constants• Assignment operator =• Arithmetic operators
– +, -, *, /, %• Compound assignment
– +=, -=, *=, /=, %=– Value += increase Value = Value + increase– Value -= increase Value = Value - increase– Value *= increase Value = Value * increase– Value /= increase Value = Value / increase– Value %= increase Value = Value % increase
• Increase / Decrease– ++ --– C++;– C+=1;– C=C+1– Can be used both as prefix or suffix– Prefix is evaluated before result of expression is evaluated– Suffix is evaluated after expression is evaluated
Operators• B= 3;
• A= ++B;
• //A now contains 4, B contains 4
• B = 3;
• A= B++;
• //A contains 3, B contains 4
• In the first scenario, B is increased before value is assigned to A
• In the second scenario, B is increased after the value is assigned to A
Operators• Relational and Equality Operators
– == Equal to
– != Not equal to
– > Greater than
– < Less than
– >= Greater than or equal to
– <= Less than or equal to• Logical Operators
– !, &&, ||
• Type casting operators
– int I;
– float F = 3.14;
– I = (int) F;
While Loops
• // custom countdown using while
• #include <iostream>• using namespace std;
• int main ()• {• int n;• cout << "Enter the starting number > ";• cin >> n;
• while (n>0) {• cout << n << ", ";• --n;• }
• cout << "FIRE!\n";• return 0;• }
• Enter the starting number > 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE!