0% found this document useful (0 votes)
2 views30 pages

C++ Tokens: Keywords, Identifiers, Constants

xyz

Uploaded by

gowri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views30 pages

C++ Tokens: Keywords, Identifiers, Constants

xyz

Uploaded by

gowri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-II

C++ TOKENS
 Tokens in C++ are the smallest units of a program that have meaning to the compiler.
 They include identifiers, keywords, constants, strings, operators, and punctuation symbols.
 The C++ compiler uses tokens to understand and process the source code during
compilation, parsing it into meaningful components for further analysis and execution.
There are 6 types of tokens in C++ :
1. Keyword
2. Identifiers
3. Constants
4. Strings
5. Special symbols
6. Operators
1. Keywords
 Keywords in programming languages, including C and C++, are reserved words with
predefined meanings and cannot be used as identifiers (variable names, function names,
etc.).
 These keywords are essential to the language syntax and define control structures, data
types, and other language constructs.
int main() {
int x, y, sum;

//taking the value of the two numbers


cout << "Enter the two integers you want to add: ";
cin >> x >> y;

// storing the sum of two integers in sum


sum = x + y;

// prints sum
cout << x << " + " << y << " = " << sum;

return 0;
}

Output:
Enter the two integers you want to add: 3
2
3+2=9

 Keywords are predefined reserved words that have a special meaning to the
compiler. These cannot be used as identifiers.
Some of the reserved keywords in C/C++ are given below.
auto break case char const continue
default do double else enum extern
float for goto if int long
register return short signed sizeof static
struct switch typedef union unsigned void
volatile while class friend new delete
this public private protected inline try
throw catch template

2. Identifiers
 Identifiers are symbols or words that one supplies to the variables, functions, types, classes,
objects and other such components of one’s code.
 If we look again at the program to add two numbers in C++, we observe that to identify the
value of the first number, we use the identifier ‘x’, for the second number, ‘y’ and for the
sum of the two, we use ‘sum’.
 There are some rules that must be followed while using identifiers as tokens in C/C++ these
are as follows:
 Keywords cannot be used as identifiers. However, identifiers that contain a keyword are
legal. For example, ‘Tint’ is a legal identifier, but ‘int’ is not.
 Identifiers are case-sensitive. Thus ‘FileName’ will correspond to a different memory
address than ‘fileName’.
 The first character of an identifier must be an alphabetic character, either uppercase or
lowercase, or an underscore ( _ ). Therefore, ‘2numbers’ is an illegal identifier.
3. Constant
 A constant is a token in C that corresponds to a number, character, or character string that
can be used as a value in a program.
 Every constant has a type and a value on the basis of which, constants are categorized into
the following types:
 Floating Point Constants: It is a decimal number that represents a signed real number. The
representation of a signed real number includes an integer portion, a fractional portion, and an
exponent.
 Integer Constants: It is a decimal (base 10), octal (base 8), or hexadecimal (base 16) number
that represents an integral value. We use these to represent integer values that cannot be
changed.
 Character Constants: A “character constant” is formed by enclosing a single character from
the representable character set within single quotation marks (‘ ‘).
//floating point constants
15.75 1.575E1 // = 15.75
1575e-2 // = 15.75
2.5e-3 // = -0.0025
25E-4 // = 0.0025

//integer constants
28 0x1C // = Hexadecimal representation for decimal 28
034 // = Octal representation for decimal 28

//character constants
char schar = 'x'; // A character constant
wchar_t wchar = L 'x'; // A wide-character constant for the same character
4. Strings
 In the C and C++ programming languages, a string token represents a series of characters
enclosed within double quotes (" ").
 It is a basic data type used to represent textual information. String tokens receive their
interpretation as character arrays, and their conclusion involves appending a null character ('\
0') to signify the string's ending.
 It enables the handling, storage, and manipulation of textual data within a program.
//Initialize a character array with individual characters
char string1[50] = { 'c', 'o', 'd', 'i', 'n', 'g', 'n', 'i', 'n', 'j', 'a', 's' };

//Initialize a character array


char string2[12] = { "codingninjas" };
5. Special symbols
 In the C and C++ programming languages, special symbols refer to specific characters with
predefined meanings within the language syntax.
 These symbols have distinct purposes and are used to denote operations, control structures,
and language constructs. Below are several frequently employed special symbols in C and
C++:
 Asterisk (*): used to create a pointer variable and multiply the two variables.
 Colon (:): used to initialize a list.
 Pre-processor (#): serves as a macro processor that the compiler uses to modify your
program before the start of actual compilation.
 Comma(,): separates multiple statements, such as individual parameters within
function calls.
 Bracket ([ ]): Opening and closing brackets are used in arrays to indicate one-
dimensional and multi-dimensional arrays.
 Braces ({ }): Indicates a code's starting and ending point in which multiple
executable commands are added.
6. Operators
 In C++, operators are symbols that represent specific actions or computations to be
performed on operands.
 These operands can be variables, constants, or expressions. Operators facilitate various
operations such as arithmetic, logical, relational, assignment, bitwise, and conditional
operations, among others.
1. Arithmetic Operators: These operators perform basic arithmetic operations such as addition
(+), subtraction (-), multiplication (*), division (/), and modulus (%). They manipulate numeric
operands to produce a result based on the operation specified.
2. Relational Operators: Relational operators compare two operands and evaluate to either true
or false based on the relationship between them. Examples include less than (<), greater than
(>), equal to (==), not equal to (!=), less than or equal to (<=), and greater than or equal to
(>=).
3. Logical Operators: Logical operators perform logical operations on boolean operands. They
include logical AND (&&), logical OR (||), and logical NOT (!). These operators are used to
combine multiple conditions and evaluate their truth values.
4. Assignment Operators: Assignment operators are used to assign values to variables. The
basic assignment operator (=) assigns the value on the right-hand side to the variable on the
left-hand side. Compound assignment operators such as +=, -=, *=, /=, and %= combine
arithmetic operations with assignment.
5. Bitwise Operators: Bitwise operators perform operations at the bit level. They include bitwise
AND (&), bitwise OR (|), bitwise XOR (^), bitwise NOT (~), left shift (<<), and right shift
(>>). These operators manipulate the individual bits of integer operands.
6. Conditional Operator (Ternary Operator): The conditional operator (?:) is a ternary
operator that evaluates a condition and returns one of two values based on whether the
condition is true or false. It provides a concise way to express conditional expressions.

DATA TYPES:

 A data type is used to indicate the type of data value stored in a variable. All C compilers
support a variety of data types.

 This variety of data types allows the programmer to select the type appropriate to the
needs of the application as well as the machine. ANSI C supports the following classes of
data types:
 All the variables in C++ use various data types to restrict the type of data to be stored
during declaration.
 If a variable is defined in C++ language, then the compiler allocates some specific
memory based on that particular data type.
Types
There are 3 different Data types in C++, which are:

 Primary (fundamental) data types.

 Derived data types.

 User-defined data types


Primitive Data type
 Primitive data types in C++ are some inbuilt data types that can be used by the user directly
for the declaration of the variable. Some primitive data types in C++ are:
1. Integer
2. Character
3. Boolean
4. Floating Point
5. Double Floating Point
6. Valueless or Void
1.) Integer
 Integer data types represent whole numbers without a fractional or decimal part. They can be
signed (positive, negative, or zero) or unsigned (only positive or zero).
Example
int signedInt = -42;
unsigned int unsignedInt = 123;
 This code declares two integer variables, one signed ("signedInt") with a value of -42 and
the other unsigned ("unsignedInt") with a value of 123.
2.) Character
 Character data types represent individual characters from a character set, like ASCII or
Unicode. In C++, `char` is commonly used to represent characters.
Example
char myChar = 'A';
 The character variable "myChar" with the value "A" is declared using this code.
3.) Boolean
 Boolean data types represent binary values, typically used for true (1) or false (0) conditions.
In C++, `bool` is used for Boolean data.
Example
bool isTrue = true;
bool isFalse = false;
 The two boolean variables "isTrue" and "isFalse" are declared in this code with the
values true and false, respectively.
4.) Floating Point
 Floating-point data types represent numbers with a fractional part. In C++, `float` is a single-
precision floating-point type.
Example
float myFloat = 3.14159f;
 The floating-point variable "myFloat" is declared in this code with the value 3.14159.
5.) Double Floating Point
 Double-precision floating-point data types are used to represent numbers with a larger range
and higher precision compared to 'float'. In C++, 'double' is commonly used.
Example
double myDouble = 3.141592653589793;
 This code declares a high-precision double-precision floating-point variable named
"myDouble" with the value of (pi).
6.) Valueless or Void
 The void data type in C++ is used to indicate that a function does not return any value or to
declare generic pointers that do not point to a specific data type.
Example
void myFunction() { // This function does not return a value
}
void* genericPointer;
 This code declares a generic void pointer named "genericPointer" as well as the void
function "myFunction," which has no return value.
Derived Data type
The derived data type in C++ is derived from the primitive data type.
There are some derived data types in C++ language:
1. Function
2. Array
3. Pointer
1. Function
 A function is a reusable block of code that performs a specific task. It is a derived data type
because you can define functions to work with other data types and can even return values of
different data types.
Example
// Function that adds two integers and returns the result
int add(int a, int b) {
return a + b;
} // Function that concatenates two strings and returns the result
 The function in this code has functions "add" and it returns sum of value of a+b .
2. Array
 An array is a derived data type that represents a collection of elements of the same data type,
stored in contiguous memory locations. The elements can be accessed by their index.
Example
// Declaration and initialization of an integer array
int numbers[5] = {1, 2, 3, 4, 5}; // Accessing elements of the array
int firstNumber = numbers[0]; // Accessing the first element (index 0)
int thirdNumber = numbers[2]; // Accessing the third element (index 2)
 This code defines and initializes an integer array called "numbers" with values ranging from
1 to 5. It then accesses and assigns the first element to "firstNumber" and the third element
to "thirdNumber" by referring to the elements' respective indices (0 and 2).
3. Pointer
 A pointer is a derived data type that stores the memory address of another data type. Pointers
are often used for dynamic memory allocation and for accessing memory locations directly.
Example
// Declaration and initialization of a pointer
int* ptr; // Pointer to an integer
int num = 42;
ptr = &num; // Assigning the address of 'num' to 'ptr' // Accessing the value
through the pointer
int value = *ptr; // Dereferencing the pointer to get the value (value = 42)
 This code defines and initializes an integer pointer called "ptr," gives it the address of the
integer variable "num," and then accesses the value stored at that address by dereferencing
the pointer. The value 42 is then stored in the variable "value."
User-defined data types:

 The data types defined by the user are known as the user-defined data types.

 They are structure,union,class and enumeration

C++ VARIABLES
 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++

Syntax:
datatype var = value;
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.

OPERATORS AND EXPRESSIONS

o An operator is a symbol which represents a particular operation that can be


performed on data. An operand is the object on which an operation is performed.

o By combining the operators and operands we form an expression.

o An expression is a sequence of operands and operators that reduces to a single value.


C++ operators can be classified as
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment or Decrement operators
6. Conditional operator
7. Bit wise operators
8. unary operator
9. Special operators
10. Additional operators in c++
Arithmetic Operators
 Arithmetic operators in C++ are the basic operators, which are used for basic mathematical
or arithmetical operations on operands. These operators are essential for performing
calculations and manipulating data within a program.
 There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2


% Modulus Operator and remainder of after an integer division B % A will give 0

++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by one A-- will give 9

Relational Operators

 Relational operators are used to compare two values or expressions. These operators return a
boolean value − true if the comparison is correct, and else false.

 They are essential for making decisions and controlling the flow of a program based on
conditions.
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −

Operato
Description Example
r

Checks if the values of two operands are equal or not, if yes then (A == B) is
==
condition becomes true. not true.

Checks if the values of two operands are equal or not, if values are not (A != B) is
!=
equal then condition becomes true. true.

Checks if the value of left operand is greater than the value of right (A > B) is not
>
operand, if yes then condition becomes true. true.

Checks if the value of left operand is less than the value of right (A < B) is
<
operand, if yes then condition becomes true. true.

Checks if the value of left operand is greater than or equal to the value (A >= B) is
>=
of right operand, if yes then condition becomes true. not true.

Checks if the value of left operand is less than or equal to the value of (A <= B) is
<=
right operand, if yes then condition becomes true. true.
Logical Operators

 Logical operators are used to perform logical operations on boolean values (true or false).
These operators are essential for controlling the flow of a program based on conditions.
There are three primary logical operators in C++ as mentioned below −

 There are following logical operators supported by C++ language.


Assume variable A holds 1 and variable B holds 0, then −

Operato
Description Example
r

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

Called Logical NOT Operator. Use to reverses the logical state of its
!(A && B)
! operand. If a condition is true, then Logical NOT operator will make
is true.
false.
Bitwise Operators

 Bitwise operators are used to perform operations at the bit level on integer data types. These
operations work on direct manipulation of bits, such as low-level programming, graphics,
and cryptography.

 Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |,
and ^ are as follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1
The Bitwise operators supported by C++ language are listed in the following table. Assume variable
A holds 60 and variable B holds 13, then −
Assignment Operators

 Assignment operators are used to assign values to variables. These operators allow you to
set or update the value stored in a variable.

 There are following assignment operators supported by C++ language −

Operator Description Example

Simple assignment operator, Assigns values from right side C = A + B will assign
=
operands to left side operand. value of A + B into C

Add AND assignment operator, It adds right operand to the C += A is equivalent to C


+=
left operand and assign the result to left operand. =C+A

Subtract AND assignment operator, It subtracts right


C -= A is equivalent to C =
-= operand from the left operand and assign the result to left
C-A
operand.

Multiply AND assignment operator, It multiplies right


C *= A is equivalent to C =
*= operand with the left operand and assign the result to left
C*A
operand.

Divide AND assignment operator, It divides left operand C /= A is equivalent to C =


/=
with the right operand and assign the result to left operand. C/A
Modulus AND assignment operator, It takes modulus using C %= A is equivalent to C
%=
two operands and assign the result to left operand. =C%A

C <<= 2 is same as C = C
<<= Left shift AND assignment operator.
<< 2

C >>= 2 is same as C = C
>>= Right shift AND assignment operator.
>> 2

C &= 2 is same as C = C &


&= Bitwise AND assignment operator.
2

C ^= 2 is same as C = C ^
^= Bitwise exclusive OR and assignment operator.
2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2


Operators Precedence in C++

 Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator −

 For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

 Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right


Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Decision Making in C++


 Decision-making in C++ involves the usage of conditional statements (also called decision
control statements) to execute specific blocks of code primarily based on given situations
and their results.

Types of Decision-Making Statements in C++


In C++, the following decision-making statements are available:
1. if Statement
2. if-else Statement
3. if-else-if Ladder
4. Nested if Statement
5. switch Statement
6. Conditional Operator
7. Jump Statements: break, continue, go, return
1. if in C++
 In C++, the if statement is the simplest decision-making statement. It allows the execution of
a block of code if the given condition is true. The body of the 'if' statement is executed only
if the given condition is true.
Syntax of if in C++
if (condition) {
// code to be executed if the condition is true
}
Here if the condition is true then the code inside the if block will be executed otherwise not.

Flowchart of if in C++
Example of if in C++
The below example demonstrates the use of the if statement by finding if the age of a person is
greater than 18 or not. if the condition is true then he/she is allowed to vote.

// C++ program to find if the age of a person id greater than 18 or not


#include <iostream>
using namespace std;
int main()
{
int age = 19;
if (age > 18) {
cout << "allowed to vote" << endl;
}
return 0;
}
Output
allowed to vote

2. if-else in C++
 The if-else decision-making statement allows us to make a decision based on the evaluation
of a given condition. If the given condition evaluates to true then the code inside the 'if'
block is executed and in case the condition is false, the code inside the 'else' block is
executed.
Syntax of if-else in C++
if (condition) {
// Code to be executed if the condition is true
}
else {
// Code to be executed if the condition is false
}
Flowchart of if-else in C++

Example of if-else in C

// C++ program to find if the given number is positive or non positive


#include <iostream>
int main()
{
int num = 5;
if (num > 0) {
cout << "number is positive." << endl;
}
else {
cout << "number is non-positive." << endl;
}
return 0;
}
Output
number is positive.

3. if-else if Ladder in C++


 The if-else-if statements allow us to include additional situations after the preliminary if
condition.
 The 'else if' condition is checked only if the above condition is not true. , and the `else` is the
statement that will be executed if none of the above conditions is true. If some condition is
true, then only the associated block is executed.
Syntax if-else-if Ladder
if (condition1) {
// code to be executed if condition1 is true
}
else if (condition2) {
// code to be executed if condition2 is true
}
else {
// code to be executed if both the condition is false
}
We can use multiple else if statements with an if-else pair to specify different conditions.
Flowchart of if-else-if Ladder in C++

Example of if-else-ladder in C++


// C++ program to find if the person is child, growing age or adult using if else-if ladder
#include <iostream>
using namespace std;
int main()
{
int age = 18;
if (age < 13) {
cout << "child" << endl;
}
else if (age >= 1 and age <= 18) {
cout << "Growing stage" << endl;
}
else {
cout << "adult" << endl;
}
return 0;
}

Output
Growing stage

4. Nested if-else in C++


 The Nested if-else statement contains an 'if' statement inside another 'if' statement. This
structure lets in more complex selection-making by way of comparing multiple conditions.
 In this type of statement, multiple conditions are checked, and then the body of the last if
statement is executed.
Syntax of Nested if-else in C++
if (condition1) {
// code to be executed if condition 1 is true
if (condition2) {
// code to be executed when condition 2 is true.
}
else {
// code to be executed if condition1 is true but condition2 is false.
}
}
else {
// code to be executed when condition 1 is false
}

Flowchart of Nested if-else


Flow diagram of Nested if-else
Example of Nested if-else in C++
// C++ program to check if the given number is positive, negative or zero if positive then check if it
is even or odd

#include <iostream>
using namespace std;
int main()
{
int number = 44;
if (number > 0)
{
if (number % 2 == 0) {
cout << "positive and even number" << endl;
}
else {
cout << "positive and odd number" << endl;
}
}
else if (number == 0) {
cout << "the number is zero" << endl;
}
else {
cout << "the number is negative" << endl;
}
return 0;
}

Output
positive and even number

5. Switch Statement in C++


 In C++, the switch statement is used when multiple situations need to be evaluated primarily
based on the value of a variable or an expression. switch statement acts as an alternative to
multiple if statements or if-else ladder and has a cleaner structure and it is easy for handling
multiple conditions.
Syntax of C++ switch
switch (expression) {
case value1:
// code to be executed if the value of expression is value1.
break;
case value2:
// code to be executed if the value of expression is value2.
break;
//…..
default:
// code to be executed if expression doesn't match any case.
}

Flowchart of switch in C++


// C++ program to use switch case and print certain output based on some conditions
#include <iostream>
using namespace std;
int main()
{
char input = 'B';
switch (input) {
case 'A':
cout << "GFG" << endl;
break;
case 'B':
cout << "GeeksforGeeks" << endl;
break;
default:
cout << "invalid input" << endl;
}
return 0;
}
Output
GeeksforGeeks

6. Ternary Operator ( ? : ) in C++


 The conditional operator is also known as a ternary operator. It is used to write conditional
operations provided by C++.
 The '?' operator first checks the given condition, if the condition is true then the first
expression is executed otherwise the second expression is executed.
 It is an alternative to an if-else condition in C++.
Syntax of Ternary Operator in C++
condition ? expression1 : expression2
Flowchart of Conditional Operator in C++

// C++ program to demonstrate the use of ternary/conditional operator to find the max from two
numbers
#include <iostream>
using namespace std;
int main()
{
int num1 = 10, num2 = 40;
int max;
max = (num1 > num2) ? num1 : num2;
cout << max;
return 0;
}

Output
40

7. Jump Statements in C++


 Jump statements are used to alter the normal flow of the code. If you want to break the flow
of the program without any conditions then these jump statements are used. C++ provides
four types of jump statements.
 break
 continue
 goto
 return
A) break
 break is a control flow statement that is used to terminate the loop and switch statements
whenever a break statement is encountered and transfer the control to the statement just
after the loop.
Syntax
break;
 break statement is generally used when the actual number of iterations are not predefined
so we want to terminate the loop based on some conditions.
Flowchart of break
// C++ program to use break statement to break the loop when i become 3
#include <iostream>
using namespace std;
int main(){
for (int i = 0; i < 5; i++) {
if (i == 3) {
break;
}
cout << i << endl;
}
return 0;
}

Output
0
1
2
B) continue
 The continue statement is used to skip the loop body for the current iteration and
continue from the next iteration.
 Unlike the break statement which terminates the loop completely, continue allows us just
to skip one iteration and continue with the next iteration.
Syntax
continue;
// C++ program to use continue statement to continue the loop when i become 3
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 5; i++) {
if (i == 3) {
continue;
}
cout << i << endl;
}
return 0;
}

Output
0
1
2
4
C) goto
It is a jump statement that is used to transfer the control to another part of the program. It transfers
the control unconditionally to the labeled statement.
Syntax
goto label;
// ...
label:
// Statement or block of code

// C++ program to demonstrate the use of goto statement


#include <iostream>

using namespace std;


int main()
{
int age = 17;
if (age < 18) {
goto Noteligible;
}
else {
cout << "You can vote!";
}
Noteligible:
cout << "You are not eligible to vote!\n";
return 0;
}
Output
You are not eligible to vote!

D) return
 The return statement is used to exit the function immediately and optionally returns a
value to the calling function.
 It returns to the function from where it was called and if it is the 'main' function then it
marks the end of the execution. So basically, return is a mechanism used to communicate
the results back to the calling function.
Syntax
return expression;
Flowchart of return

// C++ program to use return statement to return the sum calculated by a function
#include <iostream>
using namespace std;
int add(int a, int b)
{
int sum = a + b;
return sum; // Return the sum to the calling code
}
int main()
{
int res = add(3, 5);
cout << "The sum is: " << res << endl;
return 0;
}

Output
The sum is: 8

LOOP STATEMENT
In C++ programming, a loop is an instruction that is used to repeatedly execute a code until a
certain condition is reached. They are useful for performing repetitive tasks without having to
write the same code multiple times.
Loops can be classified on the basis of the sequency in which they check the condition relative to
the execution of the associated block of code.
1. Entry Controlled loops: In this type of loop, the test condition is tested before entering the
loop body.
2. 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.
C++ provides three loops:
Types of Loops
 for Loop
 while Loop
 do while Loop
for Loop
A for loop is a repetition control structure that allows us to write a loop that is executed a specific
number of times. It is an entry-controlled loop that enables us to perform n number of steps
together in one line.
Syntax
for (initialization; condition; updation) {
// body of for loop
}
The various parts of the for loop are:
 Initialization: Initialize the loop variable to some initial value.
 Test Condition: This specifies the test condition. If the condition evaluates to true, then body
of the loop is executed, and loop variable is updated according to update expression. If
evaluated false, loop is terminated.
 Update Expression: After executing the loop body, this expression increments/decrements the
loop variable by some value.
Example
#include <iostream>
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
return 0;
}

Output
12345

Important Properties of for Loop


 The initialization and updation statements can perform operations unrelated to the condition
statement, or nothing at all – if you wish to do. But the good practice is to only perform
operations directly relevant to the loop.
 A variable declared in the initialization statement is visible only inside the scope of the for loop
and will be released out of the loop.
 Don’t forget that the variable which was declared in the initialization statement can be modified
during the loop, as well as the variable checked in the condition.
Range Based for Loop
There is a type of for loop that does not need the condition and updation statement. It is
called range based for loop and it can only be used for iteratable objects such as vector, set, etc.
For a vector named v, it can be written to print its elements as:
int main() {
for(int i=1,i<=5;i++)
{
cout << i << " ";
return 0;
}

Output
12345

while Loop
while loop is used in situations where we do not know the exact number of iterations of the loop
beforehand. It is an entry-controlled loop whose execution is terminated on the basis of the test
conditions.
Syntax
while (condition) {
// Body of the loop
update expression
}
Only the condition is the part of while loop syntax, we have to do
the initialization and updation manually outside and inside the loop respectively.
Example
#include <iostream>
int main()
{
int i = 1;
while (i <= 5)
{
cout << i << " ";
i++;
}
return 0;
}
Output
12345

do while Loop
The do-while loop is also a loop whose 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. So, in a do-while loop, the loop body will execute at
least once irrespective of the test condition.
Syntax
do {
// Body of the loop
// Update expression
} while (condition);
Like while loop, only the condition is the part of do while loop syntax, we have to do
the initialization and updation manually outside and inside the loop respectively.
Example
#include <iostream>
int main() {
int i = 1;
do {
cout << i << " ";
i++;
}while (i <= 5);
return 0;
}

Output
12345

Remember the last semicolon at the end of the loop.

You might also like