0% found this document useful (0 votes)
17 views112 pages

EContent 11 2025 02 05 22 06 30 Unit2 ProgrammingBasicspdf 2025 02 03 12 15 51

The document covers the basics of Object Oriented Design and Programming in C++, focusing on directives, input/output operations, variables, data types, and tokens. It explains preprocessor directives, the use of 'cout' and 'cin' for output and input, variable declaration, and the different types of data types including built-in, derived, and user-defined. Additionally, it discusses the importance of comments, scopes of variables, and various tokens such as keywords, identifiers, constants, and operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views112 pages

EContent 11 2025 02 05 22 06 30 Unit2 ProgrammingBasicspdf 2025 02 03 12 15 51

The document covers the basics of Object Oriented Design and Programming in C++, focusing on directives, input/output operations, variables, data types, and tokens. It explains preprocessor directives, the use of 'cout' and 'cin' for output and input, variable declaration, and the different types of data types including built-in, derived, and user-defined. Additionally, it discusses the importance of comments, scopes of variables, and various tokens such as keywords, identifiers, constants, and operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 112

Programming Basics

Unit-2
Object Oriented Design and Programming/01AI0403

Department of Computer Engineering


Prof. Shilpa Singhal
Content
 Directives
 Output using cout
 Input with cin
 Variables in C++
 Data Types in C++
 Tokens
 Decision Making Statements
 Looping Structure
 Type conversions
 Manipulator
Directives
• All the statements starting with the # (hash) symbol are known as preprocessor
directives in C++.
• To perform certain tasks, the directives instruct the preprocessor to perform

certain tasks to improve the program’s performance/capabilities.


• Every directive is a one-line long command which contains the following:
 All the preprocessor directives in C++ start with the # (hash) symbol).
 A pre-processor instruction after the # (hash) symbol
like #include, #define, #ifdef, #elif, #error, #pragma etc.
• Example:
#include<iostream>, #define PI 3.14, #ifdef PI etc.
Directives
Preprocessor Directives
• Preprocessor programs provide preprocessor directives that tell the
compiler to preprocess the source code before compiling.
• All of these preprocessor directives begin with a ‘#’ (hash) symbol.
• The ‘#’ symbol indicates that whatever statement starts with a ‘#’ will go
to the preprocessor program to get executed.
• Examples of some preprocessor directives are:
#include, #define, #ifndef etc.
Directives
• There are 2 Main Types of Preprocessor Directives:
1) Inclusion Directive
2) Macro Definition Directive
1) Inclusion Directive
 This type of preprocessor directive tells the compiler to include a file in the
source code program.
 There are two types of files that can be included by the user in the
program:
- Header files or Standard files
- User-defined files
Directives
Header files or Standard files
• These files contain definitions of pre-defined functions like printf(),
scanf(), etc. These files must be included to work with these
functions.
• Different functions are declared in different header files.
• Syntax:
#include< file_name >
• where file_name is the name of the file to be included. The ‘<‘ and ‘>’
brackets tell the compiler to look for the file in the standard directory.
Directives
User-defined files
• When a program becomes very large, it is a good practice to divide it into
smaller files and include them whenever needed. These types of files are
user-defined files.
• Syntax: #include "filename“
2) Macro Definition Directive
• Macros are pieces of code in a program that is given some name.
• Whenever this name is encountered by the compiler, the compiler replaces
the name with the actual piece of code. The ‘#define’ directive is used to
define a macro.
Directives
Macro Definition – Example
#include <iostream>
using namespace std;
#define LIMIT 5 // macro definition
int main()
{
for (int i = 0; i < LIMIT; i++)
{
cout << i << "\n";
}
return 0;
}
C++ iostream
• iostream stands for standard input-output stream. #include
iostream declares objects that control reading from and writing to the
standard streams.
• In other words, the iostream library is an object-oriented library that
provides input and output functionality using streams.
• A stream is a sequence of bytes. You must include iostream header file to
input and output from a C++ program.
i.e
• #include iostream provides the most used standard input and output
streams, cin and cout.
Standard Output Stream -- cout
• It is an instance of the ostream class. It produces output on the standard
output device, i.e., the display screen.
• We need to use the stream insertion operator << to insert data into the
standard output stream cout, which has to be displayed on the screen.
• Syntax:
cout << variable_name;
OR
cout << variable1 << variable2 << ... ;
(This way of using multiple stream insertion operators with a single cout is
called cascading. It helps print multiple variables adjacent to each other on
the same line.)
Standard Output Stream -- cout
How to Separate lines in Output?
• There are two ways – new line character and endl
Using \n, the new line character
Syntax:

cout << variable1 << '\n' << variable2;

• 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

Using endl, a manipulator


Syntax:
cout << variable1 << endl << variable2;

• A manipulator in C++ changes the behavior of an input or output stream.


• endl manipulator is a part of the std namespace and can also be used to
insert a new line.
Standard Output Stream -- cout
C++ Program using 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

• It is an instance of the istream class.


• It reads input from the standard input device, i.e., the keyboard.
• We need to use the stream extraction operator >> to extract data entered
using the keyboard.
Syntax:
cin >> variable_name;
OR
• Cascading can also be done with cin to extract multiple variables.
cin >> variable1 >> variable2 >> ... ;
How to Write Comments in C++?

• 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++?

Single line comments


Single line comments can be provided by using / /....................
Multiple line comments
Multiple line comments can be provided by using /*......................*/
Note: When we are working with the multiple line comments then nested
comments are not possible.
Variable in C++

• Variable is an identifier which holds data or another one variable is an


identifier whose value can be changed at the execution time of program.
• Variable is an identifier which can be used to identify input data in a
program.
Variable in C++
Variable declarations
• This is the process of allocating sufficient memory space for the data in term of
variable.
Syntax
datatype variable_name;
4 byte
Example
int a;
float b;
string name;
• If no input values are assigned by the user than system will gives a default value
called garbage value.
Variable in C++
Garbage value
• Garbage value can be any value given by system and that is no way related to
correct programs. It is a disadvantage and it can overcome using variable
initialization.
Variable initialization
• It is the process of allocating sufficient memory space with user defined values.
Syntax
datatype nariable_name=value;
Example
int b = 30;
Variable Declaration Rules in C++

• Every variable name should start with alphabets or underscore (_).


• No spaces are allowed in variable declaration.
• Except underscore (_) no special symbol are allowed in the middle of the
variable declaration.
• Every variable name always should exist in the left hand side of assignment
operator.
• No keyword should access variable name.
Scope of Variable in C++

In C++ language, a variable can be either of global or local scope.


Global variable
• Global variables are defined outside of all the functions, generally on top of
the program. The global variables will hold their value throughout the life-
time of your program.
Local variable
• A local variable is declared within the body of a function or a block. Local
variable only use within the function or block where it is declare.
Scope of Variable in C++
Example of Global and Local variable

#include<iostream.h>
using namespace std;
int a; // global variable
int main()
{ Output

int b; // local variable Value of a: 10

a=10, b=20; Value of b: 20

cout<<"Value of a: "<<a;
cout<<"Value of b: "<<b;
}
Data types in C++

• A data type is the type of data a variable can hold.


• For example, a Boolean variable can have boolean data, and an
integer variable can hold integer data.
Data types in C++

1) Built-In/Primitive Data Types


• These are the data types whose variable can hold maximum one value at a time,
in C++ language it can be achieve by int, float, double, char.
• These data types are built-in or predefined data types and can be used directly by
the user to declare variables. example: int, char , float, bool etc.
• Primitive data types available in C++ are:
 Integer  Double Floating Point

 Character  Valueless or Void

 Boolean  Wide Character

 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 };

By default, spring is 0, summer is 1 ….


Enumerated Data type in C++
#include <iostream>
using namespace std;

enum week { Sunday, Monday, Tuesday, Wednesday,


Thursday, Friday, Saturday };

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

The smallest individual units in a program are known as tokens.


• Keywords
• Identifiers
• Constants
• Strings
• Operators
Tokens - Keywords
• A reserved word is a word that cannot be used as an identifier, such as
the name of a variable, function, or label – it is "reserved from use".

auto bool break case catch char class

const continue double default delete else enum

explicit friend float for int long mutable

new operator private protected public register return

struct switch short sizeof static this typedef

throw true try union virtual void while


Tokens - Identifiers

• 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

• A valid identifier is a sequence of one or more letters, digits or underscore


characters (_).

• Neither spaces nor punctuation marks or symbols can be part of an


identifier.

• Only letters, digits and single underscore characters are valid.

• In addition, variable identifiers always have to begin with a letter.

• They can also begin with an underline character (_).


Tokens - Constants

• 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

• A string in C++ is a type of object representing a collection (or sequence)


of different characters.
• Strings in C++ are a part of the standard string class.
• The string class stores the characters of a string as a collection of bytes in
contiguous memory locations.
• Strings are most commonly used in the programs where we need to work
with texts.
• C++ supports both strings and character arrays.
Tokens – Strings
Example:
#include <iostream>
using namespace std;
int main()
{
char name[6] = {'h', 'e', 'l', 'l', 'o', '\0’}; // Using char datatype
char str[10]; // Using char datatype
string name1="HELLO"; // Using String datatype
cout<<name;
cout<<name1;
return 0;
}
Tokens – Operators

• An operator is a symbol that tells the compiler to perform specific


mathematical or logical manipulations.
• C++ is rich in built-in operators and provide the following types of operators.
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Special Operators
Tokens – Operators
Arithmetic Operators
Operator Name Description Example
+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x / x++

-- Decrement Decreases the value of a variable by 1 --x / x--


Tokens – Operators
Relational Operators
Operator Name Description Example
== Equal to Checks if the values of two operands are equal or not, if yes (A == B) is not true.
then condition becomes true.
!= Not equal to Checks if the values of two operands are equal or not, if (A != B) is true.
values are not equal then condition becomes true.
> Greater than Checks if the value of left operand is greater than the value (A > B) is not true.
of right operand, if yes then condition becomes true.
< Less than Checks if the value of left operand is less than the value of (A < B) is true.
right operand, if yes then condition becomes true.
>= Greater than Checks if the value of left operand is greater than or equal (A >= B) is not true.
equal to to the value of right operand, if yes then condition becomes
true.
<= Less than Checks if the value of left operand is less than or equal to (A <= B) is true.
equal to the value of right operand, if yes then condition becomes
true.
Tokens – Operators
Logical Operators

Operator Name Description Example

&& AND Called Logical AND operator. If both the (A && B) is false.
operands are non-zero, then condition
becomes true.

|| OR Called Logical OR Operator. If any of the (A || B) is true.


two operands is non-zero, then condition
becomes true.

! NOT Called Logical NOT Operator. Use to !(A && B) is true.


reverses the logical state of its operand. If
a condition is true, then Logical NOT
operator will make false.
Tokens – Operators
Bitwise Operators
Operator Description Example

& Binary AND Operator copies a bit to the result if it


(A & B) will give 12 which is 0000 1100
exists in both operands.
| Binary OR Operator copies a bit if it exists in either (A | B) will give 61 which is 0011 1101
operand.
^ Binary XOR Operator copies the bit if it is set in one
(A ^ B) will give 49 which is 0011 0001
operand but not both.
~ Binary Ones Complement Operator is unary and has (~A ) will give -61 which is 1100 0011 in 2's
the effect of 'flipping' bits. complement form due to a signed binary
number.
<< Binary Left Shift Operator. The left operands value
is moved left by the number of bits specified by the A << 2 will give 240 which is 1111 0000
right operand.
>> Binary Right Shift Operator. The left operands value
is moved right by the number of bits specified by A >> 2 will give 15 which is 0000 1111
the right operand.
Tokens – Operators
Assignment Operators
Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side C = A + B will assign value of A
operand. + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assign C += A is equivalent to C = C +
the result to left operand. A
-= Subtract AND assignment operator, It subtracts right operand from the left operand
C -= A is equivalent to C = C - A
and assign the result to left operand.
*= Multiply AND assignment operator, It multiplies right operand with the left operand C *= A is equivalent to C = C *
and assign the result to left operand. A
/= Divide AND assignment operator, It divides left operand with the right operand and C /= A is equivalent to C = C /
assign the result to left operand. A
%= Modulus AND assignment operator, It takes modulus using two operands and assign C %= A is equivalent to C = C %
the result to left operand. A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2
Tokens – Operators
Special Operators
S.No Operator Description Example

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())

• C++ allows us to allocate the memory of a variable or an array in run


time. This is known as dynamic memory allocation.
• In other programming languages such as Java and Python, the compiler
automatically manages the memories allocated to variables. But this is not
the case in C++.
• In C++, we need to deallocate the dynamically allocated memory
manually after we have no use for the variable.
• We can allocate and then deallocate memory dynamically using the new
and delete operators respectively.
Memory management operators (new() operator)
C++ New Operator

The new operator allocates memory to a variable. For example,


// declare an int pointer

int* pointVar;

// dynamically allocate memory


// using the new keyword
pointVar = new int;

// assign value to allocated memory

*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;

// assigning value using dereference operator


*ptr = 10;

// printing value and address


cout << "Address: " << ptr << endl;
cout << "Value: " << *ptr; Output:
Address: 0x162bc20
return 0; Value: 10
}
Memory management operators (new(), delete())

• 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())

C++ delete Operator

Once we no longer need to use a variable that we have declared


• 🞄
dynamically, we can deallocate the memory occupied by the variable.

• For this, the delete operator is used. It returns the memory to the operating
system. This is known as memory deallocation.

• The syntax for this operator is,

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

// assign value to the variable memory pointer pointVar.


• After printing the contents of pointVar,
*pointVar = 10;
// print the value stored in memory we deallocated the memory using delete.

cout << *pointVar;


// deallocate the memory
delete pointVar;
delete() 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;

// assigning value using dereference operator


*ptr = 10;

// printing value and address


cout << "Address: " << ptr << endl;
cout << "Value: " << *ptr; Output:
delete ptr; Address: 0x162bc20
Value: 10
return 0;
}
Library Functions
• The library contains the function implementation, and by including the header
file for the corresponding library, we can use the required function in our
program.
• The C++ Standard Library provides a rich collection of functions for performing
common mathematical calculations, string manipulations, character
manipulations, input/output, error checking and many other useful operations.
• This makes the programmer's job easier, because these functions provide many
of the capabilities programmers need.
• The C++ Standard Library functions are provided as part of the C++
programming environment.
Library Functions
C++ Standard Library
Description
Header File
This library consists of several general-purpose functions like conversion
< cstdlib > related, sequence generation related, dynamic memory management
related, etc.
< ctime > It contains functions to get and manipulate the date and time.
This library contains IO manipulators that are used to format the stream
< iomanip >
of data.
This library contains the function and classes that are useful to work
< string >
with the string in C++.
< cstring > It consists of the string handling functions for c-styled strings.
This library defines the constant for the fundamental integral types. We
< climits >
generally use these constants for comparisons.
< vector > < list > < These all header files are corresponding to the container of the standard
deque > < queue > < template library of C++. Each container exhibits unique properties and
stack > < map > < set > < is used to store data. The implementation of the data type is written in
bitset > the associated library.
Library Functions
C++ Standard Library
Description
Header File
It contains classes and functions related to iterators that help us in accessing
< iterator >
the data of containers.
< algorithm > It provides various general purpose algorithms to operate on the containers.
This is the normal utility library which provides various functions in unrelated
< utility >
domains.
< functional > The functionality provided by this library is used by the algorithm library.
It contains classes for exception handling and other related functions to assist
< exception >
the error handling.
As the name suggests, this library contains functions and streams for standard
< iostream >
input and standard output in C++.
< cassert > It contains macros and functions that are used in the debugging.
Library Functions
Mathematical Functions
• Some of the important mathematical functions in header file
<cmath> are
• Example:
log 10(x) Logarithm of number x to the base 10

sqrt(x) Square root of x

pow(x, y) x raised to the power y

abs(x) Absolute value of integer number x

fabs(x) Absolute value of real number x


Library Functions
Character Functions
• All the character functions require <cctype> header file. The following table lists
the function.
• Example:
Function Meaning
isalpha(c) It returns True if C is an uppercase letter and False if c is lowercase.
isdigit(c) It returns True if c is a digit (0 through 9) otherwise False.
isalnum(c) It returns True if c is a digit from 0 through 9 or an alphabetic character (either
uppercase or lowercase) otherwise False.

islower(c) It returns True if C is a lowercase letter otherwise False.


isupper(c) It returns True if C is an uppercase letter otherwise False.
toupper(c) It converts c to uppercase letter.
tolower(c) It converts c to lowercase letter.
Decision Making Statement

• Decision making statement is depending on the condition block need to be


executed or not which is decided by condition.
• If the condition is "true" statement block will be executed, if condition is
"false" then statement block will not be executed.
• In C++ language there are three types of decision making statement.
 if
 if-else
 switch
if Statement

• If statement is most basic statement of Decision making statement. It tells to


program to execute a certain part of code only if particular condition is true.

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.

• Think of it as multiple layers of if statements. There is a first, outer if statement,


and inside it is another, inner 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

 Reduce length of Code

 take less memory space.


• There are mainly two types of loops,
 Entry Controlled loops: In this type of loop, the test condition is tested
before entering the loop body. For Loop and While Loop is entry-
controlled loops.
 Exit Controlled Loops: In this type of loop the test condition is tested or
evaluated at the end of the loop body. Therefore, the loop body will
execute at least once, irrespective of whether the test condition is true
or false. the do-while loop is exit controlled loop.
Control Flow / Looping statements
for loop
• It is called as entry controlled loop.
• A For loop is a repetition control structure that allows us to write a loop that
is executed a specific number of times. The loop enables us to perform n
number of steps together in one line.
• for loop contains 3 parts.
 Initialization Syntax:
 Condition for ( initial value; condition; increment/decrement )
 Iteration {
statement(s);
}
for loop – Example

#include <iostream> Output:


using namespace std; value of a: 10
int main () value of a: 11
{ value of a: 12
// for loop execution value of a: 13
for( int a = 10; a<20; a++) value of a: 14
{ value of a: 15
cout << "value of a: " << a << endl; value of a: 16
} value of a: 17
return 0; value of a: 18
} value of a: 19
While loop

• 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);

Note: Notice the semi – colon(“;”)in the end of loop.


Do - While loop Example
#include <iostream>
using namespace std;
int main()
{
int i = 2; // Initialization condition Output
do { Hello World
// loop body
cout << "Hello World\n";
i++; // update expression
} while (i < 1); // test condition
return 0;
}
Jump statements in C++

• 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.

• Break statement is used with decision-making statements such as if, if-


else, or switch statement which is inside the for loop which can
be for loop, while loop, or do-while loop.

• It forces the loop to stop the execution of the further iteration.


Syntax:
break;
Jump statements in C++
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i < 10; i++) Output:
{ 1234
if (i == 5) // Breaking Condition
break;
cout << i << " ";
}
return 0;
}
Jump statements in C++
return statement
• It takes control out of the function itself. It is stronger than a break.
• It is used to terminate the entire function after the execution of the
function or after some condition.
• Every function has a return statement with some returning value except
the void() function.
• Although void() function can also have the return statement to end the
execution of the function.
Syntax:
return expression;
Jump statements in C++
#include <iostream>
using namespace std;
int main()
{
Output:
cout << "Begin "; Begin 0 1 2 3 4
for (int i = 0; i < 10; i++)
{
if (i == 5)
return 0;
cout << i << " ";
}
cout << "end";
return 0;
}
Jump statements in C++

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

Implicit Type Conversion


• The type conversion that is done automatically done by the compiler is
known as implicit type conversion. This type of conversion is also known
as automatic conversion.
• Done by the compiler on its own, without any external trigger from the
user.
• Generally takes place when in an expression more than one data type is
present. In such condition type conversion (type promotion) takes place
to avoid lose of data.
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

• It is also known as explicit type conversion.


• Explicit type conversions can be forced in any expression to change the
type by programmer.
• This process is also called type casting and it is user-defined. Here the
user can typecast the result to make it of a particular data type.
• In C++, it can be done by two ways:
Syntax:
(type-name) expression; OR type-name (expression);
Type conversion
Example 1 Example 2

#include <iostream> #include <iostream>


using namespace std; using namespace std;

int main() int main()


{ {
short a; int a=5,b=2, c=6;
float c=4264.56789; float d;
a=(short)c; d= float (a+b+c) / 3;
cout<<a; // value of a = 4264 cout<<d; // value of d = 4.33333

}
}
Manipulators in C++

• Manipulators are helping functions that can modify the input/output


stream.
• It does not mean that we change the value of a variable, it only modifies
the I/O stream using insertion (<<) and extraction (>>) operators.
• Manipulators are special functions that can be included in the I/O
statement to alter the format parameters of a stream.
• Manipulators are operators that are used to format the data display.
• To access manipulators, the file iomanip.h should be included in the
program.
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!!!

You might also like