EContent 11 2025 02 05 22 06 30 Unit2 ProgrammingBasicspdf 2025 02 03 12 15 51
EContent 11 2025 02 05 22 06 30 Unit2 ProgrammingBasicspdf 2025 02 03 12 15 51
Unit-2
Object Oriented Design and Programming/01AI0403
• It will print variable1's value and print a new line. Finally, it prints
the variable2's value on a new line.
Standard Output Stream -- cout
#include<iostream>
using namespace std;
int main()
{
cout<<"Welcome to MU\n";
cout<<"Welcome to\nMU";
cout<<"\nWelcome to"<<endl<<"MU";
return 0;
}
Standard Input Stream -- cin
• Comments are used to provide the description about the Logic written in
program. Comments are not display on output screen.
• When we are used the comments, then that specific part will be ignored by
compiler.
• In 'C++' language two types of comments are possible
Single line comments
Multiple line comments
How to Write Comments in C++?
#include<iostream.h>
using namespace std;
int a; // global variable
int main()
{ Output
cout<<"Value of a: "<<a;
cout<<"Value of b: "<<b;
}
Data types in C++
Floating Point
Data types in C++
2) Derived Data Types
• These data type are derived from primitive or built-in data types. Variables of
derived data type allow us to store multiple values of same type in one variable but
never allows to store multiple values of different types.
• These are the data type whose variable can hold more than one value of similar
type.
• These can be of four types namely,
Function
Array
Pointer
Reference
Data types in C++
3) User defined(Abstract) data types
• User defined data types related variables allows us to store multiple values either
of same type or different type or both.
• This is a data type whose variable can hold more than one value of dissimilar type,
in C++ language.
• These data types are defined by user itself. C++ provides the following user-
defined datatypes
Class
Structure
Union
Enumeration
Data types in C++
Data types in C++
Enumerated Data type in C++
• An enumeration is a user-defined data type that consists of integral
constants.
• Enumerator types of values are also known as enumerators. It is also
assigned by zero the same as the array. It can also be used with switch
statements.
• The enum keyword is used to declare enumerated types.
Example:
enum season { spring, summer, autumn, winter };
int main()
{
week today;
today = Wednesday;
cout << "Day " << today+1;
return 0;
} Output:
Day 4
Enumerated Data type in C++
#include <iostream>
using namespace std;
int main()
{
enum Gender { Male, Female }; // Defining enum Gender
Gender gender = Male; // Creating Gender type variable
switch (gender)
{
case Male:
cout << "Gender is Male";
break;
case Female:
cout << "Gender is Female";
break;
default:
Output:
cout << "Value can be Male or Female";
}
return 0; Gender is Male
}
Tokens
• Identifiers in C++ are short and informative names uniquely identifying C++
variables or function names.
• They are user-defined words.
• We can't use keywords as identifiers because keywords are pre-defined
reserved words.
Tokens
Rules for Identifiers
• Any value declared as const can not be modified by the program in any way.
• It is starting with a const keyword followed by a datatype, an identifier, an
assignment operator, and the value.
• Constants can be defined locally or globally through this method.
Syntax:
const datatype constantName = value;
Example:
Tokens - Constants
Literals
• The value stored in a constant variable is known as a literal. However,
constants and literals are often considered synonyms.
• Literals can be classified on the basis of datatypes.
Types of literals:
Integer literals
Floating-point literals
Characters literals
Strings literals
Boolean literals
User-defined literals
Tokens - Constants
Integer Literals
When integer values are stored and represented as literal, then such literals
are known as integer literals.
Examples:
//defining decimal-literal //defining hex-literal
const int DECIMAL = 128; const int HEX = 0x80;
//defining octal-literal //defining binary-literal
const int OCTAL = 0200; const int BINARY = 0b10000000;
Tokens - Constants
Floating-Point Literals
• The floating-point literals contain the real numbers.
• The real numbers hold an integer part, a real part and a fractional part
and an exponential part in it.
• A floating-point literal can be stored or represented in two forms: decimal
or exponential form.
• Example:
const float P= 128.88;
Tokens - Constants
Character Literals
• When a single character enclosed by a single quote is stored and
represented as a literal, then the literal is known as a character
literal.
• More than one character should not be stored as a character
literal otherwise, it will show a warning along with only the last
character of the literal will be displayed.
Example:
const char VARA = 'A'
Tokens - Constants
String Literals
• When more than one character is stored in double-quotes and represented
as literals. Such a literal is known as a string literal.
• It can store all the special as well as escape sequence characters.
Example:
const string A = "this a\ngood\tlearning platform";
Tokens - Constants
Boolean Literals
• This literal stores boolean values i.e. True and false.
• True is used to represent success while false represents failure.
• True is the same as int 1 while false is similar to int 0.
Example:
const bool VAR1 = true;
const bool VAR2 = false;
Tokens – Strings
&& AND Called Logical AND operator. If both the (A && B) is false.
operands are non-zero, then condition
becomes true.
1 sizeof sizeof operator returns the size of a variable. sizeof(a), where ‘a’ is integer, and will
return 4.
2 ?: Exp1 ? Exp2 : Exp3;
If Condition is true then it returns value of X otherwise var = (y < 10) ? 30 : 40;
returns value of Y.
3 , Comma operator causes a sequence of operations to bevar = (count = 19, incr = 10,
performed. The value of the entire comma expression iscount+1);
the value of the last expression of the comma-separated
list.
4 . (dot) and -> (arrow) Member operators are used to reference individual
members of classes, structures, and unions.
5 Cast Casting operators convert one data type to another. Forint(2.2000) would return 2.
example,
6 & Pointer operator & returns the address of a variable. For example &a; will give actual
address of the variable.
7 * Pointer operator * is pointer to a variable. For example *var; will pointer to a
variable var.
Some C++ Operators
New operators (All C operators are valid in C++)
<< Insertion Operator
>> Extraction Operator
:: Scope Resolution Operator
::* Pointer-to-member declaration
->* Pointer-to-member Operator
.* Pointer-to-member Operator
delete Memory Release Operator
endl Line Feed Operator
new Memory Allocation Operator
setw Field Width Operator
Memory management operators (new(), delete())
int* pointVar;
*pointVar = 10;
new() operator example
#include <iostream>
using namespace std;
int main()
{
// pointer to store the address returned by the new
int* ptr;
// allocating memory for integer
ptr = new int;
• Here, we have dynamically allocated memory for an int variable using the
new operator.
• Notice that we have used the pointer pointVar to allocate the memory
dynamically.
• This is because the new operator returns the address of the memory location.
• In the case of an array, the new operator returns the address of the first
element of the array.
• From the example above, we can see that the syntax for using the new
operator is
pointerVariable = new dataType;
Memory management operators (new(), delete())
• For this, the delete operator is used. It returns the memory to the operating
system. This is known as memory deallocation.
delete pointerVariable;
Memory management operators (new(), delete())
// declare an int pointer
int* pointVar;
// dynamically allocate memory
• Here, we have dynamically allocated
// for an int variable
pointVar = new int; memory for an int variable using the
int main()
{
// pointer to store the address returned by the new
int* ptr;
// allocating memory for integer
ptr = new int;
Syntax
if(condition)
{
..........
..........
}
if Statement - Example
#include<iostream>
using namespace std;
int main()
{
int time;
cout<<“Enter time:”;
cin>>time;
if(time<12)
{
cout<<"Good morning";
}
return 0;
}
if-else statement
• It can be used to execute one block of statement among two blocks.
• If the condition is “true”, first block of statements to be executed. Otherwise
else block of statements has been executed.
• Syntax:
if(condition)
{
........
........
}
else
{
........
........
}
if-else statement – Example
#include<iostream>
using namespace std;
int main()
{
int time;
cout<<"Enter time:";
cin>>time;
if(time<12)
{
cout<<"Good morning";
}
else
{
cout<<"Good afternoon";
}
return 0;
}
if...else...else if statement
• The if...else statement is used to execute a block of code among two alternatives.
• We need to make a choice between more than two alternatives, we use the if...else
if...else statement.
Syntax
if (condition1)
{
// code block 1
}
else if (condition2)
{
// code block 2
}
Else
{
// code block 3
}
if...else...else if statement
#include <iostream> else
using namespace std; {
int main() cout << "You entered 0." << endl;
{ }
int n; return 0;
cout << "Enter an integer: "; }
cin >> n;
if (n > 0)
{
cout << "You entered a positive integer: " << n;
} Output:
else if (n < 0) Enter an integer: 12
{
cout << "You entered a negative integer: " <<n; You entered a positive integer: 12
}
Nested ifelse
• We need to use an if statement inside another if statement. This is known as
nested if statement.
Syntax:
if (condition1) // outer if statement
{
// statements
if (condition2) // inner if statement
{
// statements
}
}
Nested ifelse
#include <iostream> else // outer else condition
using namespace std; {
int main() cout << "The number is 0 and it is neither
{ positive nor negative";
int n; }
cout << "Enter an integer: ";
cin >> n; return 0;
if (n!= 0) // outer if condition }
{
if (n > 0) // inner if condition
{
Output:
cout << "The number is positive";
}
Enter an integer: 0
else // inner else condition
The number is 0 and it is neither positive nor
{
negative.
cout << "The number is negative";
This line is always printed.
}
}
Switch Statement
• A switch statement work with short, char and int primitive data type, it also
works with enumerated types and string.
Rules for apply switch
With switch statement use only short, int, char data type.
You can use any number of case statements within a switch.
Value for a case must be same as the variable in switch .
Switch case variables can have only int and char data type.
Limitations of switch
• float data type is not allowed.
• Logical operators cannot be used with switch statement.
Switch Statement
Syntax
switch(ch)
{
case1:
//statement 1;
break;
case2:
statement 2;
break;
default:
//statement
}
Switch Statement - Example
#include<iostream.h>
case 4:
using namespace std;
cout<<"Today is Thursday";
int main()
break;
{
case 5:
int ch;
cout<<"Today is Friday"; Output
cout<<"Enter any number (1 to 7)";
break; Enter any number (1 to 7): 5
cin>>ch;
case 6: Today is Friday
switch(ch)
cout<<"Today is Saturday";
{
break;
case 1:
case 7:
cout<<"Today is Monday";
cout<<"Today is Sunday";
break;
break;
case 2:
default:
cout<<"Today is Tuesday";
cout<<"Only enter value 1 to 7";
break;
}
case 3:
return 0;
cout<<"Today is Wednesday";
}
break;
Control Flow / Looping statements
Loops
• Set of instructions given to the compiler to execute set of statements until
condition becomes false is called loops.
• The basic purpose of loop is code repetition that means same code repeated
again and again.
Why use Loop
• Where need repetition of same code a number of times at that place use Loop
in place of writing more than one statements.
• The way of the repetition will be forms a circle that's why repetition
statements are called loops.
Control Flow / Looping statements
• Advantage with looping statement
• In C++, while loop is used to iterate a part of the program several times.
• while loops are used in situations where we do not know the exact number of
iterations of the loop beforehand. The loop execution is terminated on the
basis of the test conditions.
Syntax:
initialization;
while (test_condition)
{
// statements
update_expression;
}
While loop – Example
#include <iostream>
using namespace std;
int main()
{
Output:
int i = 1; // initialization
while (i < 6) // test condition
Hello World
{
Hello World
cout << "Hello World\n";
Hello World
i++; // update expression
Hello World
}
Hello World
return 0;
}
Do - While loop
• In Do-while loops also the loop execution is terminated on the basis of test
conditions.
• The main difference between a do-while loop and the while loop is in the do-
while loop the condition is tested at the end of the loop body, i.e do-while
loop is exit controlled whereas the other two loops are entry-controlled
loops.
• In a do-while loop, the loop body will execute at least once irrespective of
the test condition.
Do - While loop
Syntax:
initialization condition;
do
{
// statements
update_expression;
} while (test_condition);
• Jump statements are used to manipulate the flow of the program if some
conditions are met.
• It is used to terminating or continues the loop inside a program or to stop
the execution of a function.
• In C++ there is four jump statements, They are
continue
break
return
goto
Jump statements in C++
Continue statement
• It is used to execute other parts of the loop while skipping some parts
declared inside the condition, rather than terminating the loop, it
continues to execute the next iteration of the same loop.
• It is used with a decision-making statement which must be present
inside the loop.
• This statement can be used inside for loop or while or do-while loop.
Syntax:
continue;
Jump statements in C++
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i < 10; i++)
{ Output:
if (i == 5)
continue; 12346789
cout << i << " ";
}
return 0;
}
Jump statements in C++
Break statement
• It is used to terminate the whole loop if the condition is met. Unlike the
continue statement after the condition is met, it breaks the loop and the
remaining part of the loop is not executed.
Goto Statement
• This statement is used to jump directly to that part of the program to
which it is being called.
• Every goto statement is associated with the label which takes them to
part of the program for which they are called.
• The label statements can be written anywhere in the program it is not
necessary to use before or after goto statement.
Jump statements in C++
Syntax:
goto label_name;
.
.
.
label_name:
Jump statements in C++
#include <iostream>
using namespace std;
int main()
{
int n = 4;
if (n % 2 == 0)
Output:
goto label1;
else Even
goto label2;
label1:
cout << "Even" << endl;
return 0;
label2:
cout << "Odd" << endl;
}
Type conversion
• When the expression has data of mixed data types at that time, type
conversion is necessary.
• The data type is promoted from lower to higher because converting
higher to lower involves loss of precision and value
• C++ allows us to convert data of one type to that of another. This is
known as type conversion.
• There are two types of type conversion in C++.
Implicit Conversion
Explicit Conversion (Type Casting)
Type conversion
1.int x = 20;
2.short int y = 5;
3.int z = x + y;
In the above example, there are two different data type variables, x, and y, where x is an int type, and
the y is of short int data type. And the resultant variable z is also an integer type that stores x and y
variables. But the C++ compiler automatically converts the lower rank data type (short int) value into
higher type (int) before resulting the sum of two numbers.
Type conversion
The following is the correct order of data types from lower rank to higher rank:
bool -> char -> short int -> int -> unsigned int -> long int -
> unsigned long int -> long long int -> float -> double -> long double
Type conversion
#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII value of 'a' is 97
x = x + y;
// x is implicitly converted to float Output:
float z = x + 1.0;
x = 107
cout << "x = " << x << endl
<< "y = " << y << endl y=a
<< "z = " << z << endl;
z = 108
return 0;
}
Type conversion
}
}
Manipulators in C++
Manipulator Meaning
endl - This manipulator has the same functionality as
‘\n’(newline character).
setw (int n) - To set field width to n
setprecision (int p) - The precision is fixed to p
setfill (Char f) - To set the character to be filled
Setbase(int b) - To set the base of the number to b
Manipulators in C++
• endl function is used to insert a new line character and flush the stream.
• Working of endl manipulator is similar to '\n' character in C++. It prints the
output of the following statement in the next line.
• Example:
#include<iostream>
using namespace std;
int main()
{
cout << "Hello" << endl << "World!";
}
Manipulators in C++
setw ()
The setw() function is an output manipulator that inserts whitespace between
two variables. You must enter an integer value equal to the needed space.
Syntax:
setw ( int n)
Example:
int a=15; int b=20;
cout << setw(10) << a << setw(10) << b << endl;
Output:
15 20
Manipulators in C++
setfill()
• It replaces setw(whitespaces )’s with a different character. It’s similar to setw() in
that it manipulates output, but the only parameter required is a single character.
Syntax:
setfill(char ch)
Example:
int a,b;
a=15; b=20;
cout<< setfill(‘*’) << endl;
Output:
cout << setw(10) << a << setw(10) << a << endl;
********15********20
Manipulators in C++
setprecision
• It is an output manipulator that controls the number of digits to display
after the decimal for a floating point integer.
Syntax:
setprecision (int p)
Example:
float A = 1.34255;
cout <<fixed<< setprecision(3) << A << endl;
Output:
1.343
Manipulators in C++
setbase()
• The setbase() manipulator is used to change the base of a number to a
different value.
• The following base values are supported by the C++ language.
hex (Hexadecimal = 16)
oct (Octal = 8)
dec (Decimal = 10)
Manipulators in C++
setbase() – Example Output
#include <iostream> Hex Value = 64
#include <iomanip> Octal Value= 144
using namespace std;
Setbase Value= 144
int main()
Setbase Value= 64
{
int number = 100;
cout << "Hex Value =" << " " << hex << number << endl;
cout << "Octal Value=" << " " << oct << number << endl;
cout << "Setbase Value=" << " " << setbase(8) << number << endl;
cout << "Setbase Value=" << " " << setbase(16) << number << endl;
return 0;
}
Thank you!!!