C++ Semester1
C++ Semester1
Object-Oriented Programming
First semester
asus
[COMPANY NAME]
1.1 A Brief Overview of Computers Lecture One
A computer is an electronic device capable of performing commands. The basic
commands that a computer performs are input (get data), output (display result),
storage, and performance of arithmetic and logical operations. There are two main
components of a computer system: hardware and software.
Major hardware components include the central processing unit (CPU);
main memory (MM), also called random access memory (RAM); input/output
devices; and secondary storage. Some examples of input devices are the keyboard,
mouse, and secondary storage. Examples of output devices are the screen, printer,
and secondary storage. See figure(1).
1
System programs control the computer. The operating system is the system
program that loads first when you turn on your PC. Without an operating system, the
computer is useless. Application programs perform a specific task. Word
processors, spreadsheets, and games are examples of application programs. The
operating system is the program that runs application programs.
Remember that a computer is an electronic device. Electrical signals are used
inside the computer to process information. There are two types of electrical signals:
analog and digital. Analog signals are continuous waveforms used to represent such
things as sound. Audio tapes, for example, store data in analog signals. Digital
signals represent information with a sequence of 0s and 1s. A 0 represents a low
voltage, and a 1 represents a high voltage. Digital signals are more reliable carriers
of information than analog signals and can be copied from one device to another
with exact precision. Because digital signals are processed inside a computer, the
language of a computer, called machine language, is a sequence of 0s and 1s. The
digit 0 or 1 is called a binary digit, or bit. Sometimes a sequence of 0s and 1s is
referred to as a binary code or a binary number. Bit: A binary digit 0 or 1. A sequence
of eight bits is called a byte. Moreover, 1024 bytes is called a kilobyte (KB).
Every letter, number, or special symbol (such as * or {) on your keyboard is
encoded as a sequence of bits, each having a unique representation. The seven-bit
American Standard Code for Information Interchange (ASCII) is the most
commonly used encoding scheme on personal computers.
2
necessarily the same as the machine language of another machine. The only
consistency among computers is that all data is stored and manipulated as binary
codes.
Assembly languages were developed to make the programmer’s job easier.
In assembly language, instruction is an easy-to-remember. It is much easier to
write instructions in assembly language. However, a computer cannot execute
assembly language instructions directly. The instructions first have to be translated
into machine language. A program called an assembler translates the assembly
language instructions into machine language.
Moving from machine language to assembly language made programming
easier, but a programmer was still forced to think in terms of individual machine
instructions. The next step toward making programming easier was to devise high-
level languages that were closer to natural languages. Basic, FORTRAN, COBOL,
Pascal, C, C++, C#, and Java are all high-level languages.
EX: write the weekly wages equation
C++ Assembly Machine Language
wages = rate * hours; LOAD rate 100100 010001
MULT hours 100110 010010
STOR wages 100010 010011
3
Object-oriented design (OOD) is a widely used programming methodology.
In OOD, the first step in the problem-solving process is to identify the components
called objects, which form the basis of the solution, and to determine how these
objects interact. A programming language that implements OOD is called an object-
oriented programming (OOP) language.
1.4 Reviewing the basics of a C++ language syntax
In this section, we will briefly review basic C++ syntax. We are assuming that
you have a C++ programmer with non-OOP skills.
EX: Here are a few straightforward examples using the standard data types described
above:
int x = 5; float y = 9.87; double yy = 12345.78;
4
int a = x; float y2 = 10.76f; // double c = yy;
optional 'f' suffix
on float literal
float b = y;
char z= 'Z'; bool test = true;
char d = z; bool e = test;
bool f = !test;
• Relational Operators
Assume variable A holds 1 and variable B holds 2:
Operator == != > < >= <=
Expression A==B B!=A A>B B<A B>=B B<=A
Output False True False False True False
• Logical Operators
5
Assume variable A holds 1 and variable B holds 0
Operator &&(and) ||(or) !(not)
Expression A && B B || A !A
Output False True False
• Bitwise Operators
Assume variable A holds 60(00111100) and variable B holds 13(00001101)
Operator Expression Output
& (And) A&B 12 (0000 1100
| (Or) B|A 61 (0011 1101)
^ (Xor) A^B 49 (0011 0001)
~(Complement) ~A 195 (1100 0011)
<< (Binary Left Shift) A << 2 240 (1111 0000)
>> (Binary Right Shift) A>>2 15 (0000 1111)
• Assignment Operators
= += -= *= /= %= >>= <<=
C=3 C+=3 C-=3 C*=3 C/=3 C%=3 C>>=3 C<<=3
Assign
C=C+3 C=C-3 C=C*3 C=C/3 C=C%3 C=C>>3 C=C<<3
3 to c
6
++variable Variable++ --variable Variable--
X=5 X=5 X=5 X=5
++x; //x=6 X++; //x=6 --x ;//x=4 x --;//x=4
x = 5; x = 5; x = 5; x = 5;
y = ++x;//x=6,y=6 y = x++;//x=6,y=5 y = --x;//x=4,y=4 y = x--;//x=4,y=5
7
In C++, there are two selections or branch control structures: if statements and the
switch structure.
One-Way Selection Two-Way Selection Nested if
if (expression) if (expression) if (score >= 90)
statement statement1 cout << "The grade is A.";
else else if (score >= 80)
statement2 cout << "The grade is B.";
else if (score >= 70)
cout << "The grade is C.";
else if (score >= 60)
cout << "The grade is D.";
else
cout << "The grade is F." ;
8
EX: c++ program to test if character is small letter, capital letter,digits or
special character.
#include <iostream>
using namespace std;
int main()
{ char x;
cout << "Enter a character: ";
cin >> x;
if (x >= 'A' && x<='Z')
cout << "The character is CL.";
else if (x >= 'a' && x<='z')
cout << "The character is SL.";
else if (x >= '0' && x<='9')
cout << "The character is D.";
else
cout << "it is special character." ;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int x, y, z, max;
cout<<"Enter any three numbers: ";
cin>>x>>y>>z;
max = x;
if(y>max)
max = y;
if(z>max)
max = z;
cout<<"\n"<<"The largest of "<<x<<", "<<y<<" and "<<z<<" is "<<max;
return 0;
}
9
C++’s switch structure gives the computer the power to choose from among many
alternatives. A general syntax of the switch statement is:
switch (expression)
{
case value1:
statements1
break;
case value2:
statements2
break;
.
.
.
case valuen:
statementsn
break;
default:
statements
}
10
case 6:
grade = 'D';
break;
case 7:
grade = 'C';
break;
case 8:
grade = 'B';
break;
case 9:
case 10:
grade = 'A';
break;
default:
cout << "Invalid test score." << endl;
}
cout<<"grade="<<grade;
return 0;
}
EX: C++ program that shows the appropriate age to vote.
#include <iostream>
using namespace std;
int main()
{ int age;
cout << "Enter the age: ";
cin >> age;
switch (age >= 18)
{
case 1:
cout << "Old enough to be drafted." << endl;
cout << "Old enough to vote." << endl;
break;
case 0:
cout << "Not old enough to be drafted." << endl;
cout << "Not old enough to vote." << endl;
}
return 0;
}
11
• Lopping Control Structure Lecture Two
A loop statement allows us to execute a statement or group of statements multiple
times, and the following is the general form of a loop statement in most programming
languages:
12
for (initial statement; loop condition; update statement) for (i = 0; i < 20; i++)
statement cout << i << " ";
For
loop
do i = 0;
statement do
while (expression); {
cout << i << " ";
i = i + 1;
}
while (i <= 20);
Do i = 0;
while do
{
cout << i << " ";
i = i + 2;
}
while (i <= 20);
13
EX: C++ program to Calculate 12 + 22 + 32 + 42 + 52 +62 ... + n2 series
#include <iostream>
using namespace std;
int main()
{ int i,a,n,sum=0;
cout<<"enter the limit of series";
cin>>n;
cout<<endl;
for(i=1;i<=n;i++)
sum+=i*I;
cout<<"Sum: "<<sum;
return 0; }
EX: C++ program to Calculate 12 / 22+ 22 /32+ 32 /42+ ... + n2 /(n+1)2 series.
#include <iostream>
using namespace std;
int main()
{ int i,a,n,sum=0;
cout<<"enter the limit of series";
cin>>n;
cout<<endl;
for(i=1;i<=n;i++)
sum+=(i*i)/(i+1)*(i+1);
cout<<"Sum: "<<sum;
return 0; }
EX: C++ program to Calculate (1) + (1+2) + (1+2+3) + (1+2+3+4) + ... +
(1+2+3+4+...+n) series
#include <iostream>
using namespace std;
int main()
{ int i,j,n,sum=0;
cout<<"enter the limit of series";
cin>>n;
for(i=1;i<=n;i++)
for( j=1;j<=i;j++)
sum+=j;
cout<<"Sum: "<<sum;
return 0;}
14
EX: C++ program finds the sum of positive numbers the user enters. The loop
ends if the user enters a negative number.
#include <iostream>
using namespace std;
int main() {
int num;
int sum = 0;
cout << "Enter a number: ";
cin >> num;
while (num >= 0) { do {
sum += num; sum += num;
cout << "Enter a number: "; cout << "Enter a number: ";
cin >> num; } cin >> num; }
while (num >= 0);
cout << "\nThe sum is " << sum << endl;
return 0; }
EX: C++ program to Calculate 10+ 21 + 32 + 43 + 54 +65 ... + n n-1 series
#include <iostream>
using namespace std;
int main()
{ int i,j,n,sum=1,f;
cout<<"enter the limit of series";
cin>>n;
cout<<endl;
for(i=2;i<=n;i++)
{f=1;
for(j=1;j<=i-1;j++)
f*=i;
sum+=f;}
cout<<"Sum: "<<sum;
return 0; }
EX: C++ program to show the following pattern:
#include <iostream>
using namespace std; 1
int main() 2 2
{ int i,j,n; 3 3 3
cout<<"enter the limit of pattern"; 4 4 4 4
cin>>n;
cout<<endl;
15
for(i=1;i<=n;i++)
{ for(j=1;j<=i;j++)
cout<<i<<" ";
cout<<endl; }
return 0; }
EX: C++ program to show the following pattern: 1 1 1 1
2 2 1
#include <iostream> 3 3
using namespace std; 4
int main()
{ int i,j,n;
cout<<"enter the limit of pattern";
cin>>n;
cout<<endl;
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i+1;j++)
cout<<i<<" ";
cout<<endl;
} 1 2 3 4
5 6 7
return 0; } 8 9
EX: C++ program to show the following pattern: 10
#include <iostream>
using namespace std;
int main()
{ int i,j,n,a=1;
cout<<"enter the limit of pattern";
cin>>n;
cout<<endl;
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i+1;j++)
cout<<a++<<" ";
cout<<endl;
}
return 0; }
16
EX: C++ program to show the following pattern:
a b c d
#include <iostream> e f g
using namespace std; h i
int main() j
{ int i,j,n;
char a='a';
cout<<"enter the limit of pattern";
cin>>n;
cout<<endl;
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i+1;j++)
cout<<a++<<" ";
cout<<endl;
}
return 0; }
return 0; }
17
EX: C++ program to show the following pattern:
a a a a a
#include <iostream> b b b
using namespace std; c
int main()
{ int i,j,n,a;
char l='a';
cout<<"enter the limit of pattern";
cin>>n;
a=n;
cout<<endl;
for(i=1;i<=n;i++)
{ for(j=1;j<=i;j++)
cout<<" ";
for(j=1;j<=a;j++)
cout<<l<<" ";
a-=2;
cout<<endl;
l++; }
return 0; }
EX: C++ program to show the following pattern:
#include <iostream> 1
using namespace std; 2 2
int main() 3 3 3
{ int i,j,n,a; 4 4 4 4
cout<<"enter the limit of pattern";
cin>>n;
a=n-1;
cout<<endl;
for(i=1;i<=n;i++)
{
for(j=1;j<=a;j++)
cout<<" ";
a--;
for(j=1;j<=i;j++)
cout<<i<<" ";
cout<<endl;}
return 0; }
18
1.6 Array Lecture Three
The data type is called simple if variables of that type can store only one value
at a time. In contrast, in a structured data type, each data item is a collection of
other data items. Simple data types are building blocks of structured data types. The
array is a structured data type.
one-dimensional array Two-dimensional array:
dataType arrayName[intExp]; dataType arrayName[intExp1][intExp2];
int list[10]; int list[10][5];
19
EX: C++ program to find the sum and average of an array.
#include <iostream>
using namespace std;
int main()
{
int list[10],i,sum=0;
for (i = 0; i < 10; i++)
cin>>list[i] ;
for (i = 0; i < 10; i++)
cout<<list[i]<<" " ;
cout<<endl;
for (i = 0; i < 10; i++)
sum+=list[i] ;
cout<<"the summation of array is "<<sum;
cout<<"\nthe average of array is "<<sum/10;
return 0; }
20
EX: C++ program to find the Largest Element in Each Row and Each Column
in two array dimensions.
#include <iostream>
using namespace std;
int main()
{
int matrix[4][4],row,col,rows,cols,largest;
rows = 4;
cols=4;
for (row = 0; row < rows; row++)
for (col = 0; col < cols; col++)
cin>>matrix[row][col] ;
for (row = 0; row < rows; row++)
{for (col = 0; col < cols; col++)
cout<<matrix[row][col]<<" " ;
cout<<endl;}
21
EX: C++ program replaces Main Diagonal with the Secondary Diagonal in a
square array.
#include <iostream>
using namespace std;
int main() 1 2 3 666 3 2 1
{ 4 5 6 4 5 6
int matrix[5][5],row,col,rows,cols,a; 7 8 9 9 8 7
rows = 5;
cols=5;
for (row = 0; row < rows; row++)
for (col = 0; col < cols; col++)
cin>>matrix[row][col] ;
for (row = 0; row < rows; row++)
{for (col = 0; col < cols; col++)
cout<<matrix[row][col]<<" " ;
cout<<endl;}
for (row = 0; row < rows; row++)
{a=matrix[row][row];
matrix[row][row]=matrix[row][rows-1-row];
matrix[row][rows-1-row]=a;}
cout<<"the new array after replacing is :"<<endl;
for (row = 0; row < rows; row++)
{for (col = 0; col < cols; col++)
cout<<matrix[row][col]<<" " ;
cout<<endl;}
return 0;}
EX: C++ program to initialize a two-dimensional array with character
elements.
#include <iostream> for (row = 0; row < rows; row++)
using namespace std; for (col = 0; col < cols; col++)
int main() matrix[row][col]=ch++ ;
{ for (row = 0; row < rows; row++)
char matrix[5][5],ch='a'; {for (col = 0; col < cols; col++)
int row,col,rows,cols,a; cout<<matrix[row][col]<<" " ;
rows = 5; cout<<endl;}
cols=5; return 0;}
22
1.7 C++ Strings Lecture four
C++ provides the following two types of string representations:
• The C-style character string.
• The string class type was introduced with Standard C++.
#include <iostream>
using namespace std;
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;
return 0;
}
23
C++ supports a wide range of functions that manipulate null-terminated strings :
24
String class is part of the C++ library that supports much functionality over C-
strings.
string st;
st=” Hello”
St[] H e l l 0
index 0 1 2 3 4
The data type string contains several other functions for string manipulation. The
the following table describes some of these functions: suppose strVar =”C++” and
str =” language”
Expression Effect EX
strVar[index] Returns the element at cout<<strVar[2];
the position specified by Output: +
index.
strVar.append(str) Appends str to strVar. strVar.append(str);
Output:C++ language
strVar.append(n, Appends n copies of ch strVar.append(2, '&');
ch) to strVar, in which Output:c++&&
ch is a char variable or a
char constant.
strVar.compare(str) Returns 1 if strVar <> cout<<strVar.compare(strVar);
str; returns 0 Output:0
if strVar == str
cout<<strVar.compare(str);
Output:1
25
EX:c++ program that prompts the user to input a string and remove all the
vowels from the string. For example, if str = "There," after removing all the
vowels, str = "Thr."
#include <iostream>
#include <string>
using namespace std;
int main () {
string st;
cout<<"enter your string: ";
cin>>st;
int i=0;
while(i<st.length())
if (st[i]=='A'||st[i]=='E'||st[i]=='I'||st[i]==O'||st[i]=='U'||st[i]=='Y'||
st[i]=='a'||st[i]=='e'||st[i]== 'i'||st[i]== 'o'||st[i]=='u'||st[i]=='y')
for(int j=i;j<st.length();j++)
st[j]=st[j+1];
else
i++;
cout<<"\n the string without vowel letters: "<<st;
return 1;}
EX: c++ program detect if the string can be read from both sides:
#include <iostream>
#include <string>
using namespace std;
int main () {
string st1,st2="";
cout<<"enter your string: ";
cin>>st1;
int len=st1.length();
for(int i=len-1;i>=0;i--)
st2.append(1, st1[i]);
cout<< "\n the swapping string is "<<st2;
if (!st1.compare(st2))
cout<<"\n string read from both sides\n";
else
cout<<"\n string can not read from both sides\n";
return 1;
26
1.8 Functions Lecture Five
a function, also called a subprogram, is a set of instructions. When a function
executes, it accomplishes something. The function main executes automatically
when you run a program. Other functions execute only when they are activated.
C++ comes with a wealth of functions, called predefined functions, that are already
written. predefined functions are organized as a collection of libraries, called header
files. A particular header file may contain several functions. Therefore, to use a
particular function, you need to know the name of the function and a few other
things, which are described shortly.
header
function work called result
file
X=pow(2.0, 3.0)
pow (double, double) pow(x, y)=xy X=8
#include ;
<cmath> sqrt(double) sqrt(x)=√𝑥 X=Sqrt(9); X=3
abs(double/int) Return absolute value X=abs(-5); X=5
Returns 1 (true) if x is
a
lowercase letter; X=Islower('h'); x=1
islower(int)
otherwise, y=Islower('E'); y=0
it returns 0 (false);
is 1 (true)
Returns 1 (true) if x is
an
uppercase letter; X=isupper('K') ; X=1
isupper(int)
#include otherwise, y=isupper('d') ; Y=1
<cctype> it returns 0 (false);
#include <iostream>
#include <cmath>
using namespace std;
int main () {
int n,s=1;
double x,sum=1,;
cout<< "enter the values of X ";
cin>>x;
cout<<"\n enter the number of quantities ";
cin>>n;
for (int i=1;i<n;i++)
{x=pow(x,2);
sum+=(s*sqrt(x));
s*=-1;}
cout<<"\n the result is: "<<sum;
return 1;}
EX: C++ program to Calculate series √𝒙𝟎 / √𝒚𝟏 + √𝒙𝟐 /√𝒚𝟑 − √𝒙𝟑 /√𝒚𝟒 +
√𝒙𝟒 /√𝒚𝟓 − √𝒙𝟓 /√𝒚𝟔 … (+/−)√𝒙𝒏 /√𝒚𝒏+𝟏
#include <iostream>
#include <cmath>
using namespace std;
int main () {
int n,s=1;
double x,y,sum=0,;
cout<< "enter the values of X and Y ";
cin>>x>>y;
cout<<"\n enter the number of quantities ";
cin>>n;
for (int i=0;i<n;i++)
{sum+=(s*sqrt(pow(x,i))/sqrt(pow(y,i+1)));
s*=-1;}
cout<<"\n the result is: "<<sum;
return 1;}
28
EX: C++ program to compute the number of upper letters in any string and
convert them into lower ones.
#include <iostream>
#include <string>
#include <cctype>
• Void functions—functions that do not have a return type. These functions do not
use a return statement to return a value.
29
The syntax of a value-returning function is:
30
Suppose that num, num1, and num2 are double variables. Also suppose that num1
= 45.75 and num2 = 35.50. Figure 6-3 shows various calls to the function larger.
EX: c++ program to find larger among three numbers using previous function
larger.
#include <iostream>
using namespace std;
double larger(double x, double y)
{
if (x >= y)
return x;
else
return y;
}
double compareThree(double x, double y, double z)
{
return larger(x, larger(y, z));
}
int main () {
double num1,num2,num3;
cout<<"enter three numbers: ";
cin>>num1>>num2>>num3;
cout<<"\n larger number is:"<<compareThree(num1,num2,num3);
return 1;}
31
OR:
#include <iostream>
using namespace std;
double larger(double , double ); //function prototype
double compareThree(double , double , double ); //function prototype
int main () {
double num1,num2,num3;
32
EX: C++ program to compute the number of consonant letters in any string.
#include <iostream>
#include<cctype>
#include<string>
using namespace std;
bool vowel(char ch)
{ ch=tolower(ch);
switch (ch)
{
case'e':
case'u':
case'i':
case'o':
return true;
break;
default:
return false;}}
int main() {
string st;
int len,c=0;
cout << "Enter a string: ";
cin >> st;
len=st.length();
for(int i=0;i<=len-1;i++)
if(!vowel(st[i]))
c++;
cout << "/n number of con-letters is = " << c<<endl;
return 0;}
33
1.10 Examples of Void functions Lecture six
EX: C++ program to show the following pattern using two functions one to
print space and the second to print stars.
#include <iostream> int main() {
using namespace std; int n; *
void space(int z) cout << "Enter number of columns: "; * *
{ for(int i=1;i<=z;i++) cin >> n;
cout<<" ";} for(int i=1;i<=n;i++) * * *
void stars(int z) {space(n-i); * * * *
{ for(int i=1;i<=z;i++) stars(i);
cout<<"*";} cout<<endl;}
return 0;}
EX: C++ program to show the following pattern using functions to print space
for each line.
#include <iostream>
0 1 2 3
#include <iomanip> 4 5 6 7
using namespace std; 8 9 10 11
void line(int start, int end) 12 13 14 15
{ for(int i=0;i<=end;i++)
cout<<setw(4)<<start++;}
int main() {
int n,s=0,e;
cout << "Enter number of columns: ";
cin >> n;
for(int i=1;i<=n;i++)
{line(s,n);
s=s+4;
cout<<endl;}
return 0;}
34
EX: C++ program to show the following pattern using functions to print space
for each line and the second to print numbers.
#include <iostream>
#include <iomanip>
0
using namespace std; 1 2 3
void space(int z) 4 5 6 7 8
{ for(int i=1;i<=z;i++) 9 10 11 12 13 14
cout<<setw(4)<<" ";}
void line(int start, int end)
{ for(int i=0;i<=end;i++)
cout<<setw(4)<<start++;}
int main() {
int n,s,e=0;
cout << "Enter number of columns: ";
cin >> n;
s=n-1;
for(int i=0;i<n;i++)
{space(s--);
line(i+e,e);
e=e+2;
cout<<endl;}
return 0;}
EX C++ program shows the following pattern using functions to print space
for each line.
#include <iostream> int main() { A
#include <iomanip> int n; B B
using namespace std; char ch='A'; C C C
void space(int z) cout << "Enter number of columns: "; D D D D
{ for(int i=1;i<=z;i++) cin >> n;
cout<<setw(4)<<" ";} for(int i=1;i<=n;i++)
void line_C(char c, int num) {line_C(ch++,i);
{ for(int i=0;i<num;i++) cout<<endl;}
cout<<setw(4)<<c;} return 0;}
35
1.11 Examples of functions and string
C++ program to swap any string split capital letters from small letters or
remove any digits or special characters from a string.
#include <iostream>
#include<string>
using namespace std;
string swap(string st)
{ char ch;
int len=st.length()-1;
for(int i=0;i<=len/2;i++)
{ch=st[i];
st[i]=st[len-i];
st[len-i]=ch;}
return st;
}
bool sma_let(char ch)
{
if(ch>='a' and ch<='z')
return true;
else
return false;
}
bool cap_let(char ch)
{
if(ch>='A' and ch<='Z')
return true;
else
return false;
}
void split(string st)
{ string sm="",ca="";
int len=st.length()-1;
for(int i=0;i<=len;i++)
if(sma_let(st[i]))
36
sm.append(1, st[i]);
else if(cap_let(st[i]))
ca.append(1, st[i]);
cout<<"small letter string is: "<<sm;
cout<<"\ncapitall letter string is: "<<ca;}
void remov(string st)
{ string s="ee";
int len=st.length()-1;
for(int i=0;i<=len;i++)
if((sma_let(st[i]))||(cap_let(st[i])))
s.append(1,st[i]);
cout<<"new string is: "<<s;}
void showChoices()
{
cout << "\nEnter--"<<endl;
cout << "1: To swap a string "<< endl;
cout << "2: To split capital letters from small letters"<< endl;
cout << "3: To remove any digits or special characters from a string"<< endl;
cout << "99: To quit the program." << endl;
}
int main() {
int choice;
string st;
do
{
showChoices();
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
cout << "Enter a string: ";
cin >> st ;
cout << endl;
cout<<swap(st);
37
break;
case 2:
cout << "Enter a string: ";
cin >> st ;
cout << endl;
split(st);
break;
case 3:
cout << "Enter a string: ";
cin >> st ;
cout << endl;
remov(st);
break;
case 99:
break;
default:
cout << "Invalid input." << endl;
}
}
while (choice != 99);
return 0;}
1.12 Reference variables as parameters Lecture seven
The reference parameter receives the address (memory location) of the actual
parameter. Reference parameters can pass one or more values from a function and
change the actual parameter's value.
38
EX: C++ program reads a course score and prints the course grade.
#include <iostream>
using namespace std;
void getScore(int& score)
{
39
EX: C++ program to swap the string.
#include <iostream>
#include<string>
using namespace std;
void swap_ch(char& ch1,char& ch2)
{
char temp=ch1;
ch1=ch2;
ch2=temp; }
void swap_st(string& st)
{ int len=st.length()-1;
for(int i=0;i<=len/2;i++)
swap_ch(st[i],st[len-i]);}
int main()
{string st;
cout<<"Enter the string:";
cin>>st;
swap_st(st);
cout<<"\nthe swapped string is :"<<st<<endl;}
1.13 functions and arrays
C++ does not allow functions to return a value of the type array. C++ arrays
are always passed by reference.
EX: C++ program to initialize an array, read, print, and find the larger
element in an array.
#include <iostream>
using namespace std;
int size = 10;
void initializeArray(int x[],int sizeX)
{
for(int i=0;i<=sizeX;i++)
x[i]=0;
}
40
void fillArray(int x[],int sizeX)
{ cout<<"\n enter the elements of array\n";
for(int i=0;i<=sizeX;i++)
cin>>x[i]; }
void printArray( int x[],int sizeX)
{
for(int i=0;i<=sizeX;i++)
cout<<"\nx["<<i<<"]="<<x[i]; }
int sumArray( int x[],int sizeX)
{ int sum=0;
for(int i=0;i<=sizeX;i++)
sum+=x[i];
return sum; }
int LargestElement( int x[],int sizeX)
{ int large=x[0];
for(int i=1;i<=sizeX;i++)
if(x[i]>large)
large=x[i];
return large;}
int main()
{
int list[10],size=10;
initializeArray(list,size);
printArray(list,size);
fillArray(list,size);
printArray(list,size);
41
EX: C++ program to swap each string in the array into another array and print
them together.
#include <iostream>
#include<string>
int size=5;
using namespace std;
void swap_ch(char& ch1,char& ch2)
{
char temp=ch1;
ch1=ch2;
ch2=temp;
}
void swap_st(string& st)
{ int len=st.length()-1;
for(int i=0;i<=len/2;i++)
swap_ch(st[i],st[len-i]);
}
void swap_arr(string st_ar[], string sw_st[],int sizeX)
{ cout<<"moon";
string st;
for(int i=0;i<sizeX;i++)
{st=st_ar[i];
swap_st(st);
sw_st[i]=st; } }
void print2Array(string x[],string y[],int sizeX)
{ int main()
for(int i=0;i<sizeX;i++) {
{cout<<"\nx["<<i<<"]="<<x[i]; string st[size],st2[size];
cout<<" y["<<i<<"]="<<y[i];} fillArray(st,size);
cout<<endl; } cout<<st[0];
void fillArray(string x[],int sizeX) swap_arr(st,st2,size);
{ cout<<"\n enter the elements of array\n"; print2Array(st,st2,size);}
for(int i=0;i<sizeX;i++)
cin>>x[i]; }
42
1.13 Pointers Lecture Eight
C++’s data types are classified into three categories: simple, structured, and
pointers. here discusses the third data type called the pointer data type. We have
already seen how variables are seen as memory cells that can be accessed using their
identifiers. This way we did not have to care about the physical location of our data
within memory, we simply used its identifier whenever we wanted to refer to our
variable.
The memory of your computer can be imagined as a succession of memory
cells, each one of the minimal size that computers manage (one byte). These single-
byte memory cells are numbered in a consecutive way, so as, within any block of
memory, every cell has the same number as the previous one plus one. This way,
each cell can be easily located in the memory because it has a unique address and all
the memory cells follow a successive pattern.
As soon as we declare a variable, the amount of memory needed is assigned
for it at a specific location in memory (its memory address). We generally do not
actively decide the exact location of the variable that is a task automatically
performed by the operating system during runtime. However, in some cases, we may
be interested in knowing the address where our variable is being stored during
runtime. Pointer variable: A variable whose content is an address (that is, a memory
address).
dataType *identifier;
As an example, consider the following statements:
int *p;
char *ch;
In these statements, both p and ch are pointer variables. The content of p points to
a memory location of type int, and the content of ch points to a memory location of
type char. Usually, p is called a pointer variable of type int, and ch is called a pointer
variable of type char.
43
In C++, the ampersand, &, called the address of the operator, is a unary operator
that returns the address of its operand. For example, given the statements:
int x;
int *p;
the statement:
p = &x;
assigns the address of x to p. That is, x and the value of p refers to the same memory
location.
C++ also uses * as a unary operator. When used as a unary operator, *, commonly
referred to as the dereferencing operator or indirection operator, refers to the object
to which its operand (that is, the pointer) points. For example, given the statements:
int x = 25;
int *p;
p = &x; //store the address of x in p
the statement:
cout << *p << endl;
prints the value stored in the memory space pointed to by p, which is the value of
x.
Also, the statement:
*p = 55;
stores 55 in the memory location pointed to by p—that is, in x.
int *p;
int num;
In these statements, p is a pointer variable of type int, and num is a variable of type
int. Let us assume that memory location 1200 is allocated for p, and memory location
1800 is allocated for num.
44
Consider the following statements:
1. num = 78;
2. p = #
3. *p = 24;
45
//read from pointer
cout << " Enter the radius: ";
cin >> *radiusPtr;
cout << endl;
cout << "Radius = " << radius << ", area = " << PI * radius * radius << endl;
cout << "Radius = " << *radiusPtr << ", area = " << PI * (*radiusPtr) * (*radiusPtr)
<< endl
cout << " Address of radiusPtr: "<< &radiusPtr << endl;
cout << " Value stored in radiusPtr: "<< radiusPtr << endl;
cout << " Address of radius: "<< &radius << endl;
cout << " Value stored in radius: "<< radius << endl;
return 0;
}
#include <iostream>
using namespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;
int * pf, * ps;
return 0; }
47
Pointers and arrays
The concept of array is very much bound to the one of pointer. In fact, the identifier
of an array is equivalent to the address of its first element, as a pointer is equivalent
to the address of the first element that it points to, so in fact they are the same
concept. For example, supposing these two declarations:
p = numbers;
After that, p and numbers would be equivalent and would have the same properties.
The only difference is that we could change the value of pointer p by another one,
whereas numbers will always point to the first of the 20 elements of type int with
which it was defined. Therefore, unlike p, which is an ordinary pointer, numbers is
an array, and an array can be considered a constant pointer. Therefore, the following
allocation would not be valid:
numbers = p;
EX:
#include <iostream> p = numbers;
using namespace std; *(p+4) = 50;
int main () for (int n=0; n<5; n++)
{ cout << numbers[n] << ", ";
int numbers[5]; cout <<endl;
int * p; return 0;
p = numbers; }
*p = 10;
p++; *p = 20;
p = &numbers[2];
*p = 30;
p = numbers + 3;
*p = 40;
48
Pointer arithmetics
To conduct arithmetical operations on pointers is a little different than to conduct
them on regular integer data types. To begin with, only addition and subtraction
operations are allowed to be conducted with them, the others make no sense in the
world of pointers.
and that we know that they point to memory locations 1000, 2000 and 3000
respectively.So if we write:
mychar++;
myshort++;
mylong++;
49
1.14 Data structures Lecture Nine
We have already learned how groups of sequential data can be used in C++. But this
is somewhat restrictive, since in many occasions what we want to store are not mere
sequences of elements all of the same data type, but sets of different elements with
different data types.
Data structures
A data structure is a group of data elements grouped together under one name. These
data elements, known as members, can have different types and different lengths.
Data structures are declared in C++ using the following syntax:
struct structure_name
{
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
.
} object_names;
EX:
struct product { struct product {
int weight; int weight;
float price; float price;
} apple, banana, melon; };
product apple;
product banana, melon;
It is important to clearly differentiate between what is the structure type name, and
what is an object (variable) that has this structure type. We can instantiate many
objects (i.e. variables, like apple, banana and melon) from a single structure type
(product).
50
EX: C++ Program to assign data to members of a structure variable and display
it.
#include <iostream>
using namespace std;
struct Person
{
string name;
int age;
float salary;
};
int main()
{
Person p1;
return 0;
}
#include <iostream>
using namespace std;
const int ARRAY_SIZE = 5;
struct listType
{
int listElem[ARRAY_SIZE]; //array containing the list
int listLength; //length of the list
};
int main()
{
listType intList;
intList.listLength = 0;
intList.listElem[0] = 12;
52
intList.listLength++;
intList.listElem[1] = 37;
intList.listLength++;
for (int i=0;i<=5;i++)
cin>>intList.listElem[i];
for (int i=0;i<=5;i++)
cout<<"\nintList.listElem["<<i<<"]= "<<intList.listElem[i] ;
}
struct nameType
{
string first;
string middle;
string last;
};
struct addressType
{
string city;
string state;
};
struct dateType
{
int month;
int day;
int year;
};
struct employeeType
{
nameType name;
string empID;
addressType address;
dateType hireDate;
dateType quitDate;
double salary;
};
void employ_print(employeeType em)
{
53
cout<<"\nthe employee name is: ";
cout<<em.name.first<<" "<<em.name.middle<<" "<<em.name.last;
cout<<"\nthe employee address: ";
cout<<em.address.city<<" "<<em.address.state;
cout<<"\nthe employee hireDate: ";
cout<<em.hireDate.month<<" "<<em.hireDate.day<<" "<<em.hireDate.year;
cout<<"\nthe employee quitDate: ";
cout<<em.quitDate.month<<" "<<em.quitDate.day<<" "<<em.quitDate.year;
cout<<"\nthe employee salary: ";
cout<<em.salary;
}
int main()
{
employeeType em1;
em1.name.first = "nada";
em1.name.middle = "ali";
em1.name.last="ziad";
cout<<"\nenter the address: ";
cin>>em1.address.city>>em1.address.state;
cout<<"\nenter the hireDate: ";
cin>>em1.hireDate.month>>em1.hireDate.day>>em1.hireDate.year;
cout<<"\nenter the quitDate: ";
cin>>em1.quitDate.month>>em1.quitDate.day>>em1.quitDate.year;
cout<<"\nenter the salary: ";
cin>>em1.salary;
employ_print(em1);}
54
Examples of constructs: Lecture Ten
EX: program to find the distance between Two Points while representing the
point as a struct.
#include <iostream> int main()
#include<cmath> { point p1,p2;
using namespace std; p1=point_read();
struct point p2=point_read();
{ float x; point_print(p1);
float y;}; point_print(p2);
void point_print(point po) { double dis;
cout<<"\npoint is: "; dis=sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2));
cout<<"("<<po.x<<","<<po.y<<")";} cout<<"the distance is: "<<dis<<endl; }
point point_read()
{ point po;
cout<<"\npoint is: ";
cout<<"enter x and y ";
cin>>po.x>>po.y;
cout<<endl;
return po; }
EX: program to find the smallest distance between two points among three
points while representing the point as a struct.
#include <iostream>
#include<cmath>
using namespace std;
struct point
{ float x;
float y;};
void point_print(point po) { cout<<"\npoint is: ";
cout<<"("<<po.x<<","<<po.y<<")";}
point point_read()
{ point po;
cout<<"\npoint is: ";
cout<<"enter x and y ";
55
cin>>po.x>>po.y;
cout<<endl;
return po; }
void poin_print(point po)
{ cout<<"\npoint is: ";
cout<<"("<<po.x<<","<<po.y<<")";}
double point_dis(point p1,point p2)
{ double d;
d=sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2));
return d; }
int main()
{ point p1,p2,p3;
p1=point_read();
p2=point_read();
p3=point_read();
point_print(p1);
point_print(p2);
point_print(p3);
if(point_dis(p1,p2)>=point_dis(p1,p3)&&point_dis(p1,p2)>=point_dis(p2,p3))
cout<<"the smallest distance is between p1 and p2 :"<<point_dis(p1,p2)<<endl;
else if(point_dis(p1,p3)>=point_dis(p1,p2)&&point_dis(p1,p3)>=point_dis(p2,p3))
cout<<"the smallest distance is between p1 and p3 :"<<point_dis(p1,p3)<<endl;
else
cout<<"the smallest distance is between p2 and p3 :"<<point_dis(p2,p3)<<endl;}
EX: program to illustrate the information of the graduated student, his grade
average to each year, and the acceptance year with the graduating year.
#include <iostream>
#include<string>
using namespace std;
struct student
{ string name;
int GPA [4];
int acc_y;
56
int gra_y;};
student student_read()
{ student st;
cout<<"enter the student name ";
cin>>st.name;
cout<<endl;
cout<<"first year grade average ";
cin>>st.GPA[0];
cout<<endl;
cout<<"second year grade average ";
cin>>st.GPA[1];
cout<<endl;
cout<<"third year grade average ";
cin>>st.GPA[2];
cout<<endl;
cout<<"fourth year grade average ";
cin>>st.GPA[3];
cout<<endl;
cout<<"the student accepted in ";
cin>>st.acc_y;
cout<<" the student graduated in ";
cin>>st.gra_y;
return st;
}
57
int ave(int ar[])
{
return(ar[0]*0.10+ar[1]*0.20+ar[2]*0.30+ar[3]*0.40);
}
void student_print(student st) {
cout<<"\nname of student is: "<<st.name<<endl;
cout<<"\nthe grade average for first year "<<st.GPA[0];
cout<<", for second year"<<st.GPA[1]<<", for third year"<<st.GPA[2];
cout<<", for fourth year"<<st.GPA[3]<<endl;
cout<<"accepted in "<<st.acc_y<<" and graduated in "<<st.gra_y<<endl;
cout<<"the student grade average is: "<<ave(st.GPA)<<endl;
}
int main()
{
student st1;
st1=student_read();
student_print(st1);
return 1;
58