Variables and Data Types
C++ Variables
Last Updated : 16 Jul, 2024
Variables in C++ is a name given to a memory location. It is the basic unit
of storage in a program.
The value stored in a variable can be changed during program
execution.
A variable is only a name given to a memory location, all the operations
done on the variable effects that memory location.
In C++, all the variables must be declared before use.
How to Declare Variables?
A typical variable declaration is of the form:
// Declaring a single variable
type variable_name;
// Declaring multiple variables:
type variable1_name, variable2_name, variable3_name;
A variable name can consist of alphabets (both upper and lower case),
numbers, and the underscore ‘_’ character. However, the name must not
start with a number.
Initialization of a variable in C++
In the above diagram,
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
Examples:
// Declaring float variable
float simpleInterest;
// Declaring integer variable
int time, speed;
// Declaring character variable
char var;
We can also provide values while declaring the variables as given below:
int a=50,b=100; //declaring 2 variable of integer type
float f=50.8; //declaring 1 variable of float type
char c='Z'; //declaring 1 variable of char type
Rules For Declaring Variable
The name of the variable contains letters, digits, and underscores.
The name of the variable is case sensitive (ex Arr and arr both are
different variables).
The name of the variable does not contain any whitespace and special
characters (ex #,$,%,*, etc).
All the variable names must begin with a letter of the alphabet or an
underscore(_).
We cannot used C++ keyword(ex float,double,class)as a variable name.
Valid variable names:
int x; //can be letters
int _yz; //can be underscores
int z40;//can be letters
Invalid variable names:
int 89; Should not be a number
int a b; //Should not contain any whitespace
int double;// C++ keyword CAN NOT BE USED
Difference Between Variable Declaration and
Definition
The variable declaration refers to the part where a variable is first
declared or introduced before its first use. A variable definition is a part
where the variable is assigned a memory location and a value. Most of the
time, variable declaration and definition are done together.
See the following C++ program for better clarification:
C++
// C++ program to show difference between// definition and declaration of a //
variable#include <iostream>using namespace std;
int main(){ // this is declaration of variable a int a; // this is
initialisation of a a = 10; // this is definition = declaration +
initialisation int b = 20;
// declaration and definition // of variable 'a123' char a123 = 'a';
// This is also both declaration and definition // as 'c' is allocated memory
and // assigned some garbage value. float c;
// multiple declarations and definitions int _c, _d45, e;
// Let us print a variable cout << a123 << endl;
return 0;}
Output
a
Time Complexity: O(1)
Space Complexity: O(1)
Types of Variables
There are three types of variables based on the scope of variables in C++
Local Variables
Instance Variables
Static Variables
Types of Variables in C++
Let us now learn about each one of these variables in detail.
1. Local Variables: A variable defined within a block or method or
constructor is called a local variable.
These variables are created when entered into the block or the function
is called and destroyed after exiting from the block or when the call
returns from the function.
The scope of these variables exists only within the block in which the
variable is declared. i.e. we can access this variable only within that
block.
Initialization of local variables is not mandatory, but it is highly
recommended to ensure they have a defined value before use.
2. Instance Variables: Instance variables are non-static variables and
are declared in a class outside any method, constructor, or block.
As instance variables are declared in a class, these variables are
created when an object of the class is created and destroyed when the
object is destroyed.
Unlike local variables, we may use access specifiers for instance
variables. If we do not specify any access specifier then the default
access specifier will be used.
Initialization of Instance Variable is not Mandatory.
Instance Variable can be accessed only by creating objects.
3. Static Variables: Static variables are also known as Class variables.
These variables are declared similarly as instance variables, the
difference is that static variables are declared using the static
keyword within a class outside any method constructor or block.
Unlike instance variables, we can only have one copy of a static
variable per class irrespective of how many objects we create.
Static variables are created at the start of program execution and
destroyed automatically when execution ends.
Initialization of Static Variable is not Mandatory. Its default value is 0
If we access the static variable like the Instance variable (through an
object), the compiler will show the warning message and it won’t halt
the program. The compiler will replace the object name with the class
name automatically.
If we access the static variable without the class name, the Compiler
will automatically append the class name.
Instance Variable Vs Static Variable
Each object will have its own copy of the instance variable whereas We
can only have one copy of a static variable per class irrespective of
how many objects we create.
Changes made in an instance variable using one object will not be
reflected in other objects as each object has its own copy of the
instance variable. In the case of static, changes will be reflected in
other objects as static variables are common to all objects of a class.
We can access instance variables through object references and
Static Variables can be accessed directly using the class name.
The syntax for static and instance variables:
class Example
{
static int a; // static variable
int b; // instance variable
}
C++ Data Types
Last Updated : 23 Sep, 2023
All variables use data type during declaration to restrict the type of data to
be stored. Therefore, we can say that data types are used to tell the
variables the type of data they can store. Whenever a variable is defined
in C++, the compiler allocates some memory for that variable based on
the data type with which it is declared. Every data type requires a
different amount of memory.
C++ supports a wide variety of data types and the programmer can select
the data type appropriate to the needs of the application. Data types
specify the size and types of values to be stored. However, storage
representation and machine instructions to manipulate each data type
differ from machine to machine, although C++ instructions are identical
on all machines.
C++ supports the following data types:
1. Primary or Built-in or Fundamental data type
2. Derived data types
3. User-defined data types
Data Types in C++ are Mainly Divided into 3 Types:
1. Primitive Data Types: 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
Character
Boolean
Floating Point
Double Floating Point
Valueless or Void
Wide Character
2. Derived Data Types: Derived data types that are derived from the
primitive or built-in datatypes are referred to as Derived Data Types.
These can be of four types namely:
Function
Array
Pointer
Reference
3. Abstract or User-Defined Data Types: Abstract or User-Defined
data types are defined by the user itself. Like, defining a class in C++ or a
structure. C++ provides the following user-defined datatypes:
Class
Structure
Union
Enumeration
Typedef defined Datatype
Primitive Data Types
Integer: The keyword used for integer data types is int. Integers
typically require 4 bytes of memory space and range from -2147483648
to 2147483647.
Character: Character data type is used for storing characters. The
keyword used for the character data type is char. Characters typically
require 1 byte of memory space and range from -128 to 127 or 0 to
255.
Boolean: Boolean data type is used for storing Boolean or logical
values. A Boolean variable can store either true or false. The keyword
used for the Boolean data type is bool.
Floating Point: Floating Point data type is used for storing single-
precision floating-point values or decimal values. The keyword used for
the floating-point data type is float. Float variables typically require 4
bytes of memory space.
Double Floating Point: Double Floating Point data type is used for
storing double-precision floating-point values or decimal values. The
keyword used for the double floating-point data type is double. Double
variables typically require 8 bytes of memory space.
void: Void means without any value. void data type represents a
valueless entity. A void data type is used for those function which does
not return a value.
Wide Character: Wide character data type is also a character data
type but this data type has a size greater than the normal 8-bit data
type. Represented by wchar_t. It is generally 2 or 4 bytes long.
sizeof() operator: sizeof() operator is used to find the number of bytes
occupied by a variable/data type in computer memory.
Example:
int m , x[50];
cout<<sizeof(m); //returns 4 which is the number of bytes
occupied by the integer variable “m”.
cout<<sizeof(x); //returns 200 which is the number of bytes
occupied by the integer array variable “x”.
The size of variables might be different from those shown in the above
table, depending on the compiler and the computer you are using.
C++
// C++ Program to Demonstrate the correct
size
// of various data types on your computer.
#include <iostream>
using namespace std;
int main()
{
cout << "Size of char : " <<
sizeof(char) << endl;
cout << "Size of int : " << sizeof(int)
<< endl;
cout << "Size of long : " <<
sizeof(long) << endl;
cout << "Size of float : " <<
sizeof(float) << endl;
cout << "Size of double : " <<
sizeof(double) << endl;
return 0;
}
Output
Size of char : 1
Size of int : 4
Size of long : 8
Size of float : 4
Size of double : 8
Time Complexity: O(1)
Space Complexity: O(1)
Datatype Modifiers
As the name suggests, datatype modifiers are used with built-in data
types to modify the length of data that a particular data type can hold.
Data type modifiers available in C++ are:
Signed
Unsigned
Short
Long
The below table summarizes the modified size and range of built-in
datatypes when combined with the type modifiers:
Data Type Size (in bytes) Range
short int 2 -32,768 to 32,767
unsigned short int 2 0 to 65,535
unsigned int 4 0 to 4,294,967,295
int 4 -2,147,483,648 to 2,147,483,647
long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
Data Type Size (in bytes) Range
long long int 8 -(2^63) to (2^63)-1
unsigned long long int 8 0 to 18,446,744,073,709,551,615
signed char 1 -128 to 127
unsigned char 1 0 to 255
float 4 -3.4×10^38 to 3.4×10^38
double 8 -1.7×10^308 to1.7×10^308
long double 12 -1.1×10^4932 to1.1×10^4932
wchar_t 2 or 4 1 wide character
Note: Above values may vary from compiler to compiler. In
the above example, we have considered GCC 32 bit.
We can display the size of all the data types by using the
sizeof() operator and passing the keyword of the datatype, as
an argument to this function as shown below:
Now to get the range of data types refer to the following chart
Note: syntax<limits.h> header file is defined to find the
range of fundamental data-types. Unsigned modifiers have
minimum value is zero. So, no macro constants are defined
for the unsigned minimum value.
Macro Constants
Name Expresses
CHAR_MIN The minimum value for an object of type char
CHAR_MAX Maximum value for an object of type char
SCHAR_MIN The minimum value for an object of type Signed
char
SCHAR_MAX Maximum value for an object of type Signed char
Name Expresses
UCHAR_MAX Maximum value for an object of type Unsigned
char
CHAR_BIT Number of bits in a char object
MB_LEN_MAX Maximum number of bytes in a multi-byte
character
SHRT_MIN The minimum value for an object of type short
int
SHRT_MAX Maximum value for an object of type short int
USHRT_MAX Maximum value for an object of type Unsigned
short int
INT_MIN The minimum value for an object of type int
INT_MAX Maximum value for an object of type int
UINT_MAX Maximum value for an object of type Unsigned
int
LONG_MIN The minimum value for an object of type long int
LONG_MAX Maximum value for an object of type long int
ULONG_MAX Maximum value for an object of type Unsigned
long int
LLONG_MIN The minimum value for an object of type long
long int
LLONG_MAX Maximum value for an object of type long long
int
ULLONG_MAX Maximum value for an object of type Unsigned
long long int
The actual value depends on the particular system and library
implementation but shall reflect the limits of these types in the target
platform. LLONG_MIN, LLONG_MAX, and ULLONG_MAX are defined for
libraries complying with the C standard of 1999 or later (which only
includes the C++ standard since 2011: C++11).
C++ Program to Find the Range of Data Types using Macro Constants
Example:
C++
// C++ program to Demonstrate the sizes of
data types
#include <iostream>
#include <limits.h>
using namespace std;
int main()
{
cout << "Size of char : " <<
sizeof(char) << " byte"
<< endl;
cout << "char minimum value: " <<
CHAR_MIN << endl;
cout << "char maximum value: " <<
CHAR_MAX << endl;
cout << "Size of int : " << sizeof(int)
<< " bytes"
<< endl;
cout << "Size of short int : " <<
sizeof(short int)
<< " bytes" << endl;
cout << "Size of long int : " <<
sizeof(long int)
<< " bytes" << endl;
cout << "Size of signed long int : "
<< sizeof(signed long int) << "
bytes" << endl;
cout << "Size of unsigned long int : "
<< sizeof(unsigned long int) << "
bytes" << endl;
cout << "Size of float : " <<
sizeof(float) << " bytes"
<< endl;
cout << "Size of double : " <<
sizeof(double)
<< " bytes" << endl;
cout << "Size of wchar_t : " <<
sizeof(wchar_t)
<< " bytes" << endl;
return 0;
}
Output
Size of char : 1 byte
char minimum value: -128
char maximum value: 127
Size of int : 4 bytes
Size of short int : 2 bytes
Size of long int : 8 bytes
Size of signed long int : 8 bytes
Size of unsigned long int : 8 bytes
Size of float : 4 bytes
Size of double : 8 bytes
Size of wchar_t : 4 bytes
Time Complexity: O(1)
Space Complexity: O(1)
Functions and Control Structures
Control Structures in Programming
Languages
Last Updated : 16 Jan, 2020
Control Structures are just a way to specify flow of control in programs.
Any algorithm or program can be more clear and understood if they use
self-contained modules called as logic or control structures. It basically
analyzes and chooses in which direction a program flows based on certain
parameters or conditions. There are three basic types of logic, or flow of
control, known as:
1. Sequence logic, or sequential flow
2. Selection logic, or conditional flow
3. Iteration logic, or repetitive flow
Let us see them in detail:
1. Sequential Logic (Sequential Flow)
Sequential logic as the name suggests follows a serial or sequential flow in
which the flow depends on the series of instructions given to the
computer. Unless new instructions are given, the modules are executed in
the obvious sequence. The sequences may be given, by means of
numbered steps explicitly. Also, implicitly follows the order in which
modules are written. Most of the processing, even some complex
problems, will generally follow this elementary flow pattern.
2) Selection Logic (Conditional Flow)
Selection Logic simply involves a number of conditions or parameters
which decides one out of several written modules. The structures which
use these type of logic are known as Conditional Structures. These
structures can be of three types:
Single AlternativeThis structure has the form:
If (condition) then:
[Module A]
[End of If structure]
Implementation:
C++ if Statement
Last Updated : 11 Jan, 2024
Decision-making in C++ helps to write decision-driven statements and
execute a particular set of code based on certain conditions.
The C++ if statement is the most simple decision-making statement. It is
used to decide whether a certain statement or block of statements will be
executed or not executed based on a certain type of condition.
Syntax
if(condition)
{
// Statements to execute if
// condition is true
}
Working of if statement in C++
1. Control falls into the if block.
2. The flow jumps to Condition.
3. Condition is tested.
1. If Condition yields true, goto Step 4.
2. If Condition yields false, goto Step 5.
4. The if-block or the body inside the if is executed.
5. Flow steps out of the if block.
Flowchart
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by
default if statement will consider the immediate one statement to be
inside its block.
For example:
if(condition)
statement1;
statement2; // Here if the condition is true if block will consider
only statement1 to be inside its block.
Examples of if statement in C++
Example 1
Below program demonstrates the use of if statement in C.
C++
// C++ program to illustrate If
statement
#include <iostream>
using namespace std;
int main()
{
int i = 10;
if (i < 15) {
cout << "10 is less than
15 \n";
}
cout << "I am Not in if";
}
Output
10 is less than 15
I am Not in if
Explanation:
Program starts.
i is initialized to 10.
if-condition is checked. 10 < 15, yields true.
“10 is less than 15” gets printed.
if condition yields false. “I am Not in if” is printed.
Example 2
Below program illustrates another example of if statement in C++.
C++
// C++ program to illustrate If
statement
#include <iostream>
using namespace std;
int main()
{
int i = 10;
if (i > 15) {
cout << "10 is greater
than 15 \n";
}
cout << "I am Not in if";
}
Output
I am Not in if
Java if statement with Examples
Last Updated : 22 Mar, 2023
Decision Making in Java helps to write decision-driven statements and
execute a particular set of code based on certain conditions.
The Java if statement is the most simple decision-making statement. It
is used to decide whether a certain statement or block of statements will
be executed or not i.e if a certain condition is true then a block of
statement is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Working of if statement:
1. Control falls into the if block.
2. The flow jumps to Condition.
3. Condition is tested.
1. If Condition yields true, goto Step 4.
2. If Condition yields false, goto Step 5.
4. The if-block or the body inside the if is executed.
5. Flow steps out of the if block.
Flowchart if statement:
Operation: The condition after evaluation of if-statement will be either
true or false. The if statement in Java accepts boolean values and if the
value is true then it will execute the block of statements under it.
Note: If we do not provide the curly braces ‘{‘ and ‘}’ after
if( condition ) then by default if statement will consider the
immediate one statement to be inside its block.
For example:
if(condition)
statement1;
statement2;
// Here if the condition is true, if block will consider
the statement
// under it, i.e statement1, and statement2 will not be
considered in the if block, it will still be executed
// as it is not affected by any if condition.
Example 1:
Java
// Java program to illustrate If
statement
class IfDemo {
public static void main(String
args[])
{
int i = 10;
if (i < 15)
System.out.println("10 is
less than 15");
System.out.println("Outside if-
block");
// both statements will be
printed
}
}
Output
10 is less than 15
Outside if-block
Time Complexity: O(1)
Auxiliary Space: O(1)
Dry-Running Example 1:
1. Program starts.
2. i is initialized to 10.
3. if-condition is checked. 10<15, yields true.
3.a) "10 is less than 15" gets printed.
4. "Outside if-block" is printed.
Example 2:
Java
// Java program to illustrate If
statement
class IfDemo {
public static void
main(String args[])
{
String str =
"GeeksforGeeks";
int i = 4;
// if block
if (i == 4) {
i++;
System.out.println(s
tr);
}
// Executed by default
System.out.println("i =
" + i);
}
}
Output
GeeksforGeeks
i = 5
Time Complexity: O(1)
Auxiliary Space: O(1)
Example no 3: (Implementing if else for Boolean values)
Input -
boolean a = true;
boolean b = false;
Program –
Java
public class IfElseExample {
public static void
main(String[] args) {
boolean a = true;
boolean b = false;
if (a) {
System.out.println("a
is true");
} else {
System.out.println("a
is false");
}
if (b) {
System.out.println("b
is true");
} else {
System.out.println("b
is false");
}
}
}
Output
a is true
b is false
Explanation-
The code above demonstrates how to use an if-else statement in Java with
Boolean values.
The code starts with the declaration of two Boolean variables a and b,
with a set to true and b set to false.
The first if-else statement checks the value of a. If the value of a is true,
the code inside the first set of curly braces {} is executed and the
message “a is true” is printed to the console. If the value of a is false,
the code inside the second set of curly braces {} is executed and the
message “a is false” is printed to the console.
The second if-else statement checks the value of b in the same way. If
the value of b is true, the message “b is true” is printed to the console.
If the value of b is false, the message “b is false” is printed to the
console.
This code demonstrates how to use an if-else statement to make
decisions based on Boolean values. By using an if-else statement, you
can control the flow of your program and execute code only under
certain conditions. The use of Boolean values in an if-else statement
provides a simple and flexible way to make these decisions.
Advantages of If else statement –
The if-else statement has several advantages in programming, including:
1. Conditional execution: The if-else statement allows code to be
executed conditionally based on the result of a Boolean expression. This
provides a way to make decisions and control the flow of a program
based on different inputs and conditions.
2. Readability: The if-else statement makes code more readable by
clearly indicating when a particular block of code should be executed.
This makes it easier for others to understand and maintain the code.
3. Reusability: By using if-else statements, developers can write code
that can be reused in different parts of the program. This reduces the
amount of code that needs to be written and maintained, making the
development process more efficient.
4. Debugging: The if-else statement can help simplify the debugging
process by making it easier to trace problems in the code. By clearly
indicating when a particular block of code should be executed, it
becomes easier to determine why a particular piece of code is not
working as expected.
5. Flexibility: The if-else statement provides a flexible way to control the
flow of a program. It allows developers to handle different scenarios and
respond dynamically to changes in the program’s inputs.
Overall, the if-else statement is a fundamental tool in programming that
provides a way to control the flow of a program based on conditions. It
helps to improve the readability, reusability, debuggability, and flexibility
of the code.
Double AlternativeThis structure has the form:
If (Condition), then:
[Module A]
Else:
[Module B]
[End if structure]
Implementation:
C++ if else Statement
Last Updated : 11 Jan, 2024
Decision Making in C++ helps to write decision-driven statements and
execute a particular set of code based on certain conditions.
The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won’t. But what if we
want to do something else if the condition is false. Here comes the C+
+ else statement. We can use the else statement with if statement to
execute a block of code when the condition is false.
Syntax
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Working of if-else statement
1. Control falls into the if block.
2. The flow jumps to Condition.
3. Condition is tested.
1. If Condition yields true, goto Step 4.
2. If Condition yields false, goto Step 5.
4. The if-block or the body inside the if is executed.
5. The else block or the body inside the else is executed.
6. Flow exits the if-else block.
Flowchart if-else:
Examples of if else statement in C++
Example 1:
Below program demonstrates the use of if else statements in C++.
C++
// C++ program to illustrate if-else
statement
#include <iostream>
using namespace std;
int main()
{
int i = 20;
// Check if i is 10
if (i == 10)
cout << "i is 10";
// Since is not 10
// Then execute the else
statement
else
cout << "i is 20\n";
cout << "Outside if-else block";
return 0;
}
Output
i is 20
Outside if-else block
Explanation:
Program starts.
i is initialized to 20.
if-condition is checked. i == 10, yields false.
flow enters the else block.
“i is 20” is printed
“Outside if-else block” is printed.
Example 2:
Another program to illustrate the use of if else in C.
C++
// C++ program to illustrate if-else
statement
#include <iostream>
using namespace std;
int main()
{
int i = 25;
if (i > 15)
cout << "i is greater than
15";
else
cout << "i is smaller than
15";
return 0;
}
Output
i is greater than 15
Java if-else
Last Updated : 02 Apr, 2024
Decision-making in Java helps to write decision-driven statements and
execute a particular set of code based on certain conditions. The if
statement alone tells us that if a condition is true it will execute a block
of statements and if the condition is false it won’t. In this article, we will
learn about Java if-else.
If-Else in Java
If- else together represents the set of Conditional statements in Java that
are executed according to the condition which is true.
Syntax of if-else Statement
if (condition)
{
// Executes this block if // condition is true
}else
{
// Executes this block if // condition is false
}
Java if-else Flowchart
if-else Program in Java
Dry-Run of if-else statements
1. Program starts.
2. i is initialized to 20.
3. if-condition is checked. 20<15, yields false.
4. flow enters the else block.
4.a) "i is greater than 15" is printed
5. "Outside if-else block" is printed.
Below is the implementation of the above statements:
Java
// Java program to illustrate if-else statement
class IfElseDemo { public static void main(String args[]) { int i = 20;
if (i < 15) System.out.println("i is smaller than 15"); else
System.out.println("i is greater than 15");
System.out.println("Outside if-else block"); }}
Output
i is greater than 15
Outside if-else block
Nested if statement in Java
In Java, we can use nested if statements to create more complex
conditional logic. Nested if statements are if statements inside other if
statements.
Syntax:
if (condition1) {
// code block 1
if (condition2) {
// code block 2
}
}
Below is the implementation of Nested if statements:
Java
// Java Program to implementation// of Nested if statements
// Driver Classpublic class AgeWeightExample { // main function public static
void main(String[] args) { int age = 25; double weight = 65.5;
if (age >= 18) { if (weight >= 50.0) {
System.out.println("You are eligible to donate blood."); } else {
System.out.println("You must weigh at least 50 kilograms to donate blood.");
} } else { System.out.println("You must be at least 18 years old to
donate blood."); } }}
Output
You are eligible to donate blood.
Note: The first print statement is in a block of “if” so the
second statement is not in the block of “if”. The third print
statement is in else but that else doesn’t have any
corresponding “if”. That means an “else” statement cannot
exist without an “if” statement.
Frequently Asked Questions
What is the if-else in Java?
If-else is conditional statements that execute according to
the correct statement executed. If the if condition is true
then the code block inside the if statement is executed else it
executes the else statement block.
What is the syntax for if-else?
The syntax for if-else:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Multiple AlternativesThis structure has the form:
If (condition A), then:
[Module A]
Else if (condition B), then:
[Module B]
..
..
Else if (condition N), then:
[Module N]
[End If structure]
C++ if else if Ladder
Last Updated : 11 Jan, 2024
Decision-making in C++ helps to write decision-driven statements and
execute a particular set of code based on certain conditions.
In C++, the if-else-if ladder helps the user decide from among multiple
options. The C++ if statements are executed from the top down. As soon
as one of the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the C++ else-if ladder is bypassed.
If none of the conditions is true, then the final statement will be executed.
Syntax
if (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statement;
Working of the if-else-if ladder
1. Control falls into the if block.
2. The flow jumps to Condition 1.
3. Condition is tested.
1. If Condition yields true, goto Step 4.
2. If Condition yields false, goto Step 5.
4. The present block is executed. Goto Step 7.
5. The flow jumps to Condition 2.
1. If Condition yields true, goto step 4.
2. If Condition yields false, goto Step 6.
6. The flow jumps to Condition 3.
1. If Condition yields true, goto step 4.
2. If Condition yields false, execute else block. Goto Step 7.
7. Exits the if-else-if ladder.
Flowchart if-else-if ladder
Examples of if else if the ladder
Example 1:
Below program illustrates the use if else if ladder in C++.
C++
// C++ program to illustrate if-
else-if ladder
#include <iostream>
using namespace std;
int main()
{
int i = 20;
// Check if i is 10
if (i == 10)
cout << "i is 10";
// Since i is not 10
// Check if i is 15
else if (i == 15)
cout << "i is 15";
// Since i is not 15
// Check if i is 20
else if (i == 20)
cout << "i is 20";
// If none of the above
conditions is true
// Then execute the else
statement
else
cout << "i is not present";
return 0;
}
Output
i is 20
Explanation:
Program starts.
i is initialized to 20.
condition 1 is checked. 20 == 10, yields false.
condition 2 is checked. 20 == 15, yields false.
condition 3 is checked. 20 == 20, yields true. “i is 20” gets printed.
“Outside if-else-if” gets printed.
Program ends.
Example 2:
Another example to illustrate the use of if else if ladder in C++.
C++
// C++ program to illustrate if-else-
if ladder
#include <iostream>
using namespace std;
int main()
{
int i = 25;
// Check if i is between 0 and 10
if (i >= 0 && i <= 10)
cout << "i is between 0 and
10" << endl;
// Since i is not between 0 and
10
// Check if i is between 11 and
15
else if (i >= 11 && i <= 15)
cout << "i is between 11 and
15" << endl;
// Since i is not between 11 and
15
// Check if i is between 16 and
20
else if (i >= 16 && i <= 20)
cout << "i is between 16 and
20" << endl;
// Since i is not between 0 and
20
// It means i is greater than 20
else
cout << "i is greater than
20" << endl;
}
Output
i is greater than 20
Java if-else-if ladder with Examples
Last Updated : 20 Oct, 2022
Decision Making in Java helps to write decision-driven statements and
execute a particular set of code based on certain conditions.
Java if-else-if ladder is used to decide among multiple options. The if
statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. If none of the conditions
is true, then the final else statement will be executed.
Syntax:
if (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statement;
Working of the if-else-if ladder:
1. Control falls into the if block.
2. The flow jumps to Condition 1.
3. Condition is tested.
1. If Condition yields true, goto Step 4.
2. If Condition yields false, goto Step 5.
4. The present block is executed. Goto Step 7.
5. The flow jumps to Condition 2.
1. If Condition yields true, goto step 4.
2. If Condition yields false, goto Step 6.
6. The flow jumps to Condition 3.
1. If Condition yields true, goto step 4.
2. If Condition yields false, execute else block.
Goto Step 7.
7. Exit the if-else-if ladder.
Flowchart if-else-if ladder:
Example 1:
Java
// Java program to illustrate if-else-
if ladder
import java.io.*;
class GFG {
public static void main(String[]
args)
{
// initializing expression
int i = 20;
// condition 1
if (i == 10)
System.out.println("i is
10\n");
// condition 2
else if (i == 15)
System.out.println("i is
15\n");
// condition 3
else if (i == 20)
System.out.println("i is
20\n");
else
System.out.println("i is
not present\n");
System.out.println("Outside if-
else-if");
}
}
Output:
i is 20
Outside if-else-if
Time Complexity: O(1)
Auxiliary Space: O(1)
Dry running
Example 1:
1. Program starts.
2. i is initialized to 20.
3. condition 1 is checked. 20 == 10, yields false.
4. condition 2 is checked. 20 == 15, yields false.
5. condition 3 is checked. 20 == 20, yields true.
5.a) "i is 20" gets printed.
6. "Outside if-else-if" gets printed.
7. Program ends.
Example 2:
Java
// Java program to illustrate if-else-if
ladder
import java.io.*;
class GFG {
public static void main(String[]
args)
{
// initializing expression
int i = 20;
// condition 1
if (i < 10)
System.out.println("i is
less than 10\n");
// condition 2
else if (i < 15)
System.out.println("i is
less than 15\n");
// condition 3
else if (i < 20)
System.out.println("i is
less than 20\n");
else
System.out.println("i is
greater than "
+ "or
equal to 20\n");
System.out.println("Outside if-
else-if");
}
}
Output:
i is greater than or equal to 20
Outside if-else-if
In this way, the flow of the program depends on the set of conditions that
are written. This can be more understood by the following flow charts:
Double Alternative Control Flow
2. Iteration Logic (Repetitive Flow)
The Iteration logic employs a loop which involves a repeat statement
followed by a module known as the body of a loop.
The two types of these structures are:
Repeat-For Structure
This structure has the form:
Repeat for i = A to N by I:
[Module]
[End of loop]
Here, A is the initial value, N is the end value and I is the increment. The
loop ends when A>B. K increases or decreases according to the positive
and negative value of I respectively.
Repeat-For Flow