Unit 2
Unit 2
Decision-making is the process to make a decision about which part of the code
should be executed or not based on some condition. 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.
1. if statement
Syntax
if (condition)
Example 1.
//decision01.cpp
#include <iostream>
int main() {
if(a > b) {
return 0;
Output:
20 is bigger than 10
2. if-else statement
If we want to execute some code if a condition is true and another code if the
condition is not true, use the if-else statement.
Syntax
if (condition)
else
{
code to be executed if condition is not true
Example 2.
//decision02.cpp
#include <iostream>
int main() {
int n = 10;
if(n%2 == 0) {
else {
return 0;
Output:
10 is an even number.
We should use the if-else nesting if we want to select one of many sets of lines to
execute.
Syntax
if (condition1) {
else if (condition2) {
else {
Example 3.
//decision03.cpp
#include <iostream>
int main() {
if(a > b) {
}
else {
return 0;
Output:
4. switch-case statement
We should use the switch-case statement if we want to select one of many blocks
of code to be executed.
Syntax
switch(choice)
case 1:
break;
case 2:
break;
case 3:
break;
default:
break;
This is how it works: First we have a single expression choice (most often int or
char type variable is used), that is evaluated once.
The value of the expression is then compared with the values for each case in the
structure.
If there is a match, the block of code associated with that case is executed.
We use break statement to prevent the code from running into the next case
automatically.
Example 4
//decision04.cpp
#include <iostream>
int main() {
int choice = 3;
switch(choice) {
case 1:
break;
case 2:
case 3:
break;
default:
break;
return 0;
Output:
welcome
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.
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
}
int main() {
return 0;}
while Loop
While studying for loop, we have seen that the number of iterations is known
beforehand, i.e. the number of times the loop body is needed to be executed is
known to us. 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
int main() {
// Initialization
int i = 1;
while (i <= 5) {
// Updation
i++;
return 0;
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 {
// Update expression
} while (condition);
int main() {
// Initialization
int i = 1;
do {
// Updation
i++;
return 0;
Jump statements are used to manipulate the flow of the program if some
conditions are met. It is used to terminate or continue the loop inside a program
or to stop the execution of a function.
break Statement
return Statement
goto Statement
continue Statement
The C++ continue statement 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.
int main() {
if (i == 5)
continue;
return 0;
break Statement
The C++ break statement is used to terminate the whole loop if the condition is
met. It is used with decision-making statements such as if, if-else,
or switch statement to break out of the block. It forces the loop to stop the
execution of the further iteration.
using namespace std;
int main() {
// Breaking Condition
if (i == 5)
break;
return 0;
return Statement
The return statement 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.
int main() {
int n = 10;
findNum(n);
return 0;
goto Statement
The C++ goto 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 them before or
after the goto statement.
int main() {
int n = 4;
if (n % 2 == 0) {
// Skipping to label1
goto label1;
else {
// Skipping to label2
goto label2;
label1:
return 0;
label2:
return 0;
label3:
cout << "Unspecified";
return 0;
goto Statement makes the program hard to read and follow. Further, it adds to
the complexity of the code. It makes the code buggy. Multiple goto statements
alter the program's flow and confuse the readers.
both break and continue are nothing more that renamed GOTO statements, that
are considered harmful since very long time ago, as they jump into the code
breaking the loop logic. You can always test your methods.
We have been forbidden from using goto, break and continue, and must only use
a single return statement from a function.
datatypearrayName[size1][size2]…[sizeN];
where,
datatype: Type of data to be stored in the array.
For example:
int arr1[2][4];
In C++ int data type takes 4 bytes and we have 8 elements in the array ‘arr1’ of
the int type.
int arr2[2][4][8];
#include <iostream>
int main()
{
int count = 1;
// Declaring 2D array
int array1[3][4];
array1[i][j] = count;
count++;
return 0;
Space Complexity:O(n*m)
int x[3][5][2];
x[i][j][k] = (some_value);
x[i][j][k] = count;
count++;
We have initialized the array with values. The values enclosed in curly braces ‘{}’
are assigned to the array. Here, 1 is stored in arr[0], 2 in arr[1], and so on. Here
the size of the array is 5.
We have initialized the array with values but we have not declared the length of
the array, therefore, the length of an array is equal to the number of elements
inside curly braces.
We have initialized the array using a loop after declaring the array. This method is
generally used when we want to take input from the user or we cant to assign
elements one by one to each index of the array. We can modify the loop
conditions or change the initialization values according to requirements.
Example 3: Display Sum and Average of Array Elements Using for Loop
#include <iostream>
using namespace std;
int main() {
// initialize an array without specifying size
double numbers[] = {7, 5, 6, 12, 35, 27};
double sum = 0;
double count = 0;
double average;
return 0;
}
Run Code
Output
The numbers are: 7 5 6 12 35 27
Their Sum = 92
Their Average = 15.3333
1. C-Type Strings
2. C++ String Object
3. String Manipulation Functions from C
4. String Manipulation with C++ String Class
1. C-Type Strings
strcpy(string1, string2)
1
Copies string string2 into string string1.
strcat(string1, string2)
2
Concatenates string string2 onto the end of string string1.
strlen(string1)
3
Returns the length of string string1.
strcmp(string1, string2)
4
Returns 0 if string1 and string2 are the same; less than 0 if string1<string2; greater than 0 if string1 >
strchr(string1, ch);
5
Returns a pointer to the first occurrence of character ch in string string1.
strstr(s1, s2)
6
Returns a pointer to the first occurrence of string string2 in string string1.
C++ Pointers
The address of the variable you’re working with is assigned to the pointer variable
that points to the same data type (such as an int or string).
Syntax:
datatype *var_name;
int *ptr; // ptr can point to an address which holds int data
Assigning the address of a variable to a pointer using the unary operator (&)
which returns the address of that variable.
Accessing the value stored in the address using unary operator (*) which returns
the value of the variable located at the address specified by its operand.
#include <bits/stdc++.h>
void geeks()
int* ptr;
ptr = &var;
// Driver program
int main()
geeks();
return 0;
Output
Value at ptr = 0x7ffe454c08cc
Value at var = 20
Value at *ptr = 20
Call-By-Value
Functions in C++?
Imagine you're building a house. You wouldn't construct the entire house in one
go, right? You'd break it down into smaller tasks like laying the foundation,
building walls, and installing the roof. Functions in C++ work similarly. They
allow you to break down your program into smaller, manageable pieces.
1. Organize Your Code: Functions help you structure your program logically.
2. Reuse Code: Once you write a function, you can use it multiple times in
your program.
3. Easier Debugging: When your code is divided into functions, it's easier to
find and fix errors.
4. Improve Readability: Well-named functions make your code easier to
understand.
Anatomy of a Function
Let's break down the structure of a function:
return_type function_name(parameters) {
// Function body (code block)
// ...
return result; // Optional return statement
}
return_type: The type of value the function returns (e.g., int, double, void).
function_name: A descriptive name for your function.
parameters: Inputs that the function accepts (can be optional).
Function body: The code that performs the task, enclosed in curly braces
{}.
return: Statement to send a value back (optional if return_type is void).
return_type: This specifies the data type of the value that the function will
return when it is executed. It indicates the type of the result produced by
the function. Examples of returnType include int, void, double, char, and
user-defined types.
Here's an example:
#include <iostream>
using namespace std;
int main() {
int result = squareAndDouble(3);
cout << "Result: " << result << endl; // Output: Result: 18
return 0;
}
Here's an example:
#include <iostream>
using namespace std;
int main() {
cout << "Sum: " << add(5, 3) << endl; // Output: Sum: 8
return 0;
}
Use inline functions for small, frequently called functions to potentially improve
performance.
Static Function:
class A {
public:
static void f()
{
cout << "GeeksforGeeks!";
}
};
// Driver Code
int main()
{
A::f();
}
Output:
GeeksforGeeks!
Constant Function:
#include <iostream>
using namespace std;
// Driver Code
int main()
{
const double a = 1;
return 0;
}
It is declared using the static keyword. It is declared using the const keyword.
This function can only be called by static data This function can be called using any
members and static member functions. type of object.
Static Function Constant Function
It is useful to declare global data which should It is useful with pointers or references
be updated while the program lives in memory, passed to function, used to avoid
used to restrict access to functions, reuse the accidental changes to object, can be
same function name in other files, etc. called by any type of object, etc.