0% found this document useful (0 votes)
23 views

C++ UPTO 23

Uploaded by

kavyasoni0607
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

C++ UPTO 23

Uploaded by

kavyasoni0607
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 222

Lesson :

Introduction to Programming
and C++
List of Concepts Involved:
• What is Programming?
• Why do we need Programming?
• Types of Programming Languages
• Introduction to C++
• Difference between C and C++

Topic 1: What is Programming?


Programming is simply creating a set of instructions for a computer to perform a specific task. Programming
can be done using a variety of computer programming languages eg. C,C++,Java and the list is endless !.
The best part is, out of these very many options, you can go ahead with the language of your choice to
implement the concepts in the form of a logical code.
A Common thought - I have not done programming ever before! How will I be able to learn ?!
There are many instances where we use programming concepts without even having the slightest idea.
Surprised ?! Have you ever set the alarm in your watch/phone? I am sure, all of you had during exams !!! When
you are setting the time for the alarm, you are actually giving the set of instructions (unknowingly) to the
clock/phone to ring (and vibrate) at a specific time. Sounds interesting? Lets see more such examples:

• Many of the coffee lovers here would relate to this instance !


After you set your coffee machine to start at a certain time in the morning, you're programming an activity to
trigger. Most of these straightforward machines utilize programming to execute straightforward tasks— such as
setting a timer.
• Travel itineraries or the grocery list that we often create are also programs, wondering how ? They are actually
the set of instructions for the supercomputer named ‘your brain’. Cool, isn’t it?

To know and accomplish more of such interesting things , let's now move to the learning part of programming
with programming languages.

Category of Programming Languages


Programming languages that have been developed so far can majorly be categorised into: machine language,
assembly language, and high-level language.

Machine Level Language:


As the name suggests, it is a low-level language made up of binary numbers or bits that a machine/computer
can understand. It is a sequence of 0s and 1s. It is also known as machine code or object code. Any program that
we write, finally transforms into the sequence of 0s and 1s for the computer to understand.

Assembly language:
Assembly language is intended to communicate directly with a computer's hardware. Unlike the usual machine
language, which consists of binary characters, assembly language is expressed in a more human readable form.
In future many of you are going to learn and program microprocessors in your higher studies or jobs; that would
require an expertise in assembly language.

Cracking the Coding Interview in C++ - Foundation


High-level language:
It refers to the programming languages that allow the use of symbolic operators (to signify operations, eg.+,-,*,/ etc.)
and symbolic names(to represent data and data structures, eg. variable names).They are also structured with
syntax and semantics to describe the computing algorithm/program.This often requires the use of a compiler or
an interpreter which helps in the translation from high level human understandable code into low level machine
code because the computer only works on the binary data. We will be learning and focussing on this category of
language in our course.

Topic 2: Why do we need Programming?


Computers are ridiculously fast but contrary to the assumption of being ‘smart’, they are extremely dumb
machines. You might be wondering, what ?! Can you imagine, they don't even know how to check if a number is
odd or even (which a 2nd grade child knows) but if we create a program which will enable them to do this task,
they can check a billion numbers for us in one second. Hence, to make a computer/machine ‘smart’ we need the
tool of programming.
Most of the programming is done for the real world applications and not just for big rocket or other scientific
missions. Internet banking, online shopping ticket booking, in flight, all this can be conceivable due to the
applications created by computer programming. Your washing machine too contains a few sorts of computer
programs. All these things and many more are possible through the magic of programming.
Lets now see what are the different approaches which we can follow while programming. These approaches,
in computer terminology, are referred to as paradigms. There are many types of paradigms that can be used
based on the complexity of our application but we will focus on the most widely used here :

Topic 3: Types of Programming Paradigms :


• Procedural
• Functional
• Object Oriented

Procedural:
Consider a scenario where a program has to collect some data from users (read), perform some calculations
(calculate), and then display the result(print) when requested; a simple example of this scenario is any online
transaction that you/your parents do. In procedural approach, we can write 3 different procedures/functions for
each of the operations of reading, calculating and printing (which could interact amongst each other as well).
Hence, in the procedural approach:
• The entire program code is organized as a set of procedures/functions or discrete blocks of codes that are
executed in an order.
• These procedures are also known as subroutines or functions and contain a series of steps that will be carried
out when the procedure is called/used.
• Some of the programming languages that enable us to use procedural approach : BASIC, FORTRAN, ALGOL, C,
COBOL, and Pascal.

Cracking the Coding Interview in C++ - Foundation


Functional:
Let's assume a scenario where we have to perform lots of different operations on the same set of data. This can
be in the domains such as the web, statistics, financial analysis, and machine learning. Here, the functional
programming paradigm helps a lot.

• The program code is organized in pure functions(which always yield the same value for the same set of inputs
without any deviation) with each function set up to perform a clearly defined task.
• The data/variables are passed in the function as parameters (for the functions to interact with other functions
or programs).
• Languages that support this approach are: Javascript, Python, etc.

Object Oriented:
• The program data is organized in classes and objects rather than functions and logic.
• A class is a blueprint for creating objects and an object is referred to as an instance of a class that has unique
attributes and behavior.
• A good example of this could be you, yes you! You can be a ‘student’ or a ‘working professional’. In this scenario,
under the class of ‘Person’, we can have a ‘Student’ or ‘Working professional’ class and you can be an
instance of any of these based on whether you fall in the ‘student’ category or ‘working professional’ category.
Hence, you are an object

• Languages that support object-oriented approach include: Java, C++, C#, Python, R, PHP, Visual Basic.

The programming language that we would learn in the very first go has to be a simple yet most capable one!
Yes, you guessed it right, it's C++ !!
Lets now, hit the bulls eye !!
Let's get started.

Cracking the Coding Interview in C++ - Foundation


Topic 4: Introduction to C++
• C++ is a popular programming language.
• C++ is a middle-level programming language.
• C++ is developed by Bjarne Stroustrup in 1979 at Bell Labs.
• C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
• C++ is a superset of the C language.
• C++ is closer to the compiler and faster than C language.
• C++ is a statically typed programming language i.e it uses static typing when type checking is performed
during compile-time as opposed to run-time.
• C++ is both a procedural and an object-oriented programming language. It supports OOP features such as
polymorphism, encapsulation, and inheritance.
• As C++ is an object-oriented programming language so it gives a clear structure to programs and allows
code to be reused, lowering development costs.

Topic 5: Some basic differences between C and C++ before we move


ahead:
• C is a structural programming language that doesn’t provide any support for classes and objects but C++ is an
object-oriented programming language, and it provides support for the concept of classes and objects.
• C primarily supports procedural programming for developing codes whereas C++ supports both programming
paradigms- procedural as well as object-oriented.
• The C language uses the scanf() function for the input operation and printf() function for the output operations
whereas C++ language uses the cin function for the input operation and cout function for the output.
• C++ is closer to the compiler and faster than C language.

Upcoming Class Teasers:


• Installation of vs code.

Cracking the Coding Interview in C++ - Foundation


Lesson :

Variables, Data Types and


the first C++ program
List of Concepts Involved
• C++ Variables
• C++ Identifiers
• C++ Data Types
• C++ Output
• How does the C++ program work?
• C++ user input

A computer program/code consists of various components viz. variables, data types, identifiers, keywords, etc
which helps us to build a successful program. Let us learn each one of them in detail and then move to our
first program.

Topic 1: C++ Variables


• A variable is the title of a reserved region allocated in memory. In other words, it may be referred to as the
name of a memory location.
• Each variable should be given a unique name to indicate the storage area.
• A variable is a container that holds the value while the C++ program is executed.
• A variable is assigned with a data type(we will learn about it after this).

Syntax for Declaring a Variable:


Type variable_name [= value];
The variable_name is the name of a variable. We can initialize the variable by specifying an equal sign and a
value (Initialization i.e. assigning an initial value, is optional).

Creating Variables Example:

int age = 20; value

datatype variable_name

20

Reserved Memory for Variable

RAM

Cracking the Coding Interview in C++ - Foundation


In the example above, the variable can only hold integer values, as indicated by the int data type.
Here, we assigned a value to the variable during the declaration process. However, as stated before, it is
optional. Variables can be declared and assigned separately. Example,

int rate;

rate = 40;

Change Values of Variables


Interestingly, a variable's value can also be changed in the programme. As an example,

int rate = 50;

cout<<rate; // 50

rate = 60;

cout<<rate; // 60

Initially, the value of rate was 50 but it has changed to 60 after the last updation, rate=60.

Naming Conventions for variables in C++


Like us, all C++ components are identified with their names.There are a few points to remember while naming

the variable. They are as follows -

• Variable names should not begin with a number. For Example


int 2var; // 2var is an invalid variable.

• Whitespaces are not permitted in variable names. For example,


int cricket score; // invalid variables.
There is a gap/whitespace between cricket and score.

• A C++ keyword (reserved word) cannot be used as a variable name. For example, int float; is an invalid
expression as float is pre-defined as a keyword(we will learn about them) in C++.

• As per the latest coding practices, for variable names with more than one word the first word has all lowercase
letters and first letter of subsequent words capitalised. For example, cricketScore, codePracticeProgram etc.
This type of format is called camel case

• While creating variables, it's preferable to give them meaningful names like- ‘age’, ‘earning’, ‘value’ etc. for
instance, makes much more sense than variable names like a, e, and v.

• We use all lowercase letters when creating one-word variable name. It's preferable(and in practice) to use
physics rather than PHYSICS or pHYSICS.

Cracking the Coding Interview in C++ - Foundation


Topic 2: C++ Identifiers
C++ identifier is a name given to a package, class, interface, method, or variable. All identifiers must have different
names.

In C++, there are a few points to remember while dealing with identifiers :

• Rule 1 − All identifiers should begin with a letter (A to Z or a to z), $ and and must be unique.

• Rule 2 − After the first character/letter, identifiers can have any combination of characters.

• Rule 3 − A keyword cannot be used as an identifier.

• Rule 4 − The identifiers are case sensitive.

• Rule 5 – Whitespaces are not permitted.

Examples of legal identifiers: rank, $name, _rate, __2_mark.

Examples of illegal identifiers: 102pqr, -name.

These variables, identifiers etc. consume memory units. Before proceeding ahead, let us have a look at the memory
unit concept too. Here, we will only focus on the relevant concept of memory.

Basic Memory units:


It refers to the amount of memory or storage used to measure data.

Basic memory units are:


1. Bit
A bit (binary digit 0 or 1) is the smallest unit of data that a computer can process and store.
Symbols 0 and 1 are known as bits. Here, 0 indicates the passive state of signal and 1 indicates the active state
of signal.
At a time, a bit can store only one value i.e 0 or 1. To have a greater range of value, we combine multiple bits.

2. Byte
A byte is a unit of memory/ data that is equal to 8 bits.
You may think of a byte as one letter. For example, the letter 'f' is one byte or eight bits.

The bigger units are :

3. Kilobyte
A Kilobyte is a unit of memory data equal to 1024 bytes.

4. Megabyte
A Megabyte is a unit of memory data equal to 1024 kilobytes.

Cracking the Coding Interview in C++ - Foundation


5. Gigabyte
A Gigabyte is a unit of memory data equal to 1024 Megabytes.

Lets us now move to the most important concept - data type

Topic 3: C++ Data Types


Data types specify the different sizes and values that can be stored in the variable. Based on the data type of a
variable, the operating system allocates memory and decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, we can store integers, decimals, or characters in these
variables.

Data types in C++ are categorized in three groups: Built-in (Primary), User-defined and Derived.

Data Types in C / C++

Primary Derived User Defined

- Integer - Function - Class

- Character - Array - Structure

- Boolean - Pointer - Union

- Floating Point - Reference - Enum

- Double Floating Point - Typedef

- Void

- Wide Character

Here we will discuss primary data types only.

Cracking the Coding Interview in C++ - Foundation


1. C++ int
• The int keyword is used to indicate integers.
• Its size is usually 4 bytes. Meaning, values can be stored from -2147483648 to 2147483647.
• For example: int rate=40;

2. C++ char
• This data type is used to store a single character.
• Size of char is 1 byte.
• Characters in C++ are enclosed inside single quotes ' '.
• For example: char symbol='a'

3. C++ bool
• A boolean data type is declared with the bool keyword.
• The bool data type has one of two possible values: true or false.
• For example bool flag=false;

4. C++ float
• Float is used to store floating point numbers (decimals and exponentials).
• The size of the float is 4 bytes.
• In general, 7 decimal digits precision.
• For example: float rate=40.50;

5. C++ double
• Double is used to store floating-point numbers (decimals and exponentials).
• The size of the double is 8 bytes. Hence, double has two times the precision of float.
• In general, 15 decimal digits precision.
• For example: double rate=40.6543444;

6. C++ void
• The void keyword means "nothing" or "no value".
• Void will be used in functions and pointers.
• Variables of the void type can’t be declared.

7. C++ wchar_t
• Wide character wchar_t is similar to the char data type, except its size is 2 bytes instead of 1.

Note: C++ String Data Types


• This data type is used to store a sequence of characters (text).
• This is not a built-in data type.
• String values must be surrounded by double quotes:
• For example string name= "Ramesh";

Now that we have learnt all the relevant concepts, let us go ahead and write our very first program!

Cracking the Coding Interview in C++ - Foundation


Topic 4: C++ Output/Display Program
// C++ program to display “Hello World in C++”:

#include <iostream>

using namespace std;

int main()

// prints hello world in C++

cout << "Hello World in C++";

Output: Hello World in C++

How Does this Programme Work?


• // C++ program to display “Hello World in C++”: This is a comment line. A comment is used for displaying
additional information about the program. It does not contain any programming logic. When a comment is
encountered by the compiler, that line or part of code is skipped by the compiler. Any line beginning with ‘//’
without quotes OR in between /*…*/ in C++ is a comment.

• In C++, all lines that start with a pound or hashtag(#) sign are called directives and are processed by a
preprocessor which is a program invoked by the compiler. The #include directive tells the C++ preprocessor
to include contents of the file specified in input stream to the compiler and then continue with the rest of the
original file. #include<iostream> tells the preprocessor to include the iostream header file(file that has some
already pre-written code which we are importing to avoid reinventing the wheel) in the program and
iostream is the header file which contains all the basic functions of the program like input/output etc.

• Using namespace std is used to define which input/output form is going to be used. (Explained in the forth-
coming lectures).

• int main():This line is used to declare a function having the name “main” whose return type is integer. Every
C++ program’s execution begins with the main() function, no matter where the function is located in the
program. So,it’s necessary for every C++ program to have a main() function.

• cout<<“Hello World in C++”;: This line instructs the compiler to display the message “Hello World in C++” on
the screen.

Note 1: In C++ every statement should be terminated with semicolon (;) for execution.

Note 2: In C++, we can use endl or \n to insert new lines in the output data stream.

Cracking the Coding Interview in C++ - Foundation


Additional information:
Like cout we also use printf() function that comes from the C language. C++ printf prototype defined under
<cstdio> header file is:
int printf(const char * format, ...)
When you use the printf() function, it prints the string pointed out by the format to the standard output stdout.
The format can also contain some specifiers that start with a % and replace values of variables with the
printf() function.

Example:
#include <iostream>

using namespace std;

int main()

// prints hello world in C++

printf("Hello World in C++");

Output: Hello World in C++

Example:
cout<<"Physics"<<"Wallah";

Output: PhysicsWallah

cout<<"Physics"<<endl<<"Wallah";

Output: Physics
Wallah

Cracking the Coding Interview in C++ - Foundation


Topic 5: Taking input from the user
We have already learnt that cout is used to output (print) values. Now let us explore the abilities of C++ which
will allow us to get input from users. This can be done using cin.
cin is a predefined object that reads data from the user with the extraction operator (>>) (like scanf is used in
case of C language).
In the following example, the user can input a number, which is stored in the variable x. Then we will print the
value of x:

Example:
int num;

cout << "Enter any number "; // Type a number and press enter

cin >> num; // Get user input from the keyboard

cout << "Entered number is: " << num; // Display the input value

Example: The user is asked to enter two integers and their sum is
displayed

#include <iostream>

using namespace std;

int main() {

int n1, n2, sum;

cout << "Enter two numbers: ";

cin >> n1 >> n2;

// sum of two numbers is stored in variable sum

sum = n1 + n2;

// prints sum

cout << sum <<endl;

return 0;

Run these examples on your system and check for outputs.

Congratulations! You are officially a programmer now !

Cracking the Coding Interview in C++ - Foundation


Lets now test our understanding so far :

MCQs
Q1. What will be the output of the following code?

#include <iostream>

using namespace std;

int main(){

cout << "physics" << "wallah";

a) physics wallah b) physicswallah

Ans: b) physicswallah
Explanation:
The text will be printed exactly like we place the text inside double quotes. So first we are printing "physics".
After printing, our cursor will be right next to the 's' of "physics". So "wallah" will be printed right next to the
"physics" without any spaces between them.

Q2. Which of the following data types can store the longest decimal number?

a) boolean b) double
c) float d) long

Ans: b) double
Explanation:
Out of all given options, only float and double can hold decimal numbers and double is the longest data type to
store floating-point values.

Q3. Which of the following cannot be stored in character data type?

a) Special symbols b) Letter


c) String d) Digit

Ans: c) String
Explanation:
String is a collection of characters and is stored in a variable of String data type.

Cracking the Coding Interview in C++ - Foundation


Q4. Number of digits upto which precision value of float data type is valid?

a) Upto 7 digit b) Upto 8 digit


c) Upto 9 digit d) Upto 6 digit

Ans: a) Upto 7 digit

Upcoming Class Teasers


• C++ Operators

Cracking the Coding Interview in C++ - Foundation


C++
Variables and Data Types

Assignment Solutions
Assignment Solutions

Q1 - Take 2 integer values in two variables x and y and print their product.

#include <iostream>

using namespace std;

int main()

int x = 23;

int y = 50;

cout << x*y << endl;

return 0;

Q2 - Print the ASCII value of character ‘U’.

#include <iostream>

using namespace std;

int main()

cout << "ASCII value of u is " << (int)'U' << endl;

return 0;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q3 - Write a C++ program to take length and breadth of a rectangle and print its area.

#include <iostream>

using namespace std;

int main()

int length=10;

int breadth=20;

cout <<"Lenght "<< length << endl;

cout<< "Breadth" << breadth << endl;

int area = length*breadth;

cout << "Area is " << area << endl;

return 0;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q4 - Write a C++ program to calculate the cube of a number.

#include <iostream>

using namespace std;

int main()

int x = 2;

int cube;

cout << "number is "<< x<<endl ;

cout <<"cube of the number is "<< x*x*x << endl;

return 0;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q5 - Write a C++ program to find size of basic data types.

#include <iostream>

using namespace std;

int main()

cout << "\nSize of fundamental data types :\n";

cout << " The sizeof(char) : " << sizeof(char) << " bytes \n" ;

cout << " The sizeof(short) : " << sizeof(short) << " bytes \n" ;

cout << " The sizeof(int) : " << sizeof(int) << " bytes \n" ;

cout << " The sizeof(long): " << sizeof(long) << " bytes \n" ;

cout << " The sizeof(long long) :" << sizeof(long long) << " bytes \n";

cout << " The sizeof(float) :" << sizeof(float) << " bytes \n" ;

cout << " The sizeof(double) :" << sizeof(double) << " bytes \n";

cout << " The sizeof(long double) :" << sizeof(long double) << " bytes \n";

cout << " The sizeof(bool) : " << sizeof(bool) << " bytes \n\n";

return 0;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q6 - Write a C++ program to swap two numbers with the help of a third variable.

#include <iostream>

using namespace std;

int main()

cout << "\n\n Swap two numbers :\n";

cout << "-----------------------\n";

int n1 = 2, n2 = 5, temp;

cout << " Before swapping the 1st number is : "<< n1 <<"\n" ;

cout << " Before swapping the 2nd number is : "<< n2 <<"\n" ;

temp=n2;

n2=n1;

n1=temp;

cout << " After swapping the 1st number is : "<< n1 <<"\n" ;

cout << " After swapping the 2nd number is : "<< n2 <<"\n" ;

Cracking the Coding Interview in C++ - Foundation


Lesson :

C++ Operators
Pre-Requisites:
• C++ basic syntax
• Data types
• Variables
• Identifiers
• Keywords

List of Concepts Involved:


• C++ Operators
• C++ operators precedence and their associativity

Topic : C++ Operators


Operators are the symbols that are used to perform pre-defined operations on variables and values
(commonly referred to as operands). As soon as the compiler encounters an operator, it performs the
specific mathematical or logical operation and returns the result.

Let us learn and understand about the relevant operators in detail.

Operators in C++ can be classified into 6 types:


1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Misc Operators

1. C++ Arithmetic Operators:


Arithmetic operators are used in mathematical expressions in a program. They function in the same way
as they do in algebra.

Following table lists the arithmetic operators:


Assume integer variable num1 holds a value of 20, variable num2 holds a value of 30 and num3 holds a
value of 40, then:

Cracking the Coding Interview in C++ - Foundation


Operator Description and Example
+ Addition Adds values on either side of the operator.
Example : num1 + num2 will give (20+30) that is 50

- Subtraction Subtracts the value of right-hand operand from the value of left-hand operand
Example : num1 - num2 will give (20-30) that is -10

* Multiplication Multiplies the values on either side of the operator


Example : num1 * num2 will give (20x30) that is 600

/ Division Divides left-hand operand by right-hand operand


Example : num3 / num1 will give (40/20) that is 2

% Modulus Divides left-hand operand by right-hand operand and returns remainder


Example : num2 % num1 will give (30%20) that is 10 (remainder, when 30 is
divided by 20)

Example: We can use the modulus operator for checking whether a number is
odd or even; if after dividing the number by 2 we get 0 as remainder
(number%2 == 0) then it is an even number otherwise it is an odd number.
int main() {
int a;
cin >> a;
if (a % 2 == 0)
{
cout << "even no";
}
else
{
cout << "odd no";
}

return 0;
}

++ Increment This is known as the pre-increment operator and it increases the value of
operand by 1
Example : num2++ will give (30+1) that is 31

-- Decrement This is known as the pre-decrement operator and it decreases the value of
operand by 1
Example : num1-- will give (20-1) that is 19

Let us now write a simple program to implement all the operators.You may try it yourself too !

Cracking the Coding Interview in C++ - Foundation


Example:
#include<iostream>

using namespace std;

int main(){

// declare variables p and q

int p = 20, q = 10;

int result;

// addition operator

result=p+q;

cout<<(result);

// subtraction operator

cout<<(p - q);

/*we can directly perform subtraction in print statement,no need to use result variable here*/

// multiplication operator

cout<<(p * q);

// division operator

cout<<(p / q);

// modulo operator

cout<<(p % q);

Output: 30
10
200
2
0

Note 1: When we divide two integers, if the dividend is not exactly divisible by the divisor, the division operator
returns only quotient and the remainder is discarded.

Cracking the Coding Interview in C++ - Foundation


Example:
#include<iostream>

using namespace std;

int main() {

int num1 = 26;

int num2 = 8;

int div = num1 / num2;

cout << div << endl;

Output: 3
Note 2: In case when dividend and divisor are floating point numbers, the division operator divides dividend by
divisor till the full precision of floating point number.

Example:
#include<iostream>

using namespace std;

int main() {

int num1 = 26.0;

int num2 = 8.0;

int div = num1 / num2;

cout << div << endl;

Output: 3.25

Note 3: In case either dividend or divisor is a floating point number, the division operator divides dividend
by divisor until the full precision of the floating point number.

Cracking the Coding Interview in C++ - Foundation


Example:
#include<iostream>
using namespace std;
int main()
{
float num1=26.5;
int num2=8;
cout<<num2/num1;
return 0;
}

Output: 0.301887

Note 4: floor(a) : Returns the largest integer that is smaller than or equal to a. Example floor(5.6) will return 5.
ceil(a) : Returns the smallest integer that is greater than or equal to a.
Example ceil(2.5) will return 3.

Topic : C++ Relational Operators


Operator Description Example
== Is Equal To 4 == 5 returns false

!= Not Equal To 1!= 5 returns true

> Greater Than 1 > 5 returns false

< Less Than 2 < 5 returns true

>= Greater Than or Equal To 4 >= 5 returns false

<= Less Than or Equal To 1 <= 5 returns true

Cracking the Coding Interview in C++ - Foundation


#include<iostream>

using namespace std;

int main()

// create variables

int p = 10, q = 15;

// == operator

cout<<(p == q); // false

// != operator

cout<<(p != q); // true

// > operator

cout<<(p > q); // false

// < operator

cout<<(p < q); // true

// >= operator

cout<<(p >= q); // false

// <= operator

cout<<(p <= q); // true

Output: false
true
false
true
false
true

Topic : C++ Logical Operators


Logical operators are used for decision making. This class of operators is used to check whether an expression is
true or false. Some of the commonly used logical operators are mentioned in the table below.

Cracking the Coding Interview in C++ - Foundation


Operator Example Meaning
&& (Logical AND) expression1 && expression2 true only if both expression1 and
expression2 are true

|| (Logical OR) expression1 || expression2 true if either expression1 or


expression2 is true

! (Logical NOT) !expression true if expression is false and


vice versa

Let us look at the following program to understand it better.

Example code:
#include<iostream>

using namespace std;

int main(){

// && operator

int p=15,q=10,r=5;

cout<<((p > q) && (p > r)); // true

cout<<((p > q) && (p < r)); // false

// || operator

cout<<((r < q) || (p < q)); // true

cout<<((p > q) || (q > r)); // true

cout<<((p < q) || (p < r)); // false

// ! operator

cout<<(!(p == q)); // true

cout<<(!(p > q)); // false

Cracking the Coding Interview in C++ - Foundation


Output: true
false
true
true
false
true
false

Imp: The concept of short-circuiting in boolean expression


Short-circuiting happens when the evaluation of an expression stops as soon as its outcome is determined.
For instance:

if (p == q || r == s || t == u) { // Do something }

Here,if p == q is true, then r == s and t == u are never evaluated because the expression's outcome has already
been determined and remains unaffected by the further comparisons. But, if p == q is false, then r == s is
evaluated and if (r==s) is true, then t == u is never evaluated.

4. C++ assignment operators


The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer
element given by its left-hand operand. Confused? Don’t worry, we have you covered here.

Let's have a look at some of the commonly used assignment operators available in C++ with examples.

Operator Example Equivalent to


= p = q; p = q;

+= p += q; p = p + q;

-= p -= q; p = p - q;

*= p *= q; p = p * q;

/= p /= q; p = p / q;

%= p %= q; p = p % q;

Try out the following example for better understanding.

Cracking the Coding Interview in C++ - Foundation


Example
#include<iostream>
using namespace std;

int main(){

int p = 10;
int q;

// assign value using =


q = p;
cout<<(q); // value of q is 10

// assign value using =+


q += p;
cout<<(q); // value of q is 20

// assign value using =*


q *= p;
cout<<(q); // value of q is 200
}
}

Output: 10
20
200

Question: Is there any performance difference between x+=y and x=x+y?

Solution: Yes, x+=y performs better than x=x+y.


Eg. x += 10 means

• Find the place identified by x


• Add 10 to it

Cracking the Coding Interview in C++ - Foundation


And x = x + 10 means:
• Evaluate x+10
• Find the place(memory) identified by the variable x
• Copy x into an accumulator (accumulator is a part of CPU for temporary storage)
• Add 10 to the accumulator
• Store the result in variable x
• Find the place (memory) identified by x
• Copy the accumulator(result) to it

Clearly x=+10 is better than x=x+10 since evaluation is direct with no intermediate steps for CPU to perform.

Let us look at the next class of operators.

5. C++ Bitwise operators


Operator Description
~ Bitwise Complement

<< Left Shift

>> Right Shift

>>> Unsigned Right Shift

& Bitwise AND

^ Bitwise exclusive OR
Let's look at a simple code to understand the working of these operators.

Example
#include<iostream>
using namespace std;
int main(){
// initialize p
int p = 5;
cout<<(p<<2);
// Shifting the value of p towards the left two positions
}
}

Output: 20

Cracking the Coding Interview in C++ - Foundation


Explanation:
Shifting the value of p towards the left (two positions) will make the leftmost 2 bits to be lost. Hence, the value of
p becomes 5.
The binary representation of 5 is 00000101(we will learn about this conversion in the forthcoming lecture).
After 2 left shifts, binary representation of p will be 00010100 which is equivalent to 20.

Note : Left shifting an integer “p” with an integer “q” denoted as ‘(p<<q)’ is equivalent to multiplying p with
2^q (2 raised to power q).
Left shifting an integer “p” with an integer “q” denoted as ‘(p<<q)’ is equivalent to multiplying p with
2^q (2 raised to power q).

Example:
Let's take p=22; which is 00010110 in Binary Form (We will learn about it in the next lecture).
If “p is left-shifted by 2” i.e p=p<<2 then p will become 01011000.
p=p*(2^2) will give, p=22*(2^2)= 22*4=88 which can be written as 01011000.
Let us now look into the next category of operators.

6. Miscellaneous Operators
The following table lists some of the miscellaneous operators that C++ supports.

Sr.No Operator & Description


1 sizeof
This operator is used to compute the size of a variable. For example, sizeof(p), where ‘p’
is integer, will return 4.

2 Condition ? Expression1 : Expression2


Conditional operator (?). If Condition is true then it returns the value of Expression1 otherwise
it returns the value of Expression2.
Let's try this example for clarity.
#include<iostream>

using namespace std;

int main()

{ // variable declaration

int a = 20, b = 30, c;

// Largest among a and b

c = (a > b) ? a : b;

// Print the largest number

cout << "Largest number between a and b is "<< c << endl;

return 0;

Cracking the Coding Interview in C++ - Foundation


,
3
Comma operator is a binary operator. The value of the entire comma expression is actually
the value of the last expression of the comma-separated list.

4 . (dot) and -> (arrow)


Member operators are used to reference individual members of classes, structures, and unions.
The dot operator is used for the actual object. The arrow operator is used with a pointer to
an object.

5 Cast
Casting operators convert one data type to another. For example, int(4.3000) would return 4
(i.e. a float number here is converted into int)

6 &
Address-of operator & returns the memory address of a variable. For example &p; will give the
actual memory address of the variable p.

7 *
Pointer operator * points to a variable. For example *p; will point to the variable p.

Let us now learn about the most dynamic operators.

C++ Unary Operators:


Interestingly, unlike the normal operators seen so far, C++ unary operators need only one operand to perform
operations like increment, decrement, negation, etc.
The table below will help you understand it in a better way.

Operator Meaning
+ Unary plus: optional; since numbers are by default positive.

- Unary minus: inverts the sign of an expression

++ Increment operator: increments value by 1

-- Decrement operator: decrements value by 1

! Logical complement operator: inverts the value of a boolean

Cracking the Coding Interview in C++ - Foundation


Example:
#include<iostream>
using namespace std;
int main()
{
// initialize p
int p = 5;
cout<<("Post-Increment Operator");
cout<<(p++); // 5
// p's value is incremented to 6 after returning
// current value i.e; 5
int q = 5;
cout<<("Pre-Increment Operator");
cout<<(++q); //6
// q is incremented to 6 and then it's value is returned
}

Output: Post-Increment Operator 5


Pre-Increment Operator 6

Now that we have learnt about all types of operators, let us explore the precedence/priority of each of these wrt
each other in different scenarios.

Topic : C++ Operator Precedence and Associativity


Operator precedence determines the order/sequence of evaluation of operators in an expression (analogous
to BODMAS concept in maths).

Take a look at the statement below:


int ans = 10 - 4 * 2;
What will be the value of variable ans? Will it be (10 - 4)*2, that is, 12? Or 10 - (4 * 2), that is, 2?
When two operators share a common operand (4 in this case), the operator with the highest precedence is
operated upon first. In C++, the precedence of * is higher than that of -. Hence, multiplication is performed
before subtraction, and hence the final value of the variable ans will be 2.

Cracking the Coding Interview in C++ - Foundation


Associativity of Operators in C++
A question arises here, what if the precedence of all operators in an expression is same? In that case, the
concept of associativity comes into picture.

Associativity specifies the order in which operators are evaluated by the compiler, which can be left to right
or right to left. For example, in the phrase p = q = r = 10, the assignment operator is used from right to left. It
means that the value 10 is assigned to r, then r is assigned to q, and at last, q is assigned to p. This phrase can
be parenthesized as (p = (q = (r = 10)).

Operator Precedence in C++ (Highest to Lowest)

Category Operators Associativity


Postfix ++, - - Left to right

Unary +, -, !, ~, ++, - - 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

Let us try a few questions on precedence and associativity to clear the air of confusion.

Cracking the Coding Interview in C++ - Foundation


Example: 1
Let us say we have 4 variables of type int ; p,q,r,s
Then, s = p-++r-++q;
is equivalent to
Ans: s = p-(++r)-(++q);
Explanation:
The operator precedence of prefix ++ is higher than that of - subtraction operator.

Example: 2
What does the following code fragment print?
cout<<(4 + 2 + "pqr");
cout<<("pqr" + 4 + 2);

Ans: 6pqr and pqr42, respectively.


Explanation:
The + operator is left-to-right associative, whether it is string concatenation or simple number addition.

Example: 3
What is the result of the following code fragment?
boolean p = false;
boolean q = false;
boolean r = true;
cout<<(p == q == r);
Ans: It prints true.
Explanation:
The equality operator is left-to-right associative, so p == q evaluates to true and this result is compared to r,
which again yields true.

Example: 4
#include<iostream>
using namespace std;
int main()
{
int p = 5, q = 10;
p += q -= p;
cout<<p<<" "<<q<<endl;
return 0;
}

Cracking the Coding Interview in C++ - Foundation


Ans: 10 5
Explanation:
Associativity of assignment operators if from right to left.

That is all for this lecture. Keep learning, keep exploring!

Upcoming Class Teasers


• C++ conditional statements
• if/else
• switch

Cracking the Coding Interview in C++ - Foundation


C++ Operators

Assignment Solutions
Assignment Solutions

Q1 - Write a program to check whether two numbers (entered by user) are equal or not (0 for not equal, 1
for equal)

#include <iostream>

using namespace std;

int main()

int x,y;

cout<<"Enter the first number ";

cin >> x;

cout<<"Enter the second number ";

cin >> y;

cout << (x == y) ? 1:0 ;

return 0;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q2 - Write a program to take the values of two variables a and b from the keyboard and then check if both the
conditions 'a < 50' and 'a < b' are true.

#include <iostream>

using namespace std;

int main()

int a,b;

cout << "Enter the first number : ";

cin >> a;

cout << "Enter the second number : ";

cin >> b;

cout<< ((a < 50) && (a < b))?1:0;

return 0;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q3 - There are 45 total pupils in the class, 25 of whom are boys. Write a program to find how many girls
received grades "A" if 17 boys made up 80% of the students that received grades "A".

#include <iostream>

using namespace std;

int main()

int total, boys, girls;

boys = 17;

total = (80*45)/100; //total students getting grade A

girls = total - boys; //total number of girls getting grade A

cout << "Number of girls getting grade A = " << girls << endl;

return 0;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q4 - Write a program to calculate the sum of the first and the second last digit of a 5 digit number.

#include <iostream>
using namespace std;

int main()
{
int n, first, second, third, fourth, fifth, sum;
n = 12345;
/*Take out each digit of this number and then finally add the first and the second last digits*/
first = n/10000; //first digit
n = n%10000;
second = n/1000; //second digit
n = n%1000;
third = n/100; //third digit
n = n%100;
fourth = n/10; //fourth digit
fifth = n%10; //fifth digit

sum = first + fourth;


cout << "sum of first and fourth digit is: " << sum << endl;
return 0;
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q5 - write a program to calculate the sum of digits of a 3 digit number.

#include <iostream>
using namespace std;

int main()
{
int n, first, second, third,sum;
n = 524;
/*Take out each digit of this number and then finally add the digits*/
first = n/100; //first digit
n = n%100;
second = n/10; //second digit
third = n%10; //third digit

sum = first + second + third;


cout << "sum of 3 digits is: " << sum << endl;
return 0;
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q6 - Design a calculator to perform basic arithmetic operations (+,-,/,*)

# include <iostream>
using namespace std;

int main() {

float num1, num2;


cout << "Enter the first number ";
cin >> num1;
cout << "Enter the second number ";
cin >> num2;
cout << "Sum = " << num1 + num2<<endl;
cout <<"Difference = " << num1 - num2<<endl;
cout <<"Product = " << num1 * num2<<endl;
cout << "Division = " << num1 / num2<<endl;
return 0;
}

Cracking the Coding Interview in C++ - Foundation


Lesson:

Conditionals
Pre-Requisites
• Basic C++ syntax
• Data types, variables, keywords
• Operators
List of Concepts Involved
• If-statement
• If-else statment
• If-else if statement
• Nested if-else statement
• Conditional operators
• Switch statement
In real life we often encounter situations where our actions are governed by some sort of conditions.
For instance, if the weather is rainy, we carry an umbrella. Here carrying an umbrella is an action which
is performed only when the condition of the weather being rainy is fulfilled.

In programming, this kind of scenario is handled with the help of conditional statements.
Let us have a look at the different conditional statements supported by C++.

Topic 1: If statement
An if statement is the most common conditional statement. It executes when the condition being checked
evaluates to true.

Syntax
if (condition)

statements;

Let us look at this simple example


if(marks > 80)

cout << “Pass\n”;

Cracking the Coding Interview in C++ - Foundation


Case 1: marks = 85
Output: Pass
Explanation
Since the marks is greater than 80 i.e. the condition inside ‘if’ parentheses is true, we get “Pass” printed
in the output.

Case 2: marks = 70
Output : No output
Explanation
Since the marks is not greater than 80 i.e. the condition inside if parentheses is false, the statement inside
the if block is skipped/not executed i.e. we get nothing printed in the output.

Let us now look at the variation of if statement i.e. if-else.

Topic 2: If-else statement


Sometimes, we encounter situations where we have to choose between two options. For example, if it's
Tuesday I’ll eat a veg burger otherwise I’ll eat a non-veg burger.
An if-else statement is designed to give this functionality in our code. It executes statements if some
condition is true or false. If the condition is true, the if part is executed, otherwise the else part of the
statement is executed.

Syntax
if (condition)

statement - 1

} else

statement - 2

Cracking the Coding Interview in C++ - Foundation


Let us understand it with the help of the following example
To illustrate the working of an if-else statement, we can create a grading system. We’ll assume that the score
ranges between 0 to 100(both inclusive). A score above 33 gets a “Pass” verdict, otherwise it’s “Fail”.

To solve this problem, we can use an if-else statement. Lets see how !

if (score > 33)

cout << “Pass\n”;

else

cout << “Fail\n”;

Case 1: Score = 60
Output: Pass
Explanation
Since the score is more than 33 i.e. the condition inside ‘if’ parentheses is true, we get “Pass” printed.

Case 2: Score = 20
Output: Fail
Explanation
Since the score is not more than 33 i.e. the condition inside ’if’ parentheses is false,
we get “Fail” printed.

Try these:
1. Find if the input value is odd or even. If it’s odd print “Odd”, otherwise print “Even”.
Note: Input value will be between 1 and 106.

2. Find if the input character is ‘a’ or not.


Note: Input characters Would be lowercase alphabets.

There is another variation of if statement. Let us explore.

Cracking the Coding Interview in C++ - Foundation


Topic 3: If-else if statement
It works on the same principle as if-else statement,however,here we can have multiple conditions. If the condi-
tion inside the if block is true, then the code/ statement inside if block will be executed, if it is false, the control
will move to the else-if block and will check if it is true and execute the statement in the else-if block. When the
condition in else-if block is false, it will execute the statements in the final else block.

We can have multiple else-if blocks too.

Syntax
if (condition - 1)

statement - 1

else if (condition - 2)

statement - 2

else

statement - 3

Let us try to solve the example below


To implement if else-if, we can further expand our grading system problem. Apart from pass and fail now it
will give grades based on the score.

Grade Score
A 80-100

B 60-80

C 40-60

D <40

Cracking the Coding Interview in C++ - Foundation


To solve this problem, we can use an if - else if - else statement to execute different actions depending
upon the score:
if(score > 80)

cout << “A\n”;

else if (score > 60)

cout << “B\n”;

else if (score > 40)

cout << “C\n”;

else

cout << “D\n”;

Case 1: Score = 81
Output : A
Explanation
Since the score is more than 80 i.e. the condition inside if parentheses is true “A” gets printed.

Case 2: Score = 61
Output : B
Explanation
Since the score is less than 80, the first block is skipped and since it is more than 60 i.e.
the condition inside else-if parentheses is true, “B” gets printed.

Case 3: Score = 41
Output : C
Explanation
Since the score is 41, the first 2 blocks are skipped and then the condition for the third
block is checked. It turns out that it is true, so “C” gets printed and the rest is skipped.

Cracking the Coding Interview in C++ - Foundation


Case 4: Score = 21
Output : D
Explanation
Since all the conditions are false, the else-block will execute and we get “D” as output.

Try these
1. Write a program to identify people as “Child” (age < 12), “Teenager” (12 <= age < 18) or “Adult” (age >= 18).

2. Print the maximum of 3 numbers a, b, c taken as input.

Let us now increase the dimension and abilities of if and explore the concept of nested if-else statements.

Topic 4: Nested if-else


It is simply an if-else statement inside another if-else statement.

Syntax
if (condition - 1)

if (condition - 2)

statement - 1

else

statement - 2

else

statement - 3

Cracking the Coding Interview in C++ - Foundation


Consider the following scenario :
if (score > 33)

if(marks > 80)

cout << “Gracefully ”;

cout << “Pass\n”;

else

cout << “Fail\n”;

Note: Watch the curly braces { }

Input: Score=30
Output: Fail

Input : Score=90
Output : Gracefully pass

Input : Score=60
Output : Pass
Operators that assist in the functioning of conditional statements by proper and accurate condition
checks are known as conditional operators. We have already seen a few in the previous lecture but it
deserves a mention here too. So, let us learn more about them.

Cracking the Coding Interview in C++ - Foundation


Topic 5: Conditional operators
These operators are used when a condition comprises of more than one boolean expression/ condition
check. For instance, if we want to print a number only if it is greater than 2 and less than 5, then we will use
conditional operators to combine the 2 expressions. We have 3 types of conditional operators - logical-and,
logical-or and ternary operator.

a. Logical-and operator (&&)


It is used when we want the condition to be true if both the expressions are true.

Syntax
if(condition - 1 && condition - 2)

statement;

Let us look at this example


Print the number if the input value is greater than 5 and less than 10.

if (val > 5 && val < 10)

cout << val << ‘\n’;

Case 1: val = 3
Output: No output
Explanation
The input value is less than 10 but it is not greater than 5.

Case 2: val = 7
Output: 7
Explanation
The input value is both less than 10 and greater than 5.

Case 3: val = 13
Output: No output
Explanation
The input value is greater than 5 but it is not less than 10.

Cracking the Coding Interview in C++ - Foundation


Common misconception: ‘&’ v/s ‘&&’
& -> compares bitwise
&& -> logical and

The first one (&) parses through all the conditions, despite their evaluation as true or false. However, the latter
traverses through the second condition only if the first condition is evaluated as true, otherwise it negates the
entire condition. For instance,

cout << (false & 5/0==2);

It gives us a runtime error since 5 is divided by 0, which isn't a valid operation. However, if we write-

cout << (false && 5/0==2);

we get “false” as the output. This is because our first condition is false, which is enough to make the entire
condition false here.

Tip: Always use parentheses around every condition.

Try this:
Write a program to print the value of input if it is even and divisible by 3.

b. Logical-or operator (||)


This operator is used when any one of the boolean expressions is evaluated as true.

Syntax
if(condition - 1 || condition - 2)

statement;

Let us look at this example:


Print the number if the input value is greater than 10 or less than 5.

Code
if (val < 5 || val > 10)

cout << val;

Cracking the Coding Interview in C++ - Foundation


Case 1: val = 3
Output: 3
Explanation
The input value is less than 5. This is enough to satisfy the condition so the second condition won't be tested
and val will be printed.

Case 2 : val = 7
Output: No output
Explanation
Both the conditions are evaluated as false.

Case 3: val = 13
Output: 13
Explanation
The input value is not smaller than 5 but it is greater than 10. So, all in all, it will be evaluated as true.

Try this
Write a program to print the value of input if it is divisible by 3 or 5.

Common misconception: ‘|’ v/s ‘||’


| -> compares bitwise
|| -> logical or

The first one parses through all the conditions, despite their evaluation as true or false. However, the latter
traverses through the second condition only if the first condition is evaluated as false, otherwise it validates
the entire condition. For instance,

cout << (true | 5/0==2);

It gives a runtime error since 5 is being divided by 0, which isn't a valid operation. However, if we write-

cout << (true || 5/0==2);

We get “true” as the output. This is because our first condition is true, which is enough to make the entire
condition true in case of logical or.

Cracking the Coding Interview in C++ - Foundation


Ternary operator (?:)
It is a smaller version for the if-else statement. If the condition is true then statement - 1 is executed else the
statement - 2 is executed.

Syntax
condition ? statement - 1 : statement - 2;

Let us have a look at this example:

Without ternary operator


if (val % 2 == 1)
{
cout << “Value entered is odd\n”;
}
else
{
cout << “Value entered is even\n”;
}

With ternary operator


val % 2 == 1 ? cout << “Value entered is odd\n”; : cout << “Value entered is even\n”;

Case 1: val = 1
Output (without ternary operator) - Value entered is odd
Output (with ternary operator) - Value entered is odd

Case 2: val = 2
Output (without ternary operator) - Value entered is odd
Output (with ternary operator) - Value entered is odd

Cracking the Coding Interview in C++ - Foundation


Try these
1. Write a short program that gives the following as output -
For each multiple of 3, print "Fizz" instead of the number.
For each multiple of 5, print "Buzz" instead of the number.
For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
Otherwise print the number itself.
2. Write a short program that prints each number from 1 to 100 on a new line, except if the number
is a multiple of 5 or 7.
We have now reached to the final conditional statement viz switch case. This renders the program to look
extremely neat and organized. Let us learn more about it.

Topic 6: Switch statement


Assume we have a variable and we want to do multiple operations on it based upon the value it stores.
In such cases the switch statements are the most convenient and useful concept.

It is like an if-else ladder with multiple conditions, where we check for equality of a variable with different
values.

It works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and
Long.

Syntax
switch (expression)

case x:

// code

break;

case y:

// code

break;

default:

// code

Note: The case value must be literal or constant, and must be unique.

Cracking the Coding Interview in C++ - Foundation


Let us look at this example:
Write a program using switch statements to check if the input lowercase character is vowel or consonant.

Code

switch (ch) {

case ‘a’:

cout << “Vowel\n”;

break;

case ‘e’:

cout << “Vowel\n”;

break;

case ‘i’:

cout << “Vowel\n”;

break;

case ‘o’:

cout << “Vowel\n”;

break;

case ‘u’:

cout << “Vowel\n”;

break;

default:

cout << “Consonant\n”;

Case 1: ch = ‘e’
Output - Vowel

Case 2: ch = ‘w’
Output - Consonant
‘Break’ is a very important keyword when we are implementing switch statement (we will
explore it in detail in the forthcoming lectures). Lets look at an example where we implement a
logic with and without break statement.

Cracking the Coding Interview in C++ - Foundation


Case 1: Without using Break Statement
int val = 5;

switch (val)

case (5):

cout << "Five\n";

case (6):

cout << "Six\n";

case (7):

cout << "Seven\n";

Output:
Five
Six
Seven

Explanation
Surprised? You did not expect this, did you? Let us see why ?
Here, even when the first case is true, it will keep on executing all the subsequent statements until it
encounters a break statement(which we have not used anywhere). After the break statement, it will break
out of the switch statement.

To get the expected result, lets modify the program a little.

Cracking the Coding Interview in C++ - Foundation


Case 2: Using Break Statement
int val = 6;

switch (val)

case (6):

cout << "Six\n";

break;

case (7):

cout << "Seven\n";

break;

case (8):

cout << "Eight\n";

break;

Output:
Six

Explanation
Using the break keyword here, helped the program to stop executing and come out of the switch
Statement.

Try this
Write a program to print the day name based upon the day number.
1 - Monday, 2 - Tuesday, and so on.

Upcoming Class Teasers


• while loop
• The for loop
• The do-while loop
• Break keyword
• Continue keyword

Cracking the Coding Interview in C++ - Foundation


C++ Conditionals

Assignment Solutions
Assignment Solutions

Q1- Write a program which takes the values of length and breadth from user and check if it is a
square or not.

#include <iostream>

using namespace std;

int main()

int length,breadth;

cout<<"Enter length: "<<endl;

cin>>length;

cout<<"Enter breadth: "<<endl;

cin>>breadth;

if(length==breadth)

cout<<"It is a square"<<endl;

else

cout<<"It is a rectangle"<<endl;

return 0;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q2- Write a program to print absolute value of a number entered by the user.

#include <iostream>

using namespace std;

int main()

int x;

cout<<"Enter a number"<<endl;

cin>>x;

if(x<0)

x = x*(-1);

cout<<"Absolute value is "<<x<<endl;

return 0;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q3- Write a program to take input from user for Cost Price (C.P.) and Selling Price (S.P.) and calculate
Profit or Loss.

#include <iostream>

using namespace std;

int main()

int CP,SP, amt; //Input cost price and selling price of a product

cout<<"Enter cost price: ";

cin>>CP;

cout<<"Enter selling price: ";

cin>>SP;

if(SP > CP)

amt = SP - CP; //Calculate Profit

cout<<"Profit = "<<amt;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

else if(CP > SP)

amt = CP - SP; //Calculate Loss

cout<<"Loss = "<<amt;

else

cout<<"No Profit No Loss."; // Neither profit nor loss

return 0;

Q4- Write a program to print positive number entered by the user, if user enters a negative number,
it is skipped

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

#include <iostream>
using namespace std;

int main() {

int number;

cout << "Enter an integer: ";


cin >> number; // checks if the number is positive
if (number > 0)
cout << "You entered a positive integer: " << number << endl;
else
cout << "The number is negative and skipped ";

return 0;
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q5- Create a calculator using switch statement to perform addition, subtraction, multiplication and division.

#include <iostream>
using namespace std;

int main() {
char op;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> op;
cout << "Enter two numbers: " << endl;
cin >> num1 >> num2;

switch (op) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
cout << "Error! The operator is not correct";
// operator doesn't match with any case constant (+, -, *, /)
break;
}

return 0;
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q6- Write a program to calculate marks to grades . Follow the conversion rule as given below :
#include <iostream>
using namespace std;

int main(){
int marks;
cout<<"Enter Your Marks: ";
cin>>marks;
if (marks >= 90){
cout<<"Your Grade is A+";
}
else if (marks >= 80){
cout<<"Your Grade is A";
}
else if (marks >= 70){
cout<<"Your Grade is B+";
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

else if (marks >= 60){


cout<<"Your Grade is B";
}
else if (marks >= 50){
cout<<"Your Grade is C";
}
else if (marks >= 40){
cout<<"Your Grade is D";
}
else if (marks >= 30){
cout<<"Your Grade is E";
}
else if (marks <= 30){
cout<<"Your Grade is F";
}
else{
cout<<"Enter Valid Marks";
}
return 0;
}

Cracking the Coding Interview in C++ - Foundation


Lesson:

Loops
Pre-Requisites
Basic syntax of C++
Variables
Operators
Conditionals

List of Concepts Involved


Introduction to Iterative statements/Loops
The while loop
The for loop
How to choose between while loop and for loop?
The do-while loop
Break keyword
Continue keyword

Topic: Introduction to Iterative statements/Loops


Are you familiar with the word loop? The simple dictionary meaning of loop is a structure, series, or process, the
end of which is connected to the beginning. The point of focus here is that the beginning and end are
connected.

Pictorially, you can visualize a loop like this

Here, once the loop begins, end will drive start and start will drive end until certain condition to break out of loop
is encountered.

Now that we have understood the simple meaning of loop, let us now move to the computer programming
terms.

In computer programming, a loop is a sequence of instructions continually repeated until a certain condition is
reached.

Cracking the Coding Interview in C++ - Foundation


Assume this scenario, someone comes up to you and says “I want you to give me a program that can give me
all the numbers between 1 and 10000”. In such a situation, writing all the numbers from 1 to 10000 isn’t a feasible
solution. Can you connect the dots now?

Yes, that’s where the concept of loops comes in. Loops help you perform a task repeatedly until a certain
condition is met. In our example, the task would be to print the value of the number, and the till it is less than
10000.

We have the following types of iterative statements -


The while loop
The for loop
The do-while loop

Topic: The while loop


A while loop is a loop that runs through its body, known as a while statement, as long as a predetermined
condition is evaluated as true.

Syntax

while (condition)

statement;

Let us understand the working of while loop with the help of this simple

example -

Q- Print the first 10 natural numbers.

To accomplish this-
We declare a variable ‘i’ which denotes the current number. We initialize it with the value 1 (as you already
know, the first natural number).
In the while loop, we put a condition that makes the loop run till the value of the variable i doesn’t exceed 10.
Finally, we print the value of the variable ‘i’ and then increment it by 1.

Code

int i = 1;

while (i <= 10)

cout << i << “ “;

i = i + 1;

Output - 1 2 3 4 5 6 7 8 9 10

Cracking the Coding Interview in C++ - Foundation


Try these
Print the sum of the first ‘n’ natural numbers using a while loop, where n is the input.
Write a short program that prints each number from 1 to 100 on a new line.

For each multiple of 3, print "Fizz" instead of the number.

For each multiple of 5, print "Buzz" instead of the number.

For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.

Topic: For loop


This is the most widely used loop amongst all.

The advantage of a for loop is we know exactly how many times the loop will execute even before the actual
loop starts executing.

Unlike while loop, in for loop we have 3 parts in the for header.

Syntax:

for (init-statement; condition; final-expression)

statement

// logic

Init-statement: This statement is used to initialize or assign a starting value to a variable which may be altered
over the course of loop (we will see this while solving examples). It is used/referred only once at the start of the
loop.

Condition: This condition serves as a loop control statement. The loop block is executed until the condition
evaluates to true.

Final-expression: It is evaluated after each iteration of the loop. It is generally to update the values of the loop
variables.

Now that we know the use of each of these, lets understand it with an actual loop.

Execution flow of for loop:

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

cout << index << “ “;

Output - 0 1 2 3 4

Here
Init-statement is executed only once at the start of the loop. In this example, index variable is defined and
initialized to 0.
Next, the condition is evaluated. If index is less than 5, the for body is executed. Otherwise, the loop
terminates. If the condition is false in the first iteration itself, then the for body is not executed at all.
If the condition is true, the for body executes. In this case, the for body prints the value of index (the cout
statement).
Finally, the final-expression is evaluated. In this example, index is incremented by 1.

Cracking the Coding Interview in C++ - Foundation


These four steps represent the first iteration of the for loop. Step 1 is executed only once on entry to the loop.
Steps 2, 3, and 4 are repeated until the condition evaluates as false i.e. index becomes equal to 5.

Acceptable alternatives in for loop:

Omitting parts of for loop

In a ‘for’ loop, we can omit any (or all) of init-statement, condition and final-expression.

1. We can omit the init-statement when an initialization is unnecessary. This may be the case when the

variable may have already been declared.

Example-

int index = 0;

for(; index < 5; index++)

cout << index << “ “;

Note that the semicolon is necessary to indicate the absence of init-statement—more precisely, the
semicolon represents a null init-statement.

2. Omitting the condition is equivalent to setting it as true. Because of this, the for loop must have an exit

statement inside the loop. Otherwise, it may lead to a never-ending or infinite loop which is a nightmare for

any processing system.

Example-

for(int index = 0; ; index++) {

statement + code inside the loop must stop the iteration!

3. We can also omit final expression. In such loops, either the condition or the body must do something to

advance the iteration, otherwise the loop will not run any further owing to lack of information.

Example-

for(int index = 0; index < 5; ) {

cout << index << “ “;

index = index + 1;

Note
The above statements can all be omitted together too.
We can also have multiple statements inside the loop.

Let us look at this example to know what we are talking about

for(int i = 0, j = 14; i < 10 && j > 5; i++, j––);

Here, you may see that we are handling two variables, conditions wrt both and final expression, all in one for

loop.

This is why it is the most popular loop of all.

Let us take the same previous example -

Print the first 10 natural numbers.

Cracking the Coding Interview in C++ - Foundation


To accomplish this with a for loop-
We declare and define the int variable ‘i’ (int i=1), but this time we do it as a part of for loop.
We put the condition as i to be less than or equal to 10.
Inside the for loop body, we print the value of ‘i’.
Finally in the final-expression, we increment the value of the variable ‘i’.

Code

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

cout << i << “ “;

Output - 1 2 3 4 5 6 7 8 9 10

Try these using for loop

1. Print the sum of the first 10 natural numbers.

2. Write a short program that prints each number from 1 to 100 on a new line.

For each multiple of 3, print "Fizz" instead of the number.

For each multiple of 5, print "Buzz" instead of the number.

For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.

3. Print the first k multiples of a number n.

Topic: How to choose between while loop and for


loop?
We have a fair knowledge of both the loops viz while and for. The common confusion at this point is, how do we
decide which one to use ? Are both exactly the same or do they have any difference?

The simple answer to this is your own judgement and choice. Each person has different preferences. However,
generally a while loop is used whenever the total number of iterations to be made is unknown. For example,
Use a for loop when you are traversing a data structure like an array( we will learn about arrays in the forth-
coming class).
Use a for loop when you know that loop needs to run ‘n’ number of times.

Whereas,

1. Use a while loop when the termination condition is taking too much time to be checked or the termination

condition is not known beforehand.

2. Use a while loop when you are unsure till when the loop will continue, like while finding the first number

divisible by both 5 and 7.

Let us move to the next looping statement which is seldom used and is a variation of while loop.

Cracking the Coding Interview in C++ - Foundation


Topic: The do-while loop
Unlike while and for loop, do-while loop tests the condition at the end of each execution for the next iteration. In
other words, the loop is executed at least once before the condition is checked. Rest everything is the same as
while loop.

Syntax

do

statement;

} while (condition);

Let us understand it with the help of the following example :

int idx = 15;

do

cout << idx << “ “;

} while (idx < 5);

Output- 15

Explanation- In the above example, when we enter the loop, there will be no condition check. Therefore, we get
15 printed because of the cout statement inside the loop. However, in the next iteration, the program goes
through the condition check mentioned in the while part. This time it will fail and the loop execution will end.

Let us now look at this example, can you guess the output?

int idx = 15;

do {

cout << idx << “ ”;

idx = idx + 1;

} while (idx <= 16);

Output- 15 16

Let us solve another problem :

Print the sum of the stream of N integers in the input using do while loop.

Cracking the Coding Interview in C++ - Foundation


Code:

int N, sum = 0;

cin >> N;

do {

int val;

cin >> val;

sum += val;

N--;

} while (N > 0);

cout << sum << endl;

Try this

Print the sum of the first 10 natural numbers using do while loop.

Topic: Break keyword


The break command allows you to terminate and exit a loop ( do while / for / while ) or switch commands
from any point other than the logical end. It can be used in cases where we want the immediate termination
of a loop based upon certain conditions.

Let us look at these examples for clarity -

Code (without break)

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

for(int j = 1; j <= 3; j++) {

cout << j << “ “;

cout << ‘\n’;

Output- 1 2 3

1 2 3

1 2 3

Code (with break)

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

for(int j = 1; j <= 3; j++) {

cout << j << ” “;

if(i == j) break;

cout << ‘\n’;

Output- 1

1 2

1 2 3

Cracking the Coding Interview in C++ - Foundation


Explanation- Did you notice the difference in output ?Without the break statement, the inner loop is executed 3
times for each iteration of i. However, after the break statement is added to the condition that ‘i’ equals ‘j’, the
inner loop is terminated whenever this condition is true.

Note: Case for infinite loop

Break keyword can also be used to end an infinite loop and we can break the loop as per our convenience. Look
at the example given below where we need to print the first 10 even numbers.

Code:

int index = 0, val = 0;

while (1) {

cout << val << “ “;

val += 2;

index += 1;

if (index == 10) break;

Output:

0 2 4 6 8 10 12 14 16 18

Try these
Print the first multiple of 5 which is also a multiple of 7.
Tell if the number in the input is prime or not.

Topic: Continue keyword


The continue keyword is used to end the current iteration in a for loop (or a while loop), and continues to the
next iteration.It can be used in cases where we want the remaining block of code to get executed in the loop for
the specific iteration.

Let us look at the following example for clarity -

Code

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

if(i == 3) continue;

cout << i << “ “;

Output- 1 2 4 5

Explanation- When the value of i becomes equal to 3, the continue statement makes the loop jump onto the
next iteration, skipping the remainder of the code, which in this case is skipping the cout statement of printing
3.

Try these
Print all values between 1 and 100, except if it’s a multiple of 3.
Print all factors of the number in the input.

Cracking the Coding Interview in C++ - Foundation


Upcoming Class Teasers
Problem on loops

Cracking the Coding Interview in C++ - Foundation


Lesson:

Problems on loops
Pre-Requisites
Basic C++ syntax
Conditionals
Understanding of loops (for, while, do while)

List of Concepts Involved


Loop-based questions

There is no better way to practice loops other than mathematical questions. These kinds of questions not only
clear the concepts and working of loops but also help in building the logical abilities for problem-solving in the
programming domain.

Are we ready for a few challenges? Of course, we are!

So let us begin!

Topic: Problems involving digits of a number


These questions are based on extracting and working on the individual digits of a number. Let us go through
these examples to know more.

Problem 1: Count the number of digits in the given number n.

Approach
Fetch the input from the user (n)
Create a while loop that iterates until the value of 'n' is not equal to 0.
Assume (for example) the value of 'n' is 123.
In the first iteration, the value of 'n' will be 123, and the value of count will be incremented to 1.
In the second iteration, the value of 'n' will be 12, and the value of count will be incremented to 2.
In the third iteration, the value of 'n' will be 1, and the value of count will be incremented to 3.
After the completion of the third iteration, the value of 'n' becomes 0, and loop is terminated as it does not
satisfy the condition (n!=0).

Number of digits can be many but the approach will remain the same.

Let us implement it now.

Code:

#include<iostream>

using namespace std;

int main(){

int n;

cin >> n;

int count = 0;

while(n > 0)

Cracking the Coding Interview in C++ - Foundation


{

count++;

n /= 10;

cout << count << endl;

Problem 2: Find the sum of digits in a given number n.

Approach :
Fetch the number n from user
Compute the modulus/remainder of the n
Add the remainder of the n
Divide the n by 10
Repeat step 2 until n is greater than 0.

Let's implement it in the code.

Code:

#include<iostream>

using namespace std;

int main(){

int n;

cin >> n;

int sum = 0;

while(n > 0)

sum += (n % 10);

n /= 10;

cout << sum << endl;

Problem 3: Reverse the digits of a number.

Approach :
First, find the remainder of the given number by using the modulo (%) operator.
Multiply the variable ans by 10 and add the remainder to it.
Divide the number by 10.
Repeat the above steps until the number becomes 0.

This may seem a little difficult to understand in the first go but try to run this program with a number of your
choice and you will understand how it works. It is mathematics in coding !

Let us code the approach now :

Cracking the Coding Interview in C++ - Foundation


Code:

#include<iostream>

using namespace std;

int main(){

int n;

cin >> n;

int ans = 0; // reversed number

while(n > 0) {

int remainder = n % 10;

ans = ans * 10 + remainder;

n /= 10;

cout << ans << endl;

Topic: Maths problems


This topic would cover the problems which are based on the concept of pure mathematical calculations. Let us
look at them to know more.

Problem 1: Find the sum of the following series

1 - 2 + 3 - 4 … n

Approach: Observe the pattern here. We can clearly see that the sum of the above series follows a pattern of
alternating positive and negative integers starting from 1 to N:

Hence, from the above pattern, we can conclude that:


when n is odd => ans = ans+i
when n is even => ans=ans-i

Let's write the code to implement this.

Code:

#include<iostream>

using namespace std;

int main(){

int n;

cin >> n;

int ans = 0;

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

if(i % 2 == 0) ans -= i; // subtracting the even numbers

else ans += i; // and adding the odd numbers

cout << ans << endl;

Cracking the Coding Interview in C++ - Foundation


Problem 2: Given 2 numbers a and b. Find a raise to the power b.

Approach :
To calculate ab, we multiply a*a*a*a*a…...*a b times.
To get this, let’s have a variable which will store the value of the calculated result and name it ans. Let’s
assign ans the value of a.
If we multiply ans with a and assign this value to ans then:

ans = ans*a = i.e. a2

let’s multiply again,

ans = ans*a i.e. a3 (as power was a2 with previous multiplication).

4. Similarly, we can obtain an.

Let us see the code implementation

Code:

#include<iostream>

using namespace std;

int main(){

int a,b;

cin >> a >> b;

int ans = 1;

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

ans *= a;

cout << ans << endl; }

Problem 3: Print the nth factorial number.

Approach :
To calculate the factorial of a number, we multiply all the previous numbers to it till 1.
To get this, let’s have a variable which will store the value of the calculated result and name it fact. Let’s
assign fact=1.
Multiply fact with i (loop variable) and assign this value to fact until you reach the number n (for which
factorial is to be calculated).
The final value of fact is the product of all numbers from 1 to n.

Let's see the code implementation:

Code :

#include<iostream>

using namespace std;

int main(){

int n;

cin >> n;

int fact = 1;

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

fact *= i;}

cout << fact << '\n';

Cracking the Coding Interview in C++ - Foundation


Hope you enjoyed solving these questions with the help of given approaches. However, we also encourage you
to solve these questions with different approaches.

Upcoming Class Teasers


Pattern-based questions in loops

Cracking the Coding Interview in C++ - Foundation


Lesson:

Pattern Problems based on loops


Pre-Requisites
Basic C++ syntax
Conditionals
Good understanding of loops (for, while, do while)

Have you gone through the previous lecture/ lesson plan? If not, we highly recommend you to be thorough with
the previous lectures and assignments on loops to have a well-informed discussion here.

List of Concepts Involved


Pattern-based questions

Did you know, you can actually draw the basic shapes on the output screen with the knowledge acquired so
far?

Yes, we are serious! You absolutely can!

Now that you are curious, let us not waste time arguing and get to work straight away!

Are we ready?

In the questions ahead, we are going to draw patterns and shapes using an asterisk(*), characters(alphabets)
and numbers.

Topic: Rectangular pattern


The problems discussed here would involve printing a rectangular pattern of different types with the help of the
concept of loops.

Problem 1 : Given height h and width w, print a rectangular pattern as shown in the example below.

Example: h=3,w=6

******

******

******

Solution:

#include<iostream>

using namespace std;

int main()

int h=3,w=6, i, j;

for(i = 1; i <= h; i++)

for(j = 1; j <= w; j++)

cout<<"*";

cout<<endl;

Cracking the Coding Interview in C++ - Foundation


Explanation
Input the height and width; i.e h=3, w=6 respectively.
For the height of the rectangle, run the outer loop from 1 to height.

for (i = 1; i < = h ; i++)


For the columns of the rectangle, run the inner loop from 1 to width.

for (j = 1; j < = w; j++)


Print star.
After printing all columns of a row, print a new line after the inner loop.

Problem 2 : Given height h and width w, print a rectangular pattern as shown in the example below.

Example: h=4,w=6

******

* *

* *

******

Solution :

#include<iostream>

using namespace std;

int main()

int h=4,w=6;

for (int i = 0; i < h; i++)

cout<<endl;

for (int j = 0; j < w; j++)

// Print * if this is first

// row or last row. Or this

// column is first or last.

if (i == 0 || i == h-1 ||

j== 0 || j == w-1)

cout<<"*";

else

cout<<" ";

Explanation
Input the height and width of the rectangle; i.e h=4, w=6 respectively.
For height of the rectangle run the outer loop from 0 to h-1.

for (i = 0; i < h ; i++)


For width of the rectangle run the inner loop from 0 to w-1.

for (j = 0; j < w; j++)


Print a star for the first or last row (h value) or for the first or last column (w value), otherwise print blank
space.
After printing all columns of a row, print a new line after the inner loop.

Cracking the Coding Interview in C++ - Foundation


Problem 3 : Given height h and width w, print a rectangular pattern as shown in the example below.

Example: h=4,w=6

*.*.*.

.*.*.*

*.*.*.

.*.*.*

Solution :

#include<iostream>

using namespace std;

int main()

int h=4,w=6, i, j;

for(i = 1; i <= h; i++)

for(j = 1; j <= w; j++)

if((i+j)%2==1){

cout<<(".");

else{

cout<<("*"); }

cout<<endl;

Explanation
Input the height and width; i.e h=4, w=6 respectively.
For height of the rectangle run the outer loop from 1 to h.

for (i = 1; i < = height ; i++)


For width of the rectangle run the inner loop from 1 to w

for (j = 1; j < = width; j++)


Print . if (i+j) is odd, otherwise print
After printing through the width(w) of a given height(h), print a new line after the inner loop.

Topic : Triangular pattern


After a good contemplation on rectangular patterns, let us now move to draw the next shape viz. triangle.

Problem 1: Given n, print a triangular pattern as shown in the example below.

Example if n=4

**

***

****

Cracking the Coding Interview in C++ - Foundation


Solution :

#include<iostream>

using namespace std;

int main()

int n=4;

for(int i=1; i<=n; i++)

for(int j=1; j<=i; j++)

cout<<("*");

cout<<endl;

} }

Explanation
Input number of rows i.e n=4
For rows of the triangle run the outer loop from 1 to rows.

for (i = 1; i < = n ; i++)


For the columns of the triangle run the inner loop from 1 to i.

for (j = 1; j < = i; j++)


In the above pattern, you can observe that ith row has i elements
Print star.
After printing all columns of a row, print a new line after the inner loop.

Problem 2: Given n, print a triangular pattern as shown in the example below.

Example if n=4

****

***

**

Solution:

#include<iostream>

using namespace std;

int main()

int n=4;

for(int i=n; i>=1; i--)

for(int j=1; j<=i; j++)

cout<<("*");

cout<<endl;

Cracking the Coding Interview in C++ - Foundation


Explanation
Input the number of rows i.e n=4
For rows of the triangle run the outer loop from rows to 1.

for (i = n; i >=1 ; i–-


For the columns of the triangle run the inner loop from 1 to i.

for (j = 1; j < = i; j++


In the above pattern, you can observe that ith row has (n-i+1) elements
Print star.
After printing all columns of a row, print a new line after the inner loop.

Try these Set 1:

Problem 1 Print a triangular pattern as shown in the example below.

Example for n=4

***

*****

*******

(Try it yourself first and verify the code/approach with the solution provided at the end of this lesson plan)

Topic: Numerical Rectangular pattern


Numbers always fascinate a programmer. So why not explore the patterns based on numbers ? Ready ? 1,2,3…
let's start !!

Problem1 Given n, print a rectangular pattern as shown in the example below.

Example if n=7

1 2 3 4 5 6 7

2 3 4 5 6 7 1

3 4 5 6 7 1 2

4 5 6 7 1 2 3

5 6 7 1 2 3 4

6 7 1 2 3 4 5

7 1 2 3 4 5 6

Cracking the Coding Interview in C++ - Foundation


Solution:

#include<iostream>

using namespace std;

int main()

{ int n=7;

for(int i=1;i< n+1 ;i++)

for(int j=i; j < n+1 ;j++)

cout<<j<<" ";

for(int k=1; k < i ;k++)

cout<<k<<" ";

cout<<endl;

Explanation
Input the number of rows i.e n=7
For rows of the rectangle run the outer loop from 1 to rows.

for (i = 1; i <n+1 ; i++)


For the columns of the rectangle run the inner loop from i to n.

for (j = 1; j < = n; j++)

Print the value of j here


For the columns of the rectangle run the inner loop from 1 to i-1.

for(int k=1; k < i ;k++)

Print the value of k here


After printing all columns of a row, print a new line after the inner loop.

Try these Set 2:

(Try these yourself first and verify the code/approach with the solution provided at the end of this lesson plan)

Problem 1: Print a rectangular pattern as shown in the example below.

Example if row=4,col=6

123456

123456

123456

123456

Problem 2: Print a rectangular pattern as shown in the example below.

Example if row=4,col=6

123456

1 6

1 6

123456

Cracking the Coding Interview in C++ - Foundation


Problem 3 : Given n, print a rectangular pattern as shown in the example below.

Example if rows=4,col=6

121212

212121

121212

212121

Topic: Numerical Triangular pattern


Problem: Given n, print a triangular pattern as shown in the example below.

Example if n=4

12

123

1234

Solution:

#include<iostream>

using namespace std;

int main()

int n=4;

for (int i = 1; i <= n; i++)

for (int j = 1; j <= i; j++)

cout<<j<<"";

cout<<endl;

Explanation:
Input the number of rows i.e n=4
For rows of the rectangle run the outer loop from 1 to rows.

for (i = 1; i < = n ; i++)


For columns of the triangle run the inner loop from 1 to i.

for (j = 1; j < = i; j++)

print the value of j here.


In the above pattern, you can observe that ith row has i elements
After printing all columns of a row, print a new line after the inner loop.

Try these Set 3 :

(Try it yourself first and verify the code/approach with the solution provided at the end of this lesson plan)

Cracking the Coding Interview in C++ - Foundation


Problem 1 Given n, print a triangular pattern as shown in the example below.

Example if n=4

121

12321

1234321

Problem 2 Given n, print a triangular pattern as shown in the example below.

Example if n=4

2 2

3 3

4 4

Hope you enjoyed solving these problems. Do not forget to see the solutions to unsolved problems. Scroll down
further.

Upcoming Class Teasers


Number system (decimal and binary concept)

Cracking the Coding Interview in C++ - Foundation


Solutions to ‘Try these Sets’
Set -1

Solution 1:

#include <iostream>

using namespace std;

int main()

int rows;

cout <<"Enter rows: ";

cin >> rows;

for(int i = 1, k = 0; i <= rows; ++i, k = 0)

for(int s = 1; s <= rows-i; ++s)

cout <<" ";

while(k != 2*i-1)

cout << "*";

++k;

cout << endl;

return 0;

Cracking the Coding Interview in C++ - Foundation


Set - 2

Solution 1:

#include <iostream>

using namespace std;

int main()

{ int row,col;

cout<<"Enter no of rows"<<endl;

cin>>row;

cout<<"Enter no of columns"<<endl;

cin>>col;

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

for(int j=1;j<=col;j++){

cout<<j;

cout<<endl;

return 0;

Cracking the Coding Interview in C++ - Foundation


Solution 2:

#include<iostream>

using namespace std;

int main()

int i, j, rows, cols;

cout << "Enter Rows = ";

cin >> rows;

cout << "Enter Columns = ";

cin >> cols;

for(i = 1; i <= rows; i++)

for(j = 1; j <= cols; j++)

if (i == 1 || i == rows || j == 1 || j == cols )

cout << j;

else

cout << " ";

cout << "\n";

return 0;

Cracking the Coding Interview in C++ - Foundation


Solution 3:

#include<iostream>

using namespace std;

int main()

int i, j, rows, cols;

cout << "Enter Rows = ";

cin >> rows;

cout << "Enter Columns = ";

cin >> cols;

for(i = 1; i <= rows; i++)

for(j = 1; j <= cols; j++)

if ((i+j)%2==0 )

cout << 1;

else

cout << 2;

cout << "\n";

return 0;

Cracking the Coding Interview in C++ - Foundation


Set - 3

Solution 1:

#include<iostream>

using namespace std;

int main()

int i, j,k, rows;

cout << "Enter Rows = ";

cin >> rows;

for(i = rows+1; i >1 ; i--)

for(j = i; j > 2; j--)

cout<<" ";

for( k=1;k<=(rows-i+1);k++){

cout<<k;

for(int m=k;m>=1;m--){

cout<<m;

cout << "\n";

return 0;

Cracking the Coding Interview in C++ - Foundation


Solution 2:

#include<iostream>

using namespace std;

int main()

int i, j,k, rows;

cout << "Enter Rows = ";

cin >> rows;

for(i = rows+1; i >1 ; i--)

for(j = i; j > 2; j--)

cout<<" ";

for( k=1;k<=(rows-i+1);k++){

if(k==1){cout<<(rows-i+2);}

else{cout<<" ";}

for(int m=k;m>=1;m--){

if(m==1){cout<<(rows-i+2);}

else{cout<<" ";}

cout << "\n";

return 0;

End of lesson
See you in the next lesson!

Cracking the Coding Interview in C++ - Foundation


Problem on CPP loops-2

Assignment Solutions
Assignment Solutions

Q1- Write a program to calculate factorial of a number.

#include <iostream>
using namespace std;

int main()
{
int j,number;
cout << "Enter number" << "\n";
cin >> number;
int fact = 1;
for (j=1;j<=number;j++){
fact = fact*j;
}
cout << "Factorial is:" <<fact << "\n";
return 0;
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q2- Write a program to print all Armstrong numbers between 100 to 500.

#include<iostream>
using namespace std;
int main()
{
cout<<"Armstrong numbers in the range of 100 to 500 are :"<<endl;
for(int i=0;i<500;i++)
{
int sum = 0;
int t = i;
while(t!=0)
{
sum = sum+((t%10)*(t%10)*(t%10));
t = t/10;
}
if(sum == i)
{
cout << i <<"\n";
}
}
return 0;
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q3- Write a program to find the sum of n natural number.

include <iostream>
using namespace std;

int main() {
int num, sum;
sum = 0;

cout << "Enter a positive integer: ";


cin >> num;

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


sum += i;
}
cout << "Sum = " << sum << endl;

return 0;
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q4 - Write a program to reverse a given integer number.

#include<iostream>
using namespace std;
int main()
{
int n,t,r,rev=0;
cout<<"Enter any number : ";
cin>>n;
t=n;

while(t>0)
{
r=t%10;
t=t/10;
rev=rev*10+r;
}
cout<<"Reverse of number "<<n<<" is "<<rev;
return 0;
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q5 - Write a program to print the cross pattern given below (in the shape of X):

* *
**
*
**
* *

#include <iostream>
using namespace std;

int main() {

int size = 5; // size of cross,use odd number

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


for (int j = 0; j < size; j++) {
if (i==j || i+j==size-1) {
cout << "*";
} else {
cout << " ";
}
}
cout << "\n";
}
return 0;
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q6- Write a program to print alphabet diamond pattern:


A
ABC
ABCDE
ABCDEFG
ABCDEFGHI
ABCDEFG
ABCDE
ABC
A

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

#include <iostream>
using namespace std;

int main() {
int size = 5;
int alpha = 65;
int num = 0;
// upside pyramid
for (int i = 1; i <= size; i++) {
// printing spaces
for (int j = size; j > i; j--) {
cout << " ";
}
// printing alphabets
for (int k = 0; k < i * 2 - 1; k++) {
cout << ((char)(alpha+num++));
}
// set the number to 0
num = 0;
cout << "\n";
}
// downside pyramid
for (int i = 1; i <= size - 1; i++) {
// printing spaces
for (int j = 0; j < i; j++) {
cout << " ";
}
// printing alphabets
for (int k = (size - i) * 2 - 1; k > 0; k--) {
cout << ((char)(alpha+num++));
}
// set num to 0
num = 0;
cout << "\n";
}
return 0;
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q7- Write a program to print + pattern given below :

*
*
*****
*
*

#include <iostream>
using namespace std;

int main() {
// size of plus, use odd number
int size = 5;

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


for (int j = 0; j < size; j++) {
// print only stars in middle row
if (i == size / 2) {
cout << "*";
}
// other than middle row, print star only at index size/2
else {
if (j == size / 2) {
cout << "*";
} else {
cout << " ";
}
}
}
cout << "\n";
}
return 0;
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q8 - Write a C++ program to print a triangle of prime numbers upto given number of lines of the triangle.

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int x1;
int x2;
int x3;
int Number=3;
int Banner=0;
cout<<"Please enter the no of lines ";
cin>> x1;
int d= x1;
for(x2=1;x2<= x1; x2++)
{
for(int e=1;e<=d;e++)
{
cout<<" ";
}
if(x2==1)
{
cout<<"2\n";
}
else
{
for(x3=0; x3!= x2;)
{
Banner=0;
for ( int k=2;k<Number;k++)
{
if((Number%k)==0)
Banner=1;
}
if(Banner==0)
{ x3++;
cout<<Number<<" ";
}
Number++;
}
cout<<"\n";
}
d--;
}
getch();
return 0;
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q9- Write a C++ program to check whether a Number can be expressed as a Sum of Two Prime Numbers.

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

#include<iostream>
using namespace std;
int main()
{
int num, i, j;
int f1=1 , f2=1, f3=0;
cout<<"Enter a +ve Integar : ";
cin>>num;
i=3 ;
do
{
f1=1;
f2=1;
j=2;
do
{
if(i%j==0)
{
f1=0;
j=i;
}
j=2;
do
{
if((num-i)%j==0)
{
f2=0;
j=num-i;
}
j++;
}
while(j<num-i );
if(f1==1 && f2==1)
{
cout<<num <<" = "<<i<<" + "<<num-i<<endl;
f3=1;
}
j++;
}
while(j<i);
i++;
}
while(i<=num/2);
if(f3==0)
{
cout<<num<<" can not be expressed as sum of two prime numbers.";
}
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q10- Write a C++ program to print a rectangle out of *

#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
int StarRows,StarColumns,i,j;
cout<<"Please Enter the number of StarRows: ";
cin>>StarRows;
//Takes input from user for StarRows
cout<<"Please Enter the number of StarColumns: ";
cin>>StarColumns;
//Takes input from user for StarColumns
for(i=1; i<=StarRows; i++){//outer for loop
for (j=1; j<=StarColumns; j++){//inner for loop
cout<<"*";//print star
}
cout<<"\n";//move to next line
}
getch();
return 0;
}

Cracking the Coding Interview in C++ - Foundation


Lesson:

Number system - Introduction to decimal


and binary and their interconversion
Pre-Requisites
Basic Syntax of C++
Variables, keywords, identifiers
Conditionals
Loops

List of Concepts Involved


Number System - Decimal and Binary Numbers
Conversion of Binary to Decimal
Conversion of Decimal to Binary

Topic: Number System


Number system is used to represent mathematical numbers in different forms with different base values. Base
value, as we all know is defined as a set of digits used to represent number. Depending on the base value
number systems are of many types. Here, we are going to explore only two of the relevant ones, i.e., decimal
and binary.

The decimal number system is the one having base 10 which means that any number can be represented in
terms of 0 to 9 digits and powers of 10. All the numbers that we use in real life transactions are decimal
numbers.

Let us look at the decimal representation of a few numbers(Base 10) :


3451 = (3 x 103) + (4 x 102) + (5 x 101) + (1 x 100)
576 = (5 x 102) + (7 x 101) + (6 x 100)

Here, as you can see, in the decimal representation the number is represented in powers of 10. It starts with the
unit place digit having a value multiplied by the 0th power of 10 and as we move towards the left, the power of
10 keeps on increasing.

This same number can also be represented in terms of other number systems like hexadecimal where the
number is represented with the help of 0 to 15 digits with the unit place being multiplied by (16)⁰ and power of
16 keeps on increasing as we move towards left.

For binary number system, any number can be represented in powers of 2 with 0s and 1s as shown below:

Binary representation of numbers (Base 2) :


1001 = (1 x 23) + (0 x 22) + (0 x 21) + (1 x 20)
110 = (1 x 22) + (1 x 21) + (0 x 20)
0100 = (0 x 23) + (1 x 22) + (0 x 21) + (0 x 20)

Let us now look at some of the most used conversions in the number system.

Cracking the Coding Interview in C++ - Foundation


Topic: Conversion of Binary to Decimal
To convert a binary number to a decimal number, we need to multiply each digit by the respective powers of 2
as shown.

For example,
(1001)2 = (1 x 23) + (0 x 22) + (0 x 21) + (1 x 20) = (9)10
(110)2 = (1 x 22) + (1 x 21) + (0 x 20) = (6)10
(0100)2 = (0 x 23) + (1 x 22) + (0 x 21) + (0 x 20) = (4)10

Explanation :

We take the unit digit and multiply it with 2⁰, and then for the subsequent digits we keep on increasing the
power of 2 as shown above.

Parity Digit: Parity Digit of a number n refers to the remainder it gives when divided by 2. If that reminder is 0,
then the parity of the number is even otherwise odd.

Algorithm Steps:

Lets say n is the input binary number.


Step 1: Find the parity digit of n. This is then multiplied by the respective power of two.
Step 2: Increase the power of two and divide n by 10.
Step 3: Keep on repeating the steps until the n is greater than zero.

Code:

void binary_to_decimal() {

int n;

cin >> n;

int ans = 0;

// here pw is power of two, initially it will be 20 = 1

int pw = 1; // 20

while (n > 0) {

int untis_digit = n % 10;

ans += pw * untis_digit;

n /= 10; // updating the units place

pw *= 2; // increasing the power of two

cout << ans << endl;

Input :

110

0100

1001

Cracking the Coding Interview in C++ - Foundation


Output :

Topic: Conversion of Decimal to Binary


To convert the number from Decimal to Binary, we determine whether the parity of the unit place is 1 or 0 and
then keep on dividing the number by 2.

Algorithm Steps:

Let's say n is the input decimal number


Step 1: Find the remainder/parity digit when n is divided by 2. This will be the unit place of the binary
number.
Step 2: Divide n by 2.
Step 3: Keep on repeating the steps until the n is greater than zero.

Code:

void decimal_to_binary() {

int n;

cin >> n;

int ans = 0; // our final decimal number

int pw = 1; // 100 = 1

// here pw represents the power of 10 which will be needed to increment the place of the

// decimal number

while (n > 0) {

int parity = n % 2;

ans += pw * parity; // add it to our decimal number

pw *= 10;

n /= 2;

cout << ans << endl;

Input :

10

15

Output :

101

1010

1111

Cracking the Coding Interview in C++ - Foundation


That is all about the number system (that would be relevant to us)

Let us meet in the next lesson!

Till then, keep learning and keep exploring !!

Upcoming Class Teasers


Functions in C++

Cracking the Coding Interview in C++ - Foundation


Lesson:

C++ Functions
Pre-Requisites
C++ basic syntax
Operators
variables and data types
Conditionals and loops

List of Concepts Involved


Introduction of functions
Why are Functions important?
Declaring a functio
Calling a function
Function prototype

Did you know, in programming, there is a provision where you can write a block of code once and reuse it as
many times as required, without having to rewrite the program again and again. Sounds interesting? This
interesting concept is known as functions!

Topic: Functions in C++


A Function is a block of code or collection of statements or a set of codes grouped together to perform a
certain task or operation.
Function runs when it is called/invoked (in the topics ahead, we will see how).
We can pass data, known as parameters, into a function (Really? Let us move further to see how that is done)

As you might have observed already, every C++ program has at least one function which is the main()

function, but a program can have any number of functions. The main() function, however, is the starting

point of a program. When you run a code, you are actually calling the main function, where we pass some

input (or take them using stdin) and then return something (or print it out as stdout).

Topic: Why are Functions important in C++?


With functions we can group a logical set of code to perform a certain task or operation. We write a function
once and can use it as many times as required. This saves a lot of time.
Functions actually help us to follow the good coding practice of DRY i.e. Don’t Repeat Yourself principle. In
the programming domain, it simply means that you should refrain from writing the same code again.
Functions can be used to replace all repeated codes.
A program/application created with functions is easy to read, understand and dry run.
In a program, a function can be called whenever and wherever needed.

Cracking the Coding Interview in C++ - Foundation


In C++, there are two types of Functions
User-defined Functions: Here, we can create our own function based on the requirements. We will be
creating these in the exercises ahead.
Standard Library Functions: These are built-in pre-written functions that are directly available to use. We
just need to include the required header files to access and use them in our program.

Enough of talking and explanation, let us now get straight to writing our own functions.

Topic: How to declare Functions:


The Function declaration provides information about the attributes, such as visibility, return type, name, and
arguments of functions. Do not worry, this is all a part of the syntax.

Defining a Function

return_type function_name(parameter1, parameter2, ………) {

statements;

1. function_name : Each Function has its own name and it is identified by its name. Ideally, the function name

should be given in such a way that it depicts the functionality/utility of the function. Eg. area() to calculate

area, sum() to perform addition etc.

2. Return type : It defines the data type of the value returned from a Function. If we want the function to return

a value, we can use a data type (such as int, string, etc.), if the function does not return anything we can

simply use void.

3. Parameters: Parameters actually act as variables inside the Function. They are specified after the Function

name, inside the parentheses. You can add as many parameters as you want, simply separate them with

commas.

4. Function Body: It is a part of the Function declaration that contains the code for all the actions to be

performed. It is enclosed within a pair of curly braces.

Topic: Calling a Function


To call a function, we write the function name followed by two parentheses () and a semicolon;
Before calling a function, we must know the name of function that we are calling, the number of parameters
required and their data types and last but not the least, the return type to collect the value returned by the
function.

Note: As mentioned earlier, the execution of all C++ programs begins with the main function, regardless of
where the function is actually located within the code.

In the example below, welcome() function is used to print a text (the action), when it is called. You may try it
too!

Cracking the Coding Interview in C++ - Foundation


Example 1

void welcome() {

cout<<("Welcome to Physics Wallah");

int main(){

welcome();

Output: Welcome to Physics Wallah

Explanation:

In the example, we have created a function with the name welcome(). It is a simple function that takes no
parameters.

welcome(); has been used to perform the function call without passing any arguments. Since the function is
not returning any value, its return type is void.

Look at the next example now,

Example 2. C++ Program to add two numbers using functions

// create a Function

int addition(int p, int q) {

int add = p + q;

// return value

return add;

int main() {

int p = 40;

int q = 60;

// calling Function

int answer = addition(p,q);

cout<<("Sum is: ")<< answer;

Output: Sum is 100

Explanation:

In the example above, we have created a function named addition(). This function takes two parameters p and
q. The statement int answer = addition(p, q); has been used to call the addition function by passing two
arguments p and q. Since the function is returning an integer value, we have stored the value in the answer
variable of int type.

Note- We re-iterate here, if the function does not return any value, we use the void keyword as the return type
of the Function.

Cracking the Coding Interview in C++ - Foundation


Let us look at the next example now :

Example 3. Can you guess how this function is different from the previous one, before we jump to the
explanation?

// create a Function

void addition(int p, int q) {

int add = p + q;

// print value

cout<<("Sum is: ")<< add;

int main() {

int p = 40;

int q = 60;

// calling Function

addition(p,q);

return 0;

Output: Sum is 100

Explanation:

In the example above, we have created a function named addition(). The function takes two parameters p and
q. The statement addition(p, q); has been used to call the addition function by passing two arguments p and q.
Since the return type of function is void, it is not returning any value.

Great work! You did a great job !!!

Let's now dive into the concept of prototypes

Function Prototype
In C++, as a standard practice, the code of function declaration should be written before the function call.
However, if we want to define a function after the function call, we may do so by using the function prototype.

Let us look at the following example to understand this concept better.

// using function definition after main() function

// function prototype is declared before main()

#include <iostream>

using namespace std;

Cracking the Coding Interview in C++ - Foundation


// function prototype

int sub(int, int);

int main() {

int difference;

// calling the function and storing

// the returned value in difference variable

difference = sub(200, 100);

cout << difference << endl;

return 0;

// function definition

int sub(int x, int y) {

return (x - y);

Standard Library Functions

These are the built-in functions that are readily available for use. This makes the programmer's job easier
because they provide many of the capabilities that the programmers need. The C++ Standard Library,
functions are provided as part of the C++ programming environment.

Let us look at a few examples:


pow(a,b) is a function in header file <cmath>.It returns the value of a raised to the power b.
sqrt(x) is a Function in header file <cmath>. It returns the value of the square root of a number x.

Here's an example, you may try others too!

Example :

#include <iostream>

#include <math.h>

using namespace std;

int main(){

// using the sqrt() Function

cout<<("Square root of 16 is: ")<< sqrt(16);

Output:

Square root of 16 is: 4

Cracking the Coding Interview in C++ - Foundation


MCQ :
Q1. What will be the output of the following code ?

void sum(int x, int y){

cout << (x + y);

int main() {

int p = 10;

sum(p, 32);

Solution: 42

This brings us to the end of Part -1 of Functions !! In the next lesson, we will explore more about these !

Keep learning ! Keep exploring !!

Quick bite: Did you know ?

In C++, it's possible to have multiple functions with the same name as long as the function signature is
different, i.e. functions having the same name but different set of parameters(a concept called function
overloading, which will be explained in the forthcoming lectures).

Stay tuned for more !!

Upcoming Class Teasers


Scope of variables.
Pass by value and Pass by reference
Default parameter value

Cracking the Coding Interview in C++ - Foundation


Lesson:

Functions and scope of


variables
Pre-Requisites
Syntax of C++
Variables
Loops
Basics of Functions

List of Concepts Involved


Concept of scope of variables in C++
Function call by value
Function call by reference
Default parameter value

Topic: Concept of scope of Variables


The scope of a variable is the part of a program where the variable is valid and can be legally accessed. Legal
? Yes, you read it right. The concept of scope is that precise.

Variables can be classified in the following categories based on their scopes.


Local variables : variables that are declared inside a function block and can be accessed/used inside that
specific function block only. They are unknown entities outside the function.
Global variables : variables that are declared outside all blocks or functions in a program (generally at the
top of the program) and can be accessed/used anywhere in the program (i.e. their reach is not limited to a
block or function)

Note : No two(or more) variables can be declared with the same name within the same scope. However, it is
possible for two(or more) variables to have the same name if they are (all) declared in different scopes.

Cracking the Coding Interview in C++ - Foundation


Lets us understand the concept of scope with the help of different examples:

Example 1 :

#include <iostream>

using namespace std;

void func(){

int a=5; // a is local variable for function func

cout<<a;

int main(){

// cout<<a; // line 1

Here, ‘a’ is a local variable for function func but ‘a’ has no identity outside the function func.

Uncommenting line 1 would produce an error at the time of compilation, because we are trying to access
variable ‘a’ whose scope is limited to the function func().

Example 2 :

#include <iostream>

using namespace std;

//global variable

int p=20;

void func(){

cout<<p;

int main(){

cout<<p; // line 1

Here, p is a global variable and therefore, is accessible from anywhere in the program, Hence, the code will
compile without any error.

Example 3:

#include <iostream>

using namespace std;

int main()

int p = 50;

double p = 60.70;

cout<<(p)<<endl;

Here, as you might have already observed, there are two variables with the same name p that are declared in
the same scope of main () function.

Hence, the code will not compile and throw an error.

Cracking the Coding Interview in C++ - Foundation


Example 4 :

#include<iostream>

using namespace std;

int main()

int p = 5;

int p = 7, q = 9;

cout << p << endl; //7

cout<< q << endl; //9

cout << p << endl; //5

cout<< q << endl;

//error because variable q is not accessible here , it is //out of scope here

Here, p has been declared both as a local and a global variable. Inside the block, the value of p is 7 (as per
local declaration); however, outside the block, the value of p is fetched from the global declaration and the
value of p is 5.

As for q, inside the block, the value of q is 9 (as per local declaration). However, outside the block, q is an
unknown entity, hence the print statement for q, outside the block will simply throw an error.

Common Doubt :

What if there exists a local variable with the same name as that of the global variable inside a function?

If we declare a global variable and a local variable with the same name, then precedence will be given to the
local variable by the compiler i.e. in a region where both local and global variables of the same name exist, all
the operation done on the variable will be done on the local variable only.

If we deliberately want to access the global variable, we may do so using a scope resolution operator. Look at
the example below to have a clear understanding of using a scope resolution operator.

#include <iostream>

using namespace std;

//global variable

int p=23;

int main()

//local variable

int p=32;

p++;

cout<<"value of local variable p is: "<<p<<endl;

cout<<"value of global variable p is: "<<::p;

// scope resolution operator

return 0;

Cracking the Coding Interview in C++ - Foundation


Output:

value of local variable p is: 33

value of global variable p is: 23

This is all about the various possibilities while using scope.

Before proceeding to the next topic of parameter passing (in functions), let us first learn a bit about them.

A parameter is a named variable passed into a function. Yes, we can pass variables in functions too ! This will
help us to use a function to do mathematical calculations, logical operations etc rather than just printing
statements which we were doing till now.

This will also enable us to justifiably utilize the concept of scope.

In C++ functions, there are majorly two types of parameters :

Formal parameters: parameters that are defined during function definition.

Actual parameters: parameters that are passed during the function call in another function.

Confused?! We have got you covered. Let us look at the example below :

// C++ program to show the difference

// between formal and actual parameters

#include <iostream>

using namespace std;

int diff(int p,int q) // p and q are formal parameters

return p-q;

int main ()

int x=89;

int y=9;

cout<<(diff(x,y))<<endl; //x and y are actual parameters

Output: 80

Here, you may also use the same variable name p and q in place of x and y. Note that, in that case, p and q
inside the main function would be different from p and q inside the diff function because both would have
different local scopes limited to the respective functions only.

To perform any operation with the help of functions through parameter passing, we must also be aware that
this can be done in two different ways which brings us to the most interesting topic of functions !

Cracking the Coding Interview in C++ - Foundation


Topic: Parameter passing in a function- Pass by
Value and Pass by Reference
Pass by Value and Pass by reference are the two ways by which we can pass a value or reference to a function
to perform some operation. Let us read more.

Pass by Value: here, the function parameter values (i.e. value from actual parameter) are copied to another
variable (formal parameter).

This is also known as ‘call by value’.

Pass by Reference: here, actual copy of variable reference is passed to the function. This is also known as
‘call by reference’.

Example:

1. Pass by value

void changeValue(int z) {

z = 100; // changeValue has a copy of z, so it doesn't

// overwrite the value of variable a used

// in main() that called changeValue

int main() {

int a = 40;

cout<<a; // prints "40"

changeValue(a);

cout<<a; // prints "40"

Example 2. Pass by value

//Function that calculates the sum

int add (int n1, int n2) //formal parameters

int ans = n1 + n2;

return ans;

int main()

int a, b, ans;

cout<<("Enter the first number: ")<< endl;

cin>>a;

cout<<("Enter the second number: ")<< endl;

cin>>b;

ans = add(a, b); //actual parameters

cout<<("The sum of two numbers a and b is: ")<< ans << endl;

Cracking the Coding Interview in C++ - Foundation


In the example above, we are passing two values a and b (entered by the user) in a function ‘add’ as n1 and n2.
The value of sum is saved in variable ans and this value is returned from add function to ‘ans’ variable in
main().

We are now going to discuss parameter passing by reference. It is being discussed separately here because it
is a little different from whatever we have learnt so far.

Topic: Pass by reference:


Parameter passing ‘by reference’ means that we pass the reference to the actual variables rather than passing
just the value (as we did in ‘passing by value’).

To access the address/reference of any variable, we use the "&" operator. Look at the example below to
understand the use of ‘&’ operator and its use in passing by reference.

#include <iostream>

using namespace std;

void swap(int &a, int &b)

int c = a;

a = b;

b = c;

int main()

int num1 = 20;

int num2 = 32;

cout << "Before swap: " << "\n";

cout << num1 <<" "<< num2 << "\n";

// Call the function swap, which will change the values of num1

// and num2

swap(num1, num2);

cout << "After swap: " << "\n";

cout << num1 <<" "<< num2 << "\n";

return 0;

Output:

Before swap:

20 32

After swap:

32 20

Cracking the Coding Interview in C++ - Foundation


Here, the reference/address of num1 and num2 are being passed to parameters a and b of the ‘swap’ function.

After the swapping operation in the ‘swap’ function, the values are changed in the reference/address of the
variables which are printed in the main function.

If it appears confusing to you, you are not the only one! Don't worry, we will cover the reference concept more in
the forthcoming lecture on pointers.

The next topic is extremely interesting and equally important. Let us understand it with a little attention.

Topic :Default parameter/argument value


A default argument is a value in the function declaration assigned automatically by the compiler if the calling
function does not pass any value to that argument.

If a function with default arguments is called without passing arguments, then the default parameters are
used. However, if arguments are passed while calling the function, the default arguments are ignored.

Let us look at the example below :

// CPP Program to demonstrate Default Arguments

#include <iostream>

using namespace std;

// A function with default arguments,

// it can be called with

// 2 arguments or 3 arguments or 4 arguments.

int add(int a, int b, int c = 0, int d = 10)

//assigning default values to c,d as 0,10 respectively

return (a + b + c + d);

// Driver Code

int main()

// Statement 1

cout << add(30, 20) << endl;

// Statement 2

cout << add(10, 20, 30) << endl;

// Statement 3

cout << add(5, 20, 35, 50) << endl;

return 0;

Output:

60

70

110

Cracking the Coding Interview in C++ - Foundation


In the example above, we have called the add function three times
add(30,20)

When this function is called, it reaches out to the definition of the ‘add’. There it initializes a to 30, b to 20 and

the c to 0 , d to 10 by default as no value is passed. After addition of all these values gives 60 as output.
Sum(10, 20, 30)

When this function is called, a is assigned as 10, b is assigned as 20, the third parameter c is initialized to 30

instead of zero. The last value d remains 10. The sum of a,b,c,d is 70 which is returned as output.
Sum(5, 20, 35, 50)

In this function call, there are four parameter values passed into the function with a as 5, b as 20, c is 35, and

d as 50. All the values are then summed up to give 110 as the output.

We hope that the concept of default argument is pretty clear with all these combination of scenarios discussed
above.

Note: Once you have used the default value for an argument in the function definition, all subsequent
arguments must have a default value as well. This can also be stated that the default arguments are assigned
from right to left.

For example, the following function definition is invalid as the subsequent argument of the default variable d is
not default.

// Invalid because c has default value, but d after it doesn't have a default value

int sum(int a, int b, int c = 0, int d).

That brings us to the end of the function concept !

Let us now look at the practice questions :

Q1. What is the output of the following code?

void decrease(int n1, int n2)

n1--;

n2 = n2 - 2;

cout<<(n1) << ":" << (n2);

// n1 and n2 are formal parameters

int main()

int p = 26;

int q = 13;

decrease(p,q);

cout<<(p) << ":" << (q);

// p and q are actual parameters.

Ans:

25: 11

26: 13

Cracking the Coding Interview in C++ - Foundation


Explanation:

In this program snippet, changes in the values of n1 and n2 are not reflected to p and q because n1 and n2 are
formal parameters and are local to function decrease so any changes in their values here won’t affect
variables p and q inside main function.

Q2. What will be the output of the following code ?

void makeTwice(int p )

p = p * 2;

int main()

int p = 24;

makeTwice(p);

cout<<(p);

Ans : 24

Explanation:

In the code snippet, changes in the value of p is not reflected in the main function

Here we are calling the function makeTwice using the concept of ‘pass by value’.

Q3. Will the following code generate any error ?

void temp(int p)

int q = p;

q = q -100;

int main()

int p = 890;

temp(p);

cout<<(q)<<endl;

Ans: Yes, it will generate an error, because, in the main function there is no variable having name q,variable q
has scope in temp function block only.

Cracking the Coding Interview in C++ - Foundation


Q4. What is the scope of the variable declared in the user defined function?

a) only inside the {} block

b) whole program

c) header section

d) the main function

Ans: A only inside the {} block

That is all ! See you in the next lesson !! Till then, keep learning ! Keep exploring !!

Upcoming Class Teasers


Arrays

Cracking the Coding Interview in C++ - Foundation


C++ Functions

Assignment Solutions
Assignment Solutions

Q1 - Write a function to print squares of the first 5 natural numbers.


Sample Output: 1 4 9 16 25

Code:
#include <iostream>
using namespace std;
int square(int num)
{
int sq=num*num;
return sq;
}
int main()
{
for(int i=1;i<=5;i++)
{
cout<<square(i)<<" ";
}
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q2 - Given radius of a circle. Write a function to print the area and circumference of the circle.
Sample Input: r=3
Sample Output: Area : 28.26
Circumference : 18.84
Code:
#include <iostream>
using namespace std;
double circum(int r)
{
double cir=2*3.14*r;
return cir;
}
double area(int r)
{
double ar=3.14*r*r;
return ar;
}
int main()
{
cout<<"Enter the radius : ";
int r;
cin>>r;
cout<<"Area : "<<area(r)<<endl;
cout<<"Circumference : "<<circum(r);

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q3 - Given the age of a person, write a function to check if the person is eligible to vote or not.
Sample Input: 19
Sample Output: Yes
Sample Input: 17
Sample Output: No

Code:
#include <iostream>
using namespace std;
bool vote(int age)
{
if(age>=18)
{
return true;
}
return false;

}
int main()
{
cout<<"Enter the age : ";
int age;
cin>>age;
if(vote(age)==true)
{
cout<<"Yes";
}else{
cout<<"No";
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions
Q4 - Given two numbers a and b, write a program using functions to print all the odd numbers
between them.
Sample Input: 1 10
Sample Output: 1 3 5 7 9

Code:
#include <iostream>
using namespace std;
bool prime(int num)
{
for(int i=2;i<num;i++)
{
if(num%i==0)
{
return false;
}
}
return true;
}
int main()
{
int a;
int b;
cout<<"Enter the two numbers : ";
cin>>a>>b;
for(int i=a;i<=b;i++)
{
if(prime(i)){
cout<<i<<" ";
}
}
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q5 - Given two numbers a and b, write a program to print all the prime numbers present between
a and b.
Sample Input: 2 10
Sample Output: 2 3 5 7
Code:
#include <iostream>
using namespace std;
bool odd(int num)
{
if(num%2!=0)
{
return true;
}
return false;
}
int main()
{
int a;
int b;
cout<<"Enter the two numbers : ";
cin>>a>>b;
for(int i=a;i<=b;i++)
{
if(odd(i))
{
cout<<i<<" ";
}
}
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Cracking the Coding Interview in C++ - Foundation


Lesson:

Arrays in C++
Pre-Requisites
Basic C++ syntax
Variables
Loops
Functions

List of Concepts Involved


Array Introduction
Declaration
Creation
Array Types
Operations
Taking Input in an array
Problems based on an array

Suppose we have to write a program in which can accept salaries of 50 employees. If we solve this problem by
making use of variables, we need 50 variables to store employees’ salaries. Managing these 50 variables is not
an easy task and will make the program a complex and lengthy one. This problem can be solved by declaring 1
array having 50 elements. Did you notice how convenient the scenario became? If arrays are that useful, why
not learn about them?

Topic: Array Introduction - What is an array


Array is a data structure (storage, used to store and organize data) to store a group or collection of
(homogenous data) items, sequentially, inside memory. Homogenous data is data of the same type, for
example, integer or string or floating number, etc. Each array element is identified with an index number.
The indexing of an array is 0-based i.e. the first element is at index 0, second element is at index 1 and so on.
The desired array element can be directly and individually accessed using these numbered indexes.
The memory allocation in arrays is contiguous i.e. elements are stored one after another.
An array can be single-dimensional or multi-dimensional based on the utility and application.

Topic: Array Declaration and Creation


Array declaration names the array and specifies the type of elements in it. It can also define the number of
elements in the array.
Syntax for creating a new Array in C++ is

data-type array-name[array-size];

Example:

int arr[10];

Cracking the Coding Interview in C++ - Foundation


Array Literal

With the help of curly braces, we can initialize the array and add value to it during initialization without

defining the size as we did in the previous syntax.

Example :

int arr[] = { 1,2,3,4,5,6,7,8,9,10 };

You might be wondering that why arrays should be used when we already have the provision of creating as
many variables as we want/need.

Look at the scenarios mentioned below which will clear the air around utility of arrays for our good.

Case 1: Scenario without Array

In the example below, we are using five different variables to save our elements one by one.

string colour1 = “Red”;

string colour2 = “Green”;

string colour3 = "Blue”;

string colour4 = “Yellow”;

string colour5 = “Purple”;

// To print all the elements to the console

cout << colour1 << endl;// Red

cout << colour2 << endl;// Green

cout << colour3 << endl;// Blue

cout << colour4 << endl;// Yellow

cout << colour5 << endl;// Purple

Output:

Red

Green

Blue

Yellow

Purple

Woah ! It was cumbersome and may result in manual mistakes. Isn’t it ?

Cracking the Coding Interview in C++ - Foundation


Case 2: Using the array concept

Now, we will implement the same scenario using an array.

// To create an array of colours to store values

string colours[] = {“Red”, “Green”, “Blue”, “Yellow”, “Purple”};

// To print all the elements entered in a array to the console

for (int i = 0; i < 5; i++)

cout << colours [i] << endl;

Output:

Red

Green

Blue

Yellow

Purple

Thats it ?! Yes, absolutely !

Did you see how arrays made the implementation so convenient and saved a lot of our coding time !

Let us understand how these approaches are different:


With individual variable approach in case 1, each value is stored in different variables, which results in
random memory allocation for each variable; whereas in case 2, when we used the concept of array, the
values were stored in contiguous memory locations. Hence, handling and accessing data became
extremely convenient.

Arrays have an unlimited potential if we use them correctly. Let us look at its types and see how versatile these
can be to handle the most complex scenarios (which will be discussed in the forthcoming lectures)

Topic: Array Types


There can be many classifications in arrays but we will concentrate on the most widely used ones that are
based on the dimension of data that it is handling.

1. Single dimensional or one-dimensional array

When we have elements stored in a single dimension or sequentially or linearly. We can declare and

allocate memory to a single-dimensional array using a single variable.

Syntax for declaring an single dimension array -

data_type array_name [] = {element_0, element_1, element_2, element_3, ...

elementN};

Example :

string colours[] = {"Red", "Green", "Blue"};

// To print the elements in the console:

for(string colour : colours)

cout << colour << “, “;

Cracking the Coding Interview in C++ - Foundation


Output:

Red, Green, Blue

Example to create a single dimensional array:

// To create an Single-Dimension array:

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

// first element

cout << myArray[0] << endl;// to print 1

// second element

cout << myArray[1] << endl;// to print 2

// third element

cout << myArray[2] << endl;// to print 3

// fourth element

cout << myArray[3] << endl;// to print 4

// fifth element

cout << myArray[4] << endl;// to print 5

Output:

2. Multi dimensional Array:

A multidimensional array is simply an array that consists of two or more dimensions and is also commonly

referred to as an array of arrays.

The diagram below will help you visualize the actual implementation structure of a multi- dimensional

array.

Cracking the Coding Interview in C++ - Foundation


To build a two-dimensional array, wrap each array in its pair of "[]" square brackets.

Look at the example below for clarity. Here we are creating a 2-dimensional array

int items[2][2] = {

{2, 3},

{5, 6},

};

Topic: Simple operations on arrays


Here, we are going to discuss the most basic operations that can be done on arrays .

a. Size of an array

string colours[] = {"Red", "Green"," Yellow"," Purple"}

int sz = colours.size();

cout << sz << endl; // prints 4

Note: Array index always starts from 0, which means the first element is stored at index 0 and the last element
will be stored at index sz-1.

Looping through Array

There are many ways to iterate or loop over the array. The most common ways to do so are:
Using For Loop

We can iterate through the array using for loop as shown below.

// Creating an Array

string colours[] = {“Green”, “Red”, “Purple”, “Yellow”, “Blue”};

// Using loop to iterate over array

for (int = 0; i < colours.size(); i++)

// Printing array elements using index

cout << colours [i] << endl;

// Will print

// Green

// Red

// Purple

// Yellow

// Blue

Here, we are iterating over the array ‘colours[]’, using a for loop to print the elements.

Using For each loop

This loop might seem to be new to you but its very easy to understand. It helps in iterating over objects like

string, array and so on. It is like the simple loops that we have studied with a little difference, which is actually

a limitation. Let us look at the syntax first.

Cracking the Coding Interview in C++ - Foundation


Syntax:

for (<data_type> <variable_name> : <array_name> )

statement;

Limitation of for each loop:


For each loop can only be used for traversing the whole array and not part of the array.

Let us see the example below to know how for each works.

int a[] = { 1, 2, 3, 4, 5, 6, 7, 8 };

// iterating over an array

for (int i : a) {

// accessing each element of array

cout << i << endl;

Output:

Topic: Taking input in an array


To take input in an array, we simply declare it and use a ‘cin’ to take input with the help of a loop
Using a basic for loop

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

cin >> a[i];

Using while loop

int i = 0;

while(i < n) {

cin >> a[i];

i++;

Using for each loop

for(int &i : a) cin >> i;

Now that we are equipped with all the basic syntax and nuances of arrays, let us now move to some basic
problems.

Cracking the Coding Interview in C++ - Foundation


Topic: Arrays Problems
Let us now discuss some problems based on array application.

Problem 1: Calculate the sum of all the elements in the given array.

Code:

int sum = 0;

for(int i = 0; i < a.size(); i++) {

sum += a[i];

Problem 2: Find the maximum value out of all the elements in the array.

Code:

int mx = a[0];

for(int i = 0; i < a.size(); i++) {

if(a[i] > mx) mx = a[i];

Problem3: Search if the given element is present in the array or not and find the index. If not present then return
the index as -1. (Linear Search)

Code:

int index = -1;

for(int i = 0; i < a.size(); i++) {

if(a[i] == given_value) index = i;

That is all for this class ! See you in the next array lecture !! Keep learning ! Keep Exploring !!

Upcoming Class Teaser


Vectors
Operations on vectors

Cracking the Coding Interview in C++ - Foundation


Arrays in C++

Assignment Solutions
Assignment Solutions
Q1 - Given an integer array(arr) and its size(n), print the count of odd and even integers present in the array.

For ex: arr[]={1,2,3,4,5} n=5


Output: Odd Numbers = 3
Even Numbers = 2
Explanation: The even numbers present in the array are 2,4 and the odd numbers present in the array
are 1,3 and 5.

Code:
int count(int arr[],int n)
{
//we will count the number of odd elements and subtract it from n which will give
even elements
int count_odd=0;
for(int i=0;i<n;i++)
{
if(arr[i]%2!=0)
{
count_odd++;
}
}
return count_odd;
}

Q2 - Given an integer array and its size, find the sum of the greatest and the smallest integer present in the
array. Here 1< size <101
For ex: arr[]={1,2,3,4,5} n=5
Output: 6
Explanation: The smallest number in the array is 1 and the greatest numbers in the array is 5, so the sum
will be 1+5=6

Code:
int sum(int arr[],int n)
{
int max_val=INT_MIN;
int min_val=INT_MAX;
for(int i=0;i<n;i++)
{
max_val=max(max_val,arr[i]);
min_val=min(min_val,arr[i]);
}
int ans=max_val+min_val;
return ans;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q3 - Given an integer array and its size, reverse the array and print it. Here 1<size<101
For ex: arr[]={1,2,3,4,5} n=5
Output: 5,4,3,2,1
arr[]={1,1,1,1,1] n=5
Output: 1,1,1,1,1

Code:
void rev(int arr[],int n)
{
int start=0;
int end=n-1;
while(start<end)
{
int temp=arr[start];
arr[start]=arr[end];
arr[end]=temp;
start++;
end--;
}
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
}

Q4 - Given two arrays a[] and b[] of same size.Your task is to find the minimum sum of two elements such
that they belong to different arrays and are not at the same index. Here 1<size<101

For ex: a[]={5,6,10,4,9}


b[]={1,2,3,4,5}
Output: 5
Explanation: The numbers are 4 from a and 1 from b which makes sum 1+4=5

a[3] + b[0] = 5 is the lowest possible sum amongst all the possible combinations

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Algorithm:
Find minimum elements from a[] and b[]. Let these elements be minA and minB respectively.
1. If indexes of minA and minB are not the same, return minA + minB.
2. Else find second minimum elements from two arrays. Let these elements be minA2 and minB2.
Return min(minA + minB2, minA2 + minB)

Code:
int minSum(int a[], int b[], int n)
{
int minA=INT_MAX,minB=INT_MAX,indexA=0,indexB=0;
int min2A=INT_MAX,min2B=INT_MAX;
for(int i=0;i<n;i++)
{
if(a[i]<minA)
{
min2A=minA;
minA=a[i];
indexA=i;
}
else if(a[i]<min2A)
min2A=a[i];
if(b[i]<minB)
{
min2B=minB;
minB=b[i];
indexB=i;
}
else if(b[i]<min2B)
min2B=b[i];
}
if(indexA!=indexB)
return minA+minB;
return min(min2A+minB,min2B+minA);
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q5 - Given an array containing n distinct integers in the range [0,n] (inclusive of both 0 and n) (inclusive of both
0 and n). Find and return the only number of the range that is not present in the array. Here 1<n<101.

Ex: arr=[3,0,1]
Output: 2

n=3, thus the range will be [0,3]

Ex: arr=[8,6,4,2,3,5,0,1]
Output: 7

n=8, thus the range will be [0,8]

Algorithm:

We find the sum of the numbers from [0,n] and subtract the sum of the given array from it and this gives
us the missing number in the range.
Code:
int val(int arr[],int n)
{
int missing=-1;
int sum=0;
for(int i=0;i<n;i++)
{
sum+=arr[i];
}
int range_sum=(n)*(n+1)/2;
missing=range_sum-sum;
return missing;
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q6 - Given an integer array containing n elements. Find the element in the array for which all the elements to its
left are smaller than it and all the elements to the right of it are larger than it.Here 1<n<101

Ex: arr=[1,6,5,7,10,8,9]
Output: 7

Explanation: Here all the elements to the left of 7 are smaller than it and all the elements to the right of it
are greater than it.

Ex: arr=[5,6,2,8,10,9]
Output: -1
Explanation: Here there is no element in the array which satisfies the given condition.

Algorithm:
For each element in our array we find the max element to the left of that element and the minimum element to
the right of that element. If our element is greater than the left max and smaller than the right min then we
know that this is our answer.

Code:
int prefix[N];
int suffix[N];
prefix[0]=INT_MIN;
suffix[N-1]=INT_MAX;
for(in1;i<N;i++){
prefix[i]=max(prefix[i-1],arr[i-1]);
}
for(int i=N-2;i>=0;i--){
suffix[i]=min(suffix[i+1],arr[i+1]);
}
for(int i=0;i<N;i++){
if(prefix[i]<arr[i] && arr[i]<suffix[i]){
return arr[i];
}t i=
}
return -1;

Cracking the Coding Interview in C++ - Foundation


Array-3
Assignment Solutions
Assignment Solutions
Q1 - Given two vectors arr1[] and arr2[] of size m and n sorted in increasing order. Merge the
(Easy)
two arrays into a single sorted array of size m+n.
Input: arr1=[1,2,3] arr2=[4,5,6]

Output: arr=[1,2,3,4,5,6]

Input: arr1=[1,3,5] arr2=[2,4,6]

Output: arr=[1,2,3,4,5,6]

int i=m-1; //first pointer

int j=n-1; //second pointer

int k=m+n-1;

int arr[m+n];

while(i>=0 && j>=0)

if(arr1[i]<arr2[j]) //comparing the two elements at which our


pointers are

arr[k--]=arr1[j--];

}else{

arr[k--]=arr2[i--];

while(j>=0)

arr[k--]=arr2[j--];

while(i>=0)

arr[k- -]=arr1[i–];

return arr;

Q2 - Given a vector arr[] sorted in increasing order of n size and an integer x, find if there exists
(Easy)
a pair in the array whose sum is exactly x.
Given: n>0

Input: [-1,0,1,2,3] x=2

Output: Yes

Input: [1,2,3,4] x=9

Output: No

Take 2 pointers i and j where i points at the start of the array and j points at the last index of the
array now:

if arr[i]+arr[j]<k this means that we need to increase either of arr[i] and arr[j] since j points at
the last index so we need to increase i++;

else do j–;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions
int i=0;

int j=n-1;

while(i<j)

if(arr[i]+arr[j]==x)

cout<<”Yes”;

break;

}else if(arr[i]+arr[j]>x)

j--;

}else{

i++;

cout<<”No”;

Q3 - Given a vector arr[] sorted in increasing order of n size and an integer x, find if there exists
(Medium)
a pair in the array whose absolute difference is exactly x.
Given: n>0

Input: [5,10,15,20,26] x= 10

Output: Yes

Input: [5,6,7,8,9] x=4

Output: Yes

Input: [9,23,45,69,78] x=56

Output: No

Take 2 pointers i and j with i pointing at the beginning of the array and j pointing at the index next to i.

int i=0;

int j=1;

while(i<size && j<size)

if((arr[j]-arr[i])==(n))

cout<”Yes”;

}else if((arr[j]-arr[i] )< (n))

j++;

}else{

i++;

cout<<”No”;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions
Q4 - Given a vector arr[] sorted in increasing order. Return an array of squares of each (Medium)
number sorted in increasing order. Where size of vector 1<size<101.
Input: [0,1,2,3]

Output: [0,1,4,9]

Input: [-5,-4,-3,-2,-1]

Output: [1,4,9,16,25]

Input: [-4,-3,-1,0,2,10]

Output: [0,2,4,9,16,100]

int i=0;

int j=arr.size()-1;

vector<int> ans(nums.size(),0);

int ind=nums.size()-1;

while(i<=j && ind>=0)

if(abs(nums[i])>abs(nums[j])) //compare the absolute values at the two pointers


and based upon the comparison push the square of value with smaller absolute value in the
answer vector.

ans[ind]=arr[i]*arr[i];

ind--;

i++;

}else{

ans[ind]=arr[j]*arr[j];

ind--;

j--;

return ans;

Q5 - Given a vector arr[] sorted in increasing order of n size and an integer x, find the number
(Hard)
of unique pairs that exist in the array whose absolute sum is exactly x.
Input: [1,2,3,4,6] x=7

Output: 2

Explanation: 1,6 and 3,4 sum to 7

Input: [3,1,3,5,3] x=6

Output: 2

Explanation: The unique pairs are 3,3 and 1,5

Input: [2,2,2] x=4

Output: 1

Explanation: The only unique pair is 2,2

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions
int ans = 0;

int i=0, j=arr.size()-1;

while(i < j){

if(arr[i] + arr[j] == k){ // found elements just increase counter

ans++;

i++;

j--;

else if(arr[i] + arr[j] > k) j--; // sum is large so decrease the bigger element, i.e.
jth element

else i++; // sum is small so increase the smaller element, i.e. ith element

return ans;

Q6 - Given a vector array nums, print the count of triplets [nums[i], nums[j], nums[k]] such
(Hard)
that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == x. Where k is an integer

given by the user.

Note: The solution set must not contain duplicate triplets and should not have 3 loops.
Input: [-1,0,1,2,-1,-4] x=0

Output: 2

Explanation: The two triplets are: -1,0,1 and 1,2,-1

Input: [1,2,3] x=5

Output: 0

Problem is similar to two sum, we just need an extra loop which is the third element in each iteration and thus
subtract it from the required sum and then run 2 sum on the vector.In two sum problem we had the relation
a+b=x, here we have a+b+c=x which means a+b=x-c, therefore we need to find a & b which satisfies this
equation for different possible values of c.

int count=0;

for(int i=0;i<nums.size();i++) //extra loop

int j=i+1;

int k=nums.size()-1;

int val=x-nums[i];

while(j<k) //normal two sum problem

int sum=nums[j]+nums[k];

if(sum<val)

j++;

}else if(sum>val){

k--;

}else{

vector<int> temp={nums[i],nums[j],nums[k]};

count++;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions
while(j<k && nums[j]==temp[1]) //doing this so that there are no same
triplets

j++;

while(j<k && nums[k]==temp[2]) // doing this so that one triplet is


counted once

k--;

while(i+1<nums.size() && nums[i]==nums[i+1]) // doing this so that one triplet


is counted once

i++;

return count;

Cracking the Coding Interview in C++ - Foundation


Lesson:

Arrays - 2
Pre-Requisites
Loops
Functions
Basics of arrays

List of Concepts Involved


Vectors in C++
Basic STL(Standard Template Library) operations
Looping in Vector
Problems in vector

Since we have come this far in arrays, it is worth mentioning here that there is a provision in C++ wherein we
can store the elements/data dynamically and sequentially. That means the length of this container is dynamic.
These are called vectors ! Let's learn about them.

Topic: Vectors in C++


Vectors are dynamic arrays that can be resized whenever an element is inserted or deleted. Vectors also have
contiguous storage like arrays but their size can change dynamically according to the requirements of user.
Another important point to note here is that vectors are not compulsorily bound by index values.

Declaration Syntax:

vector < data_type > name;

Example:

vector<int> v;

vector<char> a;

Note: We can even declare a vector of fixed size also with the following syntax:

vector<int> v(n);

Here, a vector of size n is declared.

Topic: Basic Operations on Vectors


1 . J ust like in arrays, it returns the size of vector.

Example:

v = {10,20,30,40,50} ;

co t u v i e()
<< .s z << end ;

O utput :

Cracking the Coding Interview in C++ - Foundation


2. Resizing operation in vector

Unlike the fixed size approach of arrays, we can resize the vector according to our requirement.

Example:

vector<int> v;

v.resize(n);

Note: This is extremely useful when we do not know the size initially (at the time of creating the vector). It can

be resized anytime as per need.

Vector capacity() function: It returns the size of the storage space allocated to the vector. This capacity is

greater than or equal to the size of the vector catering the need for extra space to allow growth without the

need to reallocate on each insertion.

Note: This capacity is not the limit for growth and can be automatically expanded.

Code Example:

vector<int> v;

v.resize(10);

cout << v.capacity() << endl;

v.resize(90);

cout << v.capacity() << endl;

Output:

16

128

Note: Whenever we resize and increase the size of the vector, the total capacity gets to the next power of 2 or

the remaining memory. For example, in the above case, the vector size is 10 but its capacity is the closest next

power of 2 i.e.16. When increased to 90, its capacity went to the closest next power of 2 i.e. 128.

3. Inserting an element at the back of the vector using push_back operation.

Code:

vector<int> v = {10,20,30,40};

v.push_back(50);

Now the new vector will have values: {10,20,30,40,50}.

4. Popping the last element of the vector using pop_back operation.

Code:

vector<int> v = {10,20,30,40,50};

v.pop_back();

Now the new vector will have values: {10,20,30,40}.

Cracking the Coding Interview in C++ - Foundation


6. Insert an element somewhere in the vector's middle/ (in between the elements).

Syntax:

vector<int> v;

v.insert(position, value);

Position specifies to the iterator which points to the position where the insertion is to be done.

Example Code:

vector<int> v = {10,20,30,40,50};

v.insert(v.begin() + 2, 100);

The new vector will look like this:

{10,20,100,30,40,50}

7. Deleting an element in a vector at a specific position

Syntax:

v.erase(position);

Example Code:

vector<int> v = {10,20,30,40,50};

v.erase(v.begin() + 2);

The new vector will look like this:

{10,20,40,50}

8. Clearing the vector : clear() function is used to remove all the elements of the vector container, thus

making its size 0.

Code:

vector<int> v = {10,20,30,40,50};

v.clear();

Now v will be empty.

Topic: Looping in Vector


There are many ways to traverse through the elements of a vector. The most common and widely used ways of
looping are:

For Loop

vector<int> v;

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

v.push_back(i);

// now by the above loop v will have the values : {0,1,2,3,4}

for(int i = 0; i < v.size(); i++){

cout << v[i] << “ “;

Output :

0 1 2 3 4

Cracking the Coding Interview in C++ - Foundation


For each loop

This loop helps in iterating over iterable objects like string, array and so on.

vector<int> a = { 1, 2, 3, 4, 5, 6, 7, 8 };

for (int i : a) {

// accessing each element of the vector

cout << i << endl;

Output:

Explanation : Here, all the elements present in the array will be printed

While loop

int i = 5;

vector<int> v;

while(i > 0) {

v.push_back(i--);

Explanation: Here, we initialize the value of ‘i’ to be 5 and keep decrementing it using the post-decrement
operator and at each step insert it at the back of the vector. Therefore, in the end, the vector will contain
elements from 5 to 0.

Topic: Basic Problems in Arrays


Example 1: Find the last occurrence of an element x in a given array.

Code :

int solve(vector<int> &a, int x)

int index = -1;

for(int i = 0; i < a.size(); i++) {

if(a[i] == x)

index = i;

return index;

Explanation: Traverse through the whole vector and compare the current element with the target element ‘x’
and if it matches then it will be our last seen index.

Cracking the Coding Interview in C++ - Foundation


Example 2: Count the number of occurrences of a particular element x.

Code :

int solve(vector<int> &a, int x)

int count = 0;

for(int i = 0; i < a.size(); i++) {

if(a[i] == x)

count++;

return count;

Explanation: Just check if the element is equal to the element x and increment the count variable and in the
end return it.

Example 3: Count the number of elements strictly greater than value x.

Code :

int solve(vector<int> &a, int x)

int count = 0;

for(int i = 0; i < a.size(); i++) {

if(a[i] > x)

count++;

return count;

Explanation: Traverse the array and just check if the element is greater than x and increment the count
variable, in the end just return it.

Example 4: Check if the given array is sorted or not.

Code :

bool solve(vector<int> &a)

bool ans = true;

for(int i = 1; i < a.size(); i++) {

if(a[i] < a[i-1])

ans = false;

return ans;

Explanation: Consider the answer to be true, then traverse the array and at each point check if the previous
element is greater than the current. The answer will become false as the array will not be sorted.

Cracking the Coding Interview in C++ - Foundation


Example 5: Find the difference between the sum of elements at even indices to the sum of elements at odd
indices.

Code :

int solve(vector<int> &a)

int sum = 0;

for(int i = 0; i < a.size(); i++) {

if(i % 2 == 0) {

sum += a[i]; // adding values at even indices

} else {

sum -= a[i]; // subtracting values at odd indices

return sum;

Explanation: Traverse the vector and add values at even indices and subtract values at the odd indices.

Upcoming Class Teasers:


Problem Solving in Arrays

Cracking the Coding Interview in C++ - Foundation


Lesson:

Arrays - 3

(Basic Problem Solving)


Pre-Requisites
Concept of arrays
Vectors

List of Concepts Involved


Problem solving using arrays and vectors

Pattern: Target sum (Brute Force Approach)


In this approach, we try to find the sum of the elements of an array to yield a particular target value. In the
brute force approach, we use the nested for loop and try to match the value at every point.

Important Note: The number of loops depends on the number of elements we have to take in the array. For
example, for pair sum, we use 2 nested for loops. And for triple sum, we use triple nested for loop.

Let us go through the problems discussed below for better understanding.

Problem 1: Find the total number of pairs in the array whose sum is equal to the given value x.

Code:

int pairSum(vector<int> &a, int x) {

int count = 0;

int n = a.size();

for(int i=0;i<n;i++)

for(int j=i+1;j<n;j++)

if(a[i]+a[j]==x)

count++;

return count;

Explanation: Traverse through the array using a nested for loop (i.e. one for loop within another for loop), and
add/consolidate the sum of the elements at each iteration. Compare that sum with the target value ‘x’ and
increment the count if found equal. Return the value of count in the end.

Problem 2: Count the number of triplets whose sum is equal to a given value x.

Cracking the Coding Interview in C++ - Foundation


Code:

int findTriplet(vector<int> &a, int x) {

int n = a.size();

int count = 0;

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

for(int j=i+1;j<n;j++){

for(int k=j+1;k<n;k++){

if(a[i]+a[j]+a[k]==x){

count++;

return count;

Explanation: Traverse through the array using a triple nested for loop, and just add the sum of the elements at
each iteration, then compare that sum with target value ‘x’ and increment the count if they are found to be
equal. Return the value of count in the end.

Pattern: Basic Miscellaneous Problems

Here, we will discuss array manipulation problems where we perform some operations on the array in order to
solve the problem.

Problem 3: Find the unique number in a given array where all the elements are repeated twice with one value
being unique.

Code:

int findUnique(vector<int> &a){

int n = a.size();

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

for(int j=i+1;j<n;j++){

if(a[i]==a[j]){

a[i] = a[j] = -1;

for(int i=0;i<n;i++)

if(a[i]>0)

return a[i];

return -1;

Explanation: Traverse through the array. In the first traversal, take the current element and find if it appears
again in the array using a nested for loop. If it appears again in the array, just mark it is as -1. In the end, use a
single traversal to find if any element is positive, that means it has no duplicate and hence it is our answer.

Cracking the Coding Interview in C++ - Foundation


Problem 4: Find the second largest value in a given array.

Code:

int secondLargestValue(vector<int> &a) {

int n = a.size();

int max = INT_MIN;

int smax = INT_MIN;

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

if(max<a[i])

max = a[i];

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

if(a[i]!=max)

if(a[i]>smax)

smax = a[i];

return smax;

Explanation: First find the max using a single traversal. It can be found by comparing every element while
traversing through the array. In the second traversal, check at every point if the current element is not the max
element, it can be compared to find the second max element.

Problem 5: Rotate the given array ‘a’ by k steps, where k is non-negative.

Note: k can be greater than n as well where n is the size of array ‘a’.

Code :

// with extra space

vector<int> rotate(vector<int>& a, int k) {

int n = a.size();

k %= n; // k can be greater than n

vector<int> ans(n,-1);

for(int i = n-k; i <= n-1; i++) {

ans[i-(n-k)] = a[i];

for(int i = 0; i < n-k; i++) {

ans[i+k] = a[i];

return ans;

Cracking the Coding Interview in C++ - Foundation


Explanation: Create a new array ‘ans’ and add the last k elements first in the ans array and the rest of the
elements after that. We can do that by traversing the array twice as shown. Note: Make sure to take modulus of
k by n, as value of k can be greater than n so it will become less than n as :

k = constant * n + reminder

Here reminder = k % n

If we rotate an array n times it will not be of any use as the array will come back to the same position, so
remove that from k and take the remaining part only.

Problem 6: For Q inputs, check if the given number is present in the array or not.

Note: Value of all the elements in the array is less than 105.

Code :

int n;

cin >> n;

vector<int> a(n);

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

cin >> a[i];

const int N = 1e5 + 10;

// creating a frequency array as max(a[i]) < 105

vector<int> freq(N, 0);

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

freq[a[i]]++;

int q;

cin >> q;

while (q--) {

int val;

cin >> val;

if (freq[val] > 0) {

cout << "YES" << endl;

} else cout << "NO" << endl;

Input :

1 1 2 7

Cracking the Coding Interview in C++ - Foundation


Output:

YES

YES

NO

NO

Explanation: Create an array ‘freq’ to store frequency of element and increment the count of values that the
user is entering. This way we have the count of all the values that the user has entered and the answer/output
would be YES whenever the count of the values will be positive; when the count is 0, the answer will be NO.

That is all for this lesson! See you in the next one. Happy Learning !

Upcoming Class Teasers:


Advance problem solving using arrays

Cracking the Coding Interview in C++ - Foundation


Lesson:

Problem on Arrays
Pre-Requisites
Arrays
Vectors

List of Concepts Involved


Array Problems based on 2 pointer approach

Pattern: Two Pointers


In this approach, we declare two pointers and perform operations on the array. The two-pointers are usually
declared, one at the start and the other at the end. We increment and decrement them as per the problem.

Look at the problems discussed below to have a better understanding.

Problem 1: Sort an Array consisting of only 0s and 1s.

Explanation of approach: Take two pointers, one from start and the other from the end. If the start pointer’s
element has a value 1 and the end pointer’s element has a value 0, then we swap them (as we want to sort the
array). Check this condition, at every iteration, and interchange the values if the condition is satisfied, else
increment the starting pointer and decrement the ending pointer as done in the program.

Code:

void sortZeroesAndOne(vector<int> &a) {

int n = a.size();

int i = 0;

int j = n - 1;

while(i<j){

if(a[i]==1 && a[j]==0){

a[i] = 0;

a[j] = 1;

i++;

j--;

if(a[i]==0) i++;

if(a[j]==1) j--;

return;

Problem 2: Given an array of integers ‘a’, move all the even integers at the beginning of the array followed by
all the odd integers. The relative order of odd or even integers does not matter. Return any array that satisfies
the condition.

Input :

[1,2,3,4,5]

Output :

[4,2,3,1,5]

Cracking the Coding Interview in C++ - Foundation


Explanation of approach:

We need to keep all the even parity values at the beginning followed by the odd values so whenever we
encounter the case of an even value at the end pointer and odd value at the start pointer, we swap them. Also,
we keep on incrementing the pointers if the values are already at the correct position.

Code:

vector<int> sortArrayByParity(vector<int>& a) {

int i = 0, j = a.size()-1;

while(i < j) {

if(a[i] % 2 == 1 && a[j] % 2 == 0) {

swap(a[i], a[j]);

i++, j--;

if(a[i] % 2 == 0) i++;

if(a[j] % 2 == 1) j--;

return a;

Problem 3: Given an integer array ‘a’ sorted in non-decreasing order, return an array of the squares of each
number sorted in non-decreasing/increasing order.

Input :

[-10,-3,2,5,6]

Output :

[4,9,25,36,100]

Explanation of approach:

Note that the square of a negative number is always positive so we can just compare the absolute values.
Given that the array is sorted, we can just take the higher absolute value from the start or end of the array and
move our pointers accordingly. In the end, we will be required to reverse the answer as we are taking the higher
values first so it will be in decreasing order and we have to return our answer in non-decreasing/increasing
order.

Code:

vector<int> sortedSquares(vector<int>& a) {

int n = a.size(), i = 0, j = n-1;

vector<int> ans;

while(i <= j) {

if(abs(a[i]) < abs(a[j])) {

a[j] *= a[j];

ans.push_back(a[j--]);

} else {

a[i] *= a[i];

ans.push_back(a[i++]);

Cracking the Coding Interview in C++ - Foundation


}

reverse(ans.begin(), ans.end());

return ans;

That is all for this lesson! Do not miss the next one !!

Upcoming class teaser :


Basic problems based on arrays.

Cracking the Coding Interview in C++ - Foundation


Lesson:

Problems on Array - 3
Pre-Requisites
Arrays
Vectors

List of Concepts Involved


Array Problems based on prefix sums concept.

Pattern: Prefix Sums


In this approach, we create an array by taking the sum of values from the beginning of the array and keep
adding them. Prefix[i] represents the values from the beginning of the array till index ‘i’. Using this prefix sums
technique, we can calculate range sums easily which will be seen in the problems discussed below.

Problem 1: Given an integer array ‘a’, return the prefix sum/ running sum in the same array without creating a
new array.

Input :

5 4 1 2 3

Output :

5 9 10 12 15

Code:

vector<int> runningSum(vector<int> a) {

for (int i = 1; i < a.size(); ++i){

a[i] += a[i - 1];

return a;

Problem 2: Check if we can partition an input array into two subarrays with equal sum. More formally, check
that the prefix sum of a part of the array is equal to the suffix sum of the rest of the array.

Input :

5 2 3 4

Output :

True

Explanation of approach:

We can calculate the total sum of the whole array in the first traversal. In the second traversal, check at every
point that the sum of the prefix part of the array is equal to the suffix part of the array. Calculate the suffix using
total sum - current prefix.

Cracking the Coding Interview in C++ - Foundation


Code:

bool check(vector<int> &a) {

int n = a.size();

int pref = 0, total_sum = 0;

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

total_sum += a[i];

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

pref += a[i];

int suff = total_sum - pref;

if (pref == suff) return true;

return false;

Problem 3: Given an array of integers ‘a’ of size n. For q number of inputs, print the sum of values in a given
range of indices from l(starting index for the range) to r(ending index for the range),both l and r included in the
sum.

More formally, print a[l] + a[l+1] + a[l+2] + … + a[r] for each q.

Note: Array ‘a’ follows 1-based indexing i.e. element 1 is at index 1 and not 0, as it usually is.

Input :

5 //Number of elements in the array a

5 1 2 3 4 //All the elements (space separated)

4 //value of q

1 1 //l and r for the 1st q, q=1

1 3 //l and r for the 2nd q, q=2

4 5 //l and r for the 3rd q, q=3

1 5 // l and r for the 4th q, q=4

Output :

5 //sum from a[1] to a[1], i.e. 5 itself

8 //sum from a[1] to a[3], i.e. 5+1+2 = 8

7 //sum from a[4] to a[5], i.e. 4+3=7

15 //sum from a[1] to a[5], i.e. 5+1+2+3+4=15

Cracking the Coding Interview in C++ - Foundation


Code:

#include<iostream>

using namespace std;

int main(){

int n;

cin >> n;

vector<int> a(n + 1);

for (int i = 1; i <= n; i++) { // taking one based indexing for easier calculations

cin >> a[i];

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

a[i] += a[i - 1]; // making a prefix sum array out of given array

int q; // no of queries

cin >> q;

while (q--) {

int l, r;

cin >> l >> r;

// we need to find sum of values of indices from l to r (both included)

// so that is equal to (total sum till r - total sum till l-1 )

// note we also need to include the value at index l so subtracting only till (l-1)

cout << a[r] - a[l - 1] << endl;

That is all for this lesson! Do not miss the next one !!

Upcoming class teaser :


2-D array problems

Cracking the Coding Interview in C++ - Foundation


Problem on Arrays - 3
Assignment Solutions
Assignment Solutions
Q1 - Given an integer array and two integers L and R. Find the sum of elements between the
(Medium)
index L and index R.

Note: Both L and R inclusive.


Input: [1,2,3,4,5] L=1 R=3

Output: 9

Explanation: 2+3+4=9

Input: [1,2,3,4,5] L=2 R=2

Output: 3

Explanation: 3

for(int i=1;i<n;i++)

arr[i]+=arr[i-1];

int ans=arr[R]-arr[L-1];

return ans;

Explanation: The prefix sum will store the sum till Rth index and if we subtract the sum till L-1th
index then we get the sum between L and R.

Q2 - ​There is a man going on a trek. The trek consists of n + 1 points at different altitudes. The
(Easy)
man starts his trek on point 0 with altitude equal 0. You are given an integer array height

of length n where height[i] is the net height in altitude between points i​​and i + 1 for all

(0 <= i < n). Return the highest altitude of a point.


Input: height=[-4,1,6,0,-8]

Output: 3

Explanation: The man starts at 0 and since then the altitudes covered will be [0,-4,-3,3,3,-5] so
the greatest altitude will be 3

Input: height=[-5,-3,-2]

Output: 0

Explanation: The man starts at 0 and since then the altitudes will be[0,-5,-3,-2] so the greatest
altitude will be 0.

for(int i=1;i<n;i++)

height[i]+=height[i-1];

int ans=0; //initially the man is at height=0

for(int i=0;i<n;i++)

ans=max(ans,height[i]);

return ans;

Explanation: We just need to find the prefix sum of all heights and then find the max height
which is required as per the question.

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions
Q3 - ​Given an integer array arr consisting of 0’s and 1’s only, return the max length of
(Medium)
sequence which contains equal numbers of 0 and 1.
Input: arr=[0,1,0,1]

Output: 4

Explanation: The longest sequence is 0,1,0,1

Input: arr=[0,1,1,0,1,1,1]

Output: 4

Explanation: The longest sequence is 0,1,1,0

int ans = 0;

int height= 0;

for (int i=0;i<gain.size();i++) {

height = height + gain[i];

if(ans>height)

ans=height;

return ans;

Q4 - ​Given an integer array arr, return the number of consecutive sequences(subarrays) with
(Hard)
odd sum.
Input: [1,3,5]

Output: 4

Explanation: These sequences are [1],[3],[5] and [1,3,5]

Input: [0,2,4]

Output: 0

for(int i=1;i<n;i++)

arr[i]+=arr[i-1];

int count=0;

for(int i=0;i<n;i++)

for(int j=i+1;j<n;j++)

if(i==0 && arr[j]%2!=0)

count++;

else if((arr[j]-arr[i-1] && i!=0)%2!=0)

count++;

return count;

Explanation:Just find prefix sum and then check all the subarrays if the sum is odd

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions
Q5 - Given an integer array arr, return an array ans such that ans[i] is equal to the product of
(Hard)
all the elements of arr except arr[i].
Input: arr=[1,3,5,7]

Output: [105,35,21,15]

Explanation: ans=[3*5*7,1*5*7,1*3*7,1*3*5]

Input: [-5,-4,0,4,5]

Output: [0,0,400,0,0]

vector<int> ans(nums.size());

int pre[nums.size()];

pre[0]=nums[0];

int pos[nums.size()];

pos[nums.size()-1]=nums[nums.size()-1];

for(int i=1;i<nums.size();i++)

pre[i]=nums[i]*pre[i-1];

cout<<pos[nums.size()-1];

for(int i=nums.size()-2;i>=0;i--)

pos[i]=pos[i+1]*nums[i];

for(int i=0;i<nums.size()-1;i++)

if(i==0)

ans[0]=pos[1];

}else{

ans[i]=pos[i+1]*pre[i-1];

ans[nums.size()-1]=pre[nums.size()-2];

return ans;

Explanation: Here we need to find the prefix product of our array from the beginning as well as
the end and store it in two different vectors/arrays. We are doing this because for each index i
the answer will be product of begin[i-1]*end[i+1] i.e. the product from 0th to i-1th index and from
i+1th index to end the array.

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions
Q6 - ​Given an array of size ‘n’ (initially zero) and ‘Q’ updates (increase the value of all index
(Medium)
from l to r with value x) and in the end print all the numbers of the array.
Input: q = 3, x = 5, n = 5

[l,r] = {{0,3}, {4,4}, {1,2}

Output: [5 10 10 5 5]

void solve() {

int n, q, x;

cin >> n >> q >> x;

vector<int> a(n, 0);

while (q--) {

int l, r;

cin >> l >> r;

if (r + 1 <= n - 1) a[r + 1] -= x;

a[l] += x;

// taking prefix sums

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

a[i] += a[i - 1];

for (auto &i : a) cout << i << “ “;

Cracking the Coding Interview in C++ - Foundation


Lesson:

2D Arrays in C++
Pre-Requisites
Basic C++ synta
Basics of arrays

List of Concepts Involved


Multidimensional Arra
2D Arra
2D Array Problems

Topic: Multidimensional Array Introduction


In C++, we can create “ array of an array” which are known as a multidimensional array. It stores homogeneous
data in a tabular form. Data in multidimensional arrays are stored in row-major order i.e. elements are filled in
the current row before moving to the next row.

Syntax to declare an N-Dimensional array:

datatype array_name[size1][size2].....[sizeN];

A combination of multiple 1D arrays is known as 2D array.

Syntax to declare a 2D array:

datatype array_name[rows][columns];

where rows imply the number of rows needed for the 2D array and column implies the number of columns
needed.

For example:

int arr[4][5];

Here, arr is a two-dimensional array. It can hold a maximum of 20 elements. Let us understand how.

We can think of this array as a table with 4 rows and each row has 5 columns as shown below.
Col1 Col2 Col3 Col4 Col5

Row 1

Row 2

Row 3

Row 4

Cracking the Coding Interview in C++ - Foundation


In this array you can store the values as required. Suppose, in the above array you want to store 10 at every
index, you can do so using the following code:

#include < iostream >

using namespace std;

void main(){

int arr[4][5];

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

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

arr[i][j] = 10;

There are two methods to initialize two-dimensional arrays.

Method 1

int arr[2][3]={11,22,33,44,55,66};

Method 2

int arr[2][3]={{11,22,33},{44.55,66}};

Now that we are equipped with all the relevant information about 2-D array, let us move a step ahead to
understand 3-D arrays. Although, these are rarely used in the common problems that we solve but it is always
better to have a slight idea of how the dimensions of an array are scaled up.

Three-dimensional arrays also work in a similar way. For example:

double arr[3][2][5];

This array arr can hold a maximum of 30 elements of double type.

This array can be considered as 3 arrays of 2D which has 2 rows and 5 columns.

Cracking the Coding Interview in C++ - Foundation


Here, we have 5 elements in each row and 2 such rows so total 10 elements in one 2-D array then we have 3
such 2-D arrays so the total number of elements will be 3*10 that is 30.

We can find out the total number of elements in the array simply by multiplying its dimensions:

3*2*5=30

Topic: Taking 2D Array as input


For all implementations, we will have to take inputs from user and work on that data.

Let us learn to take inputs in a 2-D array:

A 2D array is an array that contains elements in the form of rows and columns. It means we require both rows
and columns to populate a two-dimensional array. Matrix is the best example of a 2D array. We have already
learnt to declare 2D arrays and the way to access each element.

Let us have a glance at the code to have a clear idea.

#include<iostream>

using namespace std;

int main()

int arr[3][4];

int i, j;

cout<<"\n2D Array Input By user:\n";

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

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

cout<<"\ns["<<i<<"]["<<j<<"]= ";

cin>>arr[i][j];

cout<<"\nThe 2-D Array entered by user is:\n";

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

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

cout<<"\t"<<arr[i][j];

cout<<endl;

Cracking the Coding Interview in C++ - Foundation


OUTPUT :

Explanation : In the above code firstly we are taking the input of the different elements of the array and after
taking input we are printing the elements of the array.

Cracking the Coding Interview in C++ - Foundation


Topic: Why do we need Multi-Dimensional Arrays?
Multi-dimensional arrays are the best choice for representing grids/matrices
The most commonly used multidimensional array is the two-dimensional array, also known as a table or
matrix
The advantage of a multidimensional array is that multi-dimensional input can be taken from the user, with
faster access and a predefined size
Multidimensional or 2D array is easy to access and maintain
You don't have to use multiple variables for each entity which can reside in a single variable throughout
your application. Every variable created takes up a specific resource that has to be looked up when
accessed.

Questions:

Q1. Write a program to display multiplication of two matrices entered by the user.

Input

enter the number of row=3

enter the number of column=3

enter the first matrix element=

1 2 3 4 5 6 7 8 9

enter the second matrix element=

1 2 3 4 5 6 7 8 9

Output

multiply of the matrix=

30 36 42

66 81 96

102 126 150

Explanation
For multiplication of two matrices, the number of columns of the first matrix should be equal to the number
of rows of the second matrix. Here, we have assumed both matrices have equal number of rows and
columns
The program below asks for the number of rows and columns of two matrices and then elements of the
matrices
The product of two matrices, m and n, is the sum of the products across some row of m with the
corresponding entries down some column of n. In simple words, the dot product of the first row of the first
matrix and the first column of the second matrix will result in the first element of the product matrix.

Look at the code to see how it can be implemented.

Cracking the Coding Interview in C++ - Foundation


Solution

#include <iostream>

using namespace std;

int main()

{ int m,n;

cout<<"enter the number of row=";

cin>>m;

cout<<"enter the number of column=";

cin>>n;

int arr1[m][n],arr2[m][n],ans[m][n],i,j,k;

cout<<"enter the first matrix element=\n";

for(i=0;i<m;i++)

for(j=0;j<n;j++)

cin>>arr1[i][j];

cout<<"enter the second matrix element=\n";

for(i=0;i<m;i++)

for(j=0;j<n;j++)

cin>>arr2[i][j];

cout<<"multiply of the matrix=\n";

for(i=0;i<m;i++)

for(j=0;j<n;j++)

ans[i][j]=0;

for(k=0;k<n;k++)

ans[i][j]+=arr1[i][k]*arr2[k][j];

//for printing result

for(i=0;i<m;i++)

for(j=0;j<n;j++)

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

cout<<"\n”;

return 0;

Cracking the Coding Interview in C++ - Foundation


OUTPUT :

Q2. Write a program to Print the transpose of the matrix entered by the user.

Explanation:

Input :

row=3

col=3

arr[] = {{1,2,3}, {4,5,6}, {7,8,9}}

Output : 1 4 7 2 5 8 3 6 9

Explanation:

Transpose of a matrix is obtained by changing rows to columns and columns to rows


Run a nested loop using two integer pointers i and j for 0 <= i < row and 0 <= j < co
Set trans[i][j] equal to arr[j][i]

Cracking the Coding Interview in C++ - Foundation


Solution:

#include<iostream>

using namespace std;

int main()

int row,col;

//Get size of matrix

cout<<"Enter the no of rows in the Matrix:";

cin>>row;

cout<<"Enter the no of columns in the Matrix:";

cin>>col;

int arr[row][col];

//Taking input of the matrix

int i,j;

cout<<"Enter the Elements:\n";

for(i=0;i<row;i++)

for(j=0;j<col;j++)

cin>>arr[i][j];

//compute the transpose matrix

int trans[col][row];

for(i=0;i<col;i++)

for(j=0;j<row;j++)

trans[i][j]=arr[j][i];

//display the transpose Matrix

cout<<"Transpose of the given Matrix is:\n";

for(i=0;i<col;i++)

for(j=0;j<row;j++)

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

cout<<"\n";

Cracking the Coding Interview in C++ - Foundation


OUTPUT :

That is all for the class today, let us catch up in the next lesson to solve problems based on 2-D arrays

Upcoming Class Teasers:


Practice problems based on 2D Arrays

Cracking the Coding Interview in C++ - Foundation


2D Arrays in C++
Assignment Solutions
Assignment Solutions
Q1 - Given a 2D matrix with m rows and n columns containing integers, find and print the (Easy)
maximum value present in the array.
m=3

n=3

arr[] = {{1,2,3}, {4,5,6}, {7,8,9}}

Output: 9

Explanation: We will iterate through all the elements of the matrix using 2 for loops and find the
maximum amongst all those elements i.e. mat[i][j].

Here INT_MIN is the minimum value possible for any integer variable to have. Its value is
INT_MIN = -2147483648
#include <iostream>

#include <climits>

using namespace std;

int main()

int m,n;

cin>>m>>n;

int mat[m][n];

for(int i=0;i<m;i++)

for(int j=0;j<n;j++)

cin>>mat[i][j];

int val=INT_MIN;

for(int i=0;i<m;i++)

for(int j=0;j<n;j++)

if(mat[i][j]>val)

val=mat[i][j];

cout<<val;

return 0;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q2 - You are given a n*n square matrix, you need to rotate the matrix by 90 degrees in
(Medium)
clockwise direction. You need to do it in-place i.e. you are not allowed to make a new

matrix and allocate the elements to it. Make the changes in the same matrix and print it.
n=3

arr[] = {{1,2,3}, {4,5,6}, {7,8,9}}

Output: {{7,4,1},{8,5,2},{9,6,3}}

Explanation: In order to rotate a matrix clockwise we first need to take the transpose of the matrix and then
swap the diagonal elements i.e. for diagonals we need to swap (i,j) with (j,size-j-1). The transpose and the
swapping part has been commented below in the code.

swap(a,b) : is an inbuilt function of c++ which is used to swap the values of two variables/elements(a and b).

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

#include <iostream>

#include <vector>

using namespace std;

int main()

int n;

cin>>n;

int mat[n][n];

for(int i=0;i<n;i++)

for(int j=0;j<n;j++)

cin>>mat[i][j];

for(int i=0;i<n;i++)

for(int j=0;j<i;j++)

swap(mat[i][j],mat[j][i]);

//swap diagonal elements

for(int i=0;i<n;i++)

for(int j=0;j<n/2;j++)

swap(mat[i][j],mat[i][n-j-1]);

cout<<endl;

//printing the mat

for(int i=0;i<n;i++)

for(int j=0;j<n;j++)

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

cout<<endl;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q3 - Given a m*n integer matrix. If an element of the matrix is 0 then set the complete row and
(Hard)
column of that element to 0. Make the changes inplace and print the matrix.
m=3

n=3

arr[]={{1,2,3},{1,0,1},{5,6,7}}

Output: {{1,0,3},{0,0,0},{5,0,7}}

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

Output:{{0,0,0,0},{0,4,5,0},{0,3,1,0}}

Explanation: We will first store all the cell positions(i,j) in a vector of pair which has the value 0. Then we will
traverse through the vector and make all the rows and columns corresponding to that cell(i,j) as 0.

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

#include <iostream>

#include <climits>

#include <vector>

using namespace std;

int main()

int m,n;

cin>>m>>n;

int mat[m][n];

for(int i=0;i<m;i++)

for(int j=0;j<n;j++)

cin>>mat[i][j];

vector<pair<int,int>> ans; // we are storing all the cells which have value 0

for(int i=0;i<m;i++)

for(int j=0;j<n;j++)

if(mat[i][j]==0)

ans.push_back({i,j});

for(int i=0;i<ans.size();i++) //traversing the ans vector and making row and column of
that

{ //call to 0

int x=ans[i].first;

int y=ans[i].second;

int row=0;

int col=0;

while(row<m)

mat[row][y]=0;

row++;

while(col<n)

mat[x][col]=0;

col++;

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

cout<<endl;

//printing the updated matrix

for(int i=0;i<m;i++)

for(int j=0;j<n;j++)

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

cout<<endl;

Cracking the Coding Interview in C++ - Foundation


Lesson:

2D Array Problems Set 2


Pre-Requisites
Concept of Arrays and vector
Basic understanding of multidimensional arrays

List of Concepts Involved


2D Vectors Concep
Pascal’s Triangle Problem

Topic: Introduction to 2D Vectors


A 2D vector is a “vector of vector”. Like 2D arrays, values can be declared and assigned to a 2D vector.

A normal vector is initialized as:

vector<datatype> vector_name;

Now in the case of a 2D vector, all we need to do is create a vector of datatype vector.

We simply replace "datatype" with "vector<datatype>":

vector<vector<datatype>> vector_name;

Initializing a 2-D vector with help of 1-D vector

vector<int> v1(3, 10); // vector v1 {10, 10, 10}

vector<int> v2(3, 20); // vector v2 {20, 20, 20}

vector<int> v3(3, 3); // vector v3 {30, 30, 30}

vector<vector<int>> vect {v1, v2, v3};

Initializing a 2-D vector of n rows and m columns

vector<vector<int>> vect( n ,vector<int> (m));

Let us now solve some problem to test our understanding so far.

Problems

Q1. Given an integer n, return the first n rows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

Cracking the Coding Interview in C++ - Foundation


Example 1:

Input: n = 5

Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: n = 1

Output: [[1]]

Explanation of approach
Create an auxiliary 2D vector to store generated pascal triangle values having n rows
Iterate through every row and store integer(s) in it
Every row will have a number of columns equal to the row number
First and last column in every row are 1
Other values are the sum of values just above and left of above.

Let us now code the approach.

Cracking the Coding Interview in C++ - Foundation


Solution:

#include <iostream>

#include<vector>

using namespace std;

vector<vector<int>> pascal(int numRows) {

vector<vector<int>> ret;

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

vector<int> row(i + 1, 1);

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

row[j] = ret[i - 1][j] + ret[i - 1][j - 1];

ret.push_back(row);

return ret;

int main(){

int n;

cout<<"Enter number of rows you want : ";

cin>>n;

vector<vector<int>>ans;

ans = pascal(n);

for(int i=0;i<ans.size();i++){

for(int j=0;j<ans[i].size();j++){

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

cout<<endl;

return 0;

OUTPUT :

Upcoming Class Teasers


2D Array problems

Cracking the Coding Interview in C++ - Foundation


Problems on 2D Array - 2

Assignment Solutions
Assignment Solutions

Q1. Given a m*n matrix, Write a function which returns true if the matrix is a perfect matrix. A matrix is
called perfect if every diagonal from top-left to bottom-right has the same elements.

Sample Input: arr[]=[[9,8,7,6],[5,9,8,7],[1,5,9,8]]

9 8 7 6
5 9 8 7
1 5 9 8
Sample Output: true
Explanation:We will skip the first row and column and then traverse each row(i) and check if the diagonal
elements(i-1,j-1) are equal or not, if not then return false.
Code:
#include <iostream>
#include <vector>
using namespace std;
bool check(vector<vector<int>>& mat)
{
int r=mat.size();
int c=mat[0].size();
for(int i=1;i<r;i++)
{
for(int j=1;j<c;j++)
{
if(mat[i][j]!=mat[i-1][j-1])
{
return false;
}
}
}
return true;
}

int main()
{
vector<vector<int>> mat={{9,8,7,6},{5,9,8,7},{1,5,9,8}} ;
if(check(mat))
{
cout<<"true";
}else{
cout<<"false";
}
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q2. Given an array of intervals where intervals[i] = [start, end], merge all overlapping intervals, and
create a function which returns a vector of the non-overlapping intervals that cover all the
intervals in the input.

Sample Input: arr[]=[[1,4],[2,3],[5,8],[6,9]]


Sample Output: [[1,4],[5,9]]

Sample Input: arr[]=[[1,5],[3,9]]


Sample Output: [1,9]

Explanation: We need to merge the overlapping intervals i.e. we need to check if the starting point(i) of an
interval is less than or equal to the ending point of the previous interval(j-1) then we need to merge it.
Code:
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> merge(vector<vector<int>>& s) {
vector<vector<int>> ans;
int j=0;
ans.push_back(s[0]);
for(int i=1;i<s.size();i++)
{
if(ans[j][1]>=s[i][0])
{
ans[j][1]=max(ans[j][1],s[i][1]);
}else{
j++;
ans.push_back(s[i]);
}
}
return ans;
}

int main()
{
vector<vector<int>> mat={{1,4},{2,3},{5,8},{6,9}};
vector<vector<int>> ans=merge(mat);
for(int i=0;i<ans.size();i++)
{
cout<<ans[i][0]<<" "<<ans[i][1]<<endl;
}

Cracking the Coding Interview in C++ - Foundation


Assignment Solutions

Q3. Given an array of intervals where arr[i] = [start, end], return the minimum number of intervals
you need to remove to make the rest of the intervals non-overlapping.[

Sample Input: arr[]=[[1,4],[2,3],[4,5],[6,7]]


Sample Output: 1

Explanation: The interval 1,4 and 2,3 are overlapping so removing any one of them will make the intervals
non overlapping.

Sample Input: arr[]=[[1,2],[2,3],[3,4],[4,5]]


Sample Output: 0

Explanation: Just like the previous question we need to merge the overlapping intervals and count how many
intervals we are merging using the count variable.
Code:
#include <iostream>
#include <vector>
using namespace std;
int merge(vector<vector<int>>& s) {
vector<vector<int>> ans;
int j=0;
ans.push_back(s[0]);
int count=0;
for(int i=1;i<s.size();i++)
{
if(ans[j][1]>s[i][0])
{
count++;
ans[j][1]=max(ans[j][1],s[i][1]);
}else{
j++;
ans.push_back(s[i]);
}
}
return count;
}

int main()
{
vector<vector<int>> mat={{1,4},{2,3},{4,5},{6,7}};
cout<<merge(mat);
}

Cracking the Coding Interview in C++ - Foundation


Lesson:

2D Array Problems Set 2


Pre-Requisites
Concept of Arrays and vector
Basic understanding of multidimensional arrays

List of Concepts Involved


2D Vectors Concep
Pascal’s Triangle Problem

Topic: Introduction to 2D Vectors


A 2D vector is a “vector of vector”. Like 2D arrays, values can be declared and assigned to a 2D vector.

A normal vector is initialized as:

vector<datatype> vector_name;

Now in the case of a 2D vector, all we need to do is create a vector of datatype vector.

We simply replace "datatype" with "vector<datatype>":

vector<vector<datatype>> vector_name;

Initializing a 2-D vector with help of 1-D vector

vector<int> v1(3, 10); // vector v1 {10, 10, 10}

vector<int> v2(3, 20); // vector v2 {20, 20, 20}

vector<int> v3(3, 3); // vector v3 {30, 30, 30}

vector<vector<int>> vect {v1, v2, v3};

Initializing a 2-D vector of n rows and m columns

vector<vector<int>> vect( n ,vector<int> (m));

Let us now solve some problem to test our understanding so far.

Problems

Q1. Given an integer n, return the first n rows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:

Cracking the Coding Interview in C++ - Foundation


Example 1:

Input: n = 5

Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: n = 1

Output: [[1]]

Explanation of approach
Create an auxiliary 2D vector to store generated pascal triangle values having n rows
Iterate through every row and store integer(s) in it
Every row will have a number of columns equal to the row number
First and last column in every row are 1
Other values are the sum of values just above and left of above.

Let us now code the approach.

Cracking the Coding Interview in C++ - Foundation


Solution:

#include <iostream>

#include<vector>

using namespace std;

vector<vector<int>> pascal(int numRows) {

vector<vector<int>> ret;

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

vector<int> row(i + 1, 1);

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

row[j] = ret[i - 1][j] + ret[i - 1][j - 1];

ret.push_back(row);

return ret;

int main(){

int n;

cout<<"Enter number of rows you want : ";

cin>>n;

vector<vector<int>>ans;

ans = pascal(n);

for(int i=0;i<ans.size();i++){

for(int j=0;j<ans[i].size();j++){

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

cout<<endl;

return 0;

OUTPUT :

Upcoming Class Teasers


2D Array problems

Cracking the Coding Interview in C++ - Foundation

You might also like