0% found this document useful (0 votes)
0 views29 pages

Unit 2

The document provides an overview of decision-making and looping constructs in C++, including if statements, switch-case statements, and various types of loops (for, while, do-while). It also discusses jump statements (continue, break, return, goto) and their implications on program flow, as well as multidimensional arrays and their initialization. Additionally, it touches on string manipulation in C++, though details on that section are not fully included.

Uploaded by

aayan01ku
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)
0 views29 pages

Unit 2

The document provides an overview of decision-making and looping constructs in C++, including if statements, switch-case statements, and various types of loops (for, while, do-while). It also discusses jump statements (continue, break, return, goto) and their implications on program flow, as well as multidimensional arrays and their initialization. Additionally, it touches on string manipulation in C++, though details on that section are not fully included.

Uploaded by

aayan01ku
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/ 29

Unit-2 OOPS (Sec-B)

Decision Making in C++

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.

We have the following decision control statements in C++:

 if statement – we use this statement if we want to execute some code only


if a specified condition is true
 if-else statement – we use this statement if we want to execute some code
if the condition is true and another code if the condition is false
 if-else nesting statement – we use this statement if we want to select one
of many blocks of code to be executed
 switch-case statement – we use this statement if we want to select one of
many blocks of code to be executed

1. if statement

We should use the if statement if we want to execute some code only if a


specified condition is true.

Syntax

if (condition)

code to be executed if condition is true

Example 1.

//decision01.cpp
#include <iostream>

using namespace std;

int main() {

int a = 20, b = 10;

if(a > b) {

cout << a << " is bigger than " << 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)

code to be executed if condition is true

else

{
code to be executed if condition is not true

Example 2.

//decision02.cpp

#include <iostream>

using namespace std;

int main() {

int n = 10;

// testing for even or odd number

if(n%2 == 0) {

cout << n << " is an even number.";

else {

cout << n << " is an odd number.";

return 0;

Output:

10 is an even number.

3. if-else nesting statement

We should use the if-else nesting if we want to select one of many sets of lines to
execute.
Syntax

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 condition1 and condition2 are not true

Example 3.

//decision03.cpp

#include <iostream>

using namespace std;

int main() {

int a = 30, b = 30;

if(a > b) {

cout << "a is bigger than b.";

else if(a < b) {

cout << "a is smaller than b.";

}
else {

cout << "a and b are equal.";

return 0;

Output:

a and b are equal.

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:

execute code block 1

break;

case 2:

execute code block 2

break;

case 3:

execute code block 3

break;
default:

execute code if choice is different

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>

using namespace std;

int main() {

int choice = 3;

switch(choice) {

case 1:

cout << "hello";

break;

case 2:

cout << "hi";


break;

case 3:

cout << "welcome";

break;

default:

cout << "bye";

break;

return 0;

Output:

welcome

What are Loops?

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.
 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() {

// For loop that starts with i = 1 and ends

// when i is greater than 5.

for (int i = 1; i <= 5; i++) {

cout << i << " ";

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 loop that starts with i = 1 and ends

// when i is greater than 5.

while (i <= 5) {

cout << i << " ";

// 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 {

// Body of the loop

// Update expression

} while (condition);

int main() {

// Initialization

int i = 1;

// while loop that starts with i = 1 and ends

// when i is greater than 5.

do {

cout << i << " ";

// Updation

i++;

}while (i <= 5);

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 terminate or continue the loop inside a program
or to stop the execution of a function.

In C++, there is four jump statement:


 continue Statement

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

for (int i = 1; i < 10; i++) {

// Skip the execution for i = 5

if (i == 5)

continue;

cout << i << " ";

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

// Loop to print digits from 1 to 4

for (int i = 1; i < 10; i++) {

// Breaking Condition

if (i == 5)

break;

cout << i << " ";

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;

// Calling the function

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:

cout << "Even" << endl;

return 0;

label2:

cout << "Odd" << endl;

return 0;

label3:
cout << "Unspecified";

return 0;

Benefits and limitations of jumping statement in c++

What are the benefits of jumps in loop in C?

Flexibility in Control Flow: Jump statements provide flexibility in controlling the


flow of a program. They allow programmers to navigate to specific points in the
code, break out of loops prematurely, or skip certain iterations, enabling more
dynamic and responsive programming.

Disadvantages of goto Statement in C

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.

What is Multidimensional Array in C++?

A multidimensional array is an array with more than one dimension. It is the


homogeneous collection of items where each element is accessed using multiple
indices.

Multidimensional Array Declaration

datatypearrayName[size1][size2]…[sizeN];

where,
datatype: Type of data to be stored in the array.

arrayName: Name of the array.

size1, size2,…, sizeN: Size of each dimension.

For example:

int arr1[2][4];

The array int arr1[2][4] can store total (2*4) = 8 elements.

In C++ int data type takes 4 bytes and we have 8 elements in the array ‘arr1’ of
the int type.

Total size = 4*8 = 32 bytes.

int arr2[2][4][8];

The most widely used multidimensional arrays are:

Two Dimensional Array

Three Dimensional Array

Two Dimensional Array (or 2D Array)

A two-dimensional array in C++ is a collection of elements organized in rows and


columns. It can be visualized as a table or a grid, where each element is accessed
using two indices: one for the row and one for the column. Like a one-
dimensional array, two-dimensional array indices also range from 0 to n-1 for
both rows and columns.

/ c++ program to illustrate the two dimensional array

#include <iostream>

using namespace std;

int main()
{

int count = 1;

// Declaring 2D array

int array1[3][4];

// Initialize 2D array using loop

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 4; j++) {

array1[i][j] = count;

count++;

// Printing the element of 2D array

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 4; j++) {

cout << array1[i][j] << " ";

cout << endl; }

return 0;

Time Complexity: O(n*m)

Space Complexity:O(n*m)

where n is the number of rows and m is the number of columns.


Three-Dimensional Array in C++

The 3D array is a data structure that stores elements in a three-dimensional


cuboid-like structure. It can be visualized as a collection of multiple two-
dimensional arrays stacked on top of each other. Each element in a 3D array is
identified by its three indices: the row index, column index, and depth index.

int x[3][5][2];

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 5; j++) {

for (int k = 0; k < 2; k++) {

x[i][j][k] = (some_value);

// initializing the array

for (int i = 0; i < 2; i++) {

for (int j = 0; j < 2; j++) {

for (int k = 0; k < 3; k++) {

x[i][j][k] = count;

count++;

Initialization of Array in C++


In C++, we can initialize an array in many ways but we will discuss some most
common ways to initialize an array. We can initialize an array at the time of
declaration or after declaration.

1. Initialize Array with Values in C++

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.

int arr[5] = {1, 2, 3, 4, 5};

2. Initialize Array with Values and without Size in C++

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.

int arr[] = {1, 2, 3, 4, 5};

3. Initialize Array after Declaration (Using Loops)

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.

for (int i = 0; i < N; i++) {


arr[i] = value;
}

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;

cout << "The numbers are: ";

// print array elements


// use of range-based for loop
for (const double &n : numbers) {
cout << n << " ";

// calculate the sum


sum += n;

// count the no. of array elements


++count;
}

// print the sum


cout << "\nTheir Sum = " << sum << endl;

// find the average


average = sum / count;
cout << "Their Average = " << average << endl;

return 0;
}
Run Code

Output
The numbers are: 7 5 6 12 35 27
Their Sum = 92
Their Average = 15.3333

C++ String Manipulation

In this lesson, you will learn about string manipulation in C++.


We’ll cover all the various operations that you can do with
strings.

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

As you know, C++ supersets the C language. Therefore, it supports string


functionalities from C. This is also called C-String. Strings in C are 1-
dimensional array of characters that is terminated by a null character, ‘\0’
(ASCII code for 0).

To define a C-string in C++ use the code below;

char name[] = "Kindson";


In the code above, the string name is created and holds 7 characters.

char str[4] = "Kindson";

char str[] = {'K','i','n', 'd', 's', 'o', 'n', '\0'};

char str[4] = {'H','e','l', 'l', 'o', '\0'};


The program below uses a C-type string to read a name from the input.
Then displays the name to the output.
int main () {
//you must provide a size
char name[20];
cout << "Please enter your name: ";
cin >> name;
cout << "Hello " << name << endl;
}

2. C++ String Object


C++ also provides it’s own string class. So you can create string object. This
class is provided by the standard C++ library. Unlike character array from C,
the C++ string does not have a fixed length. For example, the code below,
reads and prints the user’s name but without knowing the size of the name:

// Example with C++ String


int main () {
// size is not needed
string name;
cout << "What is your name: ";
cin >> name;
cout << "Welcome " << name << endl;
}

3. String Manipulation Methods (from C)


These are methods used for string manipulation. You need to understand
these functions to be get things done with strings.

SN Method and description

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

Pointers are symbolic representations of addresses. They enable programs to


simulate call-by-reference as well as to create and manipulate dynamic data
structures. Iterating over elements in arrays or other data structures is one of the
main use of 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

How pointer works in C++


How to use a pointer?

Define a pointer variable

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.

// C++ program to illustrate Pointers

#include <bits/stdc++.h>

using namespace std;

void geeks()

int var = 20;

// declare pointer variable

int* ptr;

// note that data type of ptr and var must be same

ptr = &var;

// assign the address of a variable to a pointer

cout << "Value at ptr = " << ptr << "\n";

cout << "Value at var = " << var << "\n";

cout << "Value at *ptr = " << *ptr << "\n";

// Driver program
int main()

geeks();

return 0;

Output
Value at ptr = 0x7ffe454c08cc
Value at var = 20
Value at *ptr = 20

References and Pointers

There are 3 ways to pass C++ arguments to a function:

 Call-By-Value

 Call-By-Reference with a Pointer Argument

 Call-By-Reference with a Reference Argument

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.

Here's why functions are so important:

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

Syntax Of Function Prototype In C++:

returnType functionName(parameterType1 parameterName1, parameterType2


parameterName2, ...);

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

 function_name: This is the name of the function. It is used for identifying


and calling functions in the code. Function names must follow the rules of
C++ naming conventions, such as not containing spaces and starting with a
letter or an underscore.

Parameters and Arguments

In C++, we distinguish between parameters and arguments:

Parameters are variables listed in a function's declaration.


Arguments are the actual values passed to the function when it's called.

Functions Calling Other Functions


In C++, functions can call other functions. This allows you to break down
complex tasks into smaller, manageable pieces.

Here's an example:

#include <iostream>
using namespace std;

int square(int num) {


return num * num;
}

int squareAndDouble(int num) {


int squared = square(num); // Call the square function
return 2 * squared;
}

int main() {
int result = squareAndDouble(3);
cout << "Result: " << result << endl; // Output: Result: 18
return 0;
}

Predefined Functions in C++


C++ comes with many built-in functions that you can use right away. Here are
some common categories:
1. Input/Output Functions: cout, cin, setprecision
2. Mathematical Functions: sqrt(), abs(), pow(), ceil(), floor()
3. Memory Operators: new, delete
4. Time Functions: time(), ctime(), difftime()
5. File Handling Functions: fopen(), fclose(), fread(), fwrite()
Inline Functions
Inline functions are a C++ feature designed to reduce the function call overhead.
When a function is declared as inline, the compiler replaces the function call
with the actual function code.

Here's an example:
#include <iostream>
using namespace std;

inline int add(int a, int b) {


return a + b;
}

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.

Difference between static and constant function in C++

Static Function:

It is a member function that is used to access only static data members. It


cannot access non-static data members not even call non-static member
functions. It can be called even if no objects of the class exist. It is also
used to maintain a single copy of the class member function across
different objects of the class.
C++ program to illustrate the use
// of static function
#include "bits/stdc++.h"
using namespace std;

class A {
public:
static void f()
{
cout << "GeeksforGeeks!";
}
};

// Driver Code
int main()
{
A::f();
}

Output:

GeeksforGeeks!
Constant Function:

It is a function that is generally declared as constant in the program. It also


guarantees that it will not allow modifying objects or call any non-const
member functions. It specifies that function is a read-only function and
does not modify the object for which it is called.
// C++ program to illustrate the use
// of const keyword

#include <iostream>
using namespace std;

// Driver Code
int main()
{
const double a = 1;

// Using the below line of code


// gives error
// a = 2.21;

cout << a << endl;

return 0;
}

Difference between static function and constant function:


Static Function Constant Function

It is declared using the static keyword. It is declared using the const keyword.

It does not allow variable or data members or


It allows specifying whether a variable
functions to be modified again. Instead, it is
is modifiable or not.
allocated for a lifetime of the program.

It helps to call functions that using class


It helps us to avoid modifying objects.
without using objects.

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.

You might also like