Basic Programming Language Overview
Basic Programming Language Overview
Basic Programming Language Overview
Overview
Programming Techniques
• Unstructured Programming
• Procedural Programming
• Modular Programming
• Object-Oriented programming
Unstructured Programming
• Drawbacks
– This programming technique can only be used in a very small program
– This has lead to the idea to extract these sequences (procedure), name
them and offering a technique to call and return from these procedures
Procedural Programming
• Thinking in OOP
• A student, a professor
• A law system
• An engineering system
• An educational system
• An economic system
• An Information system
Basic Components of OOP
• Properties
– Are data attributes (brand, model, color, HK, engine size)
• Methods
– Are functions/capabilities (start, drive, stop, service)
Basic Components of OOP
OOP Based System View
Characteristics of Object Oriented Languages
• Objects
• Classes
• Inheritance
• Reusability
• Polymorphism
Object
Escape
Character
Sequences
\a Bell (beep)
\b Backspace
\f Form feed
\n New line
\r Return
\t Tab (horizontal)
\v Tab (vertical)
\' Single quote
\" Double quote
\\ Backslash
Basic C++ Variable Types
The operator "<<" is called the insertion or put operator. It directs the contents of
the variable on its right to the object on its left.
• Declaring a variable means specifying both its name and its data type. This
tells the complier to associate a name with a memory location whose
contents are of a specific type (for example, char or string). The
following statement declares myChar to be a variable or type char:
char myChar;
Rules for Writing Variables or Identifiers
You can use upper and lowercase letters and the digits from 0 to 9
Identifier can be as long as you like but only the 247 characters (in Visual
C++)or 250 characters in(C++ Builder) will be recognized
// Initialization of variables
var1=20;
var2=var1+10;
cout<<"var1+10 is"<<var2<<endl;
cout<<"Long variable value is"<<abcdefghijklmnopqrstuvwxyz12345678;
}
Data Type
The char Data Type
The built-in type char describes data consisting of one alphanumeric
character - a letter , a digit, or a special symbol
'A‘ 'a' '8' '2' '+' '-' '$' '?' ''
• Constant declaration
const DataType Identifier = LiteralValue;
The semantics (meaning) of the assignment operator (=) is "store"; the value of the
expression is stored into the variable.
Only one variable can be on the left hand side of an assignment statement. An
assignment statement is not like a math equation (x + y = z + 4); the expression
(what is on the right hand side of the assignment operator) is evaluated, and the
resulting value is stored into the single variable on the left of the assignment
operator.
Assignment Statement (contd…)
Given the declarations
string firstName;
string middleName;
string lastName;
string title;
char middleInitial;
char letter;
The following assignment statements are valid:
firstName = "Abraham";
middleName = firstName;
middleName = " ";
lastName = "Lincoln";
title = "President";
middleInitial = ' ';
letter = middleInitial;
Assignment Statement (contd…)
then we write the following assignment statement to store the title of this book into
the variable bookTitle:
void main()
string bookTitle;
It tells the compiler to use the std namespace. Namespaces are a relatively recent
addition to C++. A namespace creates a declarative region in which various program
elements can be placed. Namespaces help in the organization of large programs. The
using statement informs the complier that you want to use the std namespace.
This is the namespace in which the entire Standard C++ library is declared. By using
the std namespace you simplify access to the standard library.
Output Statement
char ch = '2';
string first = "Marie";
string last = "Curie";
cout<<ch; 2
cout<<"ch="<<ch; ch=2
cout<<first + " " + last; Marie Curie
cout<<first <<last; MarieCurie
cout<<first << ' ' <<last; Marie Curie
cout<<"A1 \"Butch\" Jones"; A1 "Butch" Jones;
Numeric Types, Expressions and Output
Overview of C++ Data Types
Arithmetic Operators
+ Unary plus
- Unary minus
+ Addition
- Subtraction
* Multiplication
#include<iostream>
using namespace std;
const float FREEZE_PT = 32.0;
const float BOIL_PT = 212.0;
void main()
{
float avgTemp;
cout<<"Water freezes at "<<FREEZE_PT<<endl;
cout<<" and boils at "<<BOIL_PT<<" degress."<<endl;
Both the increment and decrement operators may either precede (prefix) or
follow (postfix) the operand. For example
x = x + 1;
can be written
++x; or x++;
Increment and Decrement Operators (contd..)
A difference between the prefix and postfix forms when you use these
operators in an expression.
When an increment or decrement operator precedes its operand, the
increment or decrement operation is performed before obtaining the value
of the operand for use in the expression.
If the operator follows its operands follows its operand, the value of the
operand is obtained before incrementing or decrementing it. For instance,
x = 10;
y = ++x;
sets y to 11. However, if you write the code as the same as
x = 10;
y = x++;
y is set to 10. Either way, x is set to 11; the difference is in when it
happens
Prefix & Postfix
#include<iostream>
using namespace std;
void main()
{
int count = 10;
cout<<"count = "<<count<<endl;
cout<<"count = "<<++count<<endl; //pre-increment
cout<<"count = "<<count<<endl;
cout<<"count = "<<count++<<endl; //post-increment
cout<<"count = "<<count<<endl;
}
Prefix & Postfix (contd..)
#include<iostream>
using namespace std;
void main()
{
int count = 2;
float avgWeight = 10.5;
Expression Value
10 / 2 * 3 15
10 % 3 – 4 / 2 -1
5.0 * 2.0 / 4.0 * 2.0 5.0
5.0 * 2.0 / (4.0 * 2.0) 1.25
5.0 + 2.0 / (4.0 * 2.0) 5.25
Input with cin
#include<iostream>
using namespace std;
void main()
{
float rad;
const double PI = 3.14159;
cout<<"Enter radius of circle: ";
cin>>rad;
float area = PI * rad * rad;
cout<<"Area is "<<area<<endl;
}
The keyword "cin" is an object, predefined in C++ to correspond to the standard
input stream.
The ">>" is extraction or get from operator. It takes the value from the stream object
on its left and places it in the variable on its right.
Tests Signed and Unsigned Integers
#include<iostream>
using namespace std;
void main()
{
int signedVar = 1500000000;
unsigned int unsignVar = 1500000000;
signedVar = (signedVar * 2) / 3;
unsignVar = (unsignVar * 2) / 3;
cout<<"signedVar = "<<signedVar<<endl;
cout<<"unsignVar = "<<unsignVar<<endl;
}
Type Coercion
The implicit (automatic) conversion of a value from one data type to another
If you make the declaration
int someInt;
float someFloat;
then someInt can hold only integer values and somefloat can hold only floating
point values. The assignment statement
someFloat = 12;
may seem to store the integer value 12 into someFloat, but this is not true.
The computer refuses to store anything other than a float value into someFloat.
The complier inserts extra machine language instructions that first convert 12 into
12.0 and then store 12.0 into someFloat.
This implicit (automatic) conversion of a value from one data type to another is
known as type coercion.
Type Coercion (contd..)
The statement
int someInt = 4.8;
also causes type coercion. When a floating-point value is assigned to an int variable,
the fractional part is truncated (cut off). As a result, someInt is assigned the value
4.
someFloat = 3 * someInt + 2;
someInt = 15.2 / someFloat – 3.75;
Type Casting
The explicit conversion of a value from one data type to another; also called type
conversion
A C++ cast operation consists of a data type name and then, within parentheses, the
expression to be converted
aCharVar = static_cast<char>(anIntVar);
Or
aCharVar = char(anIntVar);
Cast.cpp
#include<iostream>
using namespace std;
void main()
{
int intVar = 1500000000;
intVar = (intVar*10)/10;
cout<<"intVar = "<<intVar<<endl;
intVar = 1500000000;
intVar = (double(intVar)*10)/10;
cout<<"intVar = "<<intVar<<endl;
}
Mixed Type Expression
An expression that contains operands of different data types; also called mixed mode
expression
Whenever an integer value and a floating-point value are joined by an operator,
implicit type coercion occurs as follows
1. The integer value is temporary coerced to a floating –point value
2. The operation is performed
3. The result is a floating-point value
Let's examine how the machine evaluates the expression 4.8 + someInt -3,
where someInt contains the value 2.
First, the operands of the + operator have mixed types, so the value of someInt is
coerced to 2.0. (This conversion is only temporary; it does not affect the value that
is stored in someInt.) the addition take place, yielding a value of 6.8.
Next, the subtraction (-) operator joins a floating point value (6.8) and an integer
value (3). The value 3 is coerced to 3.0, the subtraction takes place, and the result
is the floating-point value 3.8.
The setw()Manipulator
This setw() stands for the set width. The setw() manipulator is used to set the width
of the word to be displayed on screen.
The general form of setw() is:-
setw(int w)
Where, the integer inside the bracket indicates the total field width.
#include<iostream>
#include<iomanip> //Manipulator Header File
using namespace std;
void main()
{
long pop1 = 2424785, pop2 = 47, pop3 = 9761;
cout <<setw(8)<<"LOCATION"<<setw(12)<<"POPULATION"<<endl
<<setw(8)<<"Portcity"<<setw(12)<<pop1<<endl
<<setw(8)<<"Hightown"<<setw(12)<<pop2<<endl Output:
LOCATION POPULATION
<<setw(8)<<"Lowville"<<setw(12)<<pop3<<endl;
Portcity 2424785
} Hightown 47
Lowville 9761
The setprecision()Manipulator
This setprecision() stands for the set precision. The setprecision()
manipulator is used to set the decimal precision to be used by output operations.
The general form of setprecision() is:-
setprecision(int w)
Where, the integer inside the bracket indicates the total field width.
#include<iostream>
#include<iomanip> //Manipulator Header File
using namespace std;
void main()
{
double Z = 6.8436;
Output:
cout<<"Z = "<<setprecision(4)<<Z<<endl; Z = 6.844
}
Conditions, Logical Expressions and
Selection Control Structures
Flow of Control
The order in which the computer executes statements in a program.
Flow of control is normally sequential. That is, when one statement is
finished executing, control passes to the next statement in the program.
Statement A
Statement B
Statement C
Control Structure
A statement used to alter the normally sequential flow of control.
We use a selection (or branching) control structure when we want the
computer to choose between alternative actions.
True False
Assertion
Statement A Statement B
Selection Statement (if)
if
The general form of the if statement is
if (expression)
statement;
else
statement;
void main()
{
int x;
As noted, the final else is not associated with if(j) because it is not in the same
block. Rather, the final else is associated with if(i). Also the inner else is
if (expression)
statement;
else
if (expression)
statement;
else
if (expression)
statement;
.
.
else
statement;
The conditions are evaluated from the top downward. As soon as a true condition is
found the statement associated with it, is executed and the rest of the ladder is
bypassed. If none of the condition are true, the final else is executed.
// This Program outputs an appropriate activity for a given temperature
#include<iostream>
using namespace std;
void main()
{
int temperature;
cout<<"Enter the outside temperature: ";
cin>>temperature;
cout<<"\n The recommended activity is ";
if (temperature > 85)
cout<<"Swimming."<<endl;
else
if (temperature > 70)
cout<<"Tennis."<<endl;
else
if (temperature > 32)
cout<<"Golf."<<endl;
else
if (temperature > 0)
cout<<"Skiing."<<endl;
else
cout<<"Dancing."<<endl;
}
Output:
Enter the outside temperature: 37
x = 10;
y = x > 9 ? 100 : 200;
In this example, y is assigned the value 100. if x had been less than 9, y would have
received the value 200.
Relational & Logical Operator
#include<iostream>
using namespace std;
void main()
{
int num;
Output:
Enter a number: 9
num < 10 is 1
num > 10 is 0
num == 10 is 0
// demonstrate relational operator (example-2)
#include<iostream>
using namespace std;
void main()
{
if ('a' < 109)
{
cout<<"true"<<endl;
cout<<"a = "<<int('a')<<endl;
}
else
cout<<"false"<<endl;
if ('M' > 'S')
{
cout<<"true"<<endl;
cout<<"M = "<<int('M')<<" and S = "<<int('S')<<endl;
}
else
{
cout<<"true"<<endl;
cout<<"M = "<<int('M')<<" and S = "<<int('S')<<endl;
} Output:
} true
a = 97
true
M = 77 and S = 83
Precedence of Operator
Highest Precedence ! Unary + Unary –
* / %
+ –
< <= > >=
== !=
&&
||
Lowest Precedence =
// demonstrate Logical Operator
#include<iostream>
using namespace std;
void main()
{
int x, y, z;
cout<<"\n Enter x: ";
cin>>x;
cout<<"\n z = "<<z<<endl;
Output:
Enter x: 18
}
Enter y: 8
z=0
Loops
Iteration Statements
• In C/C++, and all other modern programming languages, iteration
statements (also called loops) allow a set of instructions to be
executed repeatedly until a certain condition is reached.
for (; ;)
cout<<"This loop will run forever "<<endl;
Output:
this is about the infinite loop. Q
You typed an Q
// Calculate factorials of a number
#include<iostream>
using namespace std;
void main()
{
unsigned int num;
unsigned long fact = 1;
cout<<"Factorial is "<<fact<<endl;
}
Output:
Enter a number: 6
Factorial is 720
// Fibonacci Series
#include<iostream>
using namespace std;
void main()
{
int f = 1;
while
block of statements.
The condition may be any expression and true is any nonzero value.
The loop iterates while the condition is true. When the condition becomes
false, program control passes to the line of code immediately following the
loop.
// Multiple statements in a while loop
// Prints numbers raised to fourth power
#include<iostream>
#include<iomanip>
using namespace std;
void main()
{
int pow = 1, num = 1;
Unlike for and while loops, which test the loop condition at the top of the
loop, the do-while loop checks its condition at the bottom of the loop.
This means that a do-while loop always executes at least once.
// Demonstrate do-while loop
#include<iostream>
#include<iomanip>
using namespace std;
void main()
{
long dividend, divisor;
char ch;
do
{
cout<<"\n Enter dividend: "; Output:
cin>>dividend; Enter dividend: 5
Enter divisor: 2
cout<<"\n Enter divisor: ";
cin>>divisor; Quotient is 2
Remainder is 1
if (divisor==0) Do you want to continue (y/n):y
{
Enter dividend: 12
cout<<"\n Illegal division \n"; Enter divisor: 3
continue; Quotient is 4
} Remainder is 0
cout<<"\n Quotient is "<<dividend / divisor; Do you want to continue (y/n):n
cout<<"\n Remainder is "<<dividend % divisor;
cout<<"\n Do you want to continue (y/n):";
cin>>ch;
} while (ch!='n');
}
// Demonstrate Prime Number
#include<iostream>
using namespace std;
void main()
{
unsigned long n, j;
Output 2:
Enter a number: 12
It's not prime, divisible by 2
switch case
C/C++ has a built-in multiple branch selection statement, called switch, which
successively tests the value of an expression against a list of constants. When a
match is found, the statements associated with that condition (constant) are
executed. The general form of the switch statement is
switch(expression)
{
case constant1:
statements sequence;
break;
case constant2:
statement sequence;
break;
…
default:
statement sequence;
}
switch Case (contd..)
The expression must evaluate to a character or integer value. Floating-point
expressions, for example, are not allowed. The value of expression is tested, in order,
against the values of the constants specified in the case statements.
When a match is found, the statement sequence associated with that case is
executed until the break statement or the end of the switch statement is reached.
The default statement is executed if no matches are found.
The default is optional and, if it is not present, no action takes place if all matches
fail.
The break statement is one of C/C++'s jump statements. You can use it in loops as
well as in the switch statement. When break is encountered in a switch,
program execution "jumps" to the line of code following the switch statement.
// Demonstrate Switch Statement
#include<iostream>
using namespace std;
void main()
{
char grade;
cout<<"\n Enter your grade: ";
cin>>grade;
cout<<"\n";
switch (grade)
{
case 'A':
cout<<"Excellent Work."<<endl; break;
case 'B':
cout<<"Good Work."<<endl; break;
Output 1:
case 'C': Enter your grade: B
cout<<"Average Work."<<endl; break; Good Work.
case 'D':
Output 2:
cout<<"Poor Work."<<endl; break; Enter your grade: a
default: a is not a valid letter grade.
cout<<grade<<" is not a valid letter grade."<<endl;
}
}
Functions
Function
A function groups a number of program statements into a unit and gives it
a name. This unit can be invoked from other parts of the program.
The function's code is stored in only one place in memory, even though the
function is executed many times in the course of the program.
Flow of Control in Function Calls
Parameter
A variable declared in a function heading; also called formal argument or
formal parameter.
Syntax and Semantics of void Functions
Output:
Enter your weight in pounds: 2.2
Value Parameter
– A parameter that receives a copy of the value of the corresponding argument.
Reference Parameter
– A parameter that receives the location (memory address) of the caller's
argument.
void main()
{
int i = 21;
cout<<" i = "<<i<<endl;
i /= 3;
cout<<" I am Calling function...."<<endl;
cout<<" i = "<<myfunc(i)<<endl;
cout<<" Now Value in variable 'i' is "<<i<<endl;
}
The secret to overloading is that each redefinition of the function must use
either different types of parameters or a different number of parameters.
It is only through these differences that the complier knows which function
to call in any given situation.
// Function Overloading Prog-1
#include<iostream>
using namespace std;
int myfunc (int i); // these differ in types of parameters
double myfunc (double i);
void main()
{
cout<<myfunc(10)<<endl; // Calls myfunc(int i)
cout<<myfunc(5.4)<<endl; // Calls myfunc(double i)
}
double myfunc (double i) // Function Heading
{
return i;
}
int myfunc (int i) // Function Heading
{
return i; Output:
} 10
5.4
// Function Overloading Prog-2
#include<iostream>
using namespace std;
int myfunc (int i); // these differ in types of parameters
int myfunc (int i, int j);
void main()
{
cout<<myfunc(10)<<endl; // Calls myfunc(int i)
cout<<myfunc(4,5)<<endl; // Calls myfunc(int i, int j)
}
int myfunc (int i, int j) // Function Heading
{
return i * j;
}
int myfunc (int i) // Function Heading
{
return i; Output:
} 10
20
Function Overloading (contd..)
As mentioned, the key point about function Overloading is that the
functions must differ in regard to the types and/or number of parameters.
Two functions differing only in their return types cannot be overloaded.
Local Scope
The scope of an identifier declared inside the a block extends from the
point of declaration to the end of that block.
Also, the scope of a function parameter (formal parameter) extends from
the point of declaration to the end of the block that is the body of the
function.
Global Scope
The scope of an identifier declared outside all functions and classes extends
from the point of declaration to the end of the entire file containing the
program code.
Name Precedence
The precedence that a local identifier in a function has over a global
identifier with the same name in any references that the function makes to
that identifier; also called name hiding.
int a1;
char a2;
int main ( )
{
}
void block1 ( int a1,
{ char& b2 )
int c1;
int d2;
}
void block2 ( )
{
int a1;
int b2;
while (…)
{ //Block3
int c1;
int b2;
}
}
Lifetime of a Variable
Lifetime
– The period of time during program execution when an identifier has
memory allocated to it.
Automatic Variable
– A variable for which memory is allocated and de-allocated when control
enters and exits the block in which it is declared.
Static Variable
– A variable for which memory remains allocated throughout the
execution of the entire program.
// Demonstrates static variables
#include<iostream>
using namespace std;
float getavg (float); // Function Prototypes
void main()
{
float data=1, avg;
while (data != 0)
{
cout<<"\n Enter a number: ";
cin>>data; Output:
avg = getavg (data); Enter a number: 10
cout<<" New average is "<<avg<<endl; New average is 10
} Enter a number: 8
} New average is 9
// finds averages of old plus new data
Enter a number: 0
float getavg (float newdata) New average is 6
{
static float total = 0; // static variables are initialized
static int count = 0; // only once per program
count++; // increment count
total += newdata; // add new data to total
return total / count; // return the new average
}
Arrays
Arrays
An array is a consecutive group of memory locations.
cin>>value0;
cin>>value1;
cin>>value2;
.
.
cin>>value9999;
cout<<value9999<<endl;
cout<<value9998<<endl;
cout<<value9997<<endl;
.
.
cout<<value0<<endl;
}
/* Input 1000 integer values and print them in reverse order
using arrays */
#include<iostream>
using namespace std;
void main()
{
int value[1000];
int number;
ArrayName [IndexExpression];
int number [5] = {3, 7, 12, 24, 45}; int number [5] = {3, 7};
3 7 12 24 45 3 7 0 0 0
The rest
are filled
with 0s
int number [ ] = {3, 7, 12, 24, 45}; int number [1000] = {0};
3 7 12 24 45 0 0 …. 0 0
All filled
with 0s
the valid range of index is 0 through 99. What happen if we execute the
statement
When i is less than 0 or when i is greater than 99? The result is that a
memory location outside the array is accessed.
C++ does not check for invalid (out-of-bounds) array indexes either at
compile time or at runtime.
Aggregate Array Operations
Assignment No
Arithmetic No
Comparison No
base
void print_square (int x)
{
cout<<" "<<x*x;
x
return;
}
Passing Array as Parameters
MemberList
DataType MemberName;
DataType MemberName;
.
.
.
Specifying the Structure
The structure specifier tells how the structure is organized. It specifies what
members the structure will have. Here it is:
struct part
int modelno;
int partno;
float cost;
};
Defining a Structure Variable
The first statement in main()
part part1;
defines a variable, called part1,of type
structure part.
part1.modelno = 6244;
// Uses parts inventory to demonstrate structures
#include<iostream>
using namespace std;
void main()
{
part part1; // Define a structure variable
part1.modelno = 7896; // Accessing structure members
part1.partno = 456;
part1.cost = 321.56f;
void main()
{
part1.modelno = 7896; // Accessing structure members
part1.partno = 456;
part1.cost = 321.56f;
According to the table, one struct variable can be assigned to another. However,
both variables must be declared to be of the same type.
For example, given the declarations
StudentRec student;
StudentRec anotherStudent;
The statement
anotherStudent = student;
copies the entire contents of the struct variable student to the variable
anotherStudent, member by member.
On the other hand, aggregate arithmetic operations and comparisons are not allowed
(primarily because they wouldn't make sense):
student = student * anotherStudent; // Not allowed
if (student < anotherStudent) // Not allowed
Furthermore, aggregate I/O is not permitted:
cin>>student; // Not allowed
We must input or output a struct variable one member at a time:
cin>> student.firstName;
cin >> student.lastName;
// demonstrates nested structures
#include<iostream>
using namespace std;
struct Distance //English distance
{ int feet;
float inches;
};
struct Room //rectangular area
{ Distance length; //length of rectangle
Distance width; //width of rectangle
};
void main()
{
Room dining; //define a room
dining.length.feet = 13; //assign values to room
dining.length.inches = 6.5;
dining.width.feet = 10; Output:
dining.width.inches = 0.0; Dining room area is 135.417 square feet
//convert length & width
float l = dining.length.feet + dining.length.inches/12;
float w = dining.width.feet + dining.width.inches/12;
//find area and display it
cout<<"\n Dining room area is "<<l * w<<" square feet\n";
}
// Demonstrates passing structure as argument
#include<iostream>
using namespace std;
struct Distance //English distance
{ int feet;
float inches;
};
void engldisp (Distance); // Function Prototype
void main()
{ Distance ucs1, ucs2; // Define two lengths
//get length ucs1 from user
cout<<"\n Enter feet: "; cin>>ucs1.feet;
cout<<" Enter inches: "; cin>>ucs1.inches;
//get length ucs2 from user
Output:
cout<<"\n Enter feet: "; cin>>ucs2.feet;
Enter feet: 10
cout<<" Enter inches: "; cin>>ucs2.inches; Enter inches: 6.75
cout<<"\n ucs1 = ";
engldisp(ucs1); // Display length 1 Enter feet: 13
cout<<"\n ucs2 = "; Enter inches: 0.0
engldisp(ucs2); // Display length 2 ucs1 = 10'-6.75"
}
ucs2 = 13'-0"
// Display structure of type Distance in feet and inches
void engldisp (Distance ucs) // Parameter ucs of type Distance
{
cout<<ucs.feet<<"\'-"<<ucs.inches<<"\""<<endl;
}
// Demonstrates returning a structure
#include<iostream>
using namespace std;
struct Distance //English distance
{ int feet;
float inches;
};
• Since u.i and u.d have the same memory address, changing the
value of one alters the value of the other.
Union
• Unions have the same properties as structures.
• Unions can be initialized (the initializer specifies the value of the first
member).
• Uses of unions:
– To save space.
• Unions can be initialized (the initializer specifies the value of the first
member).
• Uses of unions:
– To save space.
• enum type:
– A small number of values are individually named and are referred to by name.
Enumeration are treated internally as Integers.
• int type:
– A large number of values are not named and are referred to by value.
// Demonstrates enum type
#include<iostream>
using namespace std;
// Specify enum type
enum days_of_week {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
void main()
{
days_of_week day1, day2;// define variables of type days_of_week
char str[11];
This makes room for the null at the end of the string.
str[0]= 'H';
str[1]= 'i';
str[2]= '\0';
String Variables
// Demonstrate String Variables
#include<iostream>
using namespace std;
const int MAX = 80;// Max characters in string
void main()
{
char str[MAX]; // String variable str
cout<<"\n Enter a string: ";
cin>>str; //put string in str
//display string from str
cout<<"You entered :"<<str<<endl;
}
Avoiding Buffer Overflow
// Avoids Buffer Overflow
#include <iostream>
#include <iomanip>
using namespace std;
const int MAX = 20; // Max characters in string
void main()
{
char str[MAX]; //string variable str
cout<<"\nEnter a string: ";
cin>>setw(MAX)>>str; //put string in str, no more than MAX chars
cout<<"You entered: "<<str<<endl;
Output:
}
Enter a string:
11223344556677889900
You entered:
1122334455667788990
String Constants
// Initialized string
#include <iostream>
using namespace std;
void main()
{
char str[] = "Listen to many, speak to a few. ";
cout<<str<<endl;
}
Output:
Listen to many, speak to a few.
Reading Embedded Blanks
// Reads string with embedded blanks
#include <iostream>
using namespace std;
void main()
{
char str[MAX]; //string variable str
cout<<"\nEnter a string: ";
cin.get(str, MAX); //put string in str
cout<<"You entered: "<<str<<endl;
}
To read text containing blanks we use another function, cin.get(). This syntax
means a member function get() of the stream class of which cin is an object.
Reading Multiple Lines
// Reads multiple lines, terminates on '$' character
#include <iostream>
using namespace std;
void main()
{
cout<<"\nEnter a string:\n";
cin.get(str, MAX, '$'); //terminate with $
cout<<"You entered:\n"<<str<<endl;
}
Copying a String the Hard Way
// Copies a string using a for loop
#include <iostream>
#include <cstring> //for strlen()
using namespace std;
const int MAX = 80; //size of str2 buffer
void main()
{ //initialized string
char str1[] = "Oh, Captain, my Captain! our fearful trip is done";
char str2[MAX]; //empty string
void main()
{ //array of strings
char star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday",
"Saturday" };
Output:
for(int j=0; j<DAYS; j++) //display every string
Sunday
Monday
cout<<star[j]<<endl; Tuesday
} Wednesday
Thursday
Friday
Saturday
Arrays of Strings
// Array of strings
#include <iostream>
using namespace std;
const int DAYS = 7; //number of strings in array
const int MAX = 10; //maximum size of each string
void main()
{ //array of strings
char star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday",
"Saturday" };
Output:
for(int j=0; j<DAYS; j++) //display every string
Sunday
Monday
cout<<star[j]<<endl; Tuesday
} Wednesday
Thursday
Friday
Saturday
Defining String Objects
// Defining and assigning string objects
#include <iostream>
#include <string>
using namespace std;
void main()
{
string s1("Man"); //initialize
Output:
string s2 = "Beast"; //initialize
s3 = Man
string s3;
s3 = Neither Man nor Beast
s3 = s1; //assign Beast nor Man
cout<<"s3 = "<<s3<<endl;
s3 = "Neither " + s1 + " nor "; //concatenate
s3 += s2; //concatenate
cout<<"s3 = "<<s3<<endl;
cout<<"s1: "<<s1<<endl;
cout<<"s1 is "<<s1.size()<<" characters"<<endl;
} Output:
s1: Cal is better language !
s1 is 24 characters
Classes & Objects
Class
• A class is an expanded concept of a data structure: instead of holding only data,
it can hold both data and functions.
• An object is an instantiation of a class. In terms of variables, a class would be
the type, and an object would be the variables.
• Classes are generally declared using the keyword class, with the following
format:
class class-name
{
private data and functions
access-specifier:
data and functions
access-specifier:
data and functions
// ………
access-specifier:
data and functions
} object-list;
Class (contd..)
• The object-list is optional, it declares objects of the class. Here
access-specifier is one of these three C++ keywords:
– public
– Private
– protected
• These specifier modify the access rights that the members following
them acquire:
– Private members of a class are accessible only from within other members of the
same class or from their friends.
– Protected members are accessible from members of their same class and from
their friends, but also from members of their derived classes.
– Finally, public members are accessible from anywhere where the object is visible.
Specifying the Class
• By default, all members of a class declared with the class keyword have
private access for all its members. Therefore, any member that is declared
before one other class specifier automatically has private access. For
example:
class CRectangle
{
int x, y;
public:
void set_values (int,int);
int area ();
} rect;
#include <iostream>
using namespace std;
class CRectangle
{
int x, y;
public:
void set_values(int,int);
int area() { return (x*y); }
};
void CRectangle::set_values (int a, int b)
{
x = a;
y = b;
}
void main ()
{
CRectangle rect, rectb;
rect.set_values(3,4);
rectb.set_values(5,6);
cout<<"rect area: "<<rect.area()<<endl; Output:
cout<<"rectb area: "<<rectb.area()<<endl; rect area: 12
} rectb area: 30
One Class, Two Objects
• In this concrete case, the class (type of the objects) to which we are talking
about is CRectangle, of which there are two instances or
objects: rect and rectb. Each one of them has its own member variables and
member functions.
• Notice that the call to rect.area() does not give the same result as the call
to rectb.area(). This is because each object of class CRectangle has its
own variables x and y, as they, in some way, have also their own function
members set_value() and area() that each uses its object's own variables
to operate.
• For example, what would happen if in the previous example we called the
member function area() before having called function set_values()?
Probably we would have gotten an undetermined result since the
members x and y would have never been assigned a value.
• In order to avoid that, a class can include a special function called constructor,
which is automatically called whenever a new object of this class is created. This
constructor function must have the same name as the class, and cannot have
any return type; not even void.
// class constructor
#include <iostream>
using namespace std;
class CRectangle
{
int width, height;
public:
CRectangle (int, int);
int area () {return (width * height); }
};
CRectangle::CRectangle (int a, int b)
{
width = a;
height = b;
}
void main ()
{
CRectangle rect (3,4);
CRectangle rectb (5,6);
cout<<"rect area: "<<rect.area()<<endl; Output:
cout<<"rectb area: "<<rectb.area()<<endl; rect area: 12
} rectb area: 30
Constructors (contd..)
• As you can see, the result of this example is identical to the previous one. But
now we have removed the member function set_values(), and have included
instead a constructor that performs a similar action: it initializes the values
of width and height with the parameters that are passed to it.
• Notice how these arguments are passed to the constructor at the moment at
which the objects of this class are created:
• You can also see how neither the constructor prototype declaration (within the
class) nor the latter constructor definition include a return value; not even void.
Destructor
• The destructor fulfills the opposite functionality. It is automatically called when
an object is destroyed.
• The destructor must have the same name as the class, but preceded with a tilde
sign (~) and it must also return no value.