This document provides an overview of a C++ programming course. It introduces fundamental C++ concepts like data types, variables, input/output statements, and arithmetic, relational, and logical operators. It also presents some simple example programs to calculate the mean of input numbers to demonstrate basic programming constructs like comments, functions, and conditional statements.
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
OOPS using C++
1. Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Semester: 3rd Semester
Subject Code:108
Name of the Subject:
OOPS using C++
2. A C++ program
//include headers; these are modules that include functions that you may use in
your
//program; we will almost always need to include the header that
// defines cin and cout; the header is called iostream.h
#include <iostream.h>
int main() {
//variable declaration
//read values input from user
//computation and print output to user
return 0;
}
After you write a C++ program you compile it; that is, you run a program called
compiler that checks whether the program follows the C++ syntax
– if it finds errors, it lists them
– If there are no errors, it translates the C++ program into a program in machine language
which you can execute
Introduction to Programming
3. Notes
• what follows after // on the same line is considered comment
• indentation is for the convenience of the reader; compiler ignores all spaces and
new line ; the delimiter for the compiler is the semicolon
• all statements ended by semicolon
• Lower vs. upper case matters!!
– Void is different than void
– Main is different that main
Introduction to Programming
4. The infamous
Hello world program
When learning a new language, the first program people
usually write is one that salutes the world :)
Here is the Hello world program in C++.
#include <iostream.h>
int main() {
cout << “Hello world!”;
return 0;
}
Introduction to Programming
5. Variable declaration
type variable-name;
Meaning: variable <variable-name> will be a variable of type <type>
Where type can be:
– int //integer
– double //real number
– char //character
Example:
int a, b, c;
double x;
int sum;
char my-character;
Introduction to Programming
6. Input statements
cin >> variable-name;
Meaning: read the value of the variable called <variable-
name> from the user
Example:
cin >> a;
cin >> b >> c;
cin >> x;
cin >> my-character;
Introduction to Programming
7. Output statements
cout << variable-name;
Meaning: print the value of variable <variable-name> to the user
cout << “any message “;
Meaning: print the message within quotes to the user
cout << endl;
Meaning: print a new line
Example:
cout << a;
cout << b << c;
cout << “This is my character: “ << my-character << “ he he he”
<< endl;
Introduction to Programming
9. Boolean conditions
..are built using
• Comparison operators
== equal
!= not equal
< less than
> greater than
<= less than or equal
>= greater than or equal
• Boolean operators
&& and
|| or
! not
Introduction to Programming
10. Examples
Assume we declared the following variables:
int a = 2, b=5, c=10;
Here are some examples of boolean conditions we can use:
• if (a == b) …
• if (a != b) …
• if (a <= b+c) …
• if(a <= b) && (b <= c) …
• if !((a < b) && (b<c)) …
Introduction to Programming
11. If example
#include <iostream.h>
void main() {
int a,b,c;
cin >> a >> b >> c;
if (a <=b) {
cout << “min is “ << a << endl;
}
else {
cout << “ min is “ << b << endl;
}
cout << “happy now?” << endl;
}
Introduction to Programming
13. While example
//read 100 numbers from the user and output their sum
#include <iostream.h>
void main() {
int i, sum, x;
sum=0;
i=1;
while (i <= 100) {
cin >> x;
sum = sum + x;
i = i+1;
}
cout << “sum is “ << sum << endl;
}
Introduction to Programming
14. C++ Programming
Introduction to Programming
Every programming language has facilities to: In C++
Read data from some input device cin >>
Write output information onto an output device cout <<
Perform arithmetic operations + - * /
Perform relational operations < == >
Perform logical operations ! && ||
Branch to a non-sequential instruction (w/wo structure) while
Store (and retrieve) data values to (and from) memory =
15. Running a simple C++ program
•You will need a C++ compiler to do the work required for this
course. Any C++ compiler will do – e.g., MS Visual C++, Xcode
for Mac, etc.
• We will use Microsoft Visual C++. To get used to working
with the software, follow the step-by-step guide at
– http://sites.google.com/site/proffriedmancplusplus/pdf-files/usingMSVisualStudio.pdf
• Do this now and then return to continue with the rest of this
lecture.
• The test program you used in this guide is explained in the
following slides.
Introduction to Programming
16. Some parts of the program
• This is the program you just ran in your ide:
• // hello.cpp
• // A First Program in C++
• #include <iostream>
• Using namespace std;
•
• int main()
• {
• cout << "Hello. My name is Big Bird.n";
• return 0; //indicates that the program ended successfully
• }
Introduction to Programming
17. Some parts of the program
• Comments - a type of program documentation
•
• // indicates that the remainder of
the line is a comment
•
• /* comments can also look like this
*/
•
• /* also
• like
• this
• */
Introduction to Programming
18. Some parts of the program
•#include <iostream> - a preprocessor directive
•
•Tells the pre-processor to include in the program the
contents of the I/O stream header file called
iostream.h . This allows us to use standard stream
input and output objects like cout (displays to the
screen).
•
•As you can see, we need to also code the using
namespace std; statement. For now, let’s just say
that this is so that we don’t have to use ugly prefixes on
cout, like std::cout.
Introduction to Programming
19. Some parts of the program
• int main( ) - main function header
• Every C++ program has at least one function,
called main. And there is ONLY ONE main.
Program execution begins with the first
statement in main.
•
• { brackets to denote the body of the function }
•
Introduction to Programming
20. Some parts of the program
• ; statement terminator
– Every C++ statement must end with a semicolon.
• << stream insertion operator
– Expression to the right of the operator is inserted (sent) to the
cout object (the display screen or console window).
Introduction to Programming
21. Some parts of the program
• n newline escape sequence
– The backslash is an escape character. The character
following it takes on a different meaning, e.g.:
t - tab
a - alert; ring bell
- prints a backslash
” - prints a double quotation mark
• return - exits from the function
– In this case control over execution is transferred back to
the operating system.
Introduction to Programming
22. A simple C++ program
•The best approach in learning programming for the first time is to treat it like a game. And, as anyone
knows, when you learn a game don't try to understand it just yet – simply learn the "rules of the game"
at first. When you have a few simple programs under your belt, you will be able to understand a bit
about why the code is the way it is.
– This program here produces the output on the next slide
• //mean1.cpp
• // This program calculates the mean of three numbers.
•
• #include <iostream>
• using namespace std; //need this to drop std::
• int main()
• {
• cout << "First Arithmetic Program by Big Bird.nn";
• cout << (12+5+10)/3;
• return 0;
• } //end main
Introduction to Programming
23. A simple C++ program
•This program here produces the output below.
• //mean1.cpp
• // This program calculates the mean of three
numbers.
•
• #include <iostream>
• using namespace std; //need this to drop std::
• int main()
• {
• cout << "First Arithmetic Program by Big
Bird.nn";
• cout << (12+5+10)/3;
• return 0;
• } //end main
Introduction to Programming
24. A simple C++ program
•So we know how to do simple arithmetic with
C++. (Woo hoo!!)
•In the next lecture we will
learn to use variables to store
our data.
Introduction to Programming
25. Review
– arithmetic operator
– assignment operator
– comment
– compiler
– function header
– ide
– link, load, execute
– logical operator
– main function
– object program
– preprocessor
– relational operator
– return statement
– source program
– stream insertion
operator
Introduction to Programming
What did we learn in this lecture? Plenty.
26. Compute the mean of 3 numbers
•This program here produces the output below.
• //mean1.cpp
• // This program calculates the mean of
three numbers.
•
• #include <iostream>
• using namespace std; //need this to drop std::
• int main()
• {
• cout << "First Arithmetic Program by
Big Bird.nn";
• cout << (12+5+10)/3;
• return 0;
• } //end main
Introduction to Programming
27. Compute the mean of 3 numbers
• Now, let’s try using a variable to store the mean before printing it.
• //mean2.cpp
• // This program calculates the mean of three numbers.
• // Big Bird learns about variables.
•
• #include <iostream>
• using namespace std;
• int main()
• {
• float mean;
• cout << "Second Arithmetic Program by Big
Bird.nn";
• mean = (12+5+10)/3;
• cout << mean;
• return 0;
• } //end main
Introduction to Programming
28. Stored Data
•Variables (objects) must be declared as a certain type,
e.g., int, float, char, … This declaration may appear
anywhere in the program, as long as it appears before the
variable is first used. The declaration creates the object.
•For the following declaration,
•int n;
•The name of the object is n, the type (or class) is int. The
object does not yet have a value.
•n = 66; //now it has a value
•or
•int n=66; //This declaration also
gives a value to n
Introduction to Programming
29. Stored Data
•A Variable (object) has:
• A name
• A location in main memory. This is an address in primary
memory where the value of the object is stored while the
program is executing.
• A type (class). A class defines the way the data item looks (e.g.,
char or int), how much space it takes up in memory, and how
it operates.
• A value. It may have a value stored in the named location.
There are 3 ways to give a variable a value:
• Give it an initial value at the declaration: int n=66;
• Assign it a value using the assignment (=) operator: n=66;
• Read the value in from an input device such as the keyboard: cin >> n;
Introduction to Programming
30. Names (Identifiers)
•Variables and other program elements will have to have
names. Names should be meaningful to help document your
program.
–may use letters, digits, underscores. No spaces.
–may not begin with a digit
–may be any length but better if less than 31 characters long.
–C++ is case sensitive; upper and lower case letters are different.
–no reserved words (e.g., const, void, int, …).
–Avoid using names beginning with _ (underscore) or _ _ (double
underscore). The C++ compiler uses names like that for special
purposes.
Introduction to Programming
31. Compute the mean of 3 numbers
(again)
• //mean3.cpp
• // This program calculates the mean of three numbers.
• // Big Bird tries new data.
•
• #include <iostream>
• using namespace std;
• int main()
• {
• float mean;
• cout << "Third Arithmetic Program by Big Bird.nn";
• mean = (11+5+10)/3;
• cout << mean;
• return 0;
• } //end main
• OOPS!! What happened?
Introduction to Programming
32. Types of errors in our programs
• Syntax errors – compile-time errors
– These errors are picked up by the compiler and we will
usually get error messages about them. Syntax errors
result from using the language incorrectly.
• Logic errors – run-time errors
– These errors are generally not flagged by the system.
We find out about them by checking the output to see
whether it is correct.
Introduction to Programming
33. Compute the mean of 3 numbers
• This is better:
• //mean4.cpp
• // This program calculates the mean of three numbers.
• // Big Bird learns that expressions have a type.
•
• #include <iostream>
• using namespace std;
• int main()
• {
• float mean;
• cout << "Fourth Arithmetic Program by Big
Bird.nn";
• mean = (11+5+10)/3.0;
• cout << mean;
• return 0;
• } //end main
Introduction to Programming
34. Compute the mean of 3 numbers
•NOW we have a working program that correctly
gives us the mean of 11 and 5 and 10…. WOW!!
[Uh… How useful is this?]
•What if we want to be able to calculate the
mean of ANY three numbers? We need to input
data to the program.
Introduction to Programming
35. Compute the mean of any 3 numbers
• //mean5.cpp
• // This program calculates the mean of ANY three numbers.
• // Big Bird learns about input data.
•
• #include <iostream>
• using namespace std;
• int main()
• {
• float num1, num2, num3, mean;
• cout << "Big Bird learns about input data.n";
• cout << endl;
• cout << "Enter first number: ";
• //prompt user for input
• cin >> num1;
• cout << "Enter second number: ";
• cin >> num2;
• cout << "Enter third number: ";
• cin >> num3;
• mean = (num1+num2+num3)/3.0;
• cout << "The average of " << num1 << " and " << num2 <<
• " and " << num3;
• cout << " is equal to = " << mean << endl <<endl;
• cout << "Th-th-that's all folks!n";
• return 0;
• } //end main
Introduction to Programming
36. Stream Input / Output
• cout << //means “cout gets a value”
• cin >> var //means “cin gives a value to var”
• //note: on execution press enter key to end input
• >> is the stream extraction operator
• << is the stream insertion operator
– The stream insertion operator “knows” how to output different
types of data.
•Cascading stream insertion operators - using multiple stream
insertion operators in a single statement. Also known as
concatenating or chaining, e.g.,
• cout << “The answer is: ” << result <<
".n";
Introduction to Programming
37. Review
– assignment operation
– cascading stream
insertion operators
– class
– compile-time error
– data type
– declaring a variable
– logic error
– object
– run-time error
– stream extraction
operator
– stream insertion operator
– syntax
– syntax error
– variable
Introduction to Programming
What did we learn in this lecture? Plenty. Some terms to jog your memories:
38. About data types
• A data type is a template for
– how a particular set of values is represented in memory, and
– what operations can be performed on those values.
•
• In C++ a type is the same as a class.
• There are
– predefined data types
– system-defined types
– user-defined types
Introduction to Programming
39. About data types
• Predefined data types are part of the C++ language definition.
– Examples: float, double - real. int - integer. char
• We denote char literals with single quotes, for example: ‘A’ ‘*’ ‘2’
– A string literal is a sequence of characters in double quotes:
• “ABCDE”
• “127” (not the same as int 127)
• “true” (not the same as bool true)
•
•System-defined types - part of the C++ class libraries. Not part of the original C++ language definition but
added when the compiler is written.
– The standard I/O stream objects cin and cout are defined in iostream library
– Also there is a string class (type) and classes for input and output files.
• To declare an output file: ofstream cprint (“file.txt”);
•
• User-defined types - e.g., enum type, classes
Introduction to Programming
40. declarations
•Declarations inform the compiler that it will need to set aside space in
memory to hold an object of a particular type (class) with a particular
name.
•
• Constant declarations
– Used to associate meaningful names with constants -- items that will
never change throughout the execution of the program.
– One convention is to use all uppercase letters for constant identifiers.
const float PI=3.14159;
const float METERS_TO_YARDS=1.196;
Introduction to Programming
41. declarations
• Variable declarations:
– Used to associate identifiers of a given type with
memory cells used to store values of this type. -
the values stored in the data cells are changeable.
char letter;
char letter1, letter2;
float x, y;
Introduction to Programming
42. declarations
• Object declarations
– Like variables, these are used to associate identifiers
of a given type with memory cells used to store values
of this type. - the values stored in the data cells are
changeable. We use some system-defined classes in
the standard C++ class libraries. A class is equivalent
to a type; variables can store data values and are
called objects.
ofstream cprn (“printfile.txt”);
Introduction to Programming
class object
43. Data type: int
•The variable’s type (or class) tells the compiler how the variable’s values are
to be stored and how they may be used.
•
• There are nine int types:
short int unsigned short int char
int unsigned int signed char
long int unsigned long int unsigned char
•
•The differences among these 9 types are due to the range of values each
allows. These ranges may depend somewhat on the computer system.
– short is the same as short int
•On some computers (DOS PCs) the int set of values consists of all integers in
the range –32,768 to 32,767. [Why?]
Introduction to Programming
44. Data type: char
• char type uses 8 bits to store a single character. Is
actually a numeric type in that it stores the ASCII
(American Standard Code for Information
Interchange) code value of the character.
Character input is automatically converted; on
output the value is converted to the equivalent
char first.
• char, signed char, unsigned char
• Use unsigned char for a very short bit-string.
Depending on the system, char will be equivalent
to either signed char or unsigned char.
Introduction to Programming
45. Data type: char
• examples using char data type:
char c = 54;
char d = 2 * c – 7;
c++ ;
…
…
char c = 64;
cout << c << “ “; //prints ‘@’
c = c + 1; //increments c to 65
cout << c << “ “; //prints ‘A’
c = c + 1; //increments c to 66
cout << c << “ “; //prints ‘B’
c = c + 1; //increments c to 67
cout << c << “ “; //prints ‘C’
…
Introduction to Programming
46. Data type: char typecasting
•We can convert char to int. The int(char) function is a
cast. In this next example, it converts c from char type to
int type:
#include <iostream>
using namespace std;
void main (){
char c = 64;
cout << c << " is the same as " << int(c) << endl;
c = c+ 1;
cout << c << " is the same as " << int(c) << endl;
c = c+ 1;
cout << c << " is the same as " << int(c) << endl;
c = c+ 1;
cout << c << " is the same as " << int(c) << endl;
return;
}
• This is called typecasting – we can also cast, e.g.,
float(c); int(fl); …
Introduction to Programming
47. Arithmetic Operators
• The built-in arithmetic operations are
– Addition +
– Subtraction
– Multiplication *
– Division / (is integer division if operators are integers)
– Modulus % (remainder)
Introduction to Programming
48. Arithmetic Operators
• e.g., if the value of
• is to be assigned to variable x, it is coded:
• x = b + c - d * e / f;
• Parentheses may be used. These are evaluated first. e.g.,
• x = (b + c - d)* e / f; is evaluated as:
Introduction to Programming
49. order of operations
• 1. ( )
• 2. * / %
• 3. + -
• 4. left to right
• Example. What is the order of operations in the
following expression?
z= p*r%q+w/x-y;
Introduction to Programming
Z = P * R % Q + W / X - Y ;
6 1 2 4 3 5
50. Exercise
• For each of the following arithmetic
expressions, construct the equivalent C++
expression.
Introduction to Programming
51. Using Stored Data and Arithmetic
// from Hubbard book
// Prints the sum, difference, etc. of given integers.
#include <iostream>
using namespace std;
int main(){
int m = 6, n = 7;
cout << "The integers are " << m << " and " << n << endl;
cout << "Their sum is " << (m+n) << endl;
cout << "Their difference is " << (m-n) << endl;
cout << "Their product is " << (m*n) << endl;
cout << "Their quotient is " << (m/n) << endl;
cout << "Their remainder is " << (m%n) << endl << endl <<
endl;
return 0;
}
•Trace this program.
Introduction to Programming
52. Assignment
• We will usually see an assignment operation in this format:
• <variable> = <expression>
• An expression is a combination of operators and operands.
For example,
c = c + 3;
• or
average = sum / count;
Introduction to Programming
53. Assignment
• c = c + 3; same as c +=3;
•The += operation adds the value of the expression of the right to the value
of the variable on the left and stores the result in the variable on the left.
•
• In general, <var> = <var> op <exp>; can be written as: <var> op = <exp>;
•
• Examples:
c = 4; //same as c = c 4;
c *= 5; //same as c = c *5;
c /= 6; //same as c = c /6;
•
• Can we reverse the order of the double operator? Say, c = 4;
• No. This simply is the same as the assignment c = 4;
Introduction to Programming
54. Increment / Decrement Operators
• a++; is the same as a = a + 1; and also the same as ++a;
• a; is the same as a = a 1; and also the same as a;
•
• a++ postincrement
• ++a preincrement
• a postdecrement
• a predecrement
•
•These are unary operators. They operate on only a single operand. The
operators we are more familiar with are binary operands; they operate on
two operands, much like the + operator in the expression a+b.
– The degree of an operator refers to the number of operands it takes.
Introduction to Programming
55. Increment / Decrement Operators
• Example:
•
int c;
c = 5;
cout << c << endl; // outputs 5
cout << c++ << endl; // outputs 5 (then increments)
cout << c << endl << endl; // outputs 6
c = 5;
cout << c << endl; // outputs 5
cout << ++c << endl; // outputs 6 (after incrementing)
cout << c << endl; // outputs 6
Introduction to Programming
56. Grade Point Average
// This program will calculate grade point average.
#include <iostream>
using namespace std;
int main(){
int A, B, C, D, F;
float sum, GPA;
cout << "Tell me your grades and I will calculate your GPA.";
cout << endl << endl;
cout << "How many units of A? ";
cin >> A;
cout << "How many units of B? ";
cin >> B;
cout << "How many units of C? ";
cin >> C;
cout << "How many units of D? ";
cin >> D;
cout << "How many units of F? ";
cin >> F;
sum = A + B + C + D + F;
GPA = (4*A + 3*B + 2*C + D)/sum;
cout << endl;
cout << "Your grade point average is " << GPA <<endl;
return 0;
}
Introduction to Programming
57. A Polynomial Program
#include <iostream>
using namespace std;
int main(){
float A, B, C, X;
cout << "A=? ";
cin >> A;
cout << "B=? ";
cin >> B;
cout << "C=? ";
cin >> C;
X = 5*A*A*B*C*C*C + 8*A*B*B*C*C - 4*B*B*B*C;
cout << endl;
cout << "X = " << X <<endl;
return 0;
}
• Why do we have to multiply a value by itself instead of just raising to a
power with an exponentiation operator?
Introduction to Programming
Run #2:Run #1:
58. A Polynomial Program
•C++ has no arithmetic operator for exponentiation. There is, however, a power function that can do it for us. Use the math
header file.
// Polynomial Program using the pow() function
#include <iostream>
#include <math>
using namespace std;
int main(){
float A, B, C, X;
cout << "A=? ";
cin >> A;
cout << "B=? ";
cin >> B;
cout << "C=? ";
cin >> C;
X = 5*pow(A,2)*B*pow(C,3) + 8*A*pow(B,2)*pow(C,2) - 4*pow(B,3)*C;
cout << endl;
cout << "X = " << X <<endl;
return 0;
}
Introduction to Programming
59. Functions in the math library
• To use these built-in functions we need to
include the <math.h> header file
Introduction to Programming
function what it does returned value
abs(a) absolute value of a same data type as argument
pow(a1,a2) a1 raised to the power of a2 data type of argument a1
sqrt(a) square root of a same data type as argument
sin(a) sine of a (a in radians) double
cos(a) cosine double
tan(a) tangent double
log(a) natural logarithm of a double
log10(a) base 10 log of a double
exp(a) e raised to the power of a double
60. Review
– binary operator
– degree of an
operator
– expression
– operand
– operator
– tertiary operator
– unary operator
Introduction to Programming
What did we learn in this lecture? Plenty. Some terms to jog your memory:
61. Real number types
• A real number is a value that represents a
quantity along a continuous line.
– In C++ we can use the types float, double, and long
double.
– On most systems, double uses twice as many bytes as
float. In general, float uses 4 bytes, double uses 8
bytes, and long double uses 8, 10, 12, or 16 bytes.
– We can always use a program to determine how a
type is stored on a particular computer. The program
on the next slide produced this output:
Introduction to Programming
63. How large a value can I use?
Introduction to Programming
64. How large a value can I use?
// From Hubbard book
#include <iostream>
#include <limits>
using namespace std;
void main(){
cout << "minimum char = " << CHAR_MIN << endl;
cout << "maximum char = " << CHAR_MAX << endl;
cout << "minimum short = " << SHRT_MIN << endl;
cout << "maximum short = " << SHRT_MAX << endl;
cout << "minimum int = " << INT_MIN << endl;
cout << "maximum int = " << INT_MAX << endl;
cout << "maximum long = " << LONG_MAX << endl;
cout << "maximum unsigned short = " << USHRT_MAX << endl;
cout << "maximum unsigned = " << UINT_MAX << endl;
cout << "maximum unsigned long = " << ULONG_MAX << endl;
cout << endl << endl << endl;
return;
}
Introduction to Programming
65. Overflow
•What happens if we try to store a value that is too large for the data
type to handle? We have an overflow condition. This is a run-time
error.
// From Hubbard book
#include <iostream>
#include <limits>
using namespace std;
void main(){
short n= SHRT_MAX - 1;
cout << n++ << endl;
cout << n++ << endl;
cout << n++ << endl;
cout << n++ << endl;
return; //successful termination
} //end main
Introduction to Programming
66. Exercise
• Write a program that asks the user
– Do you want to use this program? (y/n)
• If the user says ‘y’ then the program terminates
• If the user says ‘n’ then the program asks
– Are you really sure you do not want to use this program?
(y/n)
– If the user says ‘n’ it terminates, otherwise it prints again the
message
– Are you really really sure you do not want to use this
program? (y/n)
– And so on, every time adding one more “really”.
Introduction to Programming
68. Arrays
Used to store a collection of elements (variables)
type array-name[size];
Meaning:
This declares a variable called <array-name> which contains <size> elements of type <type>
The elements of an array can be accessed as: array-name[0],…array-name[size-1]
Example:
int a[100]; //a is a list of 100 integers, a[0], a[1], …a[99]
double b[50]; char c[10];
69. Declaring Arrays
• To declare an array in C++, the programmer
specifies the type of the elements and the
number of elements required by an array as
follows −
• type arrayName [ arraySize ];
70. initializing Arrays
• You can initialize C++ array elements either
one by one or using a single statement as
follows −
• double balance[5] = {1000.0, 2.0, 3.4, 17.0,
50.0};
71. Accessing Array Elements
• An element is accessed by indexing the array
name. This is done by placing the index of the
element within square brackets after the
name of the array. For example −
• double salary = balance[9];
72. Array example
//Read 100 numbers from the user
#include <iostream.h>
void main() {
int i, a[100], n;
i=0; n=100;
while (i<n) {
cout << “Input element “ << i << “: ”;
cin >> a[i];
i = i+1;
}
//do somehing with it ..
}
73. Problems
Write a C++ program to read a sequence of (non-negative) integers from the user
ending with a negative integer and write out
• the average of the numbers
• the smallest number
• the largest number
• the range of the numbers (largest - smallest)
• Example:
– The user enters: 3, 1, 55, 89, 23, 45, -1
– Your program should compute the average of {3, 1, 55, 89, 23, 45} etc
74. STRINGS
• The C-style character string originated
within the C language and continues to be
supported within C++. This string is actually
a one-dimensional array of characters
which is terminated by a null character '0'.
Thus a null-terminated string contains the
characters that comprise the string
followed by a null.
75. STRINGS
• The following declaration and initialization
create a string consisting of the word "Hello".
To hold the null character at the end of the
array, the size of the character array
containing the string is one more than the
number of characters in the word "Hello."
76. STRINGS
• char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'}; If you
follow the rule of array initialization, then you
can write the above statement as follows −
• char greeting[] = "Hello";
77. Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
C++ Classes
&
Objects
78. Chanderprabhu Jain College of Higher Studies & School of Law
Plot No. OCF, Sector A-8, Narela, New Delhi – 110040
(Affiliated to Guru Gobind Singh Indraprastha University and Approved by Govt of NCT of Delhi & Bar Council of India)
Object Oriented Programming
•Programmer thinks about and defines the attributes and behavior of
objects.
•Often the objects are modeled after real-world entities.
•Very different approach than function-based programming (like C).
79. • Programmer thinks about and defines the
attributes and behavior of objects.
• Often the objects are modeled after real-
world entities.
• Very different approach than function-based
programming (like C).
80. Object Oriented Programming
• Object-oriented programming (OOP)
– Encapsulates data (attributes) and functions
(behavior) into packages called classes.
• So, Classes are user-defined (programmer-
defined) types.
– Data (data members)
– Functions (member functions or methods)
• In other words, they are structures + functions
81. Classes in C++
• A class definition begins with the keyword
class.
• The body of the class is contained within a set
of braces, { } ; (notice the semi-colon).
class class_name
{
….
….
….
}; Class body (data member +
methods)
Any valid identifier
82. Classes in C++
• Within the body, the keywords private: and
public: specify the access level of the
members of the class.
– the default is private.
• Usually, the data members of a class are
declared in the private: section of the class
and the member functions are in public:
section.
83. Classes in C++
class class_name
{
private:
…
…
…
public:
…
…
…
};
Public members or methods
private members or methods
84. Classes in C++
• Member access specifiers
– public:
• can be accessed outside the class directly.
– The public stuff is the interface.
– private:
• Accessible only to member functions of class
• Private members and methods are for internal use only.
85. Class Example
• This class example shows how we can
encapsulate (gather) a circle information into
one package (unit or class)
class Circle
{
private:
double radius;
public:
void setRadius(double r);
double getDiameter();
double getArea();
double getCircumference();
};
No need for others classes to access
and retrieve its value directly. The
class methods are responsible for
that only.
They are accessible from outside
the class, and they can access the
member (radius)
86. Creating an object of a Class
• Declaring a variable of a class type creates an object.
You can have many variables of the same type (class).
– Instantiation
• Once an object of a certain class is instantiated, a
new memory location is created for it to store its
data members and code
• You can instantiate many objects from a class type.
– Ex) Circle c; Circle *c;
87. Special Member Functions
• Constructor:
– Public function member
– called when a new object is created (instantiated).
– Initialize data members.
– Same name as class
– No return type
– Several constructors
• Function overloading
88. Special Member Functions
class Circle
{
private:
double radius;
public:
Circle();
Circle(int r);
void setRadius(double r);
double getDiameter();
double getArea();
double getCircumference();
};
Constructor with no
argument
Constructor with one
argument
89. Implementing class methods
• Class implementation: writing the code of class
methods.
• There are two ways:
1. Member functions defined outside class
• Using Binary scope resolution operator (::)
• “Ties” member name to class name
• Uniquely identify functions of particular class
• Different classes can have member functions with same name
– Format for defining member functions
ReturnType ClassName::MemberFunctionName( ){
…
}
90. Implementing class methods
2. Member functions defined inside class
– Do not need scope resolution operator, class
name;
class Circle
{
private:
double radius;
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
Defined
inside
class
92. Accessing Class Members
• Operators to access class members
– Identical to those for structs
– Dot member selection operator (.)
• Object
• Reference to object
– Arrow member selection operator (->)
• Pointers
93. class Circle
{
private:
double radius;
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
Circle::Circle(int r)
{
radius = r;
}
double Circle::getArea()
{
return radius * radius * (22.0/7);
}
double Circle:: getCircumference()
{
return 2 * radius * (22.0/7);
}
void main()
{
Circle c1,c2(7);
cout<<“The area of c1:”
<<c1.getArea()<<“n”;
//c1.raduis = 5;//syntax error
c1.setRadius(5);
cout<<“The circumference of c1:”
<< c1.getCircumference()<<“n”;
cout<<“The Diameter of c2:”
<<c2.getDiameter()<<“n”;
}
The first
constructor is
called
The second
constructor is
called
Since radius is a
private class data
member
94. class Circle
{
private:
double radius;
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
Circle::Circle(int r)
{
radius = r;
}
double Circle::getArea()
{
return radius * radius * (22.0/7);
}
double Circle:: getCircumference()
{
return 2 * radius * (22.0/7);
}
void main()
{
Circle c(7);
Circle *cp1 = &c;
Circle *cp2 = new Circle(7);
cout<<“The are of cp2:”
<<cp2->getArea();
}
95. Destructors
• Destructors
– Special member function
– Same name as class
• Preceded with tilde (~)
– No arguments
– No return value
– Cannot be overloaded
– Before system reclaims object’s memory
• Reuse memory for new objects
• Mainly used to de-allocate dynamic memory locations
96. Another class Example
• This class shows how to handle time parts.
class Time
{
private:
int *hour,*minute,*second;
public:
Time();
Time(int h,int m,int s);
void printTime();
void setTime(int h,int m,int s);
int getHour(){return *hour;}
int getMinute(){return *minute;}
int getSecond(){return *second;}
void setHour(int h){*hour = h;}
void setMinute(int m){*minute = m;}
void setSecond(int s){*second = s;}
~Time();
};
Destructor
97. Time::Time()
{
hour = new int;
minute = new int;
second = new int;
*hour = *minute = *second = 0;
}
Time::Time(int h,int m,int s)
{
hour = new int;
minute = new int;
second = new int;
*hour = h;
*minute = m;
*second = s;
}
void Time::setTime(int h,int m,int s)
{
*hour = h;
*minute = m;
*second = s;
}
Dynamic locations
should be allocated to
pointers first
98. void Time::printTime()
{
cout<<"The time is : ("<<*hour<<":"<<*minute<<":"<<*second<<")"
<<endl;
}
Time::~Time()
{
delete hour; delete minute;delete second;
}
void main()
{
Time *t;
t= new Time(3,55,54);
t->printTime();
t->setHour(7);
t->setMinute(17);
t->setSecond(43);
t->printTime();
delete t;
}
Output:
The time is : (3:55:54)
The time is : (7:17:43)
Press any key to continue
Destructor: used here to de-allocate
memory locations
When executed, the destructor
is called
99. C++ and inheritance
• The language mechanism by which one class
acquires the properties (data and operations)
of another class
• Base Class (or superclass): the class being
inherited from
• Derived Class (or subclass): the class that
inherits
100. Advantages of Inheritance
When a class inherits from another class, there are three benefits:
(1) You can reuse the methods and data of the existing class
(2) You can extend the existing class by adding new data
and new methods
(3) You can modify the existing class by overloading its
methods with your own implementations
101. Advantages of Inheritance
When a class inherits from another class, there are three benefits:
(1) You can reuse the methods and data of the existing class
(2) You can extend the existing class by adding new data
and new methods
(3) You can modify the existing class by overloading its
methods with your own implementations
104. Different Types of Inheritance
• Single inheritance. In this inheritance, a derived
class is created from a single base class. ...
• Multi-level inheritance. In this inheritance, a derived
class is created from another derived class. ...
• Multiple inheritance. ...
• Hierarchical inheritance. ...
• Hybrid inheritance.
106. 106
Problem with Subclasses
• Given the class hierarchy below
• Consider the existence of a draw function for each
subclass
• Consider also an array of references to the superclass
(which can also point to various objects of the
subclasses)
• How do you specify which draw statement to be called
when using the references
Shape class hierarchy
Circle
Right Triangle Isosceles Triangle
Triangle
Square
Rectangle
Shape
107. 107
Introduction
• Polymorphism
– Enables “programming in the general”
– The same invocation can produce “many forms” of
results
• Interfaces
– Implemented by classes to assign common
functionality to possibly unrelated classes
108. 108
Polymorphism
• When a program invokes a method through a superclass
variable,
– the correct subclass version of the method is called,
– based on the type of the reference stored in the superclass
variable
• The same method name and signature can cause
different actions to occur,
– depending on the type of object on which the method is
invoked
109. 109
Polymorphism
• Polymorphism enables programmers to deal
in generalities and
– let the execution-time environment handle the
specifics.
• Programmers can command objects to behave
in manners appropriate to those objects,
– without knowing the types of the objects
– (as long as the objects belong to the same
inheritance hierarchy).
110. 110
Polymorphism Promotes Extensibility
• Software that invokes polymorphic behavior
– independent of the object types to which
messages are sent.
• New object types that can respond to existing
method calls can be
– incorporated into a system without requiring
modification of the base system.
– Only client code that instantiates new objects
must be modified to accommodate new types.
111. 111
Polymorphism
• Promotes extensibility
• New objects types can respond to existing
method calls
– Can be incorporated into a system without
modifying base system
• Only client code that instantiates the new
objects must be modified
– To accommodate new types
112. 112
Abstract Classes and Methods
• Abstract classes
– Are superclasses (called abstract superclasses)
– Cannot be instantiated
– Incomplete
• subclasses fill in "missing pieces"
• Concrete classes
– Can be instantiated
– Implement every method they declare
– Provide specifics
113. 113
Abstract Classes and Methods
• Purpose of an abstract class
– Declare common attributes …
– Declare common behaviors of classes in a class
hierarchy
• Contains one or more abstract methods
– Subclasses must override
• Instance variables, concrete methods of
abstract class
– subject to normal rules of inheritance
114. 114
Abstract Classes
• Classes that are too general to create real
objects
• Used only as abstract superclasses for
concrete subclasses and to declare reference
variables
• Many inheritance hierarchies have abstract
superclasses occupying the top few levels
115. 115
Keyword abstract
• Use to declare a class abstract
• Also use to declare a method abstract
• Abstract classes normally contain one or
more abstract methods
• All concrete subclasses must override all
inherited abstract methods
116. 116
Abstract Classes and Methods
• Iterator class
– Traverses all the objects in a collection, such as
an array
– Often used in polymorphic programming to
traverse a collection that contains references to
objects from various levels of a hierarchy
117. 117
Abstract Classes
• Declares common attributes and behaviors of
the various classes in a class hierarchy.
• Typically contains one or more abstract
methods
– Subclasses must override if the subclasses are to
be concrete.
• Instance variables and concrete methods of an
abstract class subject to the normal rules of
inheritance.
118. 118
Creating Abstract Superclass
Employee
• abstract superclass Employee,
Figure 10.4
– earnings is declared abstract
• No implementation can be given for earnings in the
Employee abstract class
– An array of Employee variables will store
references to subclass objects
• earnings method calls from these variables will call
the appropriate version of the earnings method
119. 119
Example Based on Employee
Abstract Class
Concrete Classes
Click on Classes to see source code
120. 120
Polymorphic Payroll System
Class hierarchy for polymorphic payroll application
Employee
SalariedEmployee HourlyEmployeeCommissionEmployee
BasePlusCommissionEmployee
121. 121
Polymorphism
• Enables programmers to deal in generalities
– Let execution-time environment handle specifics
• Able to command objects to behave in
manners appropriate to those objects
– Don't need to know type of the object
– Objects need only to belong to same inheritance
hierarchy
122. 122
Abstract Classes and Methods
• Abstract classes not required, but reduce
client code dependencies
• To make a class abstract
– Declare with keyword abstract
– Contain one or more abstract methods
public abstract void draw();
– Abstract methods
• No implementation, must be overridden
123. 123
Circle
Cylinder
Point
Shape
Polymorphic Interface For The Shape
Hierarchy Class
0.0 0.0 abstract default
Object
implement
0.0 0.0 "Point" [x,y]
πr2 0.0 "Circle" center=[x,y];
radius=r
2πr2 +2πrh πr2h "Cylinder"
center=[x,y];
radius=r;
height=h
getArea toStringgetNamegetVolume
Shape
Point
Circle
Cylinder
124. Learning Objectives
• C++ I/O streams.
• Reading and writing sequential files.
• Reading and writing random access files.
124
125. C++ Files and Streams
• C++ views each files as a sequence of bytes.
• Each file ends with an end-of-file marker.
• When a file is opened, an object is created
and a stream is associated with the object.
• To perform file processing in C++, the header
files <iostream.h> and <fstream.h> must be
included.
• <fstream.> includes <ifstream> and
<ofstream>
CPSC 231 D.H. C++ File Processing 125
126. Creating a sequential file
// Fig. 14.4: fig14_04.cpp D&D p.708
// Create a sequential file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main()
{
// ofstream constructor opens file
ofstream outClientFile( "clients.dat", ios::out );
if ( !outClientFile ) { // overloaded ! operator
cerr << "File could not be opened" << endl;
exit( 1 ); // prototype in stdlib.h
}
CPSC 231 D.H. C++ File Processing 126
127. Sequential file
cout << "Enter the account, name, and balance.n"
<< "Enter end-of-file to end input.n? ";
int account;
char name[ 30 ];
float balance;
while ( cin >> account >> name >> balance ) {
outClientFile << account << ' ' << name
<< ' ' << balance << 'n';
cout << "? ";
}
return 0; // ofstream destructor closes file
}
CPSC 231 D.H. C++ File Processing 127
128. How to open a file in C++ ?
Ofstream outClientFile(“clients.dat”, ios:out)
OR
Ofstream outClientFile;
outClientFile.open(“clients.dat”, ios:out)
CPSC 231 D.H. C++ File Processing 128
129. File Open Modes
ios:: app - (append) write all output to the end of
file
ios:: ate - data can be written anywhere in the file
ios:: binary - read/write data in binary format
ios:: in - (input) open a file for input
ios::out - (output) open afile for output
ios: trunc -(truncate) discard the files’ contents if
it exists
CPSC 231 D.H. C++ File Processing 129
130. File Open Modes cont.
ios:nocreate - if the file does NOT exists, the
open operation fails
ios:noreplace - if the file exists, the open
operation fails
CPSC 231 D.H. C++ File Processing 130
131. How to close a file in C++?
The file is closed implicitly when a
destructor for the corresponding object is
called
OR
by using member function close:
outClientFile.close();
CPSC 231 D.H. C++ File Processing 131
132. Reading and printing a sequential
file
// Reading and printing a sequential file
#include <iostream.h>
#include <fstream.h>
#include <iomanip.h>
#include <stdlib.h>
void outputLine( int, const char *, double );
int main()
{
// ifstream constructor opens the file
ifstream inClientFile( "clients.dat", ios::in );
if ( !inClientFile ) {
cerr << "File could not be openedn";
exit( 1 );
}
CPSC 231 D.H. C++ File Processing 132
134. File position pointer
<istream> and <ostream> classes provide
member functions for repositioning the file
pointer (the byte number of the next byte in
the file to be read or to be written.)
These member functions are:
seekg (seek get) for istream class
seekp (seek put) for ostream class
CPSC 231 D.H. C++ File Processing 134
135. Examples of moving a file pointer
inClientFile.seekg(0) - repositions the file get pointer to the
beginning of the file
inClientFile.seekg(n, ios:beg) - repositions the file get pointer to
the n-th byte of the file
inClientFile.seekg(m, ios:end) -repositions the file get pointer to
the m-th byte from the end of file
nClientFile.seekg(0, ios:end) - repositions the file get pointer to
the end of the file
The same operations can be performed with <ostream>
function member seekp.
CPSC 231 D.H. C++ File Processing 135
136. Member functions tellg() and
tellp().
Member functions tellg and tellp are provided to
return the current locations of the get and put
pointers, respectively.
long location = inClientFile.tellg();
To move the pointer relative to the current
location use ios:cur
inClientFile.seekg(n, ios:cur) - moves the file get
pointer n bytes forward.
CPSC 231 D.H. C++ File Processing 136
137. Updating a sequential file
Data that is formatted and written to
a sequential file cannot be modified
easily without the risk of destroying
other data in the file.
If we want to modify a record of data,
the new data may be longer than the
old one and it could overwrite parts
of the record following it.
CPSC 231 D.H. C++ File Processing 137
138. Problems with sequential files
Sequential files are inappropriate for so-
called “instant access” applications in which
a particular record of information must be
located immediately.
These applications include banking systems,
point-of-sale systems, airline reservation
systems, (or any data-base system.)
CPSC 231 D.H. C++ File Processing 138
139. Random access files
Instant access is possible with random
access files.
Individual records of a random access file
can be accessed directly (and quickly)
without searching many other records.
CPSC 231 D.H. C++ File Processing 139
140. Example of a Program that Creates
a Random Access File
// Fig. 14.11: clntdata.h
// Definition of struct clientData used in
// Figs. 14.11, 14.12, 14.14 and 14.15.
#ifndef CLNTDATA_H
#define CLNTDATA_H
struct clientData {
int accountNumber;
char lastName[ 15 ];
char firstName[ 10 ];
float balance;
};
#endif
CPSC 231 D.H. C++ File Processing 140
141. Creating a random access file
// Creating a randomly accessed file sequentially
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
ofstream outCredit( "credit1.dat", ios::out);
if ( !outCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
CPSC 231 D.H. C++ File Processing 141
142. clientData blankClient = { 0, "", "", 0.0 };
for ( int i = 0; i < 100; i++ )
outCredit.write
(reinterpret_cast<const char *>( &blankClient ),
sizeof( clientData ) );
return 0;
}
CPSC 231 D.H. C++ File Processing 142
143. <ostream> memebr function write
The <ostream> member function
write outputs a fixed number of
bytes beginning at a specific location
in memory to the specific stream.
When the stream is associated with a
file, the data is written beginning at
the location in the file specified by
the “put” file pointer.
CPSC 231 D.H. C++ File Processing 143
144. The write function expects a first
argument of type const char *, hence we
used the reinterpret_cast <const char *>
to convert the address of the blankClient
to a const char *.
The second argument of write is an
integer of type size_t specifying the
number of bytes to written. Thus the
sizeof( clientData ).
CPSC 231 D.H. C++ File Processing 144
145. Writing data randomly to a random
file
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include "clntdata.h"
int main()
{
ofstream outCredit( "credit.dat", ios::ate );
if ( !outCredit ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
CPSC 231 D.H. C++ File Processing 145
146. cout << "Enter account number "
<< "(1 to 100, 0 to end input)n? ";
clientData client;
cin >> client.accountNumber;
while ( client.accountNumber > 0 &&
client.accountNumber <= 100 ) {
cout << "Enter lastname, firstname, balancen? ";
cin >> client.lastName >> client.firstName
>> client.balance;
CPSC 231 D.H. C++ File Processing 146
152. The <istream> function read
inCredit.read (reinterpret_cast<char *>(&client),
sizeof(clientData));
The <istream> function inputs a specified
(by sizeof(clientData)) number of bytes
from the current position of the specified
stream into an object.
CPSC 231 D.H. C++ File Processing 152