UNIT 1
Basics of CPP
Difference between Cand C++
Structure of C++
Question 1
• You're at an amusement park, and the roller
coaster has a height requirement of 120cm.
Write a C++ program to check if a person
can ride.
• #include <iostream>
• using namespace std;
•
• int main() {
• int height;
• cout << "Enter your height in cm: ";
• cin >> height;
•
• if (height >= 120) {
• cout << "You can ride the roller coaster!" << endl;
• } else {
• cout << "Sorry, you cannot ride the roller coaster." << endl;
• }
•
• return 0;
• }
Data Types in C++
CONSTANTS
• Constants are identifiers whose value does not change. While variables
can change their value at any time, constants can never change their
value.
• Constants are used to define fixed values such as Pi or the charge on an
electron so that their value does not get changed in the program even by
mistake.
• A constant is an explicit data value specified by the programmer.
• The value of the constant is known to the compiler at the compile time.
Declaring Constants
• Rule 1 Constant names are usually written in capital letters to
visually distinguish them from other variable names which are
normally written in lower case characters.
• Rule 2 No blank spaces are permitted in between the # symbol
and define keyword.
• Rule 3 Blank space must be used between #define and
constant name and between constant name and constant value.
• Rule 4 #define is a preprocessor compiler directive and not a
statement. Therefore, it does not end with a semi-colon.
Cascading of Input or Output Operators
• << operator –It can use multiple times in the
same line.
• Its called Cascading
• Cout ,Cin can cascaded
• For example
• cout<<“\n Enter the Marks”;
• cin>> ComputerNetworks>>OODP;
Data Types in C++
Variables
A variable is the content of a memory location that stores a certain value. A variable is identified or denoted by a variable name. The
variable name is a sequence of one or more letters, digits or underscore, for example: character_
Rules for defining variable name:
A variable name can have one or more letters or digits or underscore for example character_.
White space, punctuation symbols or other characters are not permitted to denote variable name.
A variable name must begin with a letter.
Variable names cannot be keywords or any reserved words of the C++ programming language.
Data C++ is a case-sensitive language. Variable names written in capital letters differ from variable names with the same name but
written in small letters.
01 Local Variables 03 Instance variables
02 Static Variables 04 Final Variables
Variables
Instance variable:
LocalLocal
variable:
Variables These Instance Variables
Static Static Variables
variables: Constant Variables
These are the Constant is
are the variables Static variables are
variables which something that
which are declared also called as class
are declared in a class doesn't change. In C
within the method of a variables. These
but outside a method, language and C++
class. variables have only
constructor or any we use the keyword
one copy that is shared
block. const to make
Example: by all the different
Example: program elements
public class Car { objects in a class.
public class Car { constant.
public: Example:
private: String Example:
void display(int m) public class Car {
color; const int i = 10;
{ // Method public static int
// Created an instance void f(const int i)
int model=m; tyres;
variable color class Test
// Created a // Created a class
Car(String c) {
local variable model variable void init(){
{ const int i;
cout<<model; tyres=4;
color=c; };
} }}
}}
Print Number Entered by User
• #include <iostream>
• using namespace std;
• int main() {
• int number;
• cout << "Enter an integer: ";
• cin >> number;
• cout << "You entered " << number;
• return 0;
• }
Find Size of a Variable
• #include <iostream>
• using namespace std;
• int main()
• {
• cout << "Size of char: " << sizeof(char) << " byte" << endl;
• cout << "Size of int: " << sizeof(int) << " bytes" << endl;
• cout << "Size of float: " << sizeof(float) << " bytes" << endl;
• cout << "Size of double: " << sizeof(double) << " bytes" << endl;
• return 0;
• }
Swap Numbers (Using Temporary Variable)
• #include <iostream>
• using namespace std;
• int main()
• {
• int a = 5, b = 10, temp;
• cout << "Before swapping." << endl;
• cout << "a = " << a << ", b = " << b << endl;
• temp = a;
• a = b;
• b = temp;
• cout << "\nAfter swapping." << endl;
• cout << "a = " << a << ", b = " << b << endl;
• return 0;
• }
Swap Numbers Without Using Temporary Variables
• #include <iostream>
• using namespace std;
• int main()
• {
•
• int a = 5, b = 10;
• cout << "Before swapping." << endl;
• cout << "a = " << a << ", b = " << b << endl;
• a = a + b;
• b = a - b;
• a = a - b;
• cout << "\nAfter swapping." << endl;
• cout << "a = " << a << ", b = " << b << endl;
• return 0;
• }
Check Whether
Number is Even or Odd
using if else
• #include <iostream>
• using namespace std;
• int main() {
• int n;
• cout << "Enter an integer: ";
• cin >> n;
• if ( n % 2 == 0)
• cout << n << " is even.";
• else
• cout << n << " is odd.";
• return 0;
• }
Sum of Natural Numbers using loop
• #include <iostream>
• using namespace std;
• int main() {
• int n, sum = 0;
• cout << "Enter a positive integer: ";
• cin >> n;
• for (int i = 1; i <= n; ++i) {
• sum += i;
• }
• cout << "Sum = " << sum;
• return 0;
• }
Formatted Input and Output Operations
Formatted I/O
I/O class
Manipulat
function and
ors
flages
Formatting Output Using Manipulators
• C++ has a header file iomanip.h that
contains certain manipulators to format the
output
• #include <iostream> // Including the input-output stream header file
• #include <iomanip> // Including the header file for formatted I/O
• using namespace std; // Using the standard namespace
• int main() // Start of the main function
• {
• cout << "\n\n Formatting the output :\n"; // Outputting a message to indicate formatted output
• cout << "----------------------------\n"; // Outputting a separator line
• double pi = 3.14159265; // Initializing a double variable 'pi' with the value of pi
• cout << fixed << setprecision(4); // Setting the output format to fixed with 4 decimal places
• cout <<" The value of pi : " << pi << endl; // Displaying 'pi' with 4 decimal places
• cout << " The value of pi 4 decimal place of total width 8 : |" << setw(8) << pi << "|" << endl; // Displaying 'pi' with 4 decimal places and a width of 8
• cout << " The value of pi 4 decimal place of total width 10 : |" << setw(10) << pi << "|"<< endl; // Displaying 'pi' with 4 decimal places and a width of 10
• cout << setfill('-'); // Setting the fill character to '-'
• cout << " The value of pi 4 decimal place of total width 8 : |" << setw(8) << pi << "|" << endl; // Displaying 'pi' with 4 decimal places and a width of 8,
filled with '-'
• cout << " The value of pi 4 decimal place of total width 10 : |" << setw(10) << pi << "|"<< endl; // Displaying 'pi' with 4 decimal places and a width of 10,
filled with '-'
• cout << scientific; // Setting the output format to scientific notation
• cout <<" The value of pi in scientific format is : " << pi << endl; // Displaying 'pi' in scientific notation
• bool done = false; // Initializing a boolean variable 'done' with the value false
• cout <<" Status in number : " << done << endl; // Displaying the boolean variable 'done' as a number (0 for false, 1 for true)
• cout << boolalpha; // Setting the output format to display true or false as words
• cout <<" Status in alphabet : " << done << endl; // Displaying the boolean variable 'done' as true or false
• cout << endl; // Outputting a blank line for better readability
• return 0; // Returning 0 to indicate successful program execution
• } // End of the main function
Conditional Statements
(Decision Making):
•if statement: Executes a block of code only if a specified condition evaluates to true.
if (condition) { // code to
execute if condition is true }
if (condition1) { // code
if (condition) { // code to if condition1 is true } else if
execute if condition is true } else (condition2) { // code if
{ // code to execute if condition2 is true } else {
condition is false } // code if no conditions are
true }
• switch (expression)
• { case value1:
• // code for value1
• break;
• case value2:
• // code for value2
• break; default: // code if no
match }
Looping Statements
(Iteration):
•for loop: Executes a block of code a specific number of times, typically when the number of iterations
is known beforehand.
for (initialization; condition;
update) { // code to execute in
each iteration }
• while
do { // code to
(condition execute } while
){ // (condition);
code to
execute
}
C++ Arrays
Arrays
Used to store a collection of elements (variables)
type array-name[size];
Meaning:
This declares a variable called <array-name> which contains <size>
elements of type <type>
The elements of an array can be accessed as: array-name[0],…array-
name[size-1]
Example:
int a[100]; //a is a list of 100 integers, a[0], a[1], …a[99]
double b[50];
char c[10];
Memory representation
Array example
//Read 100 numbers from the user
#include <iostream.h>
void main() {
int i, a[100], n;
i=0; n=100;
while (i<n) {
cout << “Input element “ << i << “: ”;
cin >> a[i];
i = i+1;
}
//do somehing with it ..
}
Example
Two dimensional array
Example
• Scenario questions
• Splitting the Bill: Calculate the amount each person owes
to split a dinner bill equally, given the total bill amount
and the number of people.
• Monthly Loan Payment for a New Laptop: Calculate the
monthly loan payment using the formula M = (P × (1 +
r)) / N, where M is the monthly payment, P is the total loan
amount, r is the monthly interest rate, and N is the number
of months.
• Painting a Room: Calculate the number of paint cans
needed to paint four walls of a room, given the room's
dimensions and the paint coverage per can.
Problems
Write a C++ program to read a sequence of (non-negative) integers from the user
ending with a negative integer and write out
• the average of the numbers
• the smallest number
• the largest number
• the range of the numbers (largest - smallest)
• Example:
– The user enters: 3, 1, 55, 89, 23, 45, -1
– Your program should compute the average of {3, 1, 55, 89, 23, 45} etc
Pointers
• Pointer is variable in C++
• It holds the address of another variable
• Syntax data_type *pointer_variable;
• Example int *p,sum;
Assignment
• To assign the address of variable to pointer-ampersand symbol (&)
• p=∑
• integer type pointer can hold the address of another int variable
• P=∑//assign address of another variable
• cout<<∑ //to print the address of variable
• cout<<p;//print the value of variable
How to use it
• Example of pointer
#include<iostream.h>
using namespace std;
int main()
{ int *p,sum=10; Output:
p=∑ Address of sum : 0X77712
cout<<“Address of sum:”<<&sum<<endl;Address of sum: 0x77712
cout<<“Address of sum:”<<p<<endl; Address of p: 0x77717
Value of sum: 10
cou<<“Address of p:”<<&p<<endl;
cout<<“Value of sum”<<*p;
}
Pointers and Arrays
• assigning the address of array to pointer don’t use ampersand sign(&)
#include <iostream>
using namespace std; OUTPUT:
int main(){ 0
//Pointer declaration 1
int *p; 2
//Array declaration 3
int arr[]={1, 2, 3, 4, 5, 6}; 4
//Assignment 5
p = arr; 6
for(int i=0; i<6;i++){
cout<<*p<<endl;
//++ moves the pointer to next int position
p++;
}
return 0;
This Pointers
• this pointer hold the adderss of current object
• int num;
• This->num=num;
Function using pointers
void swap(int *a,int *b)
{
#include<iostream> int c;
using namespace std;
void swap(int *a ,int *b );
c=*a;
//Call By Reference *a=*b;
int main() *b=c;
{ }
int p,q;
cout<<"\nEnter Two Number You Want To Swap \n";
cin>>p>>q;
Output:
swap(&p,&q); Enter Two Number You Want to
cout<<"\nAfter Swapping Numbers Are Given below\n\n"; Swap
cout<<p<<" "<<q<<" \n"; 10 20
return 0; After Swapping Numbers Are
}
Given below
20 10
Type conversion and type
casting
• Type conversion or typecasting of variables refers to
changing a variable of one data type into another. While type
conversion is done implicitly, casting has to be done
explicitly by the programmer.
Type Casting
• Type casting an arithmetic expression tells the compiler to represent the value
of the expression in a certain format.
• It is done when the value of a higher data type has to be converted into the
value of a lower data type.
• However, this cast is under the programmer’s control and not under the
compiler’s control. The general syntax for type casting is
destination_variable_name=destination_data_ty--pe(source_variable_name);
float sal=10000.00;
int income;
Income=int(sal);
Class and objects
Class:
•Class is a user defined data type,
•It holds its own data members and member functions,
•It can be accessed and used by creating instance of that class.
•The variables inside class definition are called as data members and
the functions are called member functions
Class:
•Class is a user defined data type,
•It holds its own data members and member functions,
•It can be accessed and used by creating instance of that class.
•The variables inside class definition are called as data members and
the functions are called member functions
Define a Class Type
Syntax: Example:
Name of
the class class Rectangle
keyw class Class_name {
ord { private:
permission_label:
int width;
member;
int length;
Body permission_label:
member; public:
... void set(int w, int l);
}; int area();
};
76
Object creation
Example for objects
- Data members Can be of any type, built-in or
user-defined.
This may be,
• non-static data member
Each class object has its own copy
• static data member
Acts as a global variable
84
• Static data member is declared using the static keyword.
• There is only one copy of the static data member in the class. All the
objects share the static data member.
• The static data member is always initialized to zero when the first class
object is created.
Syntax:
static data_type datamember_name;
Here
static is the keyword.
data_type – int , float etc…
datamember_name – user defined
85
Static Data Member
Rectangle r1;
class Rectangle
Rectangle r2;
{ Rectangle r3;
private:
int width;
int length; count
static int count;
r1 r2
public: width width
void set(int w, int l); length length
int area(); width
} r3 length
- Data members Can be of any type, built-in or
user-defined.
This may be,
• non-static data member
Each class object has its own copy
• static data member
Acts as a global variable
87
• Static data member is declared using the static keyword.
• There is only one copy of the static data member in the class. All the
objects share the static data member.
• The static data member is always initialized to zero when the first class
object is created.
Syntax:
static data_type datamember_name;
Here
static is the keyword.
data_type – int , float etc…
datamember_name – user defined
88
Static Data Member
Rectangle r1;
class Rectangle
Rectangle r2;
{ Rectangle r3;
private:
int width;
int length; count
static int count;
r1 r2
public: width width
void set(int w, int l); length length
int area(); width
} r3 length
#include
Example program for static
<iostream>
using namespace
std;
void Test(){
static int x = 1;
x = ++x;
int y = 1;
y = ++y;
cout<<"x =
"<<x<<"n";
cout<<"y =
"<<y<<"n";
}
int main()
{
Test();
Test();
return 0;
}
Static Member Functions in C++
• Properties of static member functions:
• A static function can only access other
static variables or functions present in the
same class
• Static member functions are called using
the class name.
Syntax- class_name::function_name( )
#
Example for static member
include <iostream> Int main()
{
using namespace std; Example example1, example2;
class Example{
example1.set_n();
static int Number;
example2.set_n();
int n;
public: example1.show_n();
example2.show_n();
void set_n(){
Example::show_Number();
n = ++Number;
} return 0;
}
void show_n(){
cout<<"value of n = "<<n<<endl;
}
static void show_Number(){
cout<<"value of Number = "<<Number<<endl;
}
};
int Example:: Number;
Inline Function
C++ provides an inline functions to reduce the function call
overhead.
• Inline function is a function that is expanded in line when it is
called.
• When the inline function is called whole code of the inline
function gets inserted orsubstituted at the point of inline function
call. This substitution is performed by theC++ compiler at compile
time.
• Inline function may increase efficiency if it is small.
Friend function
• A friend function of a class is defined outside that
class' scope but it has the right toaccess all private
and protected members of the class
. • Even though the prototypes for friend functions
appear in the class definition,friends are not
member functions.
• A friend can be a function, function template, or
member function, or a class or classtemplate, in
which case the entire class and all of its members
are friends.
UML Diagrams - Introduction
• UML stands for Unified Modeling Language
•It is a modern approach to modeling and documenting
software
•It is one of the most popular business process modeling
techniques
•It is based on diagrammatic representations of software
components
• An old proverb says, “A picture is worth a thousand
words”
• By using visual representations, we are able to better
understand possible flaws or errors in software or business
processes
UML Diagrams - Introduction BLUEPRINT
•In this case, the UML diagram serves as a complete design that
requires the actual implementation of the system or software
. • Often, this is done by using CASE tools (Computer Aided
Software Engineering Tools)
•It needs more expertise and user training
Use case diagram
Definition:
• A diagram that shows a set of use cases and
actors and their relationships. Use cases
represent system functionality, the
requirements of the system from the user’s
perspective.
Notations
• use case
• A description of a set of sequences of
actions, including variants, that system
performs that yields an observable value to
an actor.
Notations
• actor
• The people or systems that provide or
receive information from the system; they
are among the stakeholders of a system.
Notations
• include
• Specifies that the source use case explicitly
incorporates the behaviour of another use
case at a location specified by the source
Notations
• extend Specifies that the target use case
extends the behaviour of the source.
Actors
Actors
Use Case Diagram – Guidelines
& Caution
• 1.Use cases should ideally begin with a verb – i.e generate report. Use
cases should NOT be open ended – i.e Register (instead should be
named as Register New User)
• 2. Avoid showing communication between actors.
• 3. Actors should be named as singular. i.e student and NOT students.
NO names should be used – i.e John, Sam, etc.
• 4. Do NOT show behaviour in a use case diagram; instead only depict
only system functionality.
• 5. Use case diagram does not show sequence – unlike DFDs
Example – Include and Extend
Exercise - Solution
Use case diagram
Draw a use case diagram for the
scenario below:
• Inventory System
• In order to generate an invoice a clerk must log in.
If a clerk is a first time user, one must have
themselves registered. There should be an option
for a user to register oneself within the login page.
Any user can use the system to view products
online. The option of login is also provided when
a user views products online.
Constructors
• Constructors are special class functions
which performs initialization of every
object.
• The Compiler calls the Constructor
whenever an object is created.
• Constructors initialize values to object
members after storage is allocated to the
object.
Rules of defining a constructor
Example for constructor
Destructors in C++
• Destructor is a special class function which
destroys the object as soon as the scope of
object ends.
• The destructor is called automatically by
the compiler when the object goes out of
scope.
Example for destructor
Class Diagram
UML Representation of Class
Relationships among Classes
• Represents a connection between
multiple classes or a class and itself
• 3 basic categories:
– association relationships
– generalization relationships
– aggregation relationships
Association Relationship
• A bidirectional semantic connection between classes
• Name of relationship type shown by:
– drawing line between classes
– labeling with the name of the relationship
– indicating with a small solid triangle beside the name of the relationship
the direction of the association
Generalization Relationship
• Enables the analyst to create classes that
inherit attributes and operations of other
classes
• Represented by a-kind-of relationship
Generalization Relationship
Generalization Relationship
Aggregation Relationship
• Specialized form of association in which a
whole is related to its part(s)
• Represented by a-part-of relationship
• Denoted by placing a diamond nearest the
class representing the aggregation
Multiplicity
• Documents how many instances of a class
can be associated with one instance of
another class
Multiplicity
• Denotes the minimum number..
maximum number of instances
Exactly one 1
Zero or more 0..* or 0..m
One or more 1..* or 1..m
Zero or one 0..1
Specified range 2..4
Multiple, disjoint ranges 1..3, 5
Guidelines
for Analyzing class diagram
• An adjective implies an attribute of an
object
• A doing verb implies an operation
• A being verb implies a relationship
between an object and its class
• A having verb implies an aggregation or
association relationship
Guidelines
for Analyzing Use Cases (3)
• An adverb implies an attribute of a
relationship or an operation
Class Diagram
• Ensure that the classes are both necessary
and sufficient to solve the underlying
problem
– no missing attributes or methods in each
class
– no extra or unused attributes or methods in
each class
– no missing or extra classes
Draw use case/Class Diagram
• Consider the university admission processing
system which covers application checking and
validation per university-wide and department-
wide requirements, finance requirements,
additional information inquiry, decision
notification, and other admission processing
•