IT2_Sem-1_Lectures_APL (C++)_2023-2024
IT2_Sem-1_Lectures_APL (C++)_2023-2024
▪ C++ gives programmers a high level of control over system resources and
memory.
▪ The language was updated 3 major times in 2011, 2014, and 2017 to
C++11, C++14, and C++17.
10/5/2023 3
Purpose of Using C++ OR Why Use C++?
10/5/2023 4
Basic Program Structure of C++
Step 1: Write the source codes (.cpp) and header files (.h).
Step 3: Compile the pre-processed source codes into object codes (.obj, .o).
Step 4: Link the compiled object codes with other object codes and the library
object codes (.lib, .a) to produce the executable code (.exe).
Step 6: Run the executable code, with the input to produce the desired output.
10/5/2023 5
Figure: Compile and Run (Execute) Processes of a C++ Program
10/5/2023 6
To Understand C++ Syntax
To break up the following code to understand it better:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Line 1: #include <iostream> is a header file library that lets us work with input
and output objects, such as cout (used in line 5). Header files add functionality to
C++ programs.
Line 2: using namespace std means that the programmer can use names for
objects and variables from the standard library.
10/5/2023 7
Line 3: A blank line. C++ ignores white space.
Line 4: Another thing that always appear in a C++ program, is int main(). This is
called a function. Any code inside its curly brackets { } will be executed.
Line 5: cout (pronounced "see-out") is an object used together with the insertion
operator (<<) to output/print text. In our example it will output "Hello World".
Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }
Remember: The compiler ignores white spaces. However, multiple lines makes
the code more readable.
Line 7: Do not forget to add the closing curly bracket } to actually end the main
function.
10/5/2023 8
Omitting Namespace
Some of C++ programs that runs without the standard namespace library. The
using namespace std line can be omitted and replaced with the std keyword,
followed by the Scope Resolution Operator (::) operator for some objects:
#include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
}
10/5/2023 9
C++ Output (Print Text)
The cout object, together with the << Programmer can add as many cout
operator, is used to output values/print objects as per need.
text:
#include <iostream>
#include <iostream> using namespace std;
using namespace std;
int main() {
int main() { cout << "Hello World!";
cout << "Hello World!"; cout << "I am learning C++";
return 0; return 0;
} }
10/5/2023 10
Thanks
Any Question
?
Advance Programming Language (C++) | Department of IT | Stage-2 Sem-1 10/5/2023 11
Lebanese French University
Constants can be of any of the basic data types like char, int, float, double,
etc. The way each constant is represented depends upon its type.
In C++, programmer can create variables for which value cannot be modify
or change. For this, programmer use the const keyword.
Example:
const int LIGHT_SPEED = 299792458;
LIGHT_SPEED = 2500 // Error! LIGHT_SPEED is a constant.
Here, programmer have used the keyword const to declare a constant named
LIGHT_SPEED. If anyone try to change the value of LIGHT_SPEED, will
get an error.
10/5/2023 15
Preprocessor definitions (#define)
Another mechanism to name constant values is the use of preprocessor
definitions. They have the following form:
NOTE: The #define lines are preprocessor directives, and as such are single-
line instructions that -unlike C++ statements- do not require semicolons (;) at
the end; the directive extends automatically until the end of the line. If a
semicolon is included in the line, it is part of the replacement sequence and is
also included in all replaced occurrences.
10/5/2023 16
Programming Examples for
Constant (const) and Preprocessor definitions (#define)
circle = 2 * pi * r; circle = 2 * PI * r;
cout << circle; cout << circle;
cout << newline; cout << NEWLINE;
} }
10/5/2023 17
Variable
10/5/2023 18
The example of declaring variable is given below:
1.int x;
2.float y;
3.char z;
Here, x, y, z are variables and int, float, char are data types.
Programmer can also provide values while declaring the variables. This is known as definition of
variables, as given below:
1.int x=5, b=10; //declaring two (2) variables of integer type
2.float f=30.8;
3.char c='A';
NOTE: After assigning value to a variable and using a ‘const’ keyword, then the variable becomes
constant. 10/5/2023 19
Rules for defining variables
10/5/2023 20
Keywords
• A keyword is a reserved word. Keywords are predefined words.
• Keywords never use it as a variable name, constant name etc.
10/5/2023 21
asm else new this
auto enum operator throw
bool explicit private true
break export protected try
case extern public typedef
catch false register typeid
char float reinterpret_cast typename
class for return union
const friend short unsigned
const_cast goto signed using
continue if sizeof virtual
default inline static void
delete int static_cast volatile
do long struct wchar_t
double mutable switch while
dynamic_cast namespace template
10/5/2023 22
Statement
In the most general sense, a statement is a part of our program that can be
executed. That is, a statement specifies an action.
Statements are always end with a semicolon (;), and are executed in the
same order in which statements appear in a program.
2. The iteration statements are while, for, and do-while. These are also
commonly called loop statements.
4. The label statements include the case and default statements (discuss
along with the switch statement) and the label statement (discuss with
goto).
For example −
// This is a comment
/* C++ comments can also
* span multiple lines
*/ 10/5/2023 25
Thanks
Any Question
?
Advance Programming Language (C++) | Department of IT | Stage-2 Sem-1 10/5/2023 26
Lebanese French University
10/5/2023 30
Structure in C++
A structure is a user-defined datatype which is a collection of simple
variables. The variables in a structure can be of different types: Some can be int,
some can be float, and so on.
The data items in a structure are called the members of the structure.
The keyword struct introduces the structure definition.
Here it is:
struct part
{
int modelnumber;
int partnumber;
float cost;
};
int main( )
{ //can do comparisons
//define variables of type days_of_week if(day1 < day2)
days_of_week day1, day2; cout << “day1 comes before day2\n”;
day1 = Mon; //give values to return 0;
day2 = Thu; //variables }
OUTPUT
Days between = 3
10/5/2023 35
day1 comes before day2
Thanks
Any Question
?
Advance Programming Language (C++) | Department of IT | Stage-2 Sem-1 10/5/2023 36
Lebanese French University
Here n starts with a value of 0, and i with 100, the condition is n!=i (that
n is not equal to i). Because n is increased by one and i is decreased by
one, so that the loop's condition will become false after the 50th loop,
when both n and i will be equal to 50.
10/5/2023 39
The break Statement
Using break, programmer can leave a loop in between, even condition to its
end, is not fulfilled. It can be used to end an infinite loop, or to force it to
end, before its natural end.
//To stop the count down before its natural end, using break
#include <iostream>
using namespace std;
int main () { OUTPUT
int n;
for (n=10; n>0; n--) { 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
cout << n << ", ";
if (n= =3){
cout << "countdown aborted!";
break;
}
}
return 0;
} 10/5/2023 40
//Example: To demonstrate break statement using while loop.
#include <iostream>
using namespace std;
int main( ){
int num = 10;
while(num <= 200) {
cout<<"Value of num is: "<<num<<endl;
if (num = = 12) {
break;
}
num++;
}
cout<<"Hey, I'm out of the loop";
return 0;
}
10/5/2023 41
The continue Statement
The continue statement causes the program to skip the rest of the loop in the
current iteration, as if the end of the statement block has been reached,
causing it to jump to the start of the following iteration.
#include <iostream>
using namespace std;
int main(){
int j = 6;
while (j >= 0) {
if (j = = 4) {
j--;
continue;
}
cout<<"Value of j: "<<j<<endl;
j--;
}
return 0;
} 10/5/2023 43
//Example: To demonstrate continue statement using do-while loop.
#include <iostream>
using namespace std;
int main( ){
int j = 4;
do {
if (j = = 7) {
j++;
continue;
}
cout<<"j is: "<<j<<endl;
j++;
}while(j < 10);
return 0;
}
10/5/2023 44
The goto Statement
goto allows to make an absolute jump //Countdown loop using goto
to another point in the program. #include <iostream>
using namespace std;
Programmer should use this feature int main ()
with caution, since its execution causes {
an unconditional jump ignoring any int n=10;
type of nesting limitations. loop:
cout << n << ", ";
The destination point is identified by a n--;
label, which is then used as an if (n>0)
argument for the goto statement. goto loop;
cout << "FIRE!\n";
A label is made of a valid identifier return 0;
followed by a colon (:). }
OUTPUT
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
10/5/2023 45
/*Example: To demonstrate goto statement to check whether the input
number is even or odd.*/
#include <iostream>
using namespace std;
int main(){
int num;
cout<<"Enter a number: ";
cin>>num;
if (num % 2==0){
goto print;
}
else {
cout<<"Odd Number";
}
print:
cout<<"Even Number";
return 0;
} 10/5/2023 46
Library Function exit( )
exit is a function defined in the stdlib library. This function causes the
program to terminate, no matter where it is in the listing in the program. It
has no return value.
The purpose of exit is to terminate the current program with a specific exit
code. Its prototype is:
The exitcode identifier is used by some operating systems and may be used
by calling programs.
10/5/2023 47
//Example: To check Prime Number or not by demonstrating exit( ) function..
# include <iostream> OUTPUT
using namespace std;
Enter a number: 13
#include <stdlib.h> //for exit( ) It’s prime
int main( ) Enter a number: 22229
It’s prime
{
Enter a number: 22231
unsigned long n, j; It’s not prime; divisible by 11
cout << “Enter a number: “;
cin >> n; //get number to test
for(j=2; j <= n/2; j++) //divide by every integer from
if(n%j == 0) //2 on up; if remainder is 0,
{ //it’s divisible by j
cout << “It’s not prime; divisible by “ << j << endl;
exit(0); //exit from the program
}
cout << “It’s prime\n”;
return 0;
}
10/5/2023 48
The Selection Statement (switch)
The syntax of the switch statement is a bit peculiar. Its objective is to check several
possible constant values for an expression. It is a wonderful concept for Menu-driven
Programming approach.
It works in the following way: switch evaluates
switch (expression) expression and checks if it is equivalent to constant1,
{
if it is, it executes group of statements 1 until it finds
case constant1: the break statement.
group of statements 1;
break; When it finds this break statement, the program
jumps to the end of the switch selective structure.
case constant2:
group of statements 2;
If expression was not equal to constant1, it will be
break; checking against constant2. If it is equal to this, it
will execute group of statements 2 until a break
…………………………..
keyword is found, and then will jump to the end of the
…………………………..
switch selective structure.
default : Finally, if the value of expression did not match any
default group of statements
of the previously specified constants, the program will
}
execute the statements included after the default:
10/5/2023 49
label, if it exists (since it is optional).
10/5/2023 50
//Example: Simple Calculator using switch with break statement.
# include <iostream>
using namespace std;
int main()
{
char op;
float num1, num2;
cout << "Enter operator either + or - or * or / : ";
cin >> op;
cout << "Enter two operands: "; case '*':
cout << num1*num2;
cin >> num1 >> num2;
break;
switch(op)
{ case '/':
case '+': cout << num1/num2;
cout << num1+num2; break;
break; default:
case '-': cout << "Error! operator is not correct";
cout << num1-num2; break;
break; }
return 0;
} 10/5/2023 51
Both of the following source-code fragments have the same behavior:
if (x = = 1)
switch (x)
{
{
cout << "x is 1";
case 1:
}
cout << "x is 1";
break;
else if (x = = 2)
{
case 2:
cout << "x is 2";
cout << "x is 2";
}
break;
else
default:
{
cout << "value of x unknown";
cout << "value of x unknown";
}
}
10/5/2023 52
Thanks
Any Question
?
Advance Programming Language (C++) | Department of IT | Stage-2 Sem-1 10/5/2023 53
Lebanese French University
//Function Declaration
return_type function_name(parameter_list);
//Function Definition
return_type function_name(data_type parameter...)
{
//code to be executed
}
10/5/2023 57
//Simple example of C++ function
#include <iostream>
NOTE: The static variable is initialized
using namespace std;
only once and exists till the end of a
program. It retains its value between
// Function Definition
multiple functions call.
void func() {
static int i=0; //static variable
The static variable has the default value
int j=0; //local variable
Zero (0) which is provided by compiler.
i++;
j++;
cout<<"i=" << i<<" and j=" <<j<<endl;
10/5/2023 59
Call by value and Call by reference in C++
There are two ways to pass value or data to function in C++
language:
1. call by value
2. call by reference
Here, value being passed to the function is locally stored by the function
parameter in stack memory location. It will not change the value of
variable inside the caller method such as main().
S.
Call by value Call by reference
No.
10/5/2023 63
Thanks
Any Question
?
Advance Programming Language (C++) | Department of IT | Stage-2 Sem-1 10/5/2023 64
Lebanese French University
C++ inline function is powerful concept that is commonly used with classes.
All the member functions defined inside the class definition are by
default declared as Inline.
If a function is inline, the compiler places a copy of the code of that function
at each point, where the function is called at compile time.
To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function.
The compiler can ignore the inline qualifier in case defined function is more
than a line.
10/5/2023 67
Contd…
Any change to an inline function could require all clients of the function to
be recompiled because compiler would need to replace all the code once
again, otherwise it will continue with old functionality.
Inline functions are actual functions, which are copied everywhere during
compilation, so the overhead of function calling is reduced.
All the functions defined inside class definition are by default inline, but
programmer can also make any non-class function inline by using
keyword inline with them.
10/5/2023 68
The syntax for defining the function inline is:
A function that calls itself, and doesn't perform any task after function call,
is known as tail recursion.
Syntax of Recursion
Recursion_function( )
{
Recursion_function( ); //calling self function
}
10/5/2023 72
/*Example:
To print factorial number using recursion in C++ language*/
#include<iostream> int factorial(int n)
using namespace std; {
int main() if(n < 0)
{ return(-1); /*Wrong value*/
int factorial(int);
int fact, value;
if(n = = 0)
cin>>value; else
fact = factorial(value);
{
cout<<"Factorial of a number is: "<<fact;
return (n * factorial(n-1));
cout<<endl;
}
return 0;
}
} OUTPUT
Enter any number: 5
Factorial of a number is: 120 10/5/2023 73
10/5/2023 74
Difference Between Recursion and Iteration
Recursion and iteration both repeatedly executes the set of instructions.
10/5/2023 75
S.
Recursion Iteration
No.
int main( )
cout<<"Factorial for 5 is “<<fac;
{
cout<<"Factorial for 5 is “<<factorial(5);
return 0;
return 0;
}
}
10/5/2023 77
Thanks
Any Question
?
Advance Programming Language (C++) | Department of IT | Stage-2 Sem-1 10/5/2023 78
Lebanese French University
dataType arrayName[arraySize];
For example,
float mark[5];
▪ If the size of an array is n, to access the last element, (n-1) index is used.
In this example, mark[4] is the last element.
▪ Suppose the starting address of mark[0] is 2120d. Then, the next address,
mark[1], will be 2124d, address of mark[2] will be 2128d and so on. It's
because the size of float is 4 bytes. 10/5/2023 83
To initialize an array in C++ programming…..
For example,
Here,
int mark[5] = {19, 10, 8, 17, 9}; mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
Array index starts from 0 (Zero) to (n-1), for total number of elements n in
an array.
Array is used to store only fixed set of elements. 10/5/2023 84
To insert and print an array elements….
cin >> mark[2]; // take input from the user and insert in third element
cin >> mark[i]; // take input from the user and insert in (i+1)th element
10/5/2023 85
/* C++ program to store and calculate the sum of 5 numbers
entered by the user using arrays.*/
For example:
Int arr[2][2]; //declaration of 2D array
Int arr[3][3][3]; //declaration of 3D array
int A[3][4];
10/5/2023 88
For example:
int X[3][4];
Here, X is a two dimensional array. It can hold a maximum of 12 elements.
For example:
float x[2][4][3];
This array x can hold a maximum of 24 elements.
Better way to initialize this array with same array elements as above.
int test[2][3] = { {2, 4, 5}, {9, 0, 0}};
int main()
{
int test[2][3][2]; //This array can store upto 12 elements
cout << "Enter 12 values: \n";
for(int i = 0; i < 2; ++i) { // Inserting the values into the test array using 3 nested for loops.
for (int j = 0; j < 3; ++j) {
for(int k = 0; k < 2; ++k ) {
cin >> test[i][j][k];
}}}
C-strings
In C programming, the collection of characters is stored in the form of
arrays, this is also supported in C++ programming. Hence it's called C-
strings.
C-strings are arrays of type char terminated with null character, that is, \0.
(ASCII value of null character is 0) 10/5/2023 96
To initialize or define a C-string:
char str[] = "C++";
In the above code, str is a string and it holds 4 characters.
Although, "C++" has 3 character, the null character ‘\0’ is added to the end
of the string automatically.
For example:
char str[100] = "C++";
10/5/2023 97
Example: C++ String to read a word.
//C++ program to display a string entered by user.
#include <iostream> Output
using namespace std;
int main() Enter a string: C++
{ You entered: C++
char str[100];
Enter another string: Programming is fun.
cout << "Enter a string: "; You entered: Programming
cin >> str;
cout << "You entered: " << str << endl;
cout << "\nEnter another string: ";
cin >> str;
cout << "You entered: "<<str<<endl;
return 0;
}
NOTE: In this example, only "Programming" is displayed instead of "Programming
is fun". This is because the extraction operator >> considers a whitespace " " has a
terminating character.
10/5/2023 98
Example: C++ String to read a line of text
//C++ program to read and display an entire line entered by user.
#include <iostream>
using namespace std;
Output
int main()
{
Enter a string: Programming is fun.
char str[100];
You entered: Programming is fun.
cout << "Enter a string: ";
cin.get(str, 100);
cout << "You entered: " << str << endl;
return 0;
}
To read the text containing blank space, cin.get function can be used. This
function takes two arguments.
First argument is the name of the string (address of first element of string)
and second argument is the maximum size of the array.
In the above program, str is the name of the string and 100 is the maximum
size of the array. 10/5/2023 99
Strings that are objects of string class (string Object)
In C++, programmer can also create a string object for holding strings.
Unlike using char arrays, string objects has no fixed length, and can be
extended as per the requirement.
//Example: C++ string using string data type
#include <iostream>
using namespace std; Output
int main()
{ Enter a string: Programming is fun.
// Declaring a string object You entered: Programming is fun.
string str;
cout << "Enter a string: ";
getline(cin, str);
cout << "You entered: " << str << endl;
return 0;
}
In this program, a string str is declared. Then the string is asked from the user.
Instead of using cin>> or cin.get() function, programmer can get the entered line of
text using getline().
getline() function takes the input stream as the first parameter which is cin and str as
the location of the line to be stored. 10/5/2023 100
C++ supports a wide range of functions that manipulate
null-terminated strings.
S.
Function Purpose
No.
1 strcpy(s1, s2); Copies string s2 into string s1.
10/5/2023 101
Following example makes use of few of the system-defined functions. When
this code is compiled and executed, it produces result such as:
#include <iostream>
#include <cstring> // concatenates str1 and str2
using namespace std; strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;
int main ()
{ // total length of str1 after concatenation
char str1[10] = "Hello"; len = strlen(str1);
char str2[10] = "World"; cout << "strlen(str1) : " << len << endl;
char str3[10];
int len ; return 0;
}
// copy str1 into str3
strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;
Output
Using namespace, programmer can define the context in which names are
defined. In essence, a namespace defines a scope.
10/5/2023 107
For accessing the class of a namespace, programmer needs to use
namespace_name : : class_name
Programmer can use using keyword before class to declare a namespace, so
that programmer does not need to use complete name all the time.
In C++, global namespace is the root namespace. The global::std will
always refer to the namespace "std" of C++ Framework.
10/5/2023 108
To write a small C++ program
Output with cout
Output with
cout
10/5/2023 109
Input with cin
cin >> ftemp;
The statement causes the program to wait for the user to type in a number.
The resulting number is placed in the variable ftemp.
The identifier cin (pronounced “C-in”) is an object, predefined in C++ to
correspond to the standard input stream.
The >> is the 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.
Input with
cin
10/5/2023 110
//Basic Program to print Hello, LFU..!!!
OUTPUT
Hello, LFU..!!!
10/5/2023 111
Explanation about the various parts of the above program, such as:
• The C++ language defines several headers, which contain information
that is either necessary or useful to the program. For this program, the
header <iostream> is needed.
• The line using namespace std; tells the compiler to use the Standard
(std) namespace.
• The next line '// Program execution begins from main()' is a single-line
comment available in C++. Single-line comments begin with // and stop
at the end of the line.
• The line int main() is the main function where program execution
begins.
• The next line cout << "Hello, LFU..!!!"; causes the message "Hello,
LFU..!!!" to be displayed on the screen.
namespace First {
void sayHello() {
cout<<"Hello First Namespace"<<endl;
}
}
namespace Second {
void sayHello() {
cout<<"Hello Second Namespace"<<endl;
}
}
Output
int main()
Hello First Namespace
{
Hello Second Namespace
First :: sayHello();
Second :: sayHello();
return 0;
10/5/2023 113
}
//Namespace example: by using namespace keywords
#include <iostream>
using namespace std;
namespace First{
void sayHello(){
cout << "Hello First Namespace" << endl;
}
}
namespace Second{
void sayHello(){
cout << "Hello Second Namespace" << endl;
}
}