SlideShare a Scribd company logo
1 of 99
Introduction to C++ 
Computer Science I
Q: What is C++ 
 C++ is a compiled, object-oriented language 
 It is the “successor” to C, a procedural 
language 
 (the “++” is called the successor operator in C++) 
 C was derived from a language called B which 
was in turn derived from BCPL 
 C was developed in the 1970’s by Dennis 
Ritchie of AT&T Bell Labs 
 C++ was developed in the early 1980’s by 
Bjarne Stroustrup of AT&T Bell Labs. 
 Most of C is a subset of C++
People & Programs 
 User: an individual who runs, or 
executes, a program 
 Programmer: an individual who creates, 
or writes, a program
C++ Program 
Consists of… 
 Declarations 
 Define the use of various identifiers, thus 
creating the elements used by the program 
(computer) 
 Statements 
 Or executable statements, representing 
actions the computer will take on the user’s 
behalf
Identifiers 
 Names for various entities used in a program; 
used for... 
 Variables: values that can change frequently 
 Constants: values that never changes 
 Functions: programming units that represents 
complex operations 
 Parameters: values that change infrequently
Simple C++ Program 
#include <iostream.h> 
int main() 
{ 
// Declarations 
// Statements 
return 0; 
} 
 Compiler 
directive: 
Tells the 
compiler 
what to do 
before 
compiling 
 This one 
includes 
source code 
from another 
file
Simple C++ Program 
#include <iostream.h> 
int main() 
{ 
// Declarations 
// Statements 
return 0; 
} 
 Main function
Simple C++ Program 
#include <iostream.h> 
int main() 
{ 
// Declarations 
// Statements 
return 0; 
} 
 Header for 
main function 
 States… 
 data type 
for the 
return value 
 identifier for 
function 
 list of 
arguments 
between 
parenthesis 
(none for 
this 
function)
Simple C++ Program 
#include <iostream.h> 
int main() 
{ 
// Declarations 
// Statements 
return 0; 
} 
 Braces 
enclose the 
body of the 
function 
 They 
represent the 
start and end 
of the 
function
Simple C++ Program 
#include <iostream.h> 
int main() 
{ 
// Declarations 
// Statements 
return 0; 
} 
 Declarations 
and 
statements 
 Main body of 
function (or 
main part) 
 “//” 
represents 
the start of a 
comment
Simple C++ Program 
#include <iostream.h> 
int main() 
{ 
// Declarations 
// Statements 
return 0; 
} 
 Return 
statement 
 specifies the 
value the 
function 
returns 
 All (almost) 
declarations 
and 
statements 
end with a 
semi-colon 
“;”
Simple C++ Program 
#include <iostream.h> 
int main() 
{ 
// Declarations 
// Statements 
return 0; 
} 
 This 
program 
doesn’t 
do 
anything 
!
Sample C++ Program 
#include <iostream.h> 
void main() 
{ 
int number; 
cout << “Enter a number” << 
endl; 
cin >> number; 
cout << “You entered: “ << 
number << endl; 
} 
 Variable 
declaration 
 The identifier 
number is 
declared as 
being of data 
type int, or 
integer
Sample C++ Program 
#include <iostream.h> 
void main() 
{ 
int number; 
cout << “Enter a number” << 
endl; 
cin >> number; 
cout << “You entered: “ << 
number << endl; 
} 
 cout 
the output 
statement for 
C++ 
 Note the 
direction of 
“<<“ 
 endl 
represents an 
end-of-line
Sample C++ Program 
#include <iostream.h> 
void main() 
{ 
int number; 
cout << “Enter a number” << 
endl; 
cin >> number; 
cout << “You entered: “ << 
number << endl; 
} 
 cin 
the input 
statement for 
C++ 
 Note the 
direction of 
“>>”
Sample C++ Program 
#include <iostream.h> 
void main() 
{ 
int number; 
cout << “Enter a number” << 
endl; 
cin >> number; 
cout << “You entered: “ << 
number << endl; 
} 
 Did you 
copy this 
down? 
 You had 
better, 
since this 
will be the 
first 
program 
you’ll try!
Sample C++ Program 
#include <iostream.h> 
void main() 
{ 
int number; 
cout << “Enter a number” << 
endl; 
cin >> number; 
cout << “You entered: “ << 
number << endl; 
} 
That 
mea 
ns 
right 
now!
Assignment 
 Assignment is an operation that assigns 
the value of an expression to a variable 
 Ex. 
Total = 2 + 3 + 5 
 First, the expresssion “2 + 3 + 5” is 
evaluated 
 Then, this value is assigned to the 
variable “Total”
Assignment 
 When a variable is declared, space is 
allocated in the computer’s memory for the 
variable 
 Each data type requires a different number of 
bytes in memory for storing a variable 
int - 2 
float - 4 
double - 8 
char, bool - 1
Assignment 
 When a variable is 
assigned a value, 
the value is placed 
into the variable’s 
memory location 
10 
Total 
Total = 2 + 3 + 5;
Arithmetic Operations 
 Addition: 2 + 3 
 Subtraction: 5 - 2 
 Multiplication: 10 * 4 
 Division: 12 / 3
Order of Operations 
 Arithmetic expressions are evaluated 
according to the following order of 
operations 
 At each level, operations are evaluated 
left to right 
 (1) Parenthesis, Functions 
(2) Multiplication, Division 
(3) Addition, Subtraction
Parenthesis 
 Parenthesis are used to alter the order 
with which operations are evaluated 
 Ex. 
4 + 5 * 2 equals 14 
(4 + 5) * 2 equals 18
Here we go! 
 Problem: To determine the average of three 
numbers 
 Task: Request, from the user, three numbers, 
compute the average and the three numbers, 
and print out the original values and the 
computed average 
 Do it! 
 You have 20 minutes!
Computer Science I 
Functions
Q: What is a function? 
 A programming unit 
 Similar to mathematical functions 
 Example: 
 f(x) = x2 + 5x + 7 
 For x = 2, f(2) = (2)2 =5(2) + 7 = 21
Q: What is a function? 
 It has... 
 ... arguments 
 ... a name 
(identifier) 
 ... a value it 
returns 
 ... a bodyint foo(int x) 
{ 
int result; 
result = x*x + 5*x + 7; 
return result; 
}
Procedural Abstraction 
 Think “Black Box” ! 
 When using a function, you only need 
to be concerned with what it does, not 
how it does it 
 When writing a function, you need to 
be concerned with the how
Example: Cube it! 
int cubeIt(int x) 
{ 
int result; 
result = x*x*x; 
return result; 
} 
int cubeIt(int x) 
{ 
int result; 
result = x; 
result = x*result; 
result = x*result; 
return result; 
}
Pseudocode 
 Looks like a programming language 
 Has all the structure of a programming 
language 
 Has a verrrrrry loose syntax
Pseudocode 
 Example: 
function foo (x) 
result  x2 + 5x + 7 
return result 
 That’s it! 
 Sloppy, ain’t it?
Computer Science I 
Decision Statements
Q: What is a decision? 
 Something that represents a branching 
point in a solution 
 Outcomes are often dependent on initial 
conditions
Decisions in Programs 
 Without decision statements (or other 
dynamic control structures), programs 
are static 
 Static programs do exactly the same 
things each time they are executed 
 Dynamic programs do not
Boolean Algebra 
 Based on values that are either True or 
False 
 True and False values are often 
represented by 1’s and 0’s, respectively
Logical Operations: And 
 A  B 
 Expression is True 
iff A and B are 
both true 
T F 
T T F 
F F F
Logical Operations: Or 
 A  B 
 Expression is True 
if either A or B are 
True 
 Note: Also True 
when A and B are 
both True 
T F 
T T T 
F T F
Logical Operations: Exercises 
A = True, B = True, C = False 
1. A  B 
2. A  C 
3. A  B  C 
4. (A  B)  (A  C)
Relational Operations 
 A < B “A less than B” 
 A > B “A greater than B” 
 A = B “A equal to B” 
 A  B “A less than or equal to B” 
“A not greater than B” 
 A  B “A greater than or equal to B” 
“A not less than B” 
 A  B “A not equal to B” 
“A less than or greater than B”
Relational Operations: 
Exercises 
A = 5, B = 3, C = -7 
1. A < B 
2. A  C 
3. (A < C)  (B < C)
Boolean Operations: C++ 
 A  B 
 A  B 
 A < B 
 A > B 
 A = B 
 A  B 
 A  B 
 A  B 
 A && B 
 A | | B 
 A < B 
 A > B 
 A = = B 
 A > = B 
 A < = B 
 A < > B
Try this! 
Problem: 
 You’d like to go see a movie. 
 The movie costs $8.00, a soda costs $2.50 
and a large popcorn costs $4.50. 
 Based on the amount of money in your 
pocket, determine whether you could... 
(a) See the movie and buy a soda, 
(b) See the movie, and buy soda and 
popcorn, or 
(c) Stay home
Know? 
 Movie costs $8.00 
 Soda costs $2.50 
 Popcorn costs $4.50 
 How much money I have in my pocket
Need? 
 Cost of movie and soda 
 Cost of movie, soda and popcorn 
 Way to select one of the three options 
(that is, make a decision!)
Do? 
 Option (a) costs $10.50 
 Option (b) costs $15.00 
 Option (c) costs nothing 
 What next?
How about a diagram? 
 This is 
called a 
flowchart 
Stay home Money < $15.00 
Movie & soda 
Movie, soda 
& popcorn 
Money < $10.50
How about a diagram? 
 Boxes 
represent 
actions 
Stay home Money < $15.00 
Movie & soda 
Movie, soda 
& popcorn 
Money < $10.50
How about a diagram? 
 Diamonds 
represent 
decision 
points 
Stay home Money < $15.00 
Movie & soda 
Movie, soda 
& popcorn 
Money < $10.50
How about a diagram? 
 Arrows 
show flow 
Stay home Money < $15.00 
Movie & soda 
Movie, soda 
& popcorn 
Money < $10.50
How about a diagram? 
 The arrow 
at the top 
tells us 
there were 
previous 
steps 
 The arrow 
at the 
bottom 
tells us 
there are 
subsequen 
t steps 
Stay home Money < $15.00 
Movie & soda 
Movie, soda 
& popcorn 
Money < $10.50
How would I write this? 
 Using Pseudocode 
 Wait! 
 What the CENSORED is Pseudocode?
Pseudocode 
 Looks like a programming language 
 Has all the structure of a programming 
language 
 Has a verrrrrry loose syntax
Pseudocode 
 Example: 
get x 
result <- x2 + 5x + 7 
print result 
 That’s it! 
 Sloppy, ain’t it?
One more time! 
 Pseudocode... 
If (Money < $10.50) then 
Stay home 
else If (Money < $15.00) then 
Movie, soda 
else Movie, soda, popcorn
How would I write this? 
 First, we need to decide how to 
organize our solution 
 Should we “hard code” the costs of the 
movie, soda and popcorn into the 
algorithm? 
 Should we input these values? 
 Let’s take another look at that problem!
How would I write this? 
 The problem 
statement tells us 
the individual costs 
 So, let’s assume 
they’re fixed or 
constant 
 No need to ask the 
user for them 
Problem: 
 You’d like to go see a movie. 
 The movie costs $8.00, a soda 
costs $2.50 and a large popcorn 
costs $4.50. 
 Based on the amount of money 
in your pocket, determine 
whether you could... 
(a) See the movie and buy a 
soda, 
(b) See the movie, and buy 
soda and popcorn, or 
(c) Stay home
How would I write this? 
 Another question: Should we pre-compute 
the cost of each option? 
 Or, should we let the program do this? 
 Since we’ve already stated that the item costs 
are fixed, it would seem logical to pre-compute 
the cost of each option 
 Movie: $8.00 
 Movie & soda: $10.50 
 All three: $15.00
How would I write this? 
 Next, we need to make sure we have a 
complete algorithm 
Input Money 
If (Money < $10.50) then 
Display “Stay home.” 
else If (Money < $15.00) then 
Display “Go to a movie;buy a soda.” 
else Display “Go to a movie; buy a 
soda and 
popcorn.” 
 Almost done!
How would I write this? 
 Determine how we wish to organize our 
program 
 Do we want one function? 
 Or, should we create a few functions? 
 Let’s two functions: One to input Money 
from the user 
 And a second to determine the outcome
How would I write this? 
 Here’s the prototypes for the functions 
int getMoney() 
void showResults(int myMoney)
Program 
 Okay, now we get to use our algorithm 
and program design to create a 
program 
 Well, what are you waiting for? 
Do It!!!
Multiway Branching 
 If statements can be used for multiway 
branching 
 That is, choosing one of n mutually 
exclusive outcomes 
 But what about n outcomes that are not 
totally unique?
Multiway Branching 
 Consider the following problem: 
Each year, a local middle school 
requires students to purchase supplies 
based on their grade level. 6th graders 
need pencils and five notebooks. 7th 
graders also need a calculator. 8th 
graders add to this a 3-ring binder with 
loose leaf paper.
Multiway Branching 
 We could use a nested If statement to handle 
this, but there is an alternative 
 Whenever we need to represent a decision 
step, with n possible outcomes, where 
 the outcomes form subsets of each other, 
and/or 
 the outcomes are chosen based upon 
unique scalar values for a control 
expression, 
 we can use a Case (switch) structure
Multiway Branching 
 Case 
When Grade = 8th 
3-ring binder 
loose leaf paper 
When Grade = 7th 
calculator 
When Grade = 6th 
pencils 
5 notebooks
Multiway Branching 
 In C++ ... 
switch (grade){ 
case 8: 
cout << “3-ring binder, loose leaf, “; 
case 7: 
cout << “calculator, “; 
case 6: 
cout << “5 notebooks, & pencils.” << endl; 
} 
 When the switch is encountered, control jumps to the 
matching case statement and continues until either a break is 
found or the end of the switch
Multiway Branching 
 Here’s an example with a few break’s 
cout << “Your lunch period comes “; 
switch (grade) { 
case 8: 
cout << “first.” << endl; 
break; 
case 7: 
cout << “second.” << endl; 
break; 
case 6: 
cout << “third.” << endl; 
} No final break
Exercise: 
 Create a program that will inform the 
user which advisor they should go to 
based on their major code number 
Well? Get started!
Computer Science I 
Loops
Q: What is a Loop? 
 A control structure that allows for a 
sequence of steps to be repeated a 
certain number of times 
 This sequence of steps is called the 
body of the loop
Q: What is a Loop? 
 There are three basic loop structures in 
programming: 
 For 
 While 
 Repeat
While loop 
Condition 
T 
Body 
F 
Look familiar? 
What if you 
added a change 
step to the end 
of the body?
For loop 
Condition 
T 
Body 
F
While loop 
Condition 
T 
Body 
F 
A while loop is 
a control 
structure where 
the body is 
repeated as long 
as the condition 
is true
While loop 
Condition 
T 
Body 
F 
When the 
condition is 
false, the body 
is bypassed, and 
flow continues 
with the next 
part of the 
algorithm
Example: Sequential search 
k  0 
found  False 
while (k<size)  (found) 
do if A[k] = target 
then found  
True 
else k = k + 
1 
(k<size)  (found) 
T 
if A[k] = target 
F 
then found  True 
else k = k + 1
Example: Sequential search 
k = 0; 
found = False; 
while ((k<size) && 
(!found)) 
if (A[k] == target) 
found = True; 
else k = k + 
1; 
(k<size)  (found) 
T 
if A[k] = target 
F 
then found  True 
else k = k + 1
Exercise 
 Strings are arrays of characters 
 How would you determine if a string 
fragment is part of a larger string? 
(needle in a haystack?)
Computer Science I 
Arrays
Q: What is an array? 
 An array is a data structure consisting 
of one or more indexed members 
 An array is like a row of mailboxes at 
the post office 
 Each box is numbered in sequence 
(indices), and … 
 Each box contains the same type of 
stuff (datatype)
An array could be drawn like 
… 
g d a f c z l 
0 1 2 3 4 5 6
An array could be drawn like 
… 
g d a f c z l 
0 1 2 3 4 5 6 
Each box is numbered in sequence
An array could be drawn like 
… 
Each box has the same datatype 
g d a f c z l 
0 1 2 3 4 5 6
In pseudocode we use … 
 X[j] 
 Where X is the name of the array 
(identifier), and … 
 j is an index indicating which position 
in the array we wish to address
An array is declared by … 
int X[10]; 
 Where int is the common datatype for all 
elements in the array, 
 X is the name of the array (identifier), and … 
 10 is the size of the array, or how many 
elements are in the array 
 Indices for a C++ array always begin with 0
Example: Student Grades 
// Declare array 
double stGrades[7]; 
: 
// Assign value to array element 
stGrades[5] = 87; 
: 
// Display array element 
cout << stGrades[3] << endl;
Problem: 
 Create a program that will ask the user 
for three (3) numbers, determine the 
average, and then display the original 
numbers and the average 
 Hint: You might wish to use a loop as 
well as an array!
Computer Science I 
Strings
What is a string? 
 A string is a sequence of characters 
 Example: 
nc9*hNB98B&^v*&G 
 Blank spaces are characters 
 Each character requires one byte of storage 
in memory 
 Each character is represented by a one byte 
character code, usually an ASCII code
Strings 
 A literal is a string bounded by 
quotation marks 
 Example: 
“nc9*hNB 98B&^v*&G” 
 Notice the blanks spaces in the 
sequence - they are characters!
Strings 
 In C++, we declare string variables as 
follows 
 char string_identifier[length]; 
 string_identifier is the name of the 
string variable 
 length represents the length of the 
string, or how many characters are in 
the sequence
Strings 
 Example: 
void main() 
{ 
char name[24]; 
cout << “Enter your name: “; 
cin >> name; 
cout << “Your name is “ << name << 
endl; 
}
Streams 
A stream … 
 Is a flow of characters 
 Is an object that represents either on input 
or an output to a program 
 Can be associated with the keyboard, 
monitor, or files 
 cout is an output stream 
 cin is an input stream
How about file I/O? 
#include <fstream.h> 
: 
ifstream in_stream; 
ofstream out_stream; 
: 
Where definitions for 
datatypes ifstream 
and ofstream are 
located 
Input stream declaration 
Output stream declaration
How about file I/O? 
#include <fstream.h> 
: 
ifstream in_stream; 
ofstream out_stream; 
: 
in_stream.open(“infile.txt”); 
out_stream.open(“outfile.txt”); 
instream >> number; 
outstream << number << endl; 
instream.close(); 
outstream.close(); 
: 
Associates files 
with streams & 
opens files for 
use 
Stream use 
Closes files
What if a file doesn’t exist? 
In_stream.open(“notthere.txt”); 
If (in_stream.fail()) 
{ 
cout << “Input file opening failed” << endl; 
exit(1); 
}
How about formatting? 
out_stream.setf(ios::fixed); 
out_stream.setf(ios::showpoint); 
out_stream.precision(2); 
out_stream.width(10); 
: 
Set flag: 
fixed/scientific 
showpoint 
showpos 
right/left 
Number of 
decimal places 
Number of digits
More member functions 
 get() 
 put() 
 eof()
Introduction to C++

More Related Content

What's hot

Virtual base class
Virtual base classVirtual base class
Virtual base classTech_MX
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member FunctionsMOHIT AGARWAL
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarSivakumar R D .
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language Mohamed Loey
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptAmanuelZewdie4
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteachingeteaching
 

What's hot (20)

Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
C introduction by thooyavan
C introduction by  thooyavanC introduction by  thooyavan
C introduction by thooyavan
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Oops ppt
Oops pptOops ppt
Oops ppt
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
 
concept of oops
concept of oopsconcept of oops
concept of oops
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
C# basics
 C# basics C# basics
C# basics
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
C program
C programC program
C program
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteaching
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Unit 8. Pointers
Unit 8. PointersUnit 8. Pointers
Unit 8. Pointers
 
C# Basics
C# BasicsC# Basics
C# Basics
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 

Viewers also liked

Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming LanguageAhmad Idrees
 
Functions assignment
Functions assignmentFunctions assignment
Functions assignmentAhmad Kamal
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Twoamiable_indian
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language samt7
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by ExampleOlve Maudal
 
Introduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsIntroduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsAndrew McNicol
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
Basics of bioinformatics
Basics of bioinformaticsBasics of bioinformatics
Basics of bioinformaticsAbhishek Vatsa
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 

Viewers also liked (13)

Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
Functions assignment
Functions assignmentFunctions assignment
Functions assignment
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
 
Overview of c++ language
Overview of c++ language   Overview of c++ language
Overview of c++ language
 
C++ language
C++ languageC++ language
C++ language
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Introduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsIntroduction to Python for Security Professionals
Introduction to Python for Security Professionals
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Basics of bioinformatics
Basics of bioinformaticsBasics of bioinformatics
Basics of bioinformatics
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Deep C
Deep CDeep C
Deep C
 

Similar to Introduction to C++

03 Variables - Chang.pptx
03 Variables - Chang.pptx03 Variables - Chang.pptx
03 Variables - Chang.pptxDileep804402
 
introductiontoc-140704113737-phpapp01.pdf
introductiontoc-140704113737-phpapp01.pdfintroductiontoc-140704113737-phpapp01.pdf
introductiontoc-140704113737-phpapp01.pdfSameerKhanPathan7
 
C++ Programming.pdf
C++ Programming.pdfC++ Programming.pdf
C++ Programming.pdfMrRSmey
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for KidsAimee Maree Forsstrom
 
Qust & ans inc
Qust & ans incQust & ans inc
Qust & ans incnayakq
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyGrejoJoby1
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
2.overview of c#
2.overview of c#2.overview of c#
2.overview of c#Raghu nath
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsDhivyaSubramaniyam
 
C101-PracticeProblems.pdf
C101-PracticeProblems.pdfC101-PracticeProblems.pdf
C101-PracticeProblems.pdfT17Rockstar
 
Introduction to python programming ( part-1)
Introduction to python programming  ( part-1)Introduction to python programming  ( part-1)
Introduction to python programming ( part-1)Ziyauddin Shaik
 
Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)ExcellenceAcadmy
 

Similar to Introduction to C++ (20)

03 Variables - Chang.pptx
03 Variables - Chang.pptx03 Variables - Chang.pptx
03 Variables - Chang.pptx
 
introductiontoc-140704113737-phpapp01.pdf
introductiontoc-140704113737-phpapp01.pdfintroductiontoc-140704113737-phpapp01.pdf
introductiontoc-140704113737-phpapp01.pdf
 
MODULE. .pptx
MODULE.                              .pptxMODULE.                              .pptx
MODULE. .pptx
 
901131 examples
901131 examples901131 examples
901131 examples
 
C++ Programming.pdf
C++ Programming.pdfC++ Programming.pdf
C++ Programming.pdf
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Qust & ans inc
Qust & ans incQust & ans inc
Qust & ans inc
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
C++
C++C++
C++
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
2.overview of c#
2.overview of c#2.overview of c#
2.overview of c#
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
 
C101-PracticeProblems.pdf
C101-PracticeProblems.pdfC101-PracticeProblems.pdf
C101-PracticeProblems.pdf
 
Introduction to python programming ( part-1)
Introduction to python programming  ( part-1)Introduction to python programming  ( part-1)
Introduction to python programming ( part-1)
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)
 

More from Bharat Kalia

PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts Bharat Kalia
 
Groupware Technology Project Report
Groupware Technology Project ReportGroupware Technology Project Report
Groupware Technology Project ReportBharat Kalia
 
Extending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific ComputingExtending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific ComputingBharat Kalia
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud ComputingBharat Kalia
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C BasicsBharat Kalia
 
OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia Bharat Kalia
 
Mingle box - Online Job seeking System
Mingle box - Online Job seeking SystemMingle box - Online Job seeking System
Mingle box - Online Job seeking SystemBharat Kalia
 
Project report of OCR Recognition
Project report of OCR RecognitionProject report of OCR Recognition
Project report of OCR RecognitionBharat Kalia
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsBharat Kalia
 
Basic Programs of C++
Basic Programs of C++Basic Programs of C++
Basic Programs of C++Bharat Kalia
 

More from Bharat Kalia (10)

PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Groupware Technology Project Report
Groupware Technology Project ReportGroupware Technology Project Report
Groupware Technology Project Report
 
Extending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific ComputingExtending Grids with Cloud Resource Management for Scientific Computing
Extending Grids with Cloud Resource Management for Scientific Computing
 
Introduction to Cloud Computing
Introduction to Cloud ComputingIntroduction to Cloud Computing
Introduction to Cloud Computing
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
 
OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia OLAP Basics and Fundamentals by Bharat Kalia
OLAP Basics and Fundamentals by Bharat Kalia
 
Mingle box - Online Job seeking System
Mingle box - Online Job seeking SystemMingle box - Online Job seeking System
Mingle box - Online Job seeking System
 
Project report of OCR Recognition
Project report of OCR RecognitionProject report of OCR Recognition
Project report of OCR Recognition
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental Concepts
 
Basic Programs of C++
Basic Programs of C++Basic Programs of C++
Basic Programs of C++
 

Recently uploaded

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 

Recently uploaded (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 

Introduction to C++

  • 1. Introduction to C++ Computer Science I
  • 2. Q: What is C++  C++ is a compiled, object-oriented language  It is the “successor” to C, a procedural language  (the “++” is called the successor operator in C++)  C was derived from a language called B which was in turn derived from BCPL  C was developed in the 1970’s by Dennis Ritchie of AT&T Bell Labs  C++ was developed in the early 1980’s by Bjarne Stroustrup of AT&T Bell Labs.  Most of C is a subset of C++
  • 3. People & Programs  User: an individual who runs, or executes, a program  Programmer: an individual who creates, or writes, a program
  • 4. C++ Program Consists of…  Declarations  Define the use of various identifiers, thus creating the elements used by the program (computer)  Statements  Or executable statements, representing actions the computer will take on the user’s behalf
  • 5. Identifiers  Names for various entities used in a program; used for...  Variables: values that can change frequently  Constants: values that never changes  Functions: programming units that represents complex operations  Parameters: values that change infrequently
  • 6. Simple C++ Program #include <iostream.h> int main() { // Declarations // Statements return 0; }  Compiler directive: Tells the compiler what to do before compiling  This one includes source code from another file
  • 7. Simple C++ Program #include <iostream.h> int main() { // Declarations // Statements return 0; }  Main function
  • 8. Simple C++ Program #include <iostream.h> int main() { // Declarations // Statements return 0; }  Header for main function  States…  data type for the return value  identifier for function  list of arguments between parenthesis (none for this function)
  • 9. Simple C++ Program #include <iostream.h> int main() { // Declarations // Statements return 0; }  Braces enclose the body of the function  They represent the start and end of the function
  • 10. Simple C++ Program #include <iostream.h> int main() { // Declarations // Statements return 0; }  Declarations and statements  Main body of function (or main part)  “//” represents the start of a comment
  • 11. Simple C++ Program #include <iostream.h> int main() { // Declarations // Statements return 0; }  Return statement  specifies the value the function returns  All (almost) declarations and statements end with a semi-colon “;”
  • 12. Simple C++ Program #include <iostream.h> int main() { // Declarations // Statements return 0; }  This program doesn’t do anything !
  • 13. Sample C++ Program #include <iostream.h> void main() { int number; cout << “Enter a number” << endl; cin >> number; cout << “You entered: “ << number << endl; }  Variable declaration  The identifier number is declared as being of data type int, or integer
  • 14. Sample C++ Program #include <iostream.h> void main() { int number; cout << “Enter a number” << endl; cin >> number; cout << “You entered: “ << number << endl; }  cout the output statement for C++  Note the direction of “<<“  endl represents an end-of-line
  • 15. Sample C++ Program #include <iostream.h> void main() { int number; cout << “Enter a number” << endl; cin >> number; cout << “You entered: “ << number << endl; }  cin the input statement for C++  Note the direction of “>>”
  • 16. Sample C++ Program #include <iostream.h> void main() { int number; cout << “Enter a number” << endl; cin >> number; cout << “You entered: “ << number << endl; }  Did you copy this down?  You had better, since this will be the first program you’ll try!
  • 17. Sample C++ Program #include <iostream.h> void main() { int number; cout << “Enter a number” << endl; cin >> number; cout << “You entered: “ << number << endl; } That mea ns right now!
  • 18. Assignment  Assignment is an operation that assigns the value of an expression to a variable  Ex. Total = 2 + 3 + 5  First, the expresssion “2 + 3 + 5” is evaluated  Then, this value is assigned to the variable “Total”
  • 19. Assignment  When a variable is declared, space is allocated in the computer’s memory for the variable  Each data type requires a different number of bytes in memory for storing a variable int - 2 float - 4 double - 8 char, bool - 1
  • 20. Assignment  When a variable is assigned a value, the value is placed into the variable’s memory location 10 Total Total = 2 + 3 + 5;
  • 21. Arithmetic Operations  Addition: 2 + 3  Subtraction: 5 - 2  Multiplication: 10 * 4  Division: 12 / 3
  • 22. Order of Operations  Arithmetic expressions are evaluated according to the following order of operations  At each level, operations are evaluated left to right  (1) Parenthesis, Functions (2) Multiplication, Division (3) Addition, Subtraction
  • 23. Parenthesis  Parenthesis are used to alter the order with which operations are evaluated  Ex. 4 + 5 * 2 equals 14 (4 + 5) * 2 equals 18
  • 24. Here we go!  Problem: To determine the average of three numbers  Task: Request, from the user, three numbers, compute the average and the three numbers, and print out the original values and the computed average  Do it!  You have 20 minutes!
  • 25. Computer Science I Functions
  • 26. Q: What is a function?  A programming unit  Similar to mathematical functions  Example:  f(x) = x2 + 5x + 7  For x = 2, f(2) = (2)2 =5(2) + 7 = 21
  • 27. Q: What is a function?  It has...  ... arguments  ... a name (identifier)  ... a value it returns  ... a bodyint foo(int x) { int result; result = x*x + 5*x + 7; return result; }
  • 28. Procedural Abstraction  Think “Black Box” !  When using a function, you only need to be concerned with what it does, not how it does it  When writing a function, you need to be concerned with the how
  • 29. Example: Cube it! int cubeIt(int x) { int result; result = x*x*x; return result; } int cubeIt(int x) { int result; result = x; result = x*result; result = x*result; return result; }
  • 30. Pseudocode  Looks like a programming language  Has all the structure of a programming language  Has a verrrrrry loose syntax
  • 31. Pseudocode  Example: function foo (x) result  x2 + 5x + 7 return result  That’s it!  Sloppy, ain’t it?
  • 32. Computer Science I Decision Statements
  • 33. Q: What is a decision?  Something that represents a branching point in a solution  Outcomes are often dependent on initial conditions
  • 34. Decisions in Programs  Without decision statements (or other dynamic control structures), programs are static  Static programs do exactly the same things each time they are executed  Dynamic programs do not
  • 35. Boolean Algebra  Based on values that are either True or False  True and False values are often represented by 1’s and 0’s, respectively
  • 36. Logical Operations: And  A  B  Expression is True iff A and B are both true T F T T F F F F
  • 37. Logical Operations: Or  A  B  Expression is True if either A or B are True  Note: Also True when A and B are both True T F T T T F T F
  • 38. Logical Operations: Exercises A = True, B = True, C = False 1. A  B 2. A  C 3. A  B  C 4. (A  B)  (A  C)
  • 39. Relational Operations  A < B “A less than B”  A > B “A greater than B”  A = B “A equal to B”  A  B “A less than or equal to B” “A not greater than B”  A  B “A greater than or equal to B” “A not less than B”  A  B “A not equal to B” “A less than or greater than B”
  • 40. Relational Operations: Exercises A = 5, B = 3, C = -7 1. A < B 2. A  C 3. (A < C)  (B < C)
  • 41. Boolean Operations: C++  A  B  A  B  A < B  A > B  A = B  A  B  A  B  A  B  A && B  A | | B  A < B  A > B  A = = B  A > = B  A < = B  A < > B
  • 42. Try this! Problem:  You’d like to go see a movie.  The movie costs $8.00, a soda costs $2.50 and a large popcorn costs $4.50.  Based on the amount of money in your pocket, determine whether you could... (a) See the movie and buy a soda, (b) See the movie, and buy soda and popcorn, or (c) Stay home
  • 43. Know?  Movie costs $8.00  Soda costs $2.50  Popcorn costs $4.50  How much money I have in my pocket
  • 44. Need?  Cost of movie and soda  Cost of movie, soda and popcorn  Way to select one of the three options (that is, make a decision!)
  • 45. Do?  Option (a) costs $10.50  Option (b) costs $15.00  Option (c) costs nothing  What next?
  • 46. How about a diagram?  This is called a flowchart Stay home Money < $15.00 Movie & soda Movie, soda & popcorn Money < $10.50
  • 47. How about a diagram?  Boxes represent actions Stay home Money < $15.00 Movie & soda Movie, soda & popcorn Money < $10.50
  • 48. How about a diagram?  Diamonds represent decision points Stay home Money < $15.00 Movie & soda Movie, soda & popcorn Money < $10.50
  • 49. How about a diagram?  Arrows show flow Stay home Money < $15.00 Movie & soda Movie, soda & popcorn Money < $10.50
  • 50. How about a diagram?  The arrow at the top tells us there were previous steps  The arrow at the bottom tells us there are subsequen t steps Stay home Money < $15.00 Movie & soda Movie, soda & popcorn Money < $10.50
  • 51. How would I write this?  Using Pseudocode  Wait!  What the CENSORED is Pseudocode?
  • 52. Pseudocode  Looks like a programming language  Has all the structure of a programming language  Has a verrrrrry loose syntax
  • 53. Pseudocode  Example: get x result <- x2 + 5x + 7 print result  That’s it!  Sloppy, ain’t it?
  • 54. One more time!  Pseudocode... If (Money < $10.50) then Stay home else If (Money < $15.00) then Movie, soda else Movie, soda, popcorn
  • 55. How would I write this?  First, we need to decide how to organize our solution  Should we “hard code” the costs of the movie, soda and popcorn into the algorithm?  Should we input these values?  Let’s take another look at that problem!
  • 56. How would I write this?  The problem statement tells us the individual costs  So, let’s assume they’re fixed or constant  No need to ask the user for them Problem:  You’d like to go see a movie.  The movie costs $8.00, a soda costs $2.50 and a large popcorn costs $4.50.  Based on the amount of money in your pocket, determine whether you could... (a) See the movie and buy a soda, (b) See the movie, and buy soda and popcorn, or (c) Stay home
  • 57. How would I write this?  Another question: Should we pre-compute the cost of each option?  Or, should we let the program do this?  Since we’ve already stated that the item costs are fixed, it would seem logical to pre-compute the cost of each option  Movie: $8.00  Movie & soda: $10.50  All three: $15.00
  • 58. How would I write this?  Next, we need to make sure we have a complete algorithm Input Money If (Money < $10.50) then Display “Stay home.” else If (Money < $15.00) then Display “Go to a movie;buy a soda.” else Display “Go to a movie; buy a soda and popcorn.”  Almost done!
  • 59. How would I write this?  Determine how we wish to organize our program  Do we want one function?  Or, should we create a few functions?  Let’s two functions: One to input Money from the user  And a second to determine the outcome
  • 60. How would I write this?  Here’s the prototypes for the functions int getMoney() void showResults(int myMoney)
  • 61. Program  Okay, now we get to use our algorithm and program design to create a program  Well, what are you waiting for? Do It!!!
  • 62. Multiway Branching  If statements can be used for multiway branching  That is, choosing one of n mutually exclusive outcomes  But what about n outcomes that are not totally unique?
  • 63. Multiway Branching  Consider the following problem: Each year, a local middle school requires students to purchase supplies based on their grade level. 6th graders need pencils and five notebooks. 7th graders also need a calculator. 8th graders add to this a 3-ring binder with loose leaf paper.
  • 64. Multiway Branching  We could use a nested If statement to handle this, but there is an alternative  Whenever we need to represent a decision step, with n possible outcomes, where  the outcomes form subsets of each other, and/or  the outcomes are chosen based upon unique scalar values for a control expression,  we can use a Case (switch) structure
  • 65. Multiway Branching  Case When Grade = 8th 3-ring binder loose leaf paper When Grade = 7th calculator When Grade = 6th pencils 5 notebooks
  • 66. Multiway Branching  In C++ ... switch (grade){ case 8: cout << “3-ring binder, loose leaf, “; case 7: cout << “calculator, “; case 6: cout << “5 notebooks, & pencils.” << endl; }  When the switch is encountered, control jumps to the matching case statement and continues until either a break is found or the end of the switch
  • 67. Multiway Branching  Here’s an example with a few break’s cout << “Your lunch period comes “; switch (grade) { case 8: cout << “first.” << endl; break; case 7: cout << “second.” << endl; break; case 6: cout << “third.” << endl; } No final break
  • 68. Exercise:  Create a program that will inform the user which advisor they should go to based on their major code number Well? Get started!
  • 70. Q: What is a Loop?  A control structure that allows for a sequence of steps to be repeated a certain number of times  This sequence of steps is called the body of the loop
  • 71. Q: What is a Loop?  There are three basic loop structures in programming:  For  While  Repeat
  • 72. While loop Condition T Body F Look familiar? What if you added a change step to the end of the body?
  • 73. For loop Condition T Body F
  • 74. While loop Condition T Body F A while loop is a control structure where the body is repeated as long as the condition is true
  • 75. While loop Condition T Body F When the condition is false, the body is bypassed, and flow continues with the next part of the algorithm
  • 76. Example: Sequential search k  0 found  False while (k<size)  (found) do if A[k] = target then found  True else k = k + 1 (k<size)  (found) T if A[k] = target F then found  True else k = k + 1
  • 77. Example: Sequential search k = 0; found = False; while ((k<size) && (!found)) if (A[k] == target) found = True; else k = k + 1; (k<size)  (found) T if A[k] = target F then found  True else k = k + 1
  • 78. Exercise  Strings are arrays of characters  How would you determine if a string fragment is part of a larger string? (needle in a haystack?)
  • 80. Q: What is an array?  An array is a data structure consisting of one or more indexed members  An array is like a row of mailboxes at the post office  Each box is numbered in sequence (indices), and …  Each box contains the same type of stuff (datatype)
  • 81. An array could be drawn like … g d a f c z l 0 1 2 3 4 5 6
  • 82. An array could be drawn like … g d a f c z l 0 1 2 3 4 5 6 Each box is numbered in sequence
  • 83. An array could be drawn like … Each box has the same datatype g d a f c z l 0 1 2 3 4 5 6
  • 84. In pseudocode we use …  X[j]  Where X is the name of the array (identifier), and …  j is an index indicating which position in the array we wish to address
  • 85. An array is declared by … int X[10];  Where int is the common datatype for all elements in the array,  X is the name of the array (identifier), and …  10 is the size of the array, or how many elements are in the array  Indices for a C++ array always begin with 0
  • 86. Example: Student Grades // Declare array double stGrades[7]; : // Assign value to array element stGrades[5] = 87; : // Display array element cout << stGrades[3] << endl;
  • 87. Problem:  Create a program that will ask the user for three (3) numbers, determine the average, and then display the original numbers and the average  Hint: You might wish to use a loop as well as an array!
  • 89. What is a string?  A string is a sequence of characters  Example: nc9*hNB98B&^v*&G  Blank spaces are characters  Each character requires one byte of storage in memory  Each character is represented by a one byte character code, usually an ASCII code
  • 90. Strings  A literal is a string bounded by quotation marks  Example: “nc9*hNB 98B&^v*&G”  Notice the blanks spaces in the sequence - they are characters!
  • 91. Strings  In C++, we declare string variables as follows  char string_identifier[length];  string_identifier is the name of the string variable  length represents the length of the string, or how many characters are in the sequence
  • 92. Strings  Example: void main() { char name[24]; cout << “Enter your name: “; cin >> name; cout << “Your name is “ << name << endl; }
  • 93. Streams A stream …  Is a flow of characters  Is an object that represents either on input or an output to a program  Can be associated with the keyboard, monitor, or files  cout is an output stream  cin is an input stream
  • 94. How about file I/O? #include <fstream.h> : ifstream in_stream; ofstream out_stream; : Where definitions for datatypes ifstream and ofstream are located Input stream declaration Output stream declaration
  • 95. How about file I/O? #include <fstream.h> : ifstream in_stream; ofstream out_stream; : in_stream.open(“infile.txt”); out_stream.open(“outfile.txt”); instream >> number; outstream << number << endl; instream.close(); outstream.close(); : Associates files with streams & opens files for use Stream use Closes files
  • 96. What if a file doesn’t exist? In_stream.open(“notthere.txt”); If (in_stream.fail()) { cout << “Input file opening failed” << endl; exit(1); }
  • 97. How about formatting? out_stream.setf(ios::fixed); out_stream.setf(ios::showpoint); out_stream.precision(2); out_stream.width(10); : Set flag: fixed/scientific showpoint showpos right/left Number of decimal places Number of digits
  • 98. More member functions  get()  put()  eof()