C++ UPTO 23
C++ UPTO 23
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++
To know and accomplish more of such interesting things , let's now move to the learning part of programming
with programming languages.
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.
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.
• 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.
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.
datatype variable_name
20
RAM
int rate;
rate = 40;
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.
• 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.
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.
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.
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.
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.
Data types in C++ are categorized in three groups: Built-in (Primary), User-defined and Derived.
- Void
- Wide Character
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.
Now that we have learnt all the relevant concepts, let us go ahead and write our very first program!
#include <iostream>
int main()
• 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.
Example:
#include <iostream>
int main()
Example:
cout<<"Physics"<<"Wallah";
Output: PhysicsWallah
cout<<"Physics"<<endl<<"Wallah";
Output: Physics
Wallah
Example:
int num;
cout << "Enter any number "; // Type a number and press enter
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>
int main() {
sum = n1 + n2;
// prints sum
return 0;
MCQs
Q1. What will be the output of the following code?
#include <iostream>
int main(){
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.
Ans: c) String
Explanation:
String is a collection of characters and is stored in a variable of String data type.
Assignment Solutions
Assignment Solutions
Q1 - Take 2 integer values in two variables x and y and print their product.
#include <iostream>
int main()
int x = 23;
int y = 50;
return 0;
#include <iostream>
int main()
return 0;
Q3 - Write a C++ program to take length and breadth of a rectangle and print its area.
#include <iostream>
int main()
int length=10;
int breadth=20;
return 0;
#include <iostream>
int main()
int x = 2;
int cube;
return 0;
#include <iostream>
int main()
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;
Q6 - Write a C++ program to swap two numbers with the help of a third variable.
#include <iostream>
int main()
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" ;
C++ Operators
Pre-Requisites:
• C++ basic syntax
• Data types
• Variables
• Identifiers
• Keywords
- 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
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 !
int main(){
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.
int main() {
int num2 = 8;
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>
int main() {
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.
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.
int main()
// create variables
// == operator
// != operator
// > operator
// < operator
// >= operator
// <= operator
Output: false
true
false
true
false
true
Example code:
#include<iostream>
int main(){
// && operator
int p=15,q=10,r=5;
// || operator
// ! operator
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.
Let's have a look at some of the commonly used assignment operators available in C++ with examples.
+= 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;
int main(){
int p = 10;
int q;
Output: 10
20
200
Clearly x=+10 is better than x=x+10 since evaluation is direct with no intermediate steps for CPU to perform.
^ 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
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.
int main()
{ // variable declaration
c = (a > b) ? a : b;
return 0;
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.
Operator Meaning
+ Unary plus: optional; since numbers are by default positive.
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.
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)).
Let us try a few questions on precedence and associativity to clear the air of confusion.
Example: 2
What does the following code fragment print?
cout<<(4 + 2 + "pqr");
cout<<("pqr" + 4 + 2);
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;
}
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>
int main()
int x,y;
cin >> x;
cin >> y;
return 0;
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>
int main()
int a,b;
cin >> a;
cin >> b;
return 0;
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>
int main()
boys = 17;
cout << "Number of girls getting grade A = " << girls << endl;
return 0;
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
#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
# include <iostream>
using namespace std;
int main() {
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;
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.
Syntax
if (condition)
statement - 1
} else
statement - 2
To solve this problem, we can use an if-else statement. Lets see how !
else
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.
Syntax
if (condition - 1)
statement - 1
else if (condition - 2)
statement - 2
else
statement - 3
Grade Score
A 80-100
B 60-80
C 40-60
D <40
else
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.
Try these
1. Write a program to identify people as “Child” (age < 12), “Teenager” (12 <= age < 18) or “Adult” (age >= 18).
Let us now increase the dimension and abilities of if and explore the concept of nested if-else statements.
Syntax
if (condition - 1)
if (condition - 2)
statement - 1
else
statement - 2
else
statement - 3
else
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.
Syntax
if(condition - 1 && condition - 2)
statement;
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.
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,
It gives us a runtime error since 5 is divided by 0, which isn't a valid operation. However, if we write-
we get “false” as the output. This is because our first condition is false, which is enough to make the entire
condition false here.
Try this:
Write a program to print the value of input if it is even and divisible by 3.
Syntax
if(condition - 1 || condition - 2)
statement;
Code
if (val < 5 || val > 10)
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.
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,
It gives a runtime error since 5 is being divided by 0, which isn't a valid operation. However, if we write-
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.
Syntax
condition ? statement - 1 : statement - 2;
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
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.
Code
switch (ch) {
case ‘a’:
break;
case ‘e’:
break;
case ‘i’:
break;
case ‘o’:
break;
case ‘u’:
break;
default:
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.
switch (val)
case (5):
case (6):
case (7):
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.
switch (val)
case (6):
break;
case (7):
break;
case (8):
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.
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>
int main()
int length,breadth;
cin>>length;
cin>>breadth;
if(length==breadth)
cout<<"It is a square"<<endl;
else
cout<<"It is a rectangle"<<endl;
return 0;
Q2- Write a program to print absolute value of a number entered by the user.
#include <iostream>
int main()
int x;
cout<<"Enter a number"<<endl;
cin>>x;
if(x<0)
x = x*(-1);
return 0;
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>
int main()
int CP,SP, amt; //Input cost price and selling price of a product
cin>>CP;
cin>>SP;
cout<<"Profit = "<<amt;
cout<<"Loss = "<<amt;
else
return 0;
Q4- Write a program to print positive number entered by the user, if user enters a negative number,
it is skipped
#include <iostream>
using namespace std;
int main() {
int number;
return 0;
}
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;
}
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+";
}
Loops
Pre-Requisites
Basic syntax of C++
Variables
Operators
Conditionals
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.
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.
Syntax
while (condition)
statement;
Let us understand the working of while loop with the help of this simple
example -
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;
i = i + 1;
Output - 1 2 3 4 5 6 7 8 9 10
For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
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:
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.
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.
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
Example-
int index = 0;
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
Example-
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-
index = index + 1;
Note
The above statements can all be omitted together too.
We can also have multiple statements inside the loop.
Here, you may see that we are handling two variables, conditions wrt both and final expression, all in one for
loop.
Code
Output - 1 2 3 4 5 6 7 8 9 10
2. Write a short program that prints each number from 1 to 100 on a new line.
For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
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
2. Use a while loop when you are unsure till when the loop will continue, like while finding the first number
Let us move to the next looping statement which is seldom used and is a variation of while loop.
Syntax
do
statement;
} while (condition);
do
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?
do {
idx = idx + 1;
Output- 15 16
Print the sum of the stream of N integers in the input using do while loop.
int N, sum = 0;
cin >> N;
do {
int val;
sum += val;
N--;
Try this
Print the sum of the first 10 natural numbers using do while loop.
Output- 1 2 3
1 2 3
1 2 3
if(i == j) break;
Output- 1
1 2
1 2 3
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:
while (1) {
val += 2;
index += 1;
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.
Code
if(i == 3) continue;
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.
Problems on loops
Pre-Requisites
Basic C++ syntax
Conditionals
Understanding of loops (for, while, do while)
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.
So let us begin!
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.
Code:
#include<iostream>
int main(){
int n;
cin >> n;
int count = 0;
while(n > 0)
count++;
n /= 10;
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.
Code:
#include<iostream>
int main(){
int n;
cin >> n;
int sum = 0;
while(n > 0)
sum += (n % 10);
n /= 10;
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 !
#include<iostream>
int main(){
int n;
cin >> n;
while(n > 0) {
n /= 10;
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:
Code:
#include<iostream>
int main(){
int n;
cin >> n;
int ans = 0;
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:
Code:
#include<iostream>
int main(){
int a,b;
int ans = 1;
ans *= a;
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.
Code :
#include<iostream>
int main(){
int n;
cin >> n;
int fact = 1;
fact *= i;}
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.
Did you know, you can actually draw the basic shapes on the output screen with the knowledge acquired so
far?
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.
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>
int main()
int h=3,w=6, i, j;
cout<<"*";
cout<<endl;
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>
int main()
int h=4,w=6;
cout<<endl;
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.
Example: h=4,w=6
*.*.*.
.*.*.*
*.*.*.
.*.*.*
Solution :
#include<iostream>
int main()
int h=4,w=6, i, 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.
Example if n=4
**
***
****
#include<iostream>
int main()
int n=4;
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.
Example if n=4
****
***
**
Solution:
#include<iostream>
int main()
int n=4;
cout<<("*");
cout<<endl;
***
*****
*******
(Try it yourself first and verify the code/approach with the solution provided at the end of this lesson plan)
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
#include<iostream>
int main()
{ int n=7;
cout<<j<<" ";
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.
(Try these yourself first and verify the code/approach with the solution provided at the end of this lesson plan)
Example if row=4,col=6
123456
123456
123456
123456
Example if row=4,col=6
123456
1 6
1 6
123456
Example if rows=4,col=6
121212
212121
121212
212121
Example if n=4
12
123
1234
Solution:
#include<iostream>
int main()
int n=4;
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.
(Try it yourself first and verify the code/approach with the solution provided at the end of this lesson plan)
Example if n=4
121
12321
1234321
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.
Solution 1:
#include <iostream>
int main()
int rows;
while(k != 2*i-1)
++k;
return 0;
Solution 1:
#include <iostream>
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;
#include<iostream>
int main()
if (i == 1 || i == rows || j == 1 || j == cols )
cout << j;
else
return 0;
#include<iostream>
int main()
if ((i+j)%2==0 )
cout << 1;
else
cout << 2;
return 0;
Solution 1:
#include<iostream>
int main()
cout<<" ";
for( k=1;k<=(rows-i+1);k++){
cout<<k;
for(int m=k;m>=1;m--){
cout<<m;
return 0;
#include<iostream>
int main()
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<<" ";}
return 0;
End of lesson
See you in the next lesson!
Assignment Solutions
Assignment Solutions
#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;
}
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;
}
include <iostream>
using namespace std;
int main() {
int num, sum;
sum = 0;
return 0;
}
#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;
}
Q5 - Write a program to print the cross pattern given below (in the shape of X):
* *
**
*
**
* *
#include <iostream>
using namespace std;
int main() {
#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;
}
*
*
*****
*
*
#include <iostream>
using namespace std;
int main() {
// size of plus, use odd number
int size = 5;
Q8 - Write a C++ program to print a triangle of prime numbers upto given number of lines of the triangle.
#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;
}
Q9- Write a C++ program to check whether a Number can be expressed as a Sum of Two Prime Numbers.
#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.";
}
}
#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;
}
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.
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:
Let us now look at some of the most used conversions in the number system.
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:
Code:
void binary_to_decimal() {
int n;
cin >> n;
int ans = 0;
int pw = 1; // 20
while (n > 0) {
ans += pw * untis_digit;
Input :
110
0100
1001
Algorithm Steps:
Code:
void decimal_to_binary() {
int n;
cin >> n;
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;
pw *= 10;
n /= 2;
Input :
10
15
Output :
101
1010
1111
C++ Functions
Pre-Requisites
C++ basic syntax
Operators
variables and data types
Conditionals and loops
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!
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).
Enough of talking and explanation, let us now get straight to writing our own functions.
Defining a Function
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
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
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
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!
void welcome() {
int main(){
welcome();
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.
// create a Function
int add = p + q;
// return value
return add;
int main() {
int p = 40;
int q = 60;
// calling Function
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.
Example 3. Can you guess how this function is different from the previous one, before we jump to the
explanation?
// create a Function
int add = p + q;
// print value
int main() {
int p = 40;
int q = 60;
// calling Function
addition(p,q);
return 0;
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.
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.
#include <iostream>
int main() {
int difference;
return 0;
// function definition
return (x - y);
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.
Example :
#include <iostream>
#include <math.h>
int main(){
Output:
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 !
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).
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.
Example 1 :
#include <iostream>
void 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>
//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>
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.
#include<iostream>
int main()
int p = 5;
int p = 7, q = 9;
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>
//global variable
int p=23;
int main()
//local variable
int p=32;
p++;
return 0;
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.
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 :
#include <iostream>
return p-q;
int main ()
int x=89;
int y=9;
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 !
Pass by Value: here, the function parameter values (i.e. value from actual parameter) are copied to another
variable (formal parameter).
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) {
int main() {
int a = 40;
changeValue(a);
return ans;
int main()
int a, b, ans;
cin>>a;
cin>>b;
cout<<("The sum of two numbers a and b is: ")<< ans << endl;
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.
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>
int c = a;
a = b;
b = c;
int main()
// Call the function swap, which will change the values of num1
// and num2
swap(num1, num2);
return 0;
Output:
Before swap:
20 32
After swap:
32 20
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.
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.
#include <iostream>
return (a + b + c + d);
// Driver Code
int main()
// Statement 1
// Statement 2
// Statement 3
return 0;
Output:
60
70
110
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
n1--;
n2 = n2 - 2;
int main()
int p = 26;
int q = 13;
decrease(p,q);
Ans:
25: 11
26: 13
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.
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’.
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.
b) whole program
c) header section
That is all ! See you in the next lesson !! Till then, keep learning ! Keep exploring !!
Assignment Solutions
Assignment Solutions
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)<<" ";
}
}
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);
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";
}
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<<" ";
}
}
}
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<<" ";
}
}
}
Arrays in C++
Pre-Requisites
Basic C++ syntax
Variables
Loops
Functions
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?
data-type array-name[array-size];
Example:
int arr[10];
With the help of curly braces, we can initialize the array and add value to it during initialization without
Example :
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.
In the example below, we are using five different variables to save our elements one by one.
Output:
Red
Green
Blue
Yellow
Purple
Output:
Red
Green
Blue
Yellow
Purple
Did you see how arrays made the implementation so convenient and saved a lot of our coding time !
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)
When we have elements stored in a single dimension or sequentially or linearly. We can declare and
elementN};
Example :
int myArray[] = { 1, 2, 3, 4 , 5 };
// first element
// second element
// third element
// fourth element
// fifth element
Output:
A multidimensional array is simply an array that consists of two or more dimensions and is also commonly
The diagram below will help you visualize the actual implementation structure of a multi- dimensional
array.
Look at the example below for clarity. Here we are creating a 2-dimensional array
int items[2][2] = {
{2, 3},
{5, 6},
};
a. Size of an array
int sz = colours.size();
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.
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
// Will print
// Green
// Red
// Purple
// Yellow
// Blue
Here, we are iterating over the array ‘colours[]’, using a for loop to print the elements.
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
statement;
Let us see the example below to know how for each works.
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
for (int i : a) {
Output:
int i = 0;
while(i < n) {
i++;
Now that we are equipped with all the basic syntax and nuances of arrays, let us now move to some basic
problems.
Problem 1: Calculate the sum of all the elements in the given array.
Code:
int sum = 0;
sum += a[i];
Problem 2: Find the maximum value out of all the elements in the array.
Code:
int mx = a[0];
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:
That is all for this class ! See you in the next array lecture !! Keep learning ! Keep Exploring !!
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.
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;
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
a[3] + b[0] = 5 is the lowest possible sum amongst all the possible combinations
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);
}
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
Ex: arr=[8,6,4,2,3,5,0,1]
Output: 7
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;
}
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;
Output: arr=[1,2,3,4,5,6]
Output: arr=[1,2,3,4,5,6]
int k=m+n-1;
int arr[m+n];
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
Output: Yes
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–;
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
Output: Yes
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;
if((arr[j]-arr[i])==(n))
cout<”Yes”;
j++;
}else{
i++;
cout<<”No”;
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;
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
Output: 2
Output: 1
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
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
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;
int j=i+1;
int k=nums.size()-1;
int val=x-nums[i];
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++;
j++;
k--;
i++;
return count;
Arrays - 2
Pre-Requisites
Loops
Functions
Basics of arrays
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.
Declaration Syntax:
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);
Example:
v = {10,20,30,40,50} ;
co t u v i e()
<< .s z << end ;
O utput :
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
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
Note: This capacity is not the limit for growth and can be automatically expanded.
Code Example:
vector<int> v;
v.resize(10);
v.resize(90);
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.
Code:
vector<int> v = {10,20,30,40};
v.push_back(50);
Code:
vector<int> v = {10,20,30,40,50};
v.pop_back();
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);
{10,20,100,30,40,50}
Syntax:
v.erase(position);
Example Code:
vector<int> v = {10,20,30,40,50};
v.erase(v.begin() + 2);
{10,20,40,50}
8. Clearing the vector : clear() function is used to remove all the elements of the vector container, thus
Code:
vector<int> v = {10,20,30,40,50};
v.clear();
For Loop
vector<int> v;
v.push_back(i);
Output :
0 1 2 3 4
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) {
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.
Code :
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.
Code :
int count = 0;
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.
Code :
int count = 0;
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.
Code :
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.
Code :
int sum = 0;
if(i % 2 == 0) {
} else {
return sum;
Explanation: Traverse the vector and add values at even indices and subtract values at the odd indices.
Arrays - 3
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.
Problem 1: Find the total number of pairs in the array whose sum is equal to the given value x.
Code:
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.
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.
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 n = a.size();
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(a[i]==a[j]){
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.
Code:
int n = a.size();
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.
Note: k can be greater than n as well where n is the size of array ‘a’.
Code :
int n = a.size();
vector<int> ans(n,-1);
ans[i-(n-k)] = a[i];
ans[i+k] = a[i];
return ans;
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);
freq[a[i]]++;
int q;
cin >> q;
while (q--) {
int val;
if (freq[val] > 0) {
Input :
1 1 2 7
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 !
Problem on Arrays
Pre-Requisites
Arrays
Vectors
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:
int n = a.size();
int i = 0;
int j = n - 1;
while(i<j){
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]
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) {
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) {
vector<int> ans;
while(i <= j) {
a[j] *= a[j];
ans.push_back(a[j--]);
} else {
a[i] *= a[i];
ans.push_back(a[i++]);
reverse(ans.begin(), ans.end());
return ans;
That is all for this lesson! Do not miss the next one !!
Problems on Array - 3
Pre-Requisites
Arrays
Vectors
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) {
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.
int n = a.size();
total_sum += a[i];
pref += a[i];
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.
Note: Array ‘a’ follows 1-based indexing i.e. element 1 is at index 1 and not 0, as it usually is.
Input :
4 //value of q
Output :
#include<iostream>
int main(){
int n;
cin >> n;
for (int i = 1; i <= n; i++) { // taking one based indexing for easier calculations
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;
// note we also need to include the value at index l so subtracting only till (l-1)
That is all for this lesson! Do not miss the next one !!
Output: 9
Explanation: 2+3+4=9
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 iand i + 1 for all
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];
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.
Output: 4
Input: arr=[0,1,1,0,1,1,1]
Output: 4
int ans = 0;
int height= 0;
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
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++)
count++;
count++;
return count;
Explanation:Just find prefix sum and then check all the subarrays if the sum is odd
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.
Output: [5 10 10 5 5]
void solve() {
int n, q, x;
while (q--) {
int l, r;
if (r + 1 <= n - 1) a[r + 1] -= x;
a[l] += x;
2D Arrays in C++
Pre-Requisites
Basic C++ synta
Basics of arrays
datatype array_name[size1][size2].....[sizeN];
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
void main(){
int arr[4][5];
arr[i][j] = 10;
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.
double arr[3][2][5];
This array can be considered as 3 arrays of 2D which has 2 rows and 5 columns.
We can find out the total number of elements in the array simply by multiplying its dimensions:
3*2*5=30
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.
#include<iostream>
int main()
int arr[3][4];
int i, j;
for(i=0;i<3;i++)
for(j=0;j<4;j++)
cout<<"\ns["<<i<<"]["<<j<<"]= ";
cin>>arr[i][j];
for(i=0;i<3;i++)
for(j=0;j<4;j++)
cout<<"\t"<<arr[i][j];
cout<<endl;
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.
Questions:
Q1. Write a program to display multiplication of two matrices entered by the user.
Input
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
Output
30 36 42
66 81 96
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.
#include <iostream>
int main()
{ int m,n;
cin>>m;
cin>>n;
int arr1[m][n],arr2[m][n],ans[m][n],i,j,k;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
cin>>arr1[i][j];
for(i=0;i<m;i++)
for(j=0;j<n;j++)
cin>>arr2[i][j];
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(i=0;i<m;i++)
for(j=0;j<n;j++)
cout<<ans[i][j]<<" ";
cout<<"\n”;
return 0;
Q2. Write a program to Print the transpose of the matrix entered by the user.
Explanation:
Input :
row=3
col=3
Output : 1 4 7 2 5 8 3 6 9
Explanation:
#include<iostream>
int main()
int row,col;
cin>>row;
cin>>col;
int arr[row][col];
int i,j;
for(i=0;i<row;i++)
for(j=0;j<col;j++)
cin>>arr[i][j];
int trans[col][row];
for(i=0;i<col;i++)
for(j=0;j<row;j++)
trans[i][j]=arr[j][i];
for(i=0;i<col;i++)
for(j=0;j<row;j++)
cout<<trans[i][j]<<" ";
cout<<"\n";
That is all for the class today, let us catch up in the next lesson to solve problems based on 2-D arrays
n=3
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>
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;
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
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).
#include <iostream>
#include <vector>
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]);
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;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cout<<mat[i][j]<<" ";
cout<<endl;
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.
#include <iostream>
#include <climits>
#include <vector>
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++;
cout<<endl;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
cout<<mat[i][j]<<" ";
cout<<endl;
vector<datatype> vector_name;
Now in the case of a 2D vector, all we need to do is create a vector of datatype vector.
vector<vector<datatype>> vector_name;
Problems
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
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.
#include <iostream>
#include<vector>
vector<vector<int>> ret;
ret.push_back(row);
return ret;
int main(){
int n;
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 :
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.
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";
}
}
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.
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;
}
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.[
Explanation: The interval 1,4 and 2,3 are overlapping so removing any one of them will make the intervals
non overlapping.
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);
}
vector<datatype> vector_name;
Now in the case of a 2D vector, all we need to do is create a vector of datatype vector.
vector<vector<datatype>> vector_name;
Problems
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
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.
#include <iostream>
#include<vector>
vector<vector<int>> ret;
ret.push_back(row);
return ret;
int main(){
int n;
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 :