mirror of
https://github.com/dholerobin/Lecture_Notes.git
synced 2025-09-13 05:42:12 +00:00
Initial Commit
This commit is contained in:
315
Academy DSA Typed Notes/Java Refresher/Refresher 1D Arrays.md
Normal file
315
Academy DSA Typed Notes/Java Refresher/Refresher 1D Arrays.md
Normal file
@@ -0,0 +1,315 @@
|
||||
# Refresher : 1D Arrays
|
||||
# Introduction To Arrays
|
||||
|
||||
---
|
||||
## Definition
|
||||
|
||||
Array is the sequential collection of same types of data. The datatype can be of any type i.e, int, float, char, etc. Below is the declaration of the array:
|
||||
```java
|
||||
int arr[] = new int[5];
|
||||
```
|
||||
It can also be declared as:
|
||||
```java
|
||||
int[] arr = new int[5]
|
||||
```
|
||||
Here, ‘int’ is the datatype, ‘arr’ is the name of the array and ‘n’ is the size of an array.
|
||||
We can access all the elements of the array as arr[0], arr[1] ….. arr[n-1].
|
||||
|
||||
**Note:** Array indexing starts with 0.
|
||||
|
||||
|
||||
---
|
||||
### Question
|
||||
Maximum index of array of size N is ?
|
||||
|
||||
Choose the correct answer
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] 1
|
||||
- [ ] 0
|
||||
- [x] N-1
|
||||
- [ ] N
|
||||
|
||||
|
||||
---
|
||||
### Question
|
||||
Given an array as arr = {3,4,1,5,1}. What is ths sum of all elements in the array?
|
||||
|
||||
Choose the correct answer
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] 12
|
||||
- [ ] 13
|
||||
- [x] 14
|
||||
- [ ] 15
|
||||
|
||||
|
||||
---
|
||||
## Question 1
|
||||
|
||||
Take an integer array **arr** of size **N** as input and print its sum.
|
||||
|
||||
#### TestCase
|
||||
##### Input
|
||||
```java
|
||||
N = 5
|
||||
arr = {1,2,3,4,5}
|
||||
```
|
||||
##### Output
|
||||
```plaintext
|
||||
15
|
||||
```
|
||||
|
||||
#### Explanation
|
||||
To calculate the sum of all the elements in the array, we need a variable say **sum** which is initially zero. Then iterate all the elements and adding them to **sum**.
|
||||
|
||||
#### PseudoCode
|
||||
```java
|
||||
int sum = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
sum = sum + arr[i];
|
||||
}
|
||||
System.out.println("Sum is " + sum);
|
||||
```
|
||||
\
|
||||
---
|
||||
### Question
|
||||
Given an array as arr = {3,4,1,5,1}. Find the maximum element.
|
||||
|
||||
Choose the correct answer
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] 3
|
||||
- [ ] 4
|
||||
- [x] 5
|
||||
- [ ] 1
|
||||
|
||||
|
||||
---
|
||||
## Question 2
|
||||
|
||||
Take an integer array **arr** of size **N** as input and print its maximum element.
|
||||
|
||||
#### TestCase
|
||||
##### Input
|
||||
```plaintext
|
||||
N = 5
|
||||
arr = {1,2,3,4,5}
|
||||
```
|
||||
##### Output
|
||||
```plaintext
|
||||
5
|
||||
```
|
||||
|
||||
#### PseudoCode
|
||||
```java
|
||||
int maximum_element = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (maximum_element < arr[i]) maximum_element = arr[i];
|
||||
}
|
||||
system.out.println("Sum is " + maximum_element);
|
||||
```
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
What will be the output of the above code with
|
||||
N = 5
|
||||
arr = {-3, -7, -2, -10, -1}
|
||||
array as input ?
|
||||
|
||||
Choose the correct answer
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] -7
|
||||
- [ ] -1
|
||||
- [x] 0
|
||||
- [ ] 2
|
||||
|
||||
**Explanation**
|
||||
|
||||
Initially we have assumed 0 as the max element in the array and in the given case, all the element is smaller than 0. So, the max element is 0.
|
||||
|
||||
---
|
||||
### Question 2 PseudoCode
|
||||
|
||||
**Note:** We can fix it by initially assigning arr[0] to the maximum_element.
|
||||
So the updated pseudocode is:
|
||||
|
||||
```java
|
||||
int maximum_element = arr[0];
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (maximum_element < arr[i]) maximum_element = arr[i];
|
||||
}
|
||||
system.out.println("Sum is " + maximum_element);
|
||||
```
|
||||
|
||||
---
|
||||
## Question 3
|
||||
|
||||
Take an integer array **arr** of size **N** as input and return its minimum element.
|
||||
|
||||
#### TestCase
|
||||
##### Input
|
||||
```java
|
||||
N = 5
|
||||
arr = {1,2,3,4,5}
|
||||
```
|
||||
##### Output
|
||||
```plaintext
|
||||
1
|
||||
```
|
||||
|
||||
#### PseudoCode
|
||||
```java
|
||||
public static int findMin(int arr[], int n) {
|
||||
int minimum_element = arr[0];
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (minimum_element > arr[i]) minimum_element = arr[i];
|
||||
}
|
||||
return minimum_element;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 4
|
||||
Take an integer array **arr** of size **N** as input and check whether an integer **k** is present in that or not.
|
||||
|
||||
#### TestCase
|
||||
##### Input
|
||||
```java
|
||||
N = 5
|
||||
arr = {1,2,3,4,5}
|
||||
k = 4
|
||||
```
|
||||
##### Output
|
||||
```plaintext
|
||||
true
|
||||
```
|
||||
|
||||
#### Explanation
|
||||
To check whether an integer **k** is present in the array or not, we need to check each element and compare it with **k**. If none of the element is equal to **k**,then return false.
|
||||
|
||||
#### PseudoCode
|
||||
```java
|
||||
public static boolean findK(int arr[], int n, int k) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (arr[i] == k) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
### Question
|
||||
Given an array as arr = {3,4,1,5,1}. What is the frequency of 1?
|
||||
|
||||
Frequency of any element is defined as the number of occurences of that element in the array.
|
||||
|
||||
Choose the correct answer
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] 0
|
||||
- [ ] 1
|
||||
- [x] 2
|
||||
- [ ] 3
|
||||
|
||||
---
|
||||
## Question 5
|
||||
|
||||
Take an integer array **arr** of size **N** as input. Return the frequency of **K** in the array.
|
||||
|
||||
#### TestCase
|
||||
|
||||
##### Input
|
||||
```java
|
||||
N = 6
|
||||
arr = {1,2,3,4,5,1}
|
||||
k = 1
|
||||
```
|
||||
##### Output
|
||||
```plaintext
|
||||
2
|
||||
```
|
||||
|
||||
|
||||
**Note:** Here frequency is the number of times the element **k** occurs in the array.
|
||||
|
||||
#### PseudoCode
|
||||
```java
|
||||
public static int frequencyK(int arr[], int n, int k) {
|
||||
int frequency = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (arr[i] == k) frequency++;
|
||||
}
|
||||
return frequency;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
## Question 6
|
||||
|
||||
Given an integer array as an input, return the frequency count of the array.
|
||||
|
||||
#### TestCase
|
||||
##### Input
|
||||
```java
|
||||
arr = {1,1,2,1,3,1,3}
|
||||
```
|
||||
##### Output
|
||||
```plaintext
|
||||
{4,4,1,4,2,4,2}
|
||||
```
|
||||
|
||||
#### PseudoCode
|
||||
```java
|
||||
int[] frecount(int arr[]) {
|
||||
int n = arr.length;
|
||||
int[] ans = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
ans[i] = frequencyK(arr, n, arr[i]);
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
## Question 7
|
||||
|
||||
Given an integer array as an input, check whether it is strictly increasing.
|
||||
|
||||
|
||||
#### TestCase
|
||||
##### Input
|
||||
```plaintext
|
||||
N = 5
|
||||
arr = {1,2,3,4,5}
|
||||
```
|
||||
##### Output
|
||||
```plaintext
|
||||
true
|
||||
```
|
||||
##### Explanation
|
||||
All the element in the array is in sorted order. So, we can say that it is in strictly increasing order.
|
||||
As
|
||||
```plaintext
|
||||
1 < 2 < 3 < 4 < 5
|
||||
```
|
||||
|
||||
#### PseudoCode
|
||||
```java
|
||||
public static boolean strictlyincreasing(int arr[]) {
|
||||
int n = arr.length;
|
||||
for (int i = 0; i < n - 1; i++) {
|
||||
if (arr[i] >= arr[i + 1]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
```
|
445
Academy DSA Typed Notes/Java Refresher/Refresher 2D Arrays.md
Normal file
445
Academy DSA Typed Notes/Java Refresher/Refresher 2D Arrays.md
Normal file
@@ -0,0 +1,445 @@
|
||||
# Refresher : 2D Arrays
|
||||
|
||||
|
||||
|
||||
# 2D Arrays
|
||||
- Store similar types of items
|
||||
- Sequential storage of elements
|
||||
- It has both length and breadth
|
||||
|
||||
## Real-Time Application Example of 2D Arrays
|
||||
- Chess
|
||||
- Theatre Seats
|
||||
- Bus
|
||||
- Egg Tray
|
||||
- Tic Toe Game
|
||||
|
||||
## Syntax
|
||||
|
||||
```cpp
|
||||
int mat[][] = new int[row][col];
|
||||
```
|
||||
In 2D arrays, we have square brackets in the declaration but in the 1D array we use one square bracket to declare it(`int[] ar=new int[]`) and in 2D matrix declaration first bracket is used to specify the number of rows and second is for the number of columns.
|
||||
|
||||
|
||||
|
||||
||||Rows||
|
||||
|-|-| -------- | -------- | -------- |
|
||||
|| |↓ |↓ |↓ |
|
||||
||→|**-**|**-**|**-**|
|
||||
|**Columns**|→|**-**|**-**|**-**|
|
||||
||→|**-**|**-**|**-**|
|
||||
|
||||
In the above matrix, we have 3 rows and 3 columns.
|
||||
|
||||
|
||||
## Example
|
||||
|-|-|-|-|
|
||||
|-|-|-|-|
|
||||
|**-**|**-**|**-**|**-**|
|
||||
|**-**|**-**|**-**|**-**|
|
||||
|
||||
In the above matrix, we have 3 rows and 4 columns, and we can declare it by writing `int[][] mat = new int[3][4]`.
|
||||
|
||||
Here also zero-based indexing works,
|
||||
|
||||
| **Col** | 0 | 1 | 2 | 3 |
|
||||
|:--------------:|:-----:|:-----:|:-----:|:-----:|
|
||||
| **Row:** **0** | **-** | **-** | **-** | - |
|
||||
| **1** | **-** | **-** | **-** | **-** |
|
||||
| **2** | **-** | **-** | **-** | **-** |
|
||||
|
||||
## How a particular cell is represented in a matrix
|
||||
Every cell is represented in the form mat[rowNo][colNo]
|
||||
|
||||
|
||||
| **Col** | 0 | 1 | 2 | 3 |
|
||||
|:--------------:|:---------:|:---------:|:---------:|:---------:|
|
||||
| **Row:** **0** | mat[0][0] | mat[0][1] | mat[0][2] | mat[0][3] |
|
||||
| **1** | mat[1][0] | mat[1][1] | mat[1][2] | mat[1][3] |
|
||||
| **2** | mat[2][0] | mat[2][1] | mat[2][2] | mat[2][3] |
|
||||
|
||||
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
How to create a matrix with 5 columns and 7 rows?
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] int[][] mat = new int[5][7];
|
||||
- [x] int[][] mat = new int[7][5];
|
||||
- [ ] int[] mat = new int[5][7];
|
||||
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
If you have a matrix of size M * N, what is the index of the top left corner?
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] [top][left]
|
||||
- [ ] [0][N - 1]
|
||||
- [x] [0][0]
|
||||
- [ ] [M - 1][N - 1]
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
If you have a matrix of size M * N, what is the index of the bottom right corner?
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] [bottom][right]
|
||||
- [ ] [0][M - 1]
|
||||
- [ ] [N - 1][M - 1]
|
||||
- [x] [M - 1][N - 1]
|
||||
|
||||
|
||||
|
||||
---
|
||||
## Print the top row of a matrix
|
||||
|
||||
Given a matrix of size N * M, print its top row.
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
|
||||
### Solution
|
||||
Coordinates of the first row of the matrix are: (0,0), (0,1), (0,2), _ _ _ , (0, M - 1).
|
||||
|
||||
Here column Number keeps on changing from 0 to M - 1 and row Number is always 0.
|
||||
|
||||
### Pseudocode
|
||||
```cpp
|
||||
for(int col = 0; i < M; i++){
|
||||
print(mat[0][i]);
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
## Print the leftmost column of a matrix
|
||||
|
||||
|
||||
### Problem Statement
|
||||
Given a matrix of size N * M, print its leftmost column.
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
|
||||
### Solution
|
||||
Coordinates of the leftmost column of the matrix are:
|
||||
(0,0),
|
||||
(1,0),
|
||||
(2,0),
|
||||
_ ,
|
||||
_ ,
|
||||
_ ,
|
||||
(N-1,0).
|
||||
|
||||
Here row Number keeps on changing from 0 to N - 1 and the column Number is always 0.
|
||||
|
||||
### Pseudocode
|
||||
```cpp
|
||||
for(int row = 0; row < N; row++){
|
||||
print(mat[row][0]);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Print matrix row by row
|
||||
|
||||
|
||||
|
||||
### Problem Statement
|
||||
Given a matrix of size N * M, print row by row
|
||||
|
||||
### Understanding the problem statement
|
||||
We have to print every row of the matrix one by one, first print the elements of the first row then print the next line character, then print its second-row elements and then again the next line character, and so on till the last row, in this way we have to print all the rows one by one.
|
||||
|
||||
|
||||
### Pseudocode
|
||||
```cpp
|
||||
for(int row = 0; row < N; row++){
|
||||
for(int col = 0; col < M; col++){
|
||||
print(mat[row][col]);
|
||||
}
|
||||
print("\n");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Print matrix column by column
|
||||
|
||||
### Problem Statement
|
||||
Given a matrix of size N * M, print column by column
|
||||
|
||||
### Example
|
||||
**Input:**
|
||||
|
||||
| **Col** | 0 | 1 | 2 |
|
||||
|:--------------:|:---:|:---:|:---:|
|
||||
| **Row:** **0** | 1 | 3 | -2 |
|
||||
| **1** | 9 | 0 | 8 |
|
||||
|
||||
|
||||
|
||||
**Output:**
|
||||
1 9
|
||||
3 0
|
||||
-2 8
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
|
||||
## Pseudocode
|
||||
```cpp
|
||||
for(int col = 0; col < M; col++){
|
||||
for(int row = 0; row < N; row++){
|
||||
print(mat[row][col]);
|
||||
}
|
||||
print("\n");
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
## Matrix coding practice
|
||||
|
||||
|
||||
### Java Code for printing matrix row by row and column by column
|
||||
|
||||
```java
|
||||
import java.util.*;
|
||||
public class Main {
|
||||
public static void printRowByRow(int mat[][]) {
|
||||
int n = mat.length; // rows
|
||||
int m = mat[0].length; // cols
|
||||
for (int row = 0; row < n; row++) {
|
||||
for (int col = 0; col < m; col++) {
|
||||
System.out.print(mat[row][col] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
System.out.println("-----------------------------");
|
||||
}
|
||||
|
||||
public static void printColByCol(int mat[][]) {
|
||||
int n = mat.length; // rows
|
||||
int m = mat[0].length; // cols
|
||||
for (int col = 0; col < m; col++) {
|
||||
for (int row = 0; row < n; row++) {
|
||||
System.out.print(mat[row][col] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
System.out.println("-----------------------------");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int n = scn.nextInt();
|
||||
int m = scn.nextInt();
|
||||
int[][] mat = new int[n][m];
|
||||
for (int row = 0; row < n; row++) {
|
||||
for (int col = 0; col < m; col++) {
|
||||
mat[row][col] = scn.nextInt();
|
||||
}
|
||||
}
|
||||
printRowByRow(mat);
|
||||
printColByCol(mat);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
## Sum of matrix
|
||||
|
||||
|
||||
### Problem statement
|
||||
Given a matrix of size N * M as an argument, return its sum.
|
||||
|
||||
### Example:
|
||||
**Input**
|
||||
||||
|
||||
|-|-|-|
|
||||
|1|3|-2|
|
||||
|9|0|8|
|
||||
|
||||
**Output:**
|
||||
19
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
### PseudoCode
|
||||
```java
|
||||
public static int sum(int mat[][]) {
|
||||
int n = mat.length; // rows
|
||||
int m = mat[0].length; // cols
|
||||
int sum = 0;
|
||||
for (int row = 0; row < n; row++) {
|
||||
for (int col = 0; col < m; col++) {
|
||||
sum = sum + mat[row][col];
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
---
|
||||
## Waveform printing
|
||||
|
||||
### Problem statement
|
||||
Given a matrix of size N * M as an argument, print it in waveform.
|
||||
|
||||
### Example:
|
||||
**Input**
|
||||
|||||
|
||||
|-|-|-|-|
|
||||
|1|3|-2|7|
|
||||
|9|0|8|-1|
|
||||
|5|6|-2|3|
|
||||
|3|4|0|2|
|
||||
|
||||
**Output:**
|
||||
1 3 -2 7
|
||||
-1 8 0 9
|
||||
5 6 -2 3
|
||||
2 0 4 3
|
||||
|
||||
### Understanding the problem statement
|
||||
Waveform printing, you have to print the first row of the matrix as it is, then print the second row in reverse order, then print the third row as it is, then print the fourth row in reverse order and so on, in this way, you have to print all the rows of the matrix.
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
|
||||
### Approach
|
||||
If the row number of a matrix is even then we have to print as it is, if the row number is odd then we have to print in reverse order.
|
||||
|
||||
### PseudoCode
|
||||
```java
|
||||
public static void wavePrint(int mat[][]) {
|
||||
int n = mat.length; // rows
|
||||
int m = mat[0].length; // cols
|
||||
for (int row = 0; row < n; row++) {
|
||||
if(row%2==0){
|
||||
for (int col = 0; col < m; col++) {
|
||||
System.out.print(mat[row][col]+" ");
|
||||
}
|
||||
}
|
||||
else{
|
||||
for (int col = m - 1; col >= 0; col--) {
|
||||
System.out.print(mat[row][col]+" ");
|
||||
}
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Row wise sum
|
||||
|
||||
|
||||
### Problem statement
|
||||
Given a matrix of size N * M as an argument, return a row-wise sum.
|
||||
|
||||
### Example:
|
||||
|
||||
|||||
|
||||
|-|-|-|-|
|
||||
|1|3|-2|7|
|
||||
|9|0|8|-1|
|
||||
|5|6|-2|3|
|
||||
|
||||
**Output:**
|
||||
[9, 16, 12]
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
|
||||
### Understanding the problem statement
|
||||
Return the sum of every row in the form of an array.
|
||||
|
||||
|
||||
### PseudoCode
|
||||
```java
|
||||
public static int[] rowWiseSum(int mat[][]) {
|
||||
int n = mat.length; // rows
|
||||
int m = mat[0].length; // cols
|
||||
int[] ans = new int[n];
|
||||
for (int row = 0; row < n; row++) {
|
||||
int sum=0;
|
||||
for (int col = 0; col < m; col++) {
|
||||
sum = sum + mat[row][col];
|
||||
}
|
||||
ans[row] = sum;
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
## Column-wise max
|
||||
|
||||
|
||||
### Problem statement
|
||||
Given a matrix of size N * M as an argument, return col-wise max.
|
||||
|
||||
### Example:
|
||||
|
||||
|||||
|
||||
|-|-|-|-|
|
||||
|1|3|-2|7|
|
||||
|9|0|8|-1|
|
||||
|5|6|-2|3|
|
||||
|
||||
**Output:**
|
||||
[9, 6, 8, 7]
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
|
||||
### Understanding the problem statement
|
||||
Return a maximum of every column in the form of an array.
|
||||
|
||||
|
||||
### PseudoCode
|
||||
```java
|
||||
public static int[] colWiseMax(int mat[][]) {
|
||||
int n = mat.length; // rows
|
||||
int m = mat[0].length; // cols
|
||||
int[] ans = new int[m];
|
||||
for (int col = 0; col < m; col++) {
|
||||
int max = mat[0][col];
|
||||
for (int row = 0; row < n; row++) {
|
||||
if(mat[row][col] > max){
|
||||
max = mat[row][col];
|
||||
}
|
||||
}
|
||||
ans[col] = max;
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
```
|
423
Academy DSA Typed Notes/Java Refresher/Refresher Arraylists.md
Normal file
423
Academy DSA Typed Notes/Java Refresher/Refresher Arraylists.md
Normal file
@@ -0,0 +1,423 @@
|
||||
# Refresher: Arraylists
|
||||
|
||||
# Arrays
|
||||
Arrays have some disadvantages:
|
||||
- Fixed-size(we cannot increase or decrease size of array)
|
||||
- Size should be known in advance.
|
||||
|
||||
Due to these arrays are not suitable for some situations.
|
||||
|
||||
|
||||
---
|
||||
## ArrayList
|
||||
ArrayList have all the advantages of arrays with some additional features
|
||||
- Dynamic size
|
||||
- Does not require to know the size in advance.
|
||||
|
||||
|
||||
## Examples
|
||||
Here are some real-world examples where using an ArrayList is preferred in comparison to using arrays.
|
||||
|
||||
- Shopping list
|
||||
- New tabs of the browser
|
||||
- Youtube playlist
|
||||
|
||||
|
||||
## Syntax
|
||||
```java
|
||||
ArrayList<Type> arr = new ArrayList<Type>();
|
||||
```
|
||||
- Here Type has to be a class, it can not be a primitive.
|
||||
- Primitives can be int, long, double, or boolean.
|
||||
- Instead of primitives we can use wrapper classes and custom objects, which means we can use Integer, Long, Double, String, etc.
|
||||
|
||||
---
|
||||
## Basic Operations
|
||||
|
||||
### Inserting element
|
||||
We can add an element in the arraylist using `add()` and it adds an element at the end of the list.
|
||||
|
||||
### Get
|
||||
It will fetch elements from the ArrayList using an index.
|
||||
|
||||
### Size
|
||||
`size()` will give us the size of the ArrayList.
|
||||
|
||||
### Remove
|
||||
It removes the element from the ArrayList present at a particular index.
|
||||
|
||||
### Set
|
||||
It updates the value of a particular index to the new value.
|
||||
|
||||
```java
|
||||
import java.util.*;
|
||||
import java.lang.*;
|
||||
class Main{
|
||||
public static void main(String args[]){
|
||||
ArrayList<Integer> arr = new ArrayList<Integer>();
|
||||
|
||||
//printing ArrayList
|
||||
System.out.println(arr);
|
||||
|
||||
// add
|
||||
arr.add(2);
|
||||
arr.add(-1);
|
||||
arr.add(5);
|
||||
|
||||
|
||||
System.out.println(arr);
|
||||
|
||||
//get
|
||||
System.out.println("2nd element is: "+arr.get(2));
|
||||
// System.out.println(arr.get(-1)); it gives an error as the -1 index does not exist for arr
|
||||
// System.out.println(arr.get(3)); it gives an error as 3 index does not exist for arr
|
||||
|
||||
|
||||
// Size
|
||||
System.out.println("Size is: " + arr.size());
|
||||
|
||||
// Remove
|
||||
arr.remove(1);
|
||||
System.out.println(arr);
|
||||
|
||||
|
||||
// Set
|
||||
arr.set(1, 8);
|
||||
System.out.println(arr);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Output**
|
||||
|
||||
```plaintext
|
||||
[]
|
||||
[2, -1, 5]
|
||||
2nd element is: 5
|
||||
Size is: 3
|
||||
[2, 5]
|
||||
[2, 8]
|
||||
```
|
||||
|
||||
---
|
||||
# Taking Arraylist as an input
|
||||
|
||||
```java
|
||||
import java.util.*;
|
||||
import java.lang.*;
|
||||
class Main{
|
||||
public static void main(String args[]){
|
||||
Scanner sc = new Scanner(System.in);
|
||||
|
||||
|
||||
// Taking ArrayList as input
|
||||
ArrayList<Integer> arr = new ArrayList<Integer>();
|
||||
|
||||
int n = sc.nextInt();
|
||||
for(int i = 0 ; i < n ; i++){
|
||||
int tmp = sc.nextInt();
|
||||
arr.add(tmp);
|
||||
}
|
||||
System.out.println(arr);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
## Problem Statement
|
||||
Given an ArrayList as input, return an ArrayList of the multiples of 5 or 7.
|
||||
|
||||
## Example
|
||||
**Input:** [1, 5, 3, 0, 7]
|
||||
**Output:** [5, 0, 7]
|
||||
|
||||
## Solution
|
||||
Iterate over the input ArrayList, and check if the element is divisible by 5 or 7 then simply add it to the result ArrayList.
|
||||
|
||||
## PsuedoCode
|
||||
|
||||
```java
|
||||
import java.util.*;
|
||||
import java.lang.*;
|
||||
class Main{
|
||||
public static ArrayList<Integer> multiples(ArrayList<Integer> arr){
|
||||
ArrayList<Integer> ans = new ArrayList<Integer>();
|
||||
for(int i = 0; i < arr.size(); i++){
|
||||
int val = arr.get(i);
|
||||
if(val % 5 == 0 || val % 7 == 0)
|
||||
ans.add(val);
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
public static void main(String args[]){
|
||||
Scanner sc = new Scanner(System.in);
|
||||
|
||||
|
||||
// Taking ArrayList as input
|
||||
ArrayList<Integer> arr = new ArrayList<Integer>();
|
||||
|
||||
int n = sc.nextInt();
|
||||
for(int i = 0 ; i < n ; i++){
|
||||
int tmp = sc.nextInt();
|
||||
arr.add(tmp);
|
||||
}
|
||||
System.out.println(multiples(arr));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
---
|
||||
## Problem Statement
|
||||
Given two integers A and B as input, return an ArrayList containing first B multiples of A.
|
||||
|
||||
## Example
|
||||
**Input:** A = 2, B = 4
|
||||
**Output:** [2, 4, 6, 8]
|
||||
|
||||
**Explanation:** First four multiple of 2 are A * 1 = 2 * 1 = 2, A * 2 = 2 * 2 = 4, A * 3 = 2 * 3 = 6, A * 4 = 2 * 4 = 8
|
||||
|
||||
|
||||
|
||||
## PsuedoCode
|
||||
|
||||
```java
|
||||
import java.util.*;
|
||||
import java.lang.*;
|
||||
class Main{
|
||||
public static ArrayList<Integer> firstB(int A, int B){
|
||||
ArrayList<Integer> ans = new ArrayList<Integer>();
|
||||
for(int i = 1; i <= B; i++){
|
||||
ans.add(A * i);
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
public static void main(String args[]){
|
||||
|
||||
System.out.println(firstB(3, 5));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Output:**
|
||||
```plaintext
|
||||
[3, 6, 9, 12, 15]
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
# 2D Arrays
|
||||
|
||||
We can imagine 2D arrays as array of arrays.
|
||||
|
||||
## 2D ArrayList
|
||||
2D ArrayList are ArrayList of ArrayLists
|
||||
|
||||
|
||||
## Syntax
|
||||
```java
|
||||
ArrayList< ArrayList<Type> > mat = new ArrayList< ArrayList<Type> >();
|
||||
```
|
||||
|
||||
## Basic Operations
|
||||
- **Add:** We can add ArrayList inside 2D ArrayList. We can ArrayLists of different sizes in a single 2D ArrayList.
|
||||
- Get
|
||||
- Size
|
||||
- Remove
|
||||
- Set
|
||||
|
||||
```java
|
||||
import java.util.*;
|
||||
import java.lang.*;
|
||||
class Main{
|
||||
public static void main(String args[]){
|
||||
ArrayList< ArrayList<Integer> > list2d = new ArrayList< ArrayList<Integer> >();
|
||||
|
||||
// Add
|
||||
ArrayList<Integer> a1 = new ArrayList<Integer>();
|
||||
a1.add(1);
|
||||
a1.add(4);
|
||||
list2d.add(a1);
|
||||
|
||||
|
||||
ArrayList<Integer> a2 = new ArrayList<Integer>();
|
||||
a2.add(0);
|
||||
list2d.add(a2);
|
||||
|
||||
ArrayList<Integer> a3 = new ArrayList<Integer>();
|
||||
a3.add(10);
|
||||
a3.add(-5);
|
||||
a3.add(1);
|
||||
list2d.add(a3);
|
||||
|
||||
System.out.println(list2d);
|
||||
|
||||
|
||||
// Get
|
||||
System.out.println(list2d.get(0));
|
||||
System.out.println(list2d.get(2).get(1));
|
||||
|
||||
|
||||
// Size
|
||||
System.out.println(list2d.size());
|
||||
System.out.println(list2d.get(1).size());
|
||||
|
||||
|
||||
// Remove
|
||||
list2d.remove(1);
|
||||
System.out.println(list2d);
|
||||
|
||||
|
||||
// Set
|
||||
ArrayList<Integer> a4 = new ArrayList<Integer>();
|
||||
a4.add(-2);
|
||||
a4.add(5);
|
||||
a4.add(8);
|
||||
list2d.set(0,a4);
|
||||
System.out.println(list2d);
|
||||
|
||||
|
||||
// Update a list element
|
||||
list2d.get(1).set(1, -15);
|
||||
System.out.println(list2d);
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
**Output:**
|
||||
```plaintext
|
||||
[[1, 4], [0], [10, -5, 1]]
|
||||
[1, 4]
|
||||
-5
|
||||
3
|
||||
1
|
||||
[[1, 4], [10, -5, 1]]
|
||||
[[-2, 5, 8], [10, -5, 1]]
|
||||
[[-2, 5, 8], [10, -15, 1]]
|
||||
```
|
||||
|
||||
|
||||
|
||||
---
|
||||
## Problem Statement
|
||||
Given a 2D Arraylist as input, print it line by line.
|
||||
|
||||
## Explanation
|
||||
Every nested list of 2D ArrayList is to be printed in different lines and the elements in a single line are separated by space.
|
||||
|
||||
## Example
|
||||
**Input:** [[1, 4], [0], [10, -5, 1]]
|
||||
**Output:**
|
||||
1 4
|
||||
0
|
||||
10 -5 1
|
||||
|
||||
|
||||
## Code
|
||||
```java
|
||||
import java.util.*;
|
||||
import java.lang.*;
|
||||
class Main{
|
||||
public static void print2DList(ArrayList< ArrayList<Integer> > list2d){
|
||||
for(int i = 0 ; i < list2d.size() ; i++){
|
||||
// get the ith ArrayList
|
||||
ArrayList<Integer> ls = list2d.get(i);
|
||||
|
||||
//Print the ith list
|
||||
for(int j = 0 ; j < ls.size() ; j++){
|
||||
System.out.print(ls.get(j) + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
public static void main(String args[]){
|
||||
ArrayList< ArrayList<Integer> > list2d = new ArrayList< ArrayList<Integer> >();
|
||||
|
||||
ArrayList<Integer> a1 = new ArrayList<Integer>();
|
||||
a1.add(1);
|
||||
a1.add(4);
|
||||
list2d.add(a1);
|
||||
|
||||
|
||||
ArrayList<Integer> a2 = new ArrayList<Integer>();
|
||||
a2.add(0);
|
||||
list2d.add(a2);
|
||||
|
||||
ArrayList<Integer> a3 = new ArrayList<Integer>();
|
||||
a3.add(10);
|
||||
a3.add(-5);
|
||||
a3.add(1);
|
||||
list2d.add(a3);
|
||||
|
||||
|
||||
print2DList(list2d);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Output:**
|
||||
```plaintext
|
||||
1 4
|
||||
0
|
||||
10 -5 1
|
||||
```
|
||||
|
||||
|
||||
|
||||
---
|
||||
## Problem Statement
|
||||
Given an integer N as input, return the numeric staircase.
|
||||
|
||||
|
||||
## Example
|
||||
**Input:** 3
|
||||
|
||||
**Output:**
|
||||
```plaintext
|
||||
[
|
||||
[1].
|
||||
[1, 2],
|
||||
[1, 2, 3]
|
||||
]
|
||||
```
|
||||
|
||||
|
||||
## Code
|
||||
|
||||
```java
|
||||
import java.util.*;
|
||||
import java.lang.*;
|
||||
class Main{
|
||||
public static ArrayList< ArrayList<Integer> > staircase(int N){
|
||||
ArrayList< ArrayList<Integer> > ans = new ArrayList< ArrayList<Integer> >();
|
||||
|
||||
for(int row = 1 ; row <= N ; row++){
|
||||
ArrayList<Integer> rw = new ArrayList<Integer>();
|
||||
for(int col = 1 ; col <= row ; col++){
|
||||
rw.add(col);
|
||||
}
|
||||
ans.add(rw);
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
public static void main(String args[]){
|
||||
System.out.println(staircase(3));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Output:**
|
||||
```plaintext
|
||||
[[1], [1, 2], [1, 2, 3]]
|
||||
```
|
||||
|
||||
|
||||
|
||||
---
|
||||
# Some pointers
|
||||
|
||||
- Use Java 8 Oracle JDK - Language
|
||||
- Gets easier with use
|
525
Academy DSA Typed Notes/Java Refresher/Refresher For Loop.md
Normal file
525
Academy DSA Typed Notes/Java Refresher/Refresher For Loop.md
Normal file
@@ -0,0 +1,525 @@
|
||||
# Refresher : For Loop
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
```java
|
||||
// 1.
|
||||
while(// 2.) {
|
||||
// 3.
|
||||
// 4.
|
||||
}
|
||||
```
|
||||
|
||||
Which sequence correctly represents the order of operations in the while loop?
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] Initialisaton , Loop work, Condition , Update
|
||||
- [ ] Initialisation , update, Loop work , Condition
|
||||
- [x] Initialisation , Condition, Loop work, Update
|
||||
- [ ] Loop work, Initialisation, Condition, Update
|
||||
|
||||
**Explanation:**
|
||||
|
||||
* **Initialization:** In this step, the loop control variable is initialized to a starting value. It is usually the first step before the loop begins.
|
||||
* **Condition:** The loop condition is evaluated before each iteration. If the condition is true, the loop body will be executed; otherwise, the loop will terminate.
|
||||
* **Loop work:** This represents the actual code or operations that are executed inside the loop body during each iteration.
|
||||
* **Update:** After each iteration, the loop control variable is updated or modified. It prepares the loop for the next iteration by changing its value.
|
||||
|
||||
So, the correct flow of the loop is Initialization -> Condition -> Loop work -> Update.
|
||||
|
||||
---
|
||||
## For Loops
|
||||
|
||||
The for loop in most programming languages follows the syntax given below:
|
||||
|
||||
```java
|
||||
for(initialization; condition; update) {
|
||||
loop work;
|
||||
}
|
||||
```
|
||||
|
||||
The meaning of each step is same as while loop.
|
||||
For Loop and while can be used interchaneably. They are like Water and Jal.
|
||||
|
||||
### Example-1:
|
||||
|
||||
Given N as input, Print from 1 to N.
|
||||
|
||||
Provided we have input N, this is how the `for` loop looks like:
|
||||
|
||||
### Code:
|
||||
|
||||
```java
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
System.out.print("Enter a number (N): ");
|
||||
int N = scanner.nextInt();
|
||||
|
||||
for (int i = 1 ; i <= N; i ++ ) {
|
||||
System.out.print(i + " ");
|
||||
}
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Explanation
|
||||
|
||||
* **Initialization:** `int i = 1`; - Firstly, we initialize i = 1. This sets the starting point for the loop.
|
||||
* **Condition:** `i <= N`; - Loop continues to execute till `i <= N`. In each iteration, it checks if i <= N. If it is true, the loop work is done; otherwise, the loop terminates.
|
||||
* **Loop Body (Action):** `System.out.print(i + " ");` - During each iteration, the loop body prints the value of i, followed by a space.
|
||||
* **Update:** `i ++` - After each iteration, i is incremented by 1. This prepares loop for next iteration.
|
||||
|
||||
|
||||
|
||||
### Example-2:
|
||||
|
||||
Given N as input, print all odd numbers from 1 to N.
|
||||
|
||||
### Approach:
|
||||
* First, we take input from user.
|
||||
* Then we run the loop from 1 to N.
|
||||
* Since we want to print only odd numbers, we increment by 2 to skip even numbers.
|
||||
* The loop body prints the value of `i`
|
||||
|
||||
|
||||
### Code:
|
||||
```java
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
System.out.print("Enter a number (N): ");
|
||||
int N = scanner.nextInt();
|
||||
|
||||
for (int i = 1; i <= N; i += 2) {
|
||||
System.out.print(i + " ");
|
||||
}
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## What are Factors of a Number
|
||||
|
||||
**i** is said to be the factor of N if i divides N completely, i.e **N % i = 0**
|
||||
|
||||
Let's take an Integer as an example and find its factors:
|
||||
|
||||
**Example 1:** Find the factors of 6.
|
||||
Since 1, 2, 3, 6 divides 6 completely, hence factors of 6 are 1, 2, 3, and 6.
|
||||
|
||||
**Example 2:** Find the factors of 10.
|
||||
Since 1, 2, 5, 10 divides 10 completely hence, the factors of 10 are 1, 2, 5, and 10.
|
||||
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
What are the factors of 24 ?
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] 2, 3, 4, 6, 8, 12
|
||||
- [ ] 1, 2, 3, 4, 6, 8, 12
|
||||
- [x] 1, 2, 3, 4, 6, 8, 12, 24
|
||||
|
||||
**Explanation**
|
||||
|
||||
Factors of 24 are 1, 2, 3, 4, 6, 8, 12, and 24.
|
||||
|
||||
---
|
||||
## Print the factors of a positive number N
|
||||
|
||||
How to print the factors of a positive number N ?
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
|
||||
### Approach:
|
||||
|
||||
* The range of factors of a positive integer N is from 1 to N.
|
||||
* We can simply iterate from 1 to N to get all the factors
|
||||
* If N % i == 0, increment count variable.
|
||||
|
||||
### Code:
|
||||
|
||||
```java
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
public static void printFactors(int N) {
|
||||
System.out.print("Factors of " + N + ": ");
|
||||
for (int i = 1; i <= N; ++ i) {
|
||||
if (N % i == 0) {
|
||||
System.out.print(i + " ");
|
||||
}
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
System.out.print("Enter a number (N): ");
|
||||
int N = scanner.nextInt();
|
||||
|
||||
printFactors(N);
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
Definition of Prime :
|
||||
If a number **"N"** is divisible by **1** and itself is called **Prime Number**.
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] True
|
||||
- [x] False
|
||||
|
||||
**Explanation:**
|
||||
|
||||
As per above definition, 1 will also be a Prime Number since its factors are 1 and itself.
|
||||
But we know 1 is not a Prime Number, hence the definition is wrong.
|
||||
|
||||
**Correct Definition:** A prime number has exactly two factors.
|
||||
|
||||
**For example:**
|
||||
2 is a prime number because it has only two factors, 1 and 2.
|
||||
3 is a prime number because it has only two factors, 1 and 3.
|
||||
5 is a prime number because it has only two factors, 1 and 5.
|
||||
|
||||
---
|
||||
## Prime Numbers
|
||||
|
||||
### How to check if a number is prime or not?
|
||||
|
||||
* We just need to check if N has exactly 2 factors, then it is Prime.
|
||||
* So, we can make use of previous code to get the factors of N and check if factors are 2 or not.
|
||||
|
||||
### Code:
|
||||
|
||||
```java
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
public static boolean isPrime(int number) {
|
||||
int divisorCount = 0;
|
||||
|
||||
for (int i = 1; i <= number; ++ i) {
|
||||
if (number % i == 0) {
|
||||
divisorCount ++ ;
|
||||
}
|
||||
}
|
||||
|
||||
return (divisorCount == 2);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
int divisorCount = 0;
|
||||
System.out.print("Enter a number: ");
|
||||
int N = scanner.nextInt();
|
||||
|
||||
for (int i = 1; i <= N; ++ i) {
|
||||
if (N % i == 0) {
|
||||
divisorCount ++ ;
|
||||
}
|
||||
}
|
||||
|
||||
if (isPrime(N)) {
|
||||
System.out.println("Prime");
|
||||
} else {
|
||||
System.out.println("Not Prime");
|
||||
}
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
What is the smallest prime number?
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] 0
|
||||
- [ ] 1
|
||||
- [x] 2
|
||||
- [ ] 3
|
||||
|
||||
**Explanation:**
|
||||
|
||||
The smallest prime number is 2. Also, it is the only even prime number.
|
||||
|
||||
---
|
||||
## Break and Continue statements
|
||||
|
||||
### Explanation of Break statement
|
||||
|
||||
The `break` statement is used to exit or terminate the nearest enclosing loop prematurely. When the `break` statement is encountered inside a loop, it immediately stops the loop's execution and transfers control to the statement following the loop. It helps avoid unnecessary iterations and is often used to terminate a loop early based on a specific condition.
|
||||
|
||||
|
||||
The code for finding if a number is prime or not can be modified using `break` statement to avoid more efforts
|
||||
|
||||
In the given code, the goal is to check if the number N is prime or not. We can use the `break` statement to optimize the loop and avoid unnecessary iterations. The idea is that if we find any divisor of N, other than 1 and N, we can conclude that N is not prime, and there is no need to check further.
|
||||
|
||||
Here's the modified code using the `break` statement:
|
||||
|
||||
```java
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
System.out.print("Enter a number: ");
|
||||
int N = scanner.nextInt();
|
||||
|
||||
int divisorCount = 0;
|
||||
for (int i = 1; i <= N; i ++ ) {
|
||||
if (N % i == 0) {
|
||||
divisorCount ++ ;
|
||||
if (divisorCount > 2) {
|
||||
// If we find more than 2 divisors, break the loop
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (divisorCount == 2) {
|
||||
System.out.println(N + " is a prime number.");
|
||||
} else {
|
||||
System.out.println(N + " is not a prime number.");
|
||||
}
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
* If `cnt` is greater than 2 (meaning N has more than two divisors), the break statement is used to terminate the loop early, avoiding unnecessary iterations.
|
||||
* After the loop, it checks if `cnt` is equal to 2. If `cnt` is exactly 2, it means N has exactly two divisors (1 and N), so it is prime.
|
||||
* Depending on the value of `cnt`, it prints either "Prime" or "Not Prime" on the screen.
|
||||
|
||||
### Explaination of Continue statement
|
||||
|
||||
The `continue` statement is used to skip the rest of the current iteration in a loop and move on to the next iteration immediately. When the `continue` statement is encountered inside a loop, it interrupts the current iteration's execution and starts the next iteration of the loop.
|
||||
|
||||
We can use the continue statement to skip odd numbers and only print the even numbers between 1 and N.
|
||||
|
||||
```java
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
System.out.print("Enter a number (N): ");
|
||||
int N = scanner.nextInt();
|
||||
|
||||
System.out.print("Even numbers between 1 and " + N + ": ");
|
||||
for (int i = 1; i <= N; ++ i) {
|
||||
if (i % 2 != 0) {
|
||||
// Skip odd numbers using continue statement
|
||||
continue;
|
||||
}
|
||||
System.out.print(i + " ");
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
* The code takes the input N from the user using `std::cin`.
|
||||
* It then enters a for loop that iterates from 1 to N.
|
||||
* Inside the loop, there is an if condition: `if (i % 2 != 0)`.
|
||||
* The condition checks if `i` is odd (i.e., not divisible by 2). If `i` is odd, the continue statement is executed, and the rest of the loop's body is skipped.
|
||||
* Therefore, when `i` is odd, the loop moves on to the next iteration, effectively skipping the odd numbers.
|
||||
* For all even values of i, the loop prints the even numbers between 1 and N, separated by spaces.
|
||||
|
||||
---
|
||||
## How to Solve Questions with T Test Cases
|
||||
|
||||
To solve questions with T test cases, you'll need to write a program that can handle multiple test cases. Typically, the input for each test case will be provided one after the other, and your program should process each test case and produce the corresponding output.
|
||||
|
||||
Here's a general approach to handle T test cases in your program:
|
||||
|
||||
* Read the value of T (the number of test cases) from the input.
|
||||
* Use a loop to iterate T times to process each test case.
|
||||
* For each test case, read the input data specific to that test case.
|
||||
* Perform the required operations or computations for that test case.
|
||||
* Output the result for that test case.
|
||||
* Repeat steps 3 to 5 until all T test cases are processed.
|
||||
|
||||
Here's an example to illustrate the process:
|
||||
|
||||
```java
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
System.out.print("Enter the number of test cases (T): ");
|
||||
int T = scanner.nextInt();
|
||||
|
||||
for (int t = 1; t <= T; ++ t) {
|
||||
// Read input data specific to the current test case
|
||||
// For example, prompt the user to enter data for each test case
|
||||
// int N = scanner.nextInt();
|
||||
// String input = scanner.next();
|
||||
// ...
|
||||
|
||||
// Perform computations or operations for the current test case
|
||||
// For example, process the input data and calculate the result
|
||||
// int result = processData(N, input);
|
||||
// ...
|
||||
|
||||
// Output the result for the current test case
|
||||
// For example, print the result for each test case
|
||||
// System.out.println("Result for Test Case " + t + ": " + result);
|
||||
// ...
|
||||
}
|
||||
|
||||
scanner.close();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Scope of Variables
|
||||
|
||||
### Explanation
|
||||
The scope of a variable refers to the region of a program where that variable is accessible and can be used. It determines the portion of the code in which a variable exists and retains its value.
|
||||
|
||||
```java
|
||||
import java.lang.*;
|
||||
import java.util.*;
|
||||
|
||||
class Main {
|
||||
|
||||
// public static void main(String args[]) {
|
||||
|
||||
// // Scope of Variable
|
||||
// // Useful lifetime of a variable
|
||||
|
||||
// int x = 10;
|
||||
// //....
|
||||
// //....
|
||||
// //....
|
||||
// System.out.println(x);
|
||||
// //....
|
||||
// //....
|
||||
// } // closing of the parent bracket
|
||||
// // Line 10-18 is the scope of the variable
|
||||
|
||||
public static void main(String args[]) {
|
||||
// Case 1
|
||||
// int x = 10;
|
||||
// int y = 15;
|
||||
// {
|
||||
// System.out.println(x + " " + y);
|
||||
// }
|
||||
|
||||
// Case 2
|
||||
// int x = 10;
|
||||
// {
|
||||
// int y = 15;
|
||||
// System.out.println(x + " " + y);
|
||||
// }
|
||||
// {
|
||||
// System.out.println(x + " " + y);
|
||||
// }
|
||||
|
||||
// Case 3
|
||||
// int x = 10;
|
||||
// int y = 15;
|
||||
// {
|
||||
// y = 10;
|
||||
// System.out.println(x + " " + y);
|
||||
// }
|
||||
// {
|
||||
// System.out.println(x + " " + y);
|
||||
// }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The provided Java code demonstrates different cases illustrating variable scope in Java. Let's go through each case:
|
||||
|
||||
**Case 1:**
|
||||
|
||||
```java
|
||||
public static void main(String args[]) {
|
||||
int x = 10;
|
||||
int y = 15;
|
||||
{
|
||||
System.out.println(x + " " + y);
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
In this case, `x` and `y` are declared and initialized in the main method. Inside the block (denoted by curly braces {}), both `x` and `y` are accessible since they are in the same scope. **The output will be "10 15"**.
|
||||
|
||||
**Case 2:**
|
||||
|
||||
```java
|
||||
public static void main(String args[]) {
|
||||
int x = 10;
|
||||
{
|
||||
int y = 15;
|
||||
System.out.println(x + " " + y);
|
||||
}
|
||||
{
|
||||
System.out.println(x + " " + y);
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
In this case, `x` is declared and initialized in the main method. Inside the first block, `x` is accessible since it is in the same scope. However, `y` is declared within this block and is only accessible within this block. Attempting to access `y` in the second block will result in a compilation error because it is outside of its scope. **The output will be "10 15"**, **followed by a compilation error for the second System.out.println(x + " " + y);**.
|
||||
|
||||
**Case 3:**
|
||||
|
||||
```java
|
||||
public static void main(String args[]) {
|
||||
int x = 10;
|
||||
int y = 15;
|
||||
{
|
||||
y = 10;
|
||||
System.out.println(x + " " + y);
|
||||
}
|
||||
{
|
||||
System.out.println(x + " " + y);
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
In this case, `x` and `y` are declared and initialized in the main method. Inside the first block, `x` and `y` are accessible since they are in the same scope. The value of `y` is modified to 10 inside the block. **The output will be "10 10"**. In the second block, `x` is accessible, but `y` is not redeclared, so the modified value from the previous block will be used. The output will be "10 10".
|
||||
|
359
Academy DSA Typed Notes/Java Refresher/Refresher Functions.md
Normal file
359
Academy DSA Typed Notes/Java Refresher/Refresher Functions.md
Normal file
@@ -0,0 +1,359 @@
|
||||
# Refresher : Functions
|
||||
## Problem in Non-Functional Programming
|
||||
Let's understand the problems arises in Non-Functional programming by taking an example as:
|
||||
Suppose we have given three integers say a,b,c & we have to calculate the sum of digits of all these numbers seperately. So, the basic program to do that is as shown below.
|
||||
```java
|
||||
main(){
|
||||
--------
|
||||
--------
|
||||
int sum1 = 0 , sum2 = 0 , sum3 = 0;
|
||||
while(a > 0){
|
||||
sum1 += a % 10;
|
||||
a /= 10;
|
||||
}
|
||||
system.out.println(sum1);
|
||||
while(b > 0){
|
||||
sum2 += b % 10;
|
||||
b /= 10;
|
||||
}
|
||||
system.out.println(sum2);
|
||||
while(c > 0){
|
||||
sum3 += c % 10;
|
||||
c /= 10;
|
||||
}
|
||||
system.out.println(sum3);
|
||||
}
|
||||
```
|
||||
In the above code, we have to write the same piece of code thrice. So this is the major problem.
|
||||
The above code have many problems:
|
||||
* **Redundancy**.
|
||||
* **Readability**.
|
||||
* **Maintainability**.
|
||||
|
||||
### How to Solve the Above Problems?
|
||||
We can solve the problems using black box technique as:
|
||||

|
||||
|
||||
Here, when we require to calculate the sum of digits then we will simply invoke this box and pass the integer in it, then it will return the sum as an output.
|
||||
|
||||
When this box is taken together with input and output then this is known as the **function**. By using the function we can overcome the problems mentioned above.
|
||||
|
||||
### Syntax of Function
|
||||
```java
|
||||
ansType function name(inputType input){
|
||||
// Main logic.
|
||||
return ans;
|
||||
}
|
||||
```
|
||||
This is how the typical function looks like.
|
||||
Let's create a function to sum 2 numbers.
|
||||
```java
|
||||
int 2sum(int a,int b){
|
||||
int sum = a + b;
|
||||
return sum;
|
||||
}
|
||||
```
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
|
||||
**Note:** In case, the return type is void then no need to return anything(return statement is optional).
|
||||
|
||||
---
|
||||
### Question
|
||||
What will be the output?
|
||||
```java
|
||||
class Test {
|
||||
public static int sum(int a, int b){
|
||||
return a + b;
|
||||
}
|
||||
|
||||
public static void main(String[] args){
|
||||
int a = 15, b = 5;
|
||||
System.out.println(sum(a, 10));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Choose the correct answer
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] 20
|
||||
- [x] 25
|
||||
- [ ] 15
|
||||
- [ ] 0
|
||||
|
||||
**Explanation**
|
||||
The a & b defined inside the sum function is different from that is defined in the main function. We have passed a & 10 as a argument. that's why the value of b that is defined inside the sum function is 10. Hence, the sum is 25.
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
What will be the output?
|
||||
```java
|
||||
class Test {
|
||||
public static int sum(int a, int b){
|
||||
return a + b;
|
||||
}
|
||||
|
||||
public static void main(String[] args){
|
||||
int a = 15, b = 5;
|
||||
sum(a,b);
|
||||
}
|
||||
}
|
||||
```
|
||||
Choose the correct answer
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] 20
|
||||
- [ ] Error
|
||||
- [ ] 15
|
||||
- [x] Nothing will be printed.
|
||||
|
||||
**Explanation**
|
||||
|
||||
There is not any printing statement like `system.out.print()`. Hence, nothing is printed.
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
What will be the output?
|
||||
```java
|
||||
class Test {
|
||||
public static int sum(int a, int b){
|
||||
System.out.print(a + b);
|
||||
}
|
||||
|
||||
public static void main(String[] args){
|
||||
int a = 15, b = 5;
|
||||
sum(a,b);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Choose the correct answer
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] 20
|
||||
- [x] Error
|
||||
- [ ] 15
|
||||
- [ ] Nothing will be printed.
|
||||
|
||||
**Explanation**
|
||||
|
||||
Error because the return type of sum function is int but it does not return anything.
|
||||
|
||||
|
||||
---
|
||||
### Question
|
||||
What will be the output?
|
||||
```java
|
||||
class Test {
|
||||
public static int sum(int a, int b){
|
||||
return a + b;
|
||||
}
|
||||
|
||||
public static void main(String[] args){
|
||||
int a = 15, b = 5;
|
||||
System.out.println(sum(20, b));
|
||||
}
|
||||
}
|
||||
```
|
||||
Choose the correct answer
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] 20
|
||||
- [ ] Error
|
||||
- [x] 25
|
||||
- [ ] Nothing will be printed.
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
What will be the output?
|
||||
```java
|
||||
class Test {
|
||||
public static int sum(int a, int b){
|
||||
return a + b;
|
||||
}
|
||||
|
||||
public static void main(String[] args){
|
||||
int a = 15, b = 5;
|
||||
System.out.println(sum(6, 10));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Choose the correct answer
|
||||
|
||||
**Choices**
|
||||
- [ ] 20
|
||||
- [ ] Error
|
||||
- [x] 16
|
||||
|
||||
---
|
||||
## Question 1
|
||||
|
||||
Given an integer **N**, return whether the integer is even or not.
|
||||
|
||||
#### TestCase
|
||||
|
||||
##### Input 1
|
||||
```plaintext
|
||||
12
|
||||
```
|
||||
##### Output 1
|
||||
```plaintext
|
||||
true
|
||||
```
|
||||
##### Input 2
|
||||
```plaintext
|
||||
5
|
||||
```
|
||||
##### Output 2
|
||||
```plaintext
|
||||
false
|
||||
```
|
||||
### PseudoCode
|
||||
```java
|
||||
public static boolean iseven(int n){
|
||||
if(n % 2 == 0) return true;
|
||||
else return false;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 2
|
||||
|
||||
Given an integer **N**, return whether its height is small, medium or large.
|
||||
* if it is less than 10, then its small.
|
||||
* if it is between 10 to 20, then its medium.
|
||||
* if it is greater than 20, then large.
|
||||
|
||||
#### TestCase
|
||||
|
||||
##### Input 1
|
||||
```plaintext
|
||||
5
|
||||
```
|
||||
##### Output 1
|
||||
```plaintext
|
||||
small
|
||||
```
|
||||
##### Input 2
|
||||
```plaintext
|
||||
51
|
||||
```
|
||||
##### Output 2
|
||||
```plaintext
|
||||
large
|
||||
```
|
||||
### PseudoCode
|
||||
```java
|
||||
public static String height(int n){
|
||||
if(n < 10) return "small";
|
||||
else if(n < 20) return "medium";
|
||||
else return "large".
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 3
|
||||
Given two doubles as argument, return the area of the rectangle.
|
||||
|
||||
#### TestCase
|
||||
|
||||
##### Input 1
|
||||
```plaintext
|
||||
1.0
|
||||
2.0
|
||||
```
|
||||
##### Output 1
|
||||
```plaintext
|
||||
2.0
|
||||
```
|
||||
### PseudoCode
|
||||
```java
|
||||
public static double areaofrectangle(double a, double b){
|
||||
double area = a * b;
|
||||
return area;
|
||||
}
|
||||
```
|
||||
---
|
||||
## Question 4
|
||||
|
||||
Given the radius(double) of the circle, return the area of the circle.
|
||||
|
||||
#### TestCase
|
||||
##### Input 1
|
||||
```plaintext
|
||||
7.0
|
||||
```
|
||||
##### Output 1
|
||||
```plaintext
|
||||
154.0
|
||||
```
|
||||
### PseudoCode
|
||||
```java
|
||||
public static double areaofcircle(double radius){
|
||||
double area = 3.14 * radius * radius;
|
||||
return area;
|
||||
}
|
||||
```
|
||||
**Note:** Instead of writing the value of PI as 3.14, we can directly use the module Math.PI. To use that we have to import the maths library.
|
||||
|
||||
---
|
||||
## Question 5
|
||||
|
||||
Given an integer **N** as an input, print all the prime numbers between 1 to N.
|
||||
|
||||
#### TestCase
|
||||
##### Input 1
|
||||
```plaintext
|
||||
10
|
||||
```
|
||||
##### Output 1
|
||||
```plaintext
|
||||
2 3 5 7
|
||||
```
|
||||
|
||||
#### Explanation
|
||||
Prime number is the number which is not divisible by any oof the number except 1 and itself. So, to find the number of prime numbers between 1 to **N**, just count the number of itegers which divides it. if it is equal to 2 then it is prime number.
|
||||
|
||||
#### PseudoCode
|
||||
|
||||
```java
|
||||
public static void primenumbers(int n) {
|
||||
for (int num = 1; num <= n; num++) {
|
||||
int factors = 0;
|
||||
for (int i = 1; i <= num; i++) {
|
||||
if (num % i == 0) factors++;
|
||||
}
|
||||
if (factors == 2) system.out.print(num);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
We can further break it as:
|
||||
|
||||
```java
|
||||
public static boolean isprime(int n) {
|
||||
int factors = 0;
|
||||
for (int i = 1; i <= num; i++) {
|
||||
if (num % i == 0) factors++;
|
||||
}
|
||||
if (factors == 2) return true;
|
||||
else return false;
|
||||
}
|
||||
public static void primenumbers(int n) {
|
||||
for (int num = 1; num <= n; num++) {
|
||||
if (isprime(num)) system.out.print(num);
|
||||
}
|
||||
}
|
||||
```
|
@@ -0,0 +1,518 @@
|
||||
# Refresher: HashMap & HashSet
|
||||
|
||||
|
||||
|
||||
# HashSet
|
||||
HashSet is a collection of unique elements.
|
||||
|
||||
## Example 1
|
||||
We have a bag, which has some numbers inside it.
|
||||
|
||||

|
||||
|
||||
This bag has unique elements, which means every number appears once only.
|
||||
|
||||
If we want to add 9 in a bag, then it will be not inserted as the bag already has 9.
|
||||
|
||||
Some other examples which contain unique elements are:
|
||||
- Email-id
|
||||
- username
|
||||
- Fingerprints
|
||||
|
||||
|
||||
## Example 2
|
||||
Let us assume we have an array `arr = [1, 3, -2, 7, 1, 1, -2]`
|
||||
|
||||
Now if we want to create a HashSet of it then it contains unique elements.
|
||||
|
||||
`HS = [1, 7, -2, 3]`
|
||||
|
||||
Here we can see that **hashset does not have any sequence of elements.**
|
||||
|
||||
## Syntax
|
||||
|
||||
```java
|
||||
HashSet<Type> hs = new HashSet<Type>();
|
||||
```
|
||||
|
||||
Here Type can be any class
|
||||
|
||||
## Basic Operations
|
||||
We can perform the following operations on HashSet.
|
||||
|
||||
- **Add:** Used to add element in HashSet.
|
||||
- **Contains** Used to check whether HashSet contains a certain element or not.
|
||||
- Size
|
||||
- Remove
|
||||
- **Print:** We use each loop for printing the elements of HashSet
|
||||
|
||||
---
|
||||
### Question
|
||||
For the given HashSet hs, what will be the size after the following operations?
|
||||
|
||||
```
|
||||
HashSet<Integer> hs = new HashSet<Integer>();
|
||||
|
||||
hs.add(3);
|
||||
hs.add(-2);
|
||||
hs.add(10);
|
||||
hs.add(3);
|
||||
hs.add(10);
|
||||
hs.add(0);
|
||||
```
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] 2
|
||||
- [ ] 3
|
||||
- [ ] 5
|
||||
- [x] 4
|
||||
|
||||
**Explanation**
|
||||
|
||||
```plaintext
|
||||
The unique elements added to the HashSet are: 3, -2, 10, 0.
|
||||
So, the size of the HashSet is 4.
|
||||
```
|
||||
|
||||
**Example**
|
||||
|
||||
|
||||
```java
|
||||
import java.util.*;
|
||||
import java.lang.*;
|
||||
class Main{
|
||||
public static void main(String args[]){
|
||||
HashSet<Integer> hs = new HashSet<Integer>();
|
||||
|
||||
//printing HashSet
|
||||
System.out.println(hs);
|
||||
|
||||
// add
|
||||
hs.add(3);
|
||||
hs.add(-2);
|
||||
hs.add(10);
|
||||
hs.add(3);
|
||||
hs.add(10);
|
||||
hs.add(0);
|
||||
|
||||
|
||||
System.out.println(hs);
|
||||
|
||||
|
||||
|
||||
// Contains
|
||||
System.out.println(hs.contains(3));
|
||||
System.out.println(hs.contains(-1));
|
||||
|
||||
|
||||
|
||||
// Size
|
||||
System.out.println("Size is: " + hs.size());
|
||||
|
||||
|
||||
|
||||
// Remove
|
||||
hs.remove(3);
|
||||
System.out.println(hs);
|
||||
|
||||
|
||||
// print
|
||||
for(Integer i : hs){ // for each loop
|
||||
System.out.println(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Output:**
|
||||
```plaintext
|
||||
[]
|
||||
[0, -2, 3, 10]
|
||||
true
|
||||
false
|
||||
Size is: 4
|
||||
[0, -2, 10]
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
## ArrayList HashSet
|
||||
|
||||
|
||||
## ArrayList
|
||||
|
||||
- Sequential order.
|
||||
- Duplicates allowed
|
||||
|
||||
## HashSet
|
||||
- Sequence not maintained
|
||||
- Unique element present only.
|
||||
|
||||
|
||||
|
||||
---
|
||||
## Problem Statement
|
||||
Given an integer array as input, add its elements to a HashSet and return the HashSet.
|
||||
|
||||
|
||||
## PseudoCode
|
||||
```java
|
||||
import java.util.*;
|
||||
import java.lang.*;
|
||||
class Main{
|
||||
public static HashSet<Integer> convertToHashset(int[] arr){
|
||||
HashSet<Integer> ans = new HashSet<Integer>();
|
||||
for(int i = 0; i < arr.length; i++){
|
||||
ans.add(arr[i]);
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
public static void main(String args[]){
|
||||
int arr[] = {1, 4, 3, -2, 1, 1, 4, 5, 3};
|
||||
System.out.println(convertToHashset(arr));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Output:**
|
||||
```plaintext
|
||||
[1, -2, 3, 4, 5]
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
## Problem Statement
|
||||
Given 2 HashSet as input, print their common elements.
|
||||
|
||||
|
||||
## Example
|
||||
**Input:**
|
||||
HS1: {0, -2, 4, 10}
|
||||
HS2: {1, -2, 3, 4, 5}
|
||||
|
||||
|
||||
**Output:** -2 3
|
||||
|
||||
## Understanding the problem
|
||||
We have to print the elements that are present in both the HashSet.
|
||||
|
||||
|
||||
## PseudoCode
|
||||
```java
|
||||
import java.util.*;
|
||||
import java.lang.*;
|
||||
class Main{
|
||||
public static void intersect(HashSet<Integer> hs1, HashSet<Integer> hs2){
|
||||
for(Integer i : hs1){
|
||||
if(hs2.contains(i)){
|
||||
System.out.print(i + " ");
|
||||
}
|
||||
}
|
||||
}
|
||||
public static HashSet<Integer> convertToHashset(int[] arr){
|
||||
HashSet<Integer> ans = new HashSet<Integer>();
|
||||
for(int i = 0; i < arr.length; i++){
|
||||
ans.add(arr[i]);
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
public static void main(String args[]){
|
||||
int arr[] = {1, 4, 3, -2, 1, 1, 4, 5, 3};
|
||||
HashSet<Integer> hs1 = convertToHashset(arr);
|
||||
System.out.println(hs1);
|
||||
|
||||
int arr2[] = {0, -2, 3, 10};
|
||||
HashSet<Integer> hs2 = convertToHashset(arr2);
|
||||
System.out.println(hs2);
|
||||
|
||||
intersect(hs1, hs2);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Output:**
|
||||
```plaintext
|
||||
[1, -2, 3, 4, 5]
|
||||
[0, -2, 3, 10]
|
||||
-2 3
|
||||
````
|
||||
|
||||
---
|
||||
### Question
|
||||
What operation is used to remove an element from a HashSet?
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] Add
|
||||
- [ ] Size
|
||||
- [x] Remove
|
||||
- [ ] Contain
|
||||
|
||||
**Explanation**
|
||||
|
||||
```plaintext
|
||||
The `Remove` operation is used to remove an element from a HashSet.
|
||||
```
|
||||
|
||||
---
|
||||
## HashMap
|
||||
HashMap is a data structure which contains key-value pairs.
|
||||
|
||||
## Example
|
||||
Let us suppose we have states and its population.
|
||||
|
||||
| States | Population |
|
||||
|:-------:|:----------:|
|
||||
| Punjab | 15 |
|
||||
| Haryana | 18 |
|
||||
| UP | 20 |
|
||||
| Delhi | 18 |
|
||||
|
||||
Now if we have the above data, and our question is to tell the population of UP, then we can simply tell the value next to UP(20).
|
||||
Here we can say UP->20 is a pair, where UP is a key, corresponding to which some values are stored, and by this key, we access the data.
|
||||
|
||||
|
||||
Here states are key and population are values.
|
||||
|
||||
| States(key) | Population(value) |
|
||||
|:-----------:|:-----------------:|
|
||||
| Punjab | 15 |
|
||||
| Haryana | 18 |
|
||||
| UP | 20 |
|
||||
| Delhi | 18 |
|
||||
|
||||
Some other examples are:
|
||||
- User id -> password
|
||||
- Word -> Meaning (dictionary)
|
||||
|
||||
|
||||
## Features of HashMap
|
||||
|
||||
- Duplicate values are allowed
|
||||
|
||||
|
||||

|
||||
|
||||
|
||||
- Duplicate keys are not allowed.
|
||||
|
||||

|
||||
|
||||
|
||||
- No order of data, key-value pairs are in random order.
|
||||
|
||||
|
||||
## Syntax
|
||||
```java
|
||||
HashMap<keyType, valueType> hm = new HashMap<keyType, valueType>();
|
||||
```
|
||||
|
||||
## Basic Operations
|
||||
|
||||
We can perform the following operations on HashMap.
|
||||
|
||||
- Add
|
||||
- Contains
|
||||
- Get
|
||||
- Update
|
||||
- Size
|
||||
- Remove
|
||||
- Print
|
||||
|
||||
### Example
|
||||
|
||||
|
||||
```java
|
||||
import java.util.*;
|
||||
import java.lang.*;
|
||||
class Main{
|
||||
public static void main(String args[]){
|
||||
|
||||
HashMap<String, Integer> hm = new HashMap<String, Integer>();
|
||||
|
||||
|
||||
|
||||
// add
|
||||
hm.put("Delhi", 18);
|
||||
hm.put("Punjab", 20);
|
||||
hm.put("Haryana", 18);
|
||||
hm.put("Goa", 5);
|
||||
|
||||
|
||||
System.out.println(hm);
|
||||
|
||||
|
||||
|
||||
// Contains
|
||||
System.out.println(hm.containsKey("Gujarat"));
|
||||
System.out.println(hm.containsKey("Goa"));
|
||||
|
||||
// Get
|
||||
System.out.println(hm.get("Gujarat"));
|
||||
System.out.println(hm.get("Goa"));
|
||||
|
||||
|
||||
// Update
|
||||
hm.put("Goa", 6);
|
||||
System.out.println(hm);
|
||||
|
||||
// Size
|
||||
System.out.println("Size is: " + hm.size());
|
||||
|
||||
|
||||
|
||||
// Remove
|
||||
hm.remove("Goa");
|
||||
System.out.println(hm);
|
||||
|
||||
|
||||
// print
|
||||
// 1. get all keys
|
||||
// hm.keySet()-> returns a set of keys of HashMap
|
||||
// 2. Use keys to iterate over the map
|
||||
for(String state : hm.keySet()){
|
||||
System.out.println(state + " -> " + hm.get(state));
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
**Output:**
|
||||
```plaintext
|
||||
{Delhi = 18, Haryana = 18, Goa = 5, Punjab = 20}
|
||||
false
|
||||
true
|
||||
null
|
||||
5
|
||||
{Delhi = 18, Haryana = 18, Goa = 6, Punjab = 20}
|
||||
Size is: 4
|
||||
{Delhi = 18, Haryana = 18, Punjab = 20}
|
||||
Delhi -> 18
|
||||
Haryana -> 18
|
||||
Punjab -> 20
|
||||
```
|
||||
|
||||
---
|
||||
### Question
|
||||
In a HashMap, what is the purpose of the get operation?
|
||||
|
||||
**Choices**
|
||||
|
||||
- [ ] Add a key-value pair
|
||||
- [x] Retrieve the value associated with a key
|
||||
- [ ] Check if a key is present
|
||||
- [ ] Remove a key-value pair
|
||||
|
||||
**Explanation**
|
||||
|
||||
```plaintext
|
||||
The `get` operation in HashMap is used to retrieve the value associated with a given key.
|
||||
```
|
||||
|
||||
---
|
||||
## Problem Statement
|
||||
Given an integer array as input, return the corresponding frequency map.
|
||||
|
||||
|
||||
## Example
|
||||
**Input:**
|
||||
arr = [1, 4, 3, -2, 1, 1, 4, 5, 3]
|
||||
|
||||
|
||||
**Output:**
|
||||
```plaintext
|
||||
hm = {
|
||||
1: 3,
|
||||
4: 2,
|
||||
3: 2,
|
||||
-2: 1,
|
||||
5: 1
|
||||
}
|
||||
```
|
||||
|
||||
## Solution
|
||||
In this, we iterate over every element of an array, for every element we have two possibilities.
|
||||
1. Current element is not in the hashmap(`hm.containsKey(arr[i]) == false`).
|
||||
then add the current element into HashMap with frequency 1.
|
||||
2. The current element is already present in the HashMap as a key and has some value.
|
||||
then simply increase the previously stored frequency of the current element by 1.
|
||||
|
||||
|
||||
## PseudoCode
|
||||
```java
|
||||
import java.util.*;
|
||||
import java.lang.*;
|
||||
class Main{
|
||||
public static HashMap<Integer, Integer> freqMap(int arr[]){
|
||||
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
|
||||
for(int i = 0; i < arr.length; i++){
|
||||
// case 1 - arr[i] not present in hashmap
|
||||
if(hm.containsKey(arr[i]) == false){
|
||||
hm.put(arr[i],1);
|
||||
}
|
||||
// case - arr[i] already present in hashmap
|
||||
// before current element, hm -> {2: 3}
|
||||
// current -> 2
|
||||
// hm -> {2: 3}
|
||||
else{
|
||||
int beforeValue = hm.get(arr[i]);
|
||||
int newValue = beforeValue + 1;
|
||||
hm.put(arr[i], newValue);
|
||||
}
|
||||
}
|
||||
return hm;
|
||||
}
|
||||
public static void main(String args[]){
|
||||
int arr[] = {1, 4, 3, -2, 1, 1, 4, 5, 3};
|
||||
System.out.println(freqMap(arr));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Output:**
|
||||
```plaintext
|
||||
{1 = 3, -2 = 1, 3 = 2, 4 = 2, 5 = 1}
|
||||
````
|
||||
|
||||
|
||||
## DryRun
|
||||
**Input:**
|
||||
arr[] = {1, 4, 3, -2, 1, 1, 4, 5, 3}
|
||||
|
||||
**Solution:**
|
||||
1. Initially our hashmap is empty, `hm = {}`,
|
||||
2. Now we start iterating array elements, first element is 1, it is not in HashMap so if the condition becomes true, then we will simply put this element in the map with frequency 1. `hm = {1: 1}`.
|
||||
3. Next element is 4, it is also not in HashMap so if the condition becomes true, then we will simply put this element in the map with frequency 1. `hm = {1: 1, 4: 1}`.
|
||||
4. Next element is 3, it is also not in HashMap so if the condition becomes true, then we will simply put this element in the map with frequency 1. `hm = {1: 1, 4: 1, 3: 1}`.
|
||||
5. Next element is -2, it is also not in HashMap so if the condition becomes true, then we will simply put this element in the map with frequency 1. `hm = {1: 1, 4: 1, 3: 1, -2: 1}`.
|
||||
6. The next element is 1, it is available in HashMap, so if the condition becomes false, we will go to the else part.
|
||||
```java
|
||||
beforeValue = hm.get(1) = 1
|
||||
newValue = beforeValue + 1 = 1 + 1 = 2
|
||||
hm.put(1, 2)
|
||||
```
|
||||
then hashmap becomes, `hm = {1: 2, 4: 1, 3: 1, -2: 1}`.
|
||||
7. The next element is again 1, it is available in HashMap, so if the condition becomes false, we will go to the else part.
|
||||
```java
|
||||
beforeValue = hm.get(1) = 2
|
||||
newValue = beforeValue + 1 = 2 + 1 = 3
|
||||
hm.put(1, 3)
|
||||
```
|
||||
then hashmap becomes, `hm = {1: 3, 4: 1, 3: 1, -2: 1}`.
|
||||
8. The next element is 4, it is available in HashMap, so if the condition becomes false, we will go to the else part.
|
||||
```java
|
||||
beforeValue = hm.get(4) = 1
|
||||
newValue = beforeValue + 1 = 1 + 1 = 2
|
||||
hm.put(4, 2)
|
||||
```
|
||||
then hashmap becomes, `hm = {1: 3, 4: 2, 3: 1, -2: 1}`.
|
||||
9. Next element is 5, it is also not in HashMap so if the condition becomes true, then we will simply put this element in the map with frequency 1. `hm = {1: 3, 4: 2, 3: 1, -2: 1, 5: 1}`.
|
||||
10. The next element is 3, it is available in HashMap, so if the condition becomes false, we will go to the else part.
|
||||
```java
|
||||
beforeValue = hm.get(3) = 1
|
||||
newValue = beforeValue + 1 = 1 + 1 = 2
|
||||
hm.put(3, 2)
|
||||
```
|
||||
then hashmap becomes, `hm = {1: 3, 4: 2, 3: 2, -2: 1, 5: 1}`.
|
@@ -0,0 +1,683 @@
|
||||
# Refresher : Introduction to Java : If-Else
|
||||
|
||||
## If-Else
|
||||
|
||||
#### Example
|
||||
Let's start with real world example of ordering coffee from a cafe :-
|
||||
|
||||
* The customer might ask the receptionist ***If* you have coffee then provide coffee.**
|
||||

|
||||
* Or ***If* you have coffee then provide coffee, *else* provide tea**
|
||||

|
||||
|
||||
* In programming we have to tackle real world situations.
|
||||
* **How can we tackle the situation described above in the example using programming ?**
|
||||
* If we pay attention to questions asked in the example we find the following keywords ***If*** & ***Else***.
|
||||
* We can code the above situations using if else conditions.
|
||||
|
||||
|
||||
#### If-Else Syntax
|
||||
```cpp
|
||||
if(is coffee available ? ){
|
||||
// serve coffee
|
||||
}
|
||||
else{
|
||||
// serve tea
|
||||
}
|
||||
```
|
||||
|
||||
* **Is coffee available ?** is the **Condition**.
|
||||
* **The condition is statement which can have only true/false as answers** or we say it's of **boolean** type
|
||||
|
||||
|
||||
|
||||
---
|
||||
## Question 1
|
||||
|
||||
|
||||
### Question
|
||||
Given an integer age as input, print whether the person is eligible to vote or not ?
|
||||
> A person is eleigible if the person's age >= 18
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
20
|
||||
```
|
||||
#### Solution 1
|
||||
|
||||
`Output : Eligible`
|
||||
#### Testcase 2
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
14
|
||||
```
|
||||
#### Solution 2
|
||||
`Output : Not Eligible`
|
||||
|
||||
#### Approach
|
||||
* Using conditional statements we check:
|
||||
* If age is >= 18 print Eligible.
|
||||
* Else print Not Eligible
|
||||
#### Pseudeocode
|
||||
```cpp
|
||||
public static void main() {
|
||||
|
||||
if (age >= 18) {
|
||||
System.out.print("Eligible");
|
||||
} else {
|
||||
System.out.print("Not Eligible");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 2
|
||||
|
||||
### Question
|
||||
Given two integers A and B as input, print the larger
|
||||
> A will not be equal to B
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
A = 4, B = 6
|
||||
```
|
||||
#### Solution 1
|
||||
`Output : 6 is bigger`
|
||||
|
||||
#### Testcase 2
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
A = 9, B = 6
|
||||
```
|
||||
#### Solution 2
|
||||
`Output : 9 is bigger`
|
||||
|
||||
#### Approach
|
||||
|
||||
* Using conditional statements we check:
|
||||
* If A > B print **A is bigger**.
|
||||
* Else print **B is bigger**.
|
||||
|
||||
#### Pseudeocode
|
||||
```java
|
||||
public static void main() {
|
||||
|
||||
scn = new Scanner(System.in);
|
||||
|
||||
int A = scn.nextInt();
|
||||
int B = scn.nextInt();
|
||||
|
||||
if (A > B) {
|
||||
System.out.print(A + "is bigger");
|
||||
} else {
|
||||
System.out.print(B + "is bigger");
|
||||
}
|
||||
}
|
||||
```
|
||||
---
|
||||
## Question 2 part 2
|
||||
|
||||
|
||||
### Question
|
||||
Given two integers A and B as input, print the large
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
A = 4, B = 6
|
||||
```
|
||||
#### Solution 1
|
||||
`Output : 6 is bigger`
|
||||
#### Testcase 2
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
A = 9, B = 6
|
||||
```
|
||||
#### Solution 2
|
||||
`Output : 9 is bigger`
|
||||
|
||||
#### Testcase 2
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
A = 6, B = 6
|
||||
```
|
||||
#### Solution 2
|
||||
`Output : Both are equal`
|
||||
|
||||
#### Approach
|
||||
* Using conditional statements we check:
|
||||
* If A > B print **A is bigger**.
|
||||
* Else if A < B print **B is bigger**.
|
||||
* Else print **Both are equal**.
|
||||
|
||||
#### Pseudeocode
|
||||
```java
|
||||
public static void main() {
|
||||
|
||||
scn = new Scanner(System.in);
|
||||
|
||||
int A = scn.nextInt();
|
||||
int B = scn.nextInt();
|
||||
|
||||
if (A > B) {
|
||||
System.out.print(A + "is bigger");
|
||||
} else if (B > A) {
|
||||
System.out.print(B + "is bigger");
|
||||
} else {
|
||||
System.out.print("Both are equal");
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
## Question 3
|
||||
|
||||
|
||||
### Question
|
||||
Given temperature of patient in farenheit as input,
|
||||
print whether the temperature is low, normal, high
|
||||
>normal from 98.2 till 98.8
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
98.1
|
||||
```
|
||||
#### Solution 1
|
||||
`Output : Low`
|
||||
#### Testcase 2
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
98.5
|
||||
```
|
||||
#### Solution 2
|
||||
`Output : normal`
|
||||
|
||||
#### Testcase 3
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
99.3
|
||||
```
|
||||
#### Solution 3
|
||||
`Output : high`
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Question
|
||||
Which data type should be used to store temperature of a patient ?
|
||||
|
||||
|
||||
**Choices**
|
||||
|
||||
- [x] Double
|
||||
- [ ] Int
|
||||
- [ ] String
|
||||
- [ ] long
|
||||
|
||||
**Solution**
|
||||
|
||||
```plaintext
|
||||
Double is used to store the numbers with decimals.
|
||||
```
|
||||
|
||||
#### Approach
|
||||
* Using conditional statements we check:
|
||||
* If temperature is < 98.2 print low.
|
||||
* Else if temperature > 98.5 print high**.
|
||||
* Else print normal
|
||||
|
||||
#### Pseudeocode
|
||||
```java
|
||||
public static void main() {
|
||||
scn = new Scanner(System.in);
|
||||
|
||||
double temperature = scn.nextDouble();
|
||||
|
||||
if (temperature < 98.2) {
|
||||
System.out.print("low");
|
||||
} else if (temperature > 98.8) {
|
||||
System.out.print("high");
|
||||
} else {
|
||||
System.out.print("normal");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Operators
|
||||
|
||||
|
||||
### Division
|
||||
* Division is denoted by **/** operator.
|
||||
* Provided below is the output datatype based on dividend and divisor datatype.
|
||||
|
||||
* int / int ---> int
|
||||
* float / int ---> float
|
||||
* int / float ---> float
|
||||
* float / float ---> float
|
||||
* long / int ---> long
|
||||
* double / float ---> double
|
||||
* int / long are replacable
|
||||
* float / double are replacable
|
||||
|
||||
* To convert a number to float put a f in the ending of it.
|
||||
* To convert a number to double we can write it with .0 in the end.
|
||||
|
||||
#### Example
|
||||
```cpp
|
||||
System.out.println(9 / 3) ; // int / int ---> int output would be 3
|
||||
System.out.println(11 / 3); // int / int ---> int output would be 3
|
||||
System.out.println(11f / 3) ; // float / int ---> float output would be 3.6666
|
||||
```
|
||||
### Multiplication
|
||||
|
||||
* Multiplication is denoted by <b>*</b> operator.
|
||||
* Provided below is the output datatype based on multiplicand and multiplier datatype.
|
||||
* int * int ---> int
|
||||
* int * long ---> long
|
||||
* long * int ---> long
|
||||
* long * long --->long
|
||||
* int / float are replacable
|
||||
* long / double are replacable
|
||||
|
||||
#### Example 1
|
||||
```java
|
||||
int x = 100000;
|
||||
int y = 100000;
|
||||
int z = x * y
|
||||
System.out.println(z); // prints garbage value
|
||||
```
|
||||
* The above code gives garbage value as output but **why ?**
|
||||
* We can see that when we multiply x and y i.e 100000 * 100000 then output would be 10<sup>10</sup>.
|
||||
* Since the range of integer datatype is roughly 10<sup>9</sup> we would get garbage value due to overflow as we store it in z (int).
|
||||
|
||||
#### Example 2
|
||||
```java
|
||||
int x = 100000;
|
||||
int y = 100000;
|
||||
long z = x * y
|
||||
System.out.println(z); // prints garbage value
|
||||
```
|
||||
* The above code gives garbage value as output but **why ?** **even though we have changed the datatype of z from int ---> long.**
|
||||
* We have changed the datatype of z but the according to rules above :-
|
||||
* int * int ---> int
|
||||
* Therefore we need to explicitly change datatype of the multiplicand or the multiplier to long so that :-
|
||||
* long * int ---> long
|
||||
* Therefore :-
|
||||
```java
|
||||
int x = 100000;
|
||||
int y = 100000;
|
||||
long z = (long)x * y;
|
||||
System.out.println(z); // prints 10000000000
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Question
|
||||
What will be the output according to Java :
|
||||
```java
|
||||
int a = 100000;
|
||||
int b = 400000;
|
||||
long c = (long)(a * b);
|
||||
System.out.println(c);
|
||||
```
|
||||
|
||||
**Choices**
|
||||
|
||||
- [x] Some random number
|
||||
- [ ] 40000000000
|
||||
- [ ] Compilation error
|
||||
- [ ] No Output
|
||||
|
||||
**Solution**
|
||||
|
||||
* First we are doing a * b i.e int * int therefore the output will be int.
|
||||
* Overflow would have already occured before typecasting to long.
|
||||
* Hence the random value is printed.
|
||||
|
||||
---
|
||||
### Operators Continued
|
||||
|
||||
|
||||
### Modulo
|
||||
* Modulo is denoted by **%** operator.
|
||||
* Gives us the remainder when a is divided by b i.e. a % b = remainder when a is divided by b.
|
||||
|
||||
#### Examples
|
||||
* 7 % 3 ---> 1
|
||||
* 8 % 5 ---> 3
|
||||
* 10 % 1 ---> 0
|
||||
* 5 % 12 ---> ?
|
||||
* Answer is 5 by **why ?**.
|
||||
* Because 5 % 12 = 12 * 0 + 5 where 5 is dividend, 12 is divisor , 0 is quotient & 5 is remainder.
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Question
|
||||
What is the result?
|
||||
System.out.print(17 % 4);
|
||||
|
||||
**Choices**
|
||||
|
||||
- [x] 1
|
||||
- [ ] 4
|
||||
- [ ] 16
|
||||
- [ ] 5
|
||||
|
||||
**Solution**
|
||||
|
||||
```plaintext
|
||||
dividend = divisor* quotient + remainder
|
||||
=> 17 = 4 * 4 + 1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Question
|
||||
What will be the result of a % b, when b perfectly divides a with no remainder ?
|
||||
|
||||
**Choices**
|
||||
|
||||
- [x] 0
|
||||
- [ ] b -1
|
||||
- [ ] b
|
||||
- [ ] a
|
||||
|
||||
**Solution**
|
||||
```plaintext
|
||||
dividend = divisor * quotient + remainder
|
||||
if dividend is divided perfectly by divisor then the remainder is 0
|
||||
```
|
||||
|
||||
---
|
||||
## Question 4
|
||||
|
||||
|
||||
### Question
|
||||
Given an integer as input, print whether it is even or Odd
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
3
|
||||
```
|
||||
|
||||
#### Solution 1
|
||||
`Output : odd`
|
||||
|
||||
#### Testcase 2
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
6
|
||||
```
|
||||
#### Solution 2
|
||||
`Output : even`
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Question
|
||||
|
||||
If a % 2 == 0, what can we say about a ?
|
||||
|
||||
**Choices**
|
||||
|
||||
- [x] even
|
||||
- [ ] odd
|
||||
- [ ] prime
|
||||
- [ ] remainder
|
||||
|
||||
---
|
||||
### Approach
|
||||
* Using conditional statements we check:
|
||||
* If A % 2 == 0 print **even**.
|
||||
* Else print **odd**.
|
||||
|
||||
#### Pseudeocode
|
||||
```cpp
|
||||
public static void main() {
|
||||
scn = new Scanner(System.in);
|
||||
|
||||
int A = scn.nextInt();
|
||||
int B = scn.nextInt();
|
||||
|
||||
if (A % 2 == 0) {
|
||||
System.out.print("even");
|
||||
} else {
|
||||
System.out.print("odd");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
## Question 5
|
||||
|
||||
|
||||
### Question
|
||||
Q5 : Given an integer as input, print its last digit
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
73
|
||||
```
|
||||
#### Solution 1
|
||||
`Output : 3`
|
||||
#### Testcase 2
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
651
|
||||
```
|
||||
#### Solution 2
|
||||
`Output : 1`
|
||||
|
||||
#### Approach
|
||||
|
||||
* Print A % 10
|
||||
|
||||
#### Pseudeocode
|
||||
```cpp
|
||||
scn = new Scanner(System.in);
|
||||
|
||||
int A = scn.nextInt();
|
||||
|
||||
System.out.print(A % 10);
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
### Operators Continued
|
||||
|
||||
|
||||
### Relational Operators
|
||||
* **A > B** ---> Checks weather A is greater than B.
|
||||
* **A < B** ---> Checks weather A is less than B.
|
||||
* **A >= B** ---> Checks weather A is greater than or equalt to B.
|
||||
* **A <= B** ---> Checks weather A is less than or equal to B.
|
||||
* **A == B** ---> Checks weather A is equals B.
|
||||
* **A != B** ---> Checks weather A is not equal to B.
|
||||
|
||||
### Logical Operators
|
||||
* AND operator is denoted by **&&**
|
||||
* Truth table is provided below.
|
||||
|
||||
| A | B | A && B |
|
||||
|:---:|:---:|:------:|
|
||||
| T | F | F |
|
||||
| F | T | F |
|
||||
| F | F | F |
|
||||
| T | T | T |
|
||||
|
||||
* OR operator is denoted by **||**
|
||||
* Truth table is provided below.
|
||||
|
||||
| A | B | A && B |
|
||||
|:---:|:---:|:------:|
|
||||
| T | F | T |
|
||||
| F | T | T |
|
||||
| F | F | F |
|
||||
| T | T | T |
|
||||
|
||||
|
||||
|
||||
---
|
||||
## Question 6
|
||||
|
||||
|
||||
### Question
|
||||
|
||||
Q6 : Given units of electricity consumed as an integer input A, print the bill amount. Provided below is the range of electricity consumed and rate at which it is charged:-
|
||||
[1-50] ---> ₹1
|
||||
[51-100] ---> ₹2
|
||||
[101 and beyond] ---> ₹4
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
20
|
||||
```
|
||||
#### Solution 1
|
||||
`Output : 20 * 1 = 20`
|
||||
|
||||
#### Testcase 2
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
80
|
||||
```
|
||||
#### Solution 2
|
||||
`Output : 50 * 1 + 30 * 2 = 110`
|
||||
|
||||
#### Testcase 3
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
120
|
||||
```
|
||||
#### Solution 3
|
||||
`Output : 50 * 1 + 50 * 2 + 20 * 4= 230`
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
|
||||
#### Pseudeocode
|
||||
```java
|
||||
public static void main() {
|
||||
|
||||
scn = new Scanner(System.in);
|
||||
int A = scn.nextInt();
|
||||
|
||||
if (A >= 1 && A <= 50) {
|
||||
System.out.print(A * 1);
|
||||
} else if (A >= 51 && A <= 100) {
|
||||
System.out.print(50 + (A - 50) * 2);
|
||||
} else {
|
||||
System.out.print(50 + (50 * 2) + ((A - 100) * 4));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
### Question 7
|
||||
|
||||
### Question
|
||||
Q7 : Given an integer A as input
|
||||
* If it is a multiple of 3, print Fizz
|
||||
* If it is a multiple of 5, print Buzz
|
||||
* If it is a multiple of 3 and 5, print Fizz-Buzz
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
5
|
||||
```
|
||||
|
||||
#### Solution 1
|
||||
`Output : Buzz`
|
||||
|
||||
#### Testcase 2
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
3
|
||||
```
|
||||
|
||||
#### Solution 2
|
||||
`Output : Fizz`
|
||||
|
||||
#### Testcase 3
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
30
|
||||
```
|
||||
|
||||
#### Solution 3
|
||||
`Output : Fizz-Buzz`
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
|
||||
#### Approach 1
|
||||
```java
|
||||
public static void main() {
|
||||
|
||||
scn = new Scanner(System.in);
|
||||
int A = scn.nextInt();
|
||||
|
||||
if (A % 3 == 0) {
|
||||
System.out.print("Fizz");
|
||||
} else if (A % 5 == 0) {
|
||||
System.out.print("Buzz");
|
||||
} else if (A % 3 == 0 && A % 5 == 0) {
|
||||
System.out.print("Fizz-Buzz");
|
||||
}
|
||||
}
|
||||
```
|
||||
* When we test the above approach on A = 30, we get output as "Fizz"
|
||||
* But correct output would be "Fizz-Buzz", so **why the wrong answer ?**
|
||||
* Since if-else work in a chained manner the condition A % 3 == 0 is checked first.
|
||||
* Therefore "Fizz" is printed
|
||||
* Correct approach would be to check condition ( A % 3 == 0 && A % 5 == 0 ) first.
|
||||
|
||||
#### Pseudeocode
|
||||
```java
|
||||
public static void main() {
|
||||
|
||||
scn = new Scanner(System.in);
|
||||
int A = scn.nextInt();
|
||||
|
||||
if (A % 3 == 0 && A % 5 == 0) {
|
||||
System.out.print("Fizz-Buzz");
|
||||
} else if (A % 5 == 0) {
|
||||
System.out.print("Buzz");
|
||||
} else if (A % 3 == 0) {
|
||||
System.out.print("Fizz");
|
||||
}
|
||||
}
|
||||
```
|
@@ -0,0 +1,476 @@
|
||||
# Introduction to Problem Solving
|
||||
|
||||
---
|
||||
## Agenda
|
||||
|
||||
1. Output in Java
|
||||
2. Data Types
|
||||
3. Typecasting
|
||||
4. Input
|
||||
5. Quizzes
|
||||
6. Dashboard Walkthrough
|
||||
|
||||
|
||||
---
|
||||
## Output in Java
|
||||
Let's start with the famous example - **Hello World**
|
||||
|
||||
|
||||
### Code to Print string/sentence/text
|
||||
```cpp
|
||||
public static void main(){
|
||||
|
||||
System.out.print("Hello World!");
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
### Code to **print number**
|
||||
```cpp
|
||||
public static void main(){
|
||||
|
||||
System.out.print(1);
|
||||
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Observation
|
||||
* Whenever we print a string, we put double quotes **" "** around it.
|
||||
* Double quotes are not required for printing numbers.
|
||||
|
||||
---
|
||||
### Question
|
||||
System.out.print("Hey There");
|
||||
|
||||
**Choices**
|
||||
- [x] Hey There
|
||||
- [ ] "Hey There"
|
||||
- [ ] Error
|
||||
- [ ] "Hey There
|
||||
|
||||
**Explanation**
|
||||
String between **""** will get printed. Therefore, solution is **Hey There**
|
||||
|
||||
---
|
||||
### Question
|
||||
system.out.print(10);
|
||||
|
||||
**Choices**
|
||||
- [x] Error
|
||||
- [ ] 2
|
||||
- [ ] 10
|
||||
- [ ] "10"
|
||||
|
||||
|
||||
**Solution**
|
||||
There is syntax error in above code.
|
||||
Instead of **"system"** it should be **"System"**.
|
||||
Error thrown is - "error: package system does not exist"
|
||||
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
Predict the output:
|
||||
System.out.print("5 * 10");
|
||||
|
||||
**Choices**
|
||||
|
||||
- [x] 5 * 10
|
||||
- [ ] "5 * 10"
|
||||
- [ ] 50
|
||||
- [ ] Error
|
||||
|
||||
|
||||
**Solution**
|
||||
|
||||
Prints the sentence / string / charactes between **""**, so instead of doing calculation & printing 50, we get :-
|
||||
**5 * 10**
|
||||
|
||||
---
|
||||
### Output in Java Continued
|
||||
|
||||
#### Code to Print Answers to Basic Arithimetic Operations
|
||||
|
||||
```cpp
|
||||
public static void main(){
|
||||
|
||||
System.out.print(5 * 10); // gives 50 as output
|
||||
System.out.print(10 / 5); // gives 2 as output
|
||||
System.out.print(10 + 5); // gives 15 as output
|
||||
System.out.print(10 - 5); // gives 5 as output
|
||||
|
||||
}
|
||||
```
|
||||
* **We use println to print in next line**
|
||||
|
||||
```cpp
|
||||
public static void main(){
|
||||
System.out.println("My name is [instructor]");
|
||||
System.out.print("I am from [Hometown]");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
```java
|
||||
System.out.println("This question");
|
||||
System.out.println("is easy!");
|
||||
```
|
||||
What's output of the above program ?
|
||||
|
||||
|
||||
**Choices**
|
||||
- [ ] This question is easy!
|
||||
- [ ] This questionis easy!
|
||||
- [x] This question
|
||||
is easy!
|
||||
- [ ] This question's easy!
|
||||
|
||||
|
||||
**Solution**
|
||||
|
||||
In first statement println is written hence "This question" gets printed and control goes to new line, then in next line, again println is there, so "is easy!" gets printed and control goes to next line.
|
||||
|
||||
|
||||
---
|
||||
### Question
|
||||
```java
|
||||
System.out.println("Red");
|
||||
System.out.print("Blue ");
|
||||
System.out.println("Green");
|
||||
System.out.print("Yellow");
|
||||
```
|
||||
What's output of the above programme ?
|
||||
|
||||
**Choices**
|
||||
- [ ] Red
|
||||
Blue Green Yellow
|
||||
- [x] Red
|
||||
Blue Green
|
||||
Yellow
|
||||
- [ ] Red
|
||||
BlueGreen
|
||||
Yellow
|
||||
- [ ] Red Blue Green Yellow
|
||||
|
||||
|
||||
**Solution**
|
||||
|
||||
First line has println, so after "Red" gets printed, control goes to new line.
|
||||
Second statement has print, so after "Blue " gets printed, controls stays in the same line
|
||||
Third line has println, so after "Green" gets printed, control goes to new line.
|
||||
Fourth statement has print, so after "Yellow" gets printed, controls stays in the same line
|
||||
|
||||
---
|
||||
### Output in Java Continued
|
||||
|
||||
* We can do single line comments by ---> **//**
|
||||
```cpp
|
||||
// single line comment
|
||||
```
|
||||
* We can do multi-line comments by ---> /* */
|
||||
```cpp
|
||||
/*
|
||||
this
|
||||
is a
|
||||
multiline
|
||||
comment
|
||||
*/
|
||||
```
|
||||
* Shortcut to do multi-line comments is to select the part to be commented and press ctrl + /
|
||||
|
||||
* We can concatenate two strings like:-
|
||||
```cpp
|
||||
System.out.println("Ram " + "Shayam"); // output: ram shayam and the control will go to the next line
|
||||
System.out.println("My age is " + 25 ); // output: My age is 25 and the control will go to the next line
|
||||
```
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
Predict the output:
|
||||
System.out.print( 7 + 1 + "156");
|
||||
|
||||
**Choices**
|
||||
- [ ] 71156
|
||||
- [x] 8156
|
||||
- [ ] 1568
|
||||
- [ ] 15617
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
Predict the output:
|
||||
System.out.print("156" + 7 + 1);
|
||||
|
||||
**Choices**
|
||||
- [ ] 1568
|
||||
- [ ] 15678
|
||||
- [x] 15671
|
||||
- [ ] 1568
|
||||
|
||||
**Solution**
|
||||
|
||||
Calculation shall happen from left to right.
|
||||
For first +, one operand is number and another is string, so it will concatenate them, i.e 1567.
|
||||
Then for second +, both operands are string, therefore concatenation will happen.
|
||||
Hence, **answer is 15671**.
|
||||
|
||||
---
|
||||
## Data types in java
|
||||
|
||||
### Data types
|
||||
|
||||
1. **Primitive Data Types**
|
||||
These are predefined in the Java programming language.
|
||||
**For example:** byte, short, int, long, double, float, boolean, char
|
||||
|
||||
2. **Non-Primitive Data Types**
|
||||
|
||||
These are not predefined but defined by the programmer according to the need for a particular task.
|
||||
**For example:** String, Arrays, class, etc.
|
||||
|
||||
|
||||

|
||||
|
||||
|
||||
**Primitive data types** are divided into two different types of values.
|
||||
|
||||
1. Numeric Data Types
|
||||
2. Non-Numeric Data Types
|
||||
|
||||
|
||||
#### Numeric Data Types
|
||||
Numeric data types are used to store numeric values such as whole numbers and fractional numbers. They are divided into two parts, **integer** and **floating**.
|
||||
|
||||
**1. Integer**
|
||||
|
||||
**Byte, short, long, and int** these data types are used to store **whole numbers**
|
||||

|
||||
|
||||
A. **Byte** Datatype:
|
||||
|
||||
It is commonly used when we want to store very small numbers of very limited size. Their data value is in the range of -128 to 127.
|
||||
```cpp
|
||||
byte a = 123;
|
||||
System.out.print(a); //Printing 123
|
||||
```
|
||||
|
||||
B. **Short** Data Type
|
||||
|
||||
The short data type can have data values- in the range of -32,768 to 32767.
|
||||
|
||||
```cpp
|
||||
short a = 123;
|
||||
System.out.println(a); //Printing 123
|
||||
```
|
||||
|
||||
C. **Int** Data Type
|
||||
|
||||
The int data type is commonly used when we want to save memory in large arrays. The range is from -2,147,483,648 (-2^31) to 2,147,483,647 (2^31-1).
|
||||
|
||||
```cpp
|
||||
int a = 123;
|
||||
System.out.println(a); //Printing the 123
|
||||
```
|
||||
|
||||
D. **Long** Data Type
|
||||
|
||||
The long data type is used when the int data type cannot handle a wider range than the int data type range. Data values is in the range of -9,223,372,036,854,775,808(-2^61) to 9,223,372,036,854,775,807(2^61 - 1).
|
||||
|
||||
```cpp
|
||||
long a = 123123123;
|
||||
System.out.println(a); //Printing the value of a
|
||||
```
|
||||
|
||||
**2. Floating Values Data Types**
|
||||
There are two types of Floating values data types in java that are used to store fractional number values.
|
||||
|
||||
E. **Float** Data Type:
|
||||
This data type is used to store numbers that have decimals up to 6 and 7 points.
|
||||
```cpp
|
||||
float a = 1231.231;
|
||||
System.out.println(a); //Printing the value of a
|
||||
```
|
||||
|
||||
F. **Double** Data Type:
|
||||
This data type is used to store numbers that have decimals up to 15 decimals
|
||||
```cpp
|
||||
double a = 12312.23123;
|
||||
System.out.print(a); //Printing the value of a
|
||||
```
|
||||
|
||||
We generally use Integer and Long Data Types.
|
||||
Remember their actual range is very tricky. Therefore, we can remember by stating in power of 10.
|
||||
|
||||
### Close Approximations:
|
||||
**Int** - { -10^9 to 10^9 }
|
||||
**Long** - { -10^18 to 10^18 }
|
||||
|
||||
#### Non Numeric Data Types
|
||||
|
||||
**String**
|
||||
Strings can be created by giving sequence of characters surrounded by double quotes to a variable.
|
||||
|
||||
Example:
|
||||
|
||||
String S = “This is a String”
|
||||
|
||||
**Note:** We will study non primitive data types later.
|
||||
|
||||
---
|
||||
## Typecasting in java
|
||||
|
||||
|
||||
### Typecasting
|
||||
* Typecasting is converting one datatype to another.
|
||||
* We can understand the concept of typecasting by following analogy.
|
||||
* Let's have two tanks
|
||||
* one large, with more capacity(say 100ml)
|
||||
* one small (say 50ml)
|
||||
* The large tanks corresponds to long datatype and small one corresponds to int datatype.
|
||||
* Let's see the cases
|
||||
* **Case 1:-** If water from smaller tank is poured to larger tank (int to long typecasting).
|
||||
* In this case the larger tank hold all the water or we can say int can be typecasted to long.
|
||||

|
||||
|
||||
* **Case 2:-** If larger tank has water <= 50 ml and water from larger tank is poured to smaller tank.
|
||||
* Since the water in larger tank is equal to smaller tanks capacity the operation can be done.
|
||||
* We can say that long can be typecasted to int, if the data is within constraints of int datatype value range.
|
||||

|
||||
|
||||
* **Case 3:-** If larger tank has water > 50 ml and water from larger tank is poured to smaller tank.
|
||||
* In this case, water will OVERFLOW.
|
||||

|
||||
* When long is typecasted to int for data not within constraints of int datatype, the result would be **garbage value**.
|
||||
|
||||
#### Using variables
|
||||
```cpp
|
||||
String name = "arnav"
|
||||
System.out.print("My name is " + name)
|
||||
```
|
||||
|
||||
* We can declare variables as follows:-
|
||||
```cpp
|
||||
int i = 5;
|
||||
long p = 1000000000l;
|
||||
float f = 3.14f;
|
||||
double d = 1.141516171819;
|
||||
```
|
||||
|
||||
* By default integers are considered int
|
||||
* By default decimal values are considered double
|
||||
* Convention of putting l ,f before long and float is only in coding area, not in input
|
||||
|
||||
#### Typecasting example 1
|
||||
```cpp
|
||||
// small --> large
|
||||
int i = 5,
|
||||
long I = i;
|
||||
System.out.println(I); // will give 5 as output
|
||||
```
|
||||
|
||||
#### Typecasting example 2
|
||||
```cpp
|
||||
// large —-> small
|
||||
long l = 100000000000l
|
||||
int i = l
|
||||
System.out.print(i);
|
||||
```
|
||||
* Above conversion will give an error:-Datatypes incompatible possible lossy conversion.
|
||||
* This type of typecasting is **implicit typecasting**.
|
||||
|
||||
#### Typecasting example 3
|
||||
```cpp
|
||||
// large —> small
|
||||
long l = 1000l;
|
||||
int i = l;
|
||||
System.out.print(i);
|
||||
```
|
||||
* For safety, above conversion will give an error:- Datatypes incompatible possible lossy conversion.
|
||||
* We can force the conversion by using **explicit typecasting**
|
||||
```cpp
|
||||
long l = 1000l;
|
||||
int i = (int)l; // forcing to convert; explicit typecasting
|
||||
System.out.print(i);// 1000 as output
|
||||
```
|
||||
* If we force the same typecasting with data out of int value range
|
||||
* In above case we would get garbage value.
|
||||
```cpp
|
||||
long l = 10000000000l;
|
||||
int i = (int)l;
|
||||
// forcing to convert
|
||||
// explicit typecasting
|
||||
System.out.print(i);// garbage value as output
|
||||
```
|
||||
|
||||
---
|
||||
### Input in java
|
||||
|
||||
|
||||
* Scanner class is used to take inputs in java.
|
||||
* Following are the methods to take number inputs in java:-
|
||||
```cpp
|
||||
scn = new Scanner(System.in);
|
||||
int i = scn.nextInt();
|
||||
long t = scn.nextLong();
|
||||
float f = scn.nextFloat( ) ;
|
||||
double d = scn.nextDouble();
|
||||
|
||||
```
|
||||
* Following are methods to take string input in java.
|
||||
```cpp
|
||||
//scn. next ( ) —> Reads only 1 word from input
|
||||
String s = scn.next();
|
||||
System. out. print(s);
|
||||
|
||||
//scn.nextLine() —> Reads entire line from input
|
||||
String s1 = scn.nextLine();
|
||||
System.out.print(s1);
|
||||
```
|
||||
|
||||
---
|
||||
## Question 1
|
||||
|
||||
### Question
|
||||
Take 2 names X and Y as input and print X loves Y.
|
||||
### Testcase
|
||||
|
||||
```java
|
||||
X = Ram
|
||||
Y = Shyam
|
||||
```
|
||||
### Solution
|
||||
|
||||
`Output : Ram loves Shyam`
|
||||
|
||||
#### Code
|
||||
```java
|
||||
String x = scn.next();
|
||||
String y = scn.next();
|
||||
System.out.print(x + " loves " + y);
|
||||
```
|
||||
|
||||
---
|
||||
## Question 2
|
||||
|
||||
|
||||
### Question
|
||||
Take name X and age Y as input and print X age is Y.
|
||||
### Testcase
|
||||
|
||||
```cpp
|
||||
X = Aarnav
|
||||
Y = 25
|
||||
```
|
||||
### Solution
|
||||
`Output : Aarnav age is 25`
|
||||
#### Code
|
||||
```java
|
||||
String x = scn.next();
|
||||
String y = scn.nextInt();
|
||||
System.out.print(x + " age is " + y);
|
||||
```
|
493
Academy DSA Typed Notes/Java Refresher/Refresher Patterns.md
Normal file
493
Academy DSA Typed Notes/Java Refresher/Refresher Patterns.md
Normal file
@@ -0,0 +1,493 @@
|
||||
# Refresher : Patterns
|
||||
|
||||
## Question 1
|
||||
Given **N** as input, print * **N** times.
|
||||
|
||||
#### TestCase
|
||||
|
||||
##### Input
|
||||
```plaintext
|
||||
5
|
||||
```
|
||||
##### Output
|
||||
```plaintext
|
||||
* * * * *
|
||||
```
|
||||
#### PseudoCode
|
||||
```java
|
||||
function pattern(int N) {
|
||||
for (int i = 1; i <= N; i++) {
|
||||
system.out.print(' * ');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 2
|
||||
|
||||
Given **N** as input. Print a square of size **N * N** containing * in each cell.
|
||||
|
||||
#### TestCase
|
||||
|
||||
##### Input
|
||||
```plaintext
|
||||
5
|
||||
```
|
||||
##### Output
|
||||
```plaintext
|
||||
* * * * *
|
||||
* * * * *
|
||||
* * * * *
|
||||
* * * * *
|
||||
* * * * *
|
||||
```
|
||||
#### PseudoCode
|
||||
```java
|
||||
function pattern(int N){
|
||||
for(int i = 1 ; i <= N ; i ++ ){
|
||||
for(int j = 1 ; j <= N ; j ++ ){
|
||||
system.out.print(' * ');
|
||||
}
|
||||
system.out.println();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 3
|
||||
|
||||
Given **N**,**M** as input, print a rectangle of size **N * M** containing * in each cell.
|
||||
|
||||
#### TestCase
|
||||
|
||||
##### Input
|
||||
```plaintext
|
||||
N = 3
|
||||
M = 4
|
||||
```
|
||||
##### Output
|
||||
```plaintext
|
||||
* * * *
|
||||
* * * *
|
||||
* * * *
|
||||
```
|
||||
#### PseudoCode
|
||||
```java
|
||||
function pattern(int N,int M){
|
||||
for(int i = 1 ; i <= N ; i ++ ){
|
||||
for(int j = 1 ; j <= M ; j ++ ){
|
||||
system.out.print(' * ');
|
||||
}
|
||||
system.out.println();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 4
|
||||
|
||||
Given **N** as input, print a staircase pattern of size **N**.
|
||||
|
||||
#### TestCase
|
||||
|
||||
##### Input
|
||||
```plaintext
|
||||
5
|
||||
```
|
||||
##### Output
|
||||
```plaintext
|
||||
*
|
||||
* *
|
||||
* * *
|
||||
* * * *
|
||||
* * * * *
|
||||
```
|
||||
#### Observation
|
||||
The key observation here is that:
|
||||
* The staircase pattern formed the right-angled triangle.
|
||||
* The number of stars in each row is equal to the row number.
|
||||
|
||||
|
||||
| Row | Stars |
|
||||
|:---:|:-----:|
|
||||
| 1 | 1 |
|
||||
| 2 | 2 |
|
||||
| 3 | 3 |
|
||||
| 4 | 4 |
|
||||
|
||||
|
||||
#### PseudoCode
|
||||
```java
|
||||
function pattern(int N){
|
||||
for(int i = 1 ; i <= N ; i ++ ){
|
||||
for(int j = 1 ; j <= i ; j ++ ){
|
||||
system.out.print(' * ');
|
||||
}
|
||||
system.out.println();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 5
|
||||
|
||||
Given **N** as input, print the pattern as shown below.
|
||||
|
||||
#### TestCase
|
||||
|
||||
##### Input 1
|
||||
```plaintext
|
||||
N = 3
|
||||
```
|
||||
##### Output 1
|
||||
```plaintext
|
||||
*
|
||||
* 2
|
||||
* 2 *
|
||||
```
|
||||
##### Input 2
|
||||
```plaintext
|
||||
N = 4
|
||||
```
|
||||
##### Output 2
|
||||
```plaintext
|
||||
*
|
||||
* 2
|
||||
* 2 *
|
||||
* 2 * 4
|
||||
```
|
||||
#### Observation
|
||||
The key observations are:
|
||||
* For even column numbers, print * .
|
||||
* For odd column numbers, print the column number.
|
||||
#### PseudoCode
|
||||
```java
|
||||
function pattern(int N){
|
||||
for(int i = 1 ; i <= N ; i ++ ){
|
||||
for(int j = 1 ; j <= i ; j ++ ){
|
||||
if(j % 2 == 1) system.out.print(' * ');
|
||||
else system.out.print(j);
|
||||
}
|
||||
system.out.println();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 6
|
||||
|
||||
Given **N** as input, print the pattern as shown below.
|
||||
|
||||
#### TestCase
|
||||
|
||||
##### Input 1
|
||||
```plaintext
|
||||
N = 3
|
||||
```
|
||||
##### Output 1
|
||||
```plaintext
|
||||
* _ *
|
||||
* _ *
|
||||
* _ *
|
||||
```
|
||||
##### Input 2
|
||||
```plaintext
|
||||
N = 4
|
||||
```
|
||||
##### Output 2
|
||||
```plaintext
|
||||
* _ _ *
|
||||
* _ _ *
|
||||
* _ _ *
|
||||
* _ _ *
|
||||
```
|
||||
#### Observation
|
||||
The key observation here is that:
|
||||
* The first and last column number of each row is * .
|
||||
* There are total (N - 2) spaces in between stars( * ).
|
||||
|
||||
|
||||
#### PseudoCode
|
||||
```java
|
||||
function pattern(int N){
|
||||
for(int i = 1 ; i <= N ; i ++ ){
|
||||
system.out.print(' * ');
|
||||
for(int j = 2 ; j <= N - 1 ; j ++ ){
|
||||
system.out.print('_');
|
||||
}
|
||||
system.out.print(' * ');
|
||||
system.out.println();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 7
|
||||
|
||||
Given **N** as input, print the pattern as shown below.
|
||||
|
||||
#### TestCase
|
||||
|
||||
##### Input 1
|
||||
```plaintext
|
||||
N = 3
|
||||
```
|
||||
##### Output 1
|
||||
```plaintext
|
||||
* * *
|
||||
* *
|
||||
*
|
||||
```
|
||||
##### Input 2
|
||||
```plaintext
|
||||
N = 4
|
||||
```
|
||||
##### Output 2
|
||||
```plaintext
|
||||
* * * *
|
||||
* * *
|
||||
* *
|
||||
*
|
||||
```
|
||||
#### Observation
|
||||
As shown in above, the number of stars in each row is one less than the previous row except 1st row where number of stars is **N**. Hence, we can derive the formula:
|
||||
* Number of stars in each row is equal to the (N - rowNumber + 1).
|
||||
|
||||
For N = 4,
|
||||
|
||||
|
||||
| Row | Stars |
|
||||
|:---:|:-----:|
|
||||
| 1 | 4 |
|
||||
| 2 | 3 |
|
||||
| 3 | 2 |
|
||||
| 4 | 1 |
|
||||
|
||||
#### PseudoCode
|
||||
```java
|
||||
function pattern(int N){
|
||||
for(int i = 1 ; i <= N ; i ++ ){
|
||||
for(int j = i ; j <= N ; j ++ ){
|
||||
system.out.print(' * ');
|
||||
}
|
||||
system.out.println();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 8
|
||||
|
||||
Given **N** as input, print the pattern as shown below.
|
||||
|
||||
#### TestCase
|
||||
##### Input 1
|
||||
```plaintext
|
||||
N = 3
|
||||
```
|
||||
##### Output 1
|
||||
```plaintext
|
||||
* *
|
||||
* *
|
||||
* *
|
||||
```
|
||||
##### Input 2
|
||||
```plaintext
|
||||
N = 4
|
||||
```
|
||||
##### Output 2
|
||||
```plaintext
|
||||
* *
|
||||
* *
|
||||
* *
|
||||
* *
|
||||
```
|
||||
#### Observation
|
||||
The key observation here is that:
|
||||
* The first and last character of each row is ' * '.
|
||||
* Number of spaces in each row is one less than the previous row except first row where number of spaces between stars is **N - 1**. Hence we can say that there are total (N - rowNumber) spaces in between stars( * ).
|
||||
|
||||
|
||||
For N = 4,
|
||||
|
||||
|
||||
| Row | Total number of spaces between stars |
|
||||
|:---:|:-----:|
|
||||
| 1 | 3 |
|
||||
| 2 | 2 |
|
||||
| 3 | 1 |
|
||||
| 4 | 0 |
|
||||
|
||||
|
||||
#### PseudoCode
|
||||
```java
|
||||
function pattern(int N) {
|
||||
for (int i = 1; i <= N; i++) {
|
||||
system.out.print(' * ');
|
||||
for (int j = 1; j <= N - i; j++) {
|
||||
system.out.print(' ');
|
||||
}
|
||||
system.out.print(' * ');
|
||||
system.out.println();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 9
|
||||
|
||||
Given **N** as input, print the pattern as shown below.
|
||||
|
||||
#### TestCase
|
||||
|
||||
##### Input 1
|
||||
```plaintext
|
||||
N = 3
|
||||
```
|
||||
##### Output 1
|
||||
```plaintext
|
||||
*
|
||||
* *
|
||||
* * *
|
||||
```
|
||||
##### Input 2
|
||||
```plaintext
|
||||
N = 4
|
||||
```
|
||||
##### Output 2
|
||||
```plaintext
|
||||
*
|
||||
* *
|
||||
* * *
|
||||
* * * *
|
||||
```
|
||||
#### Observation
|
||||
The key observation here is that:
|
||||
* Number of spaces in each row is one less than the previous row except 1st row where number of spaces are **N - 1**. Hence we can say that there are total (N - rowNumber) spaces in the starting of each row.
|
||||
* Number of sars in each row is one more than the previous row except 1st row where number of stars are **1**. Hence we can say that there are total (rowNumber) stars at the last of each row.
|
||||
|
||||
|
||||
For N = 4,
|
||||
|
||||
|
||||
| Row | Total number of spaces | Total number of stars |
|
||||
|:---:|:----------------------:|:---------------------:|
|
||||
| 1 | 3 | 1 |
|
||||
| 2 | 2 | 2 |
|
||||
| 3 | 1 | 3 |
|
||||
| 4 | 0 | 4 |
|
||||
|
||||
|
||||
|
||||
#### PseudoCode
|
||||
```java
|
||||
function pattern(int N) {
|
||||
for (int i = 1; i <= N; i++) {
|
||||
for (int j = 1; j <= N - i; j++) {
|
||||
system.out.print(' ');
|
||||
}
|
||||
for (int j = 1; j <= i; j++) {
|
||||
system.out.print(' * ');
|
||||
}
|
||||
system.out.println();
|
||||
}
|
||||
}
|
||||
```
|
||||
---
|
||||
## Question 10
|
||||
Given **N** as input, print the pattern as shown below.
|
||||
|
||||
#### TestCase
|
||||
##### Input 1
|
||||
```plaintext
|
||||
N = 4
|
||||
```
|
||||
##### Output 1
|
||||
```plaintext
|
||||
********
|
||||
*** ***
|
||||
** **
|
||||
* *
|
||||
```
|
||||
#### Observation
|
||||
The key observation here is that:
|
||||
* There are total (N - rowNumber + 1) stars in the begining and end of each row.
|
||||
* There are total ((rowNumber - 1) * 2) spaces between these stars.
|
||||
|
||||
For N = 4,
|
||||
|
||||
|
||||
| Row | Stars | Spaces | Stars |
|
||||
|:---:|:-----:|:------:|:-----:|
|
||||
| 1 | 4 | 0 | 4 |
|
||||
| 2 | 3 | 2 | 3 |
|
||||
| 3 | 2 | 4 | 2 |
|
||||
| 4 | 1 | 6 | 1 |
|
||||
|
||||
#### PseudoCode
|
||||
```java
|
||||
function pattern(int N) {
|
||||
for (int i = 1; i <= N; i++) {
|
||||
for (int j = 1; j <= N - i + 1; j++) {
|
||||
system.out.print(' * ');
|
||||
}
|
||||
for (int j = 1; j <= (i - 1) * 2; j++) {
|
||||
system.out.print(' ');
|
||||
}
|
||||
for (int j = 1; j <= N - i + 1; j++) {
|
||||
system.out.print(' * ');
|
||||
}
|
||||
system.out.println();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 11
|
||||
|
||||
Given **N** as input, print the pattern as shown below.
|
||||
|
||||
#### TestCase
|
||||
##### Input 1
|
||||
```plaintext
|
||||
N = 4
|
||||
```
|
||||
##### Output 1
|
||||
```plaintext
|
||||
*
|
||||
***
|
||||
*****
|
||||
*******
|
||||
```
|
||||
#### Observation
|
||||
The key observation here is that:
|
||||
* Number of spaces in each row is one less than the previous row except 1st row where number of spaces are **N - 1**. Hence we can say that there are total (N - rowNumber) spaces in the starting of each row.
|
||||
* Number of stars in each row is two more than the previous row except 1st row where number of stars are **1**. Hence we can say that there are total ((rowNumber - 1) * 2 + 1) stars between these spaces.
|
||||
|
||||
For N = 4,
|
||||
|
||||
|
||||
| Row | Spaces | Stars | Spaces |
|
||||
|:---:|:-----:|:------:|:-----:|
|
||||
| 1 | 3 | 1 | 3 |
|
||||
| 2 | 2 | 3 | 2 |
|
||||
| 3 | 1 | 5 | 1 |
|
||||
| 4 | 0 | 7 | 0 |
|
||||
|
||||
#### PseudoCode
|
||||
```java
|
||||
function pattern(int N) {
|
||||
for (int i = 1; i <= N; i++) {
|
||||
for (int j = 1; j <= N - i; j++) {
|
||||
system.out.print(' ');
|
||||
}
|
||||
for (int j = 1; j <= (i - 1) * 2 + 1; j++) {
|
||||
system.out.print(' * ');
|
||||
}
|
||||
for (int j = 1; j <= N - i + 1; j++) {
|
||||
system.out.print(' ');
|
||||
}
|
||||
system.out.println();
|
||||
}
|
||||
}
|
||||
```
|
279
Academy DSA Typed Notes/Java Refresher/Refresher Strings.md
Normal file
279
Academy DSA Typed Notes/Java Refresher/Refresher Strings.md
Normal file
@@ -0,0 +1,279 @@
|
||||
# Refresher : Strings
|
||||
# Introduction to String
|
||||
|
||||
---
|
||||
## Explanation
|
||||
|
||||
Lets consider this following pseudo-code:
|
||||
|
||||
```java
|
||||
System.out.print("Hello World")
|
||||
```
|
||||
|
||||
The part ie "Hello World" is known as **string**.
|
||||
String is defined as the sequence of characters.
|
||||
|
||||
Characters involves - [A - Z] , [a - z] , [0 - 9] , spaces, tabs, new line, **{@,#,$,...}**.
|
||||
|
||||
|
||||
### Examples
|
||||
|
||||
* "abc123" - This is a string
|
||||
* "abc $ - This is **not** a string, as this dont have ending double quotes.
|
||||
* " 123 " - This is a string
|
||||
* 123 - This is **not** a string. This is an integer
|
||||
|
||||
---
|
||||
## String VS Integer
|
||||
|
||||
"123" is a string but `123` is an integer. On string we apply operations like concatanation, length ,etc. In integer, we apply addition, multiplication,etc.
|
||||
|
||||
The basic difference in string and integer is in the operations we do on them.
|
||||
|
||||
---
|
||||
## String in Computers
|
||||
### Explanation
|
||||
|
||||
The computers only understands binary, which is base 2. All the numbers which is base 10 is converted to binary so that computers understands it.
|
||||
|
||||
All the texts, pictures, audios , etc are similarly converted to numbers in computers.
|
||||
|
||||
Lets suppose we have a string "xyz" and in computer x is denoted by the number a, y is by b and z is by c. So we can say that "xyz" is represented by the number [ a b c].
|
||||
|
||||
|
||||
But there is no inherent rule of mapping, all this is done by assumption, which creates a problem. So to make things uniform, ASCII standard is implemented.
|
||||
|
||||
---
|
||||
## ASCII
|
||||
### Explanation
|
||||
|
||||
ASCII, in full American Standard Code for Information Interchange, a standard data-encoding format for electronic communication between computers. ASCII assigns standard numeric values to letters, numerals, punctuation marks, and other characters used in computers.
|
||||
|
||||
The ASCII table looks like this:-
|
||||
|
||||

|
||||
|
||||
> The learners are not required to remember this.
|
||||
|
||||
---
|
||||
## ASCII
|
||||
### Explanation
|
||||
|
||||
Suppose we have a string:
|
||||
|
||||
```java
|
||||
String country = "India";
|
||||
```
|
||||
|
||||
We assume String is an array of characters, hence it is comprehended as:
|
||||
|
||||
```java
|
||||
"India" -> ['I', 'n', 'd', 'i', 'a']
|
||||
```
|
||||
|
||||
Length of string is given by
|
||||
|
||||
```java
|
||||
str.length()
|
||||
```
|
||||
|
||||
If we want to access the i-th character of the string, we use:
|
||||
|
||||
```java
|
||||
str.charAt(index)
|
||||
```
|
||||
|
||||
### Question - 1
|
||||
|
||||
Given a String, print its characters in new line
|
||||
|
||||
**Input:**
|
||||
|
||||
```java
|
||||
String -> "India"
|
||||
```
|
||||
|
||||
**Output:**
|
||||
```plaintext
|
||||
I
|
||||
n
|
||||
d
|
||||
i
|
||||
a
|
||||
```
|
||||
|
||||
**Approach:** Iterate through each character in the string using a for loop and print it on a new
|
||||
|
||||
**Code:**
|
||||
|
||||
```java
|
||||
for(int i = 0; i < country.length(); i++) {
|
||||
System.out.println(country.charAt(i));
|
||||
}
|
||||
```
|
||||
|
||||
### Question - 2
|
||||
Given a String, print the ASCII of its characters in new line
|
||||
|
||||
**Input:**
|
||||
|
||||
```java
|
||||
String -> "India"
|
||||
```
|
||||
|
||||
**Output:**
|
||||
```plaintext
|
||||
73
|
||||
110
|
||||
100
|
||||
105
|
||||
97
|
||||
```
|
||||
|
||||
> Hint : Java understands characters as numbers
|
||||
|
||||
**Approach:** Iterate through each character in the string, cast it to an integer to get its ASCII value, and then print that value on a new line.
|
||||
|
||||
**Code:**
|
||||
|
||||
```java
|
||||
String str = "India";
|
||||
for(int i = 0; i < str.length(); i++) {
|
||||
System.out.println((int)str.charAt(i));
|
||||
}
|
||||
```
|
||||
|
||||
### Question - 3
|
||||
|
||||
Given a String, print the count of upper-case characters
|
||||
|
||||
**Input:**
|
||||
|
||||
```java
|
||||
String -> "kjRS78q31@3 Q"
|
||||
```
|
||||
|
||||
**Output:** 3
|
||||
|
||||
> Hint 1 : A-Z = $65 - 90$
|
||||
> Hint 2 : You don't need Hint 1
|
||||
|
||||
|
||||
**Approach:** The approach iterates over each character of the string str. For each character, it checks if it falls within the ASCII range for uppercase letters ('A' to 'Z'). If so, it increments the counter cnt. At the end, the total count of uppercase characters is printed.
|
||||
|
||||
**Code:**
|
||||
|
||||
```java
|
||||
int cnt = 0;
|
||||
String str = "kjRS78q31@3 Q";
|
||||
for(int i = 0; i < str.length(); i++) {
|
||||
char c = str.charAt(i);
|
||||
if(c >= 'A' && c <= 'Z') {
|
||||
cnt++;
|
||||
}
|
||||
}
|
||||
System.out.println("Count of uppercase chars is " + cnt);
|
||||
```
|
||||
|
||||
### Question - 4
|
||||
|
||||
Given a String, print the count of special characters
|
||||
**Input:**
|
||||
|
||||
```java
|
||||
String -> "kjRS78q31@3 Q"
|
||||
```
|
||||
**Output:** 2
|
||||
|
||||
> Special Characters means non numeric
|
||||
|
||||
|
||||
**Approach:** The code iterates over each character of the string str. For each character, it checks if it's neither a number, nor an uppercase letter, nor a lowercase letter (i.e., it's a special character). If so, it increments the counter cnt. The final count represents the number of special characters.
|
||||
|
||||
**Code:**
|
||||
|
||||
```java
|
||||
public static int specialChars(String str) {
|
||||
int cnt = 0;
|
||||
for(int i = 0; i < str.length(); i++) {
|
||||
char c = str.charAt(i);
|
||||
if(
|
||||
!(c >= '0' && c <= '9') &&
|
||||
!(c >= 'A' && c <= 'Z') &&
|
||||
!(c >= 'a' && c <= 'z')
|
||||
) {
|
||||
cnt++;
|
||||
}
|
||||
}
|
||||
return cnt;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Question - 5
|
||||
|
||||
Given a string, return the string in reverse
|
||||
|
||||
**Input:** : "Aarnav"
|
||||
**Output:** "vanraA"
|
||||
|
||||
|
||||
|
||||
* **Approach 1:** For each character in the string (from front to back), prepend it to the result. This builds the reversed string from front to back.
|
||||
```java
|
||||
ans = ""
|
||||
ans = 'A' + ans = 'A' + "" = "A"
|
||||
ans = 'a' + ans = 'a' + "A" = "aA"
|
||||
ans = 'r' + ans = 'r' + "aA" = "raA"
|
||||
.
|
||||
.
|
||||
ans = 'v' + ans = 'v' + "anraA" = "vanraA"
|
||||
```
|
||||
* **Approach 2:** For each character in the string (from back to front), append it to the result. This builds the reversed string from back to front.
|
||||
|
||||
```java
|
||||
ans = ""
|
||||
ans = "" + 'v' = "v"
|
||||
ans = "v" + 'a' = "va"
|
||||
.
|
||||
.
|
||||
.
|
||||
ans = "vanra" + 'A' = "vanraA"
|
||||
```
|
||||
|
||||
**Code:**
|
||||
|
||||
```java
|
||||
public static String reverse(String str) {
|
||||
String ans = "";
|
||||
for(int i = 0; i < str.length(); i++) {
|
||||
ans = str.charAt(i) + ans;
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
```
|
||||
|
||||
### Question - 6
|
||||
|
||||
Given a String, check whether its a palindrome
|
||||
|
||||
**Palindrome** - A string which reads the same from front and back
|
||||
|
||||
**Examples** - madam, maam, malayalam, dad, mom, racecar, nitin
|
||||
|
||||
> Hint: Re-use previous reverse code
|
||||
|
||||
**Approach:** Reverse the given string and compare it with the original. If they are identical, then the string is a palindrome.
|
||||
|
||||
**Code:**
|
||||
|
||||
```java
|
||||
public static boolean isPalindrome(String str) {
|
||||
String rev = reverse(str);
|
||||
if (str.equals(rev)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
```
|
561
Academy DSA Typed Notes/Java Refresher/Refresher While Loop.md
Normal file
561
Academy DSA Typed Notes/Java Refresher/Refresher While Loop.md
Normal file
@@ -0,0 +1,561 @@
|
||||
# Refresher : While Loop
|
||||
## While Loop
|
||||
|
||||
|
||||
### Example
|
||||
* Say we need to print "Hello" 5 times.
|
||||
* We can do it as :-
|
||||
```cpp
|
||||
System.out.print("Hello");
|
||||
System.out.print("Hello");
|
||||
System.out.print("Hello");
|
||||
System.out.print("Hello");
|
||||
System.out.print("Hello");
|
||||
```
|
||||
* But what if we have to do the same 100 times or 1000 times ?
|
||||
* It would be not feasible.
|
||||
* Solution to above is to use **while loop** :-
|
||||
```cpp
|
||||
int count = 0 ;
|
||||
|
||||
while(count < 5)
|
||||
{
|
||||
System.out.print("Hello");
|
||||
count ++ ;
|
||||
}
|
||||
```
|
||||
|
||||
#### Syntax
|
||||
```cpp
|
||||
intialization
|
||||
|
||||
while(Condition)
|
||||
{
|
||||
// loop work
|
||||
updation
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
```
|
||||
int i = 1;
|
||||
i = i + 1;
|
||||
```
|
||||
|
||||
What is the new value of i ?
|
||||
|
||||
**Choices**
|
||||
|
||||
- [x] 2
|
||||
- [ ] 1
|
||||
- [ ] 0
|
||||
- [ ] 3
|
||||
|
||||
**Solution**
|
||||
|
||||
```plaintext
|
||||
i = 1
|
||||
i = i + 1 => i = 1 + 1 = 2
|
||||
```
|
||||
|
||||
---
|
||||
## Question 1
|
||||
|
||||
|
||||
### Question
|
||||
Given an integer N as input. Print from 1 to N ?
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
N = 4
|
||||
```
|
||||
|
||||
#### Solution 1
|
||||
`Output : 1 2 3 4`
|
||||
|
||||
#### Approach
|
||||
* Intialize the count with 1.
|
||||
* While loop will execute till count <= N.
|
||||
* Print count.
|
||||
* In loop update the count by increamenting 1.
|
||||
|
||||
#### Code
|
||||
```cpp
|
||||
public static void main(){
|
||||
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int N = scn.nextInt();
|
||||
int count = 1;
|
||||
while (count <= N) {
|
||||
System.out.printLn(count + " ");
|
||||
count++ ;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 2
|
||||
|
||||
### Question
|
||||
Given an integer N as input. Print from N to 1 ?
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
N = 4
|
||||
```
|
||||
#### Solution 1
|
||||
`Output : 4 3 2 1`
|
||||
|
||||
#### Approach
|
||||
* Intialize the count with N.
|
||||
* While loop will execute till count >= 1.
|
||||
* Print count.
|
||||
* In loop update the count by decreamenting it by 1.
|
||||
|
||||
#### Code
|
||||
```cpp
|
||||
public static void main() {
|
||||
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int N = scn.nextInt();
|
||||
int count = N;
|
||||
while (count >= 1) {
|
||||
System.out.print(count + " ");
|
||||
count--;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 3
|
||||
|
||||
### Question
|
||||
Given an integer N as input. Print odd values from 1 to N ?
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input : N = 8
|
||||
```
|
||||
#### Solution 1
|
||||
```plaintext
|
||||
Output : 1 3 5 7
|
||||
```
|
||||
#### Approach
|
||||
* Since odd numbers start from 1, intialize the count with 1.
|
||||
* While loop will execute till count <= N.
|
||||
* print count.
|
||||
* In loop update the count by increamenting it by 2 since adding 2 to previous odd will yeild next odd number.
|
||||
|
||||
#### Code
|
||||
```cpp
|
||||
public static void main() {
|
||||
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int N = scn.nextInt();
|
||||
int count = 1;
|
||||
while (count <= N) {
|
||||
System.out.print(count + " ");
|
||||
count += 2;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
---
|
||||
## Question 4
|
||||
|
||||
|
||||
### Question
|
||||
Given an integer N as input. Print odd values from 1 to N ?
|
||||
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
N = 8
|
||||
```
|
||||
#### Solution 1
|
||||
`Output : 1 3 5 7`
|
||||
|
||||
#### Approach
|
||||
* Since odd numbers start from 1, intialize the count with 1.
|
||||
* While loop will execute till count <= N.
|
||||
* print count.
|
||||
* In loop update the count by increamenting it by 2 since adding 2 to previous odd will yeild next odd number.
|
||||
|
||||
#### Code
|
||||
```cpp
|
||||
public static void main() {
|
||||
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int N = scn.nextInt();
|
||||
int count = 1;
|
||||
while (count <= N) {
|
||||
System.out.print(count + " ");
|
||||
count += 2;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 5
|
||||
|
||||
|
||||
### Question
|
||||
Given an integer N as input, print multiples Of 4 till N ?
|
||||
|
||||
#### Testcase 1
|
||||
```plaintext
|
||||
Input : N = 18
|
||||
```
|
||||
|
||||
#### Solution 1
|
||||
```plaintext
|
||||
Output : 4 8 12 16
|
||||
```
|
||||
|
||||
#### Approach
|
||||
* Since multiple of 4 numbers start from 4, intialize the count with 4.
|
||||
* While loop will execute till count <= N.
|
||||
* Print count.
|
||||
* In loop update the count by increamenting it by 4 since adding 4 to previous multiple will yeild the next multiple.
|
||||
|
||||
#### Code
|
||||
```cpp
|
||||
public static void main() {
|
||||
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int N = scn.nextInt();
|
||||
int count = 4;
|
||||
while (count <= N) {
|
||||
System.out.print(count + " ");
|
||||
count += 4;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Question
|
||||
```cpp
|
||||
int i = 1;
|
||||
while (i <= 10) {
|
||||
i = i * i;
|
||||
System.out.print(i + " ");
|
||||
i++;
|
||||
}
|
||||
```
|
||||
What will be the output ?
|
||||
|
||||
**Choices**
|
||||
|
||||
- [x] 1 4 25
|
||||
- [ ] Error
|
||||
- [ ] Infinite loop
|
||||
- [ ] 100 12 34
|
||||
|
||||
**Solution**
|
||||
|
||||
```plaintext
|
||||
|i = 1 | i <= 10 | i * i = 1 | i++ = 2 |---> iteration 1
|
||||
|i = 2 | i <= 10 | i * i = 4 | i++ = 5 |---> iteration 2
|
||||
|i = 5 | i <= 10 | i * i = 25 | i++ = 26 |---> iteration 3
|
||||
```
|
||||
|
||||
---
|
||||
### Question
|
||||
|
||||
```java
|
||||
public static void main() {
|
||||
int i = 0;
|
||||
while (i <= 10) {
|
||||
System.out.print(i + " ");
|
||||
i = i * i;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
What will be the output ?
|
||||
|
||||
**Choices**
|
||||
|
||||
- [x] Loop will never end
|
||||
- [ ] 1 4 9 16 25 36 49 64 81 100
|
||||
- [ ] 1 2 3 4
|
||||
- [ ] 0 0 0 0
|
||||
|
||||
**Solution**
|
||||
|
||||
```plaintext
|
||||
Since i would always be less than 10 hence infinite loop
|
||||
```
|
||||
|
||||
---
|
||||
## Question 6
|
||||
|
||||
|
||||
### Question
|
||||
Q5 : Given an integer N as input, print perfect squares till N ?
|
||||
> Perfect square —> An integer whose square root is an integer
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input : N = 30
|
||||
```
|
||||
#### Solution 1
|
||||
```plaintext
|
||||
Output : 1 4 9 16 25
|
||||
```
|
||||
|
||||
#### Approach
|
||||
* Intialize count = 1
|
||||
* While loop will execute till count * count <= N.
|
||||
* Print count * count.
|
||||
* In loop update the count by increamenting it by 1.
|
||||
|
||||
#### Code
|
||||
```cpp
|
||||
public static void main() {
|
||||
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int N = scn.nextInt();
|
||||
int count = 1;
|
||||
while (count * count <= N) {
|
||||
System.out.print(count * count + " ");
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 7
|
||||
|
||||
### Question
|
||||
Given an integer N as input, print it's digits ?
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input : N = 6531
|
||||
```
|
||||
#### Solution 1
|
||||
```plaintext
|
||||
Output : 1 3 5 6
|
||||
```
|
||||
#### Observations
|
||||
|
||||
|
||||
| N | N % 10 |
|
||||
|:----:|:----:|
|
||||
| 6531 | 1 |
|
||||
| 653 | 3 |
|
||||
| 65 | 5 |
|
||||
| 6 | 6 |
|
||||
|
||||
* We can see that answer to % 10 of numbers present in the table coincide with the answer.
|
||||
* We need to find a way to arrive at these numbers while iterating.
|
||||
* We can do this by dividing number in each iteration by 10.
|
||||
|
||||
| N | N/10 |
|
||||
|:----:|:----:|
|
||||
| 6531 | 653 |
|
||||
| 653 | 65 |
|
||||
| 65 | 6 |
|
||||
| 6 | 0 |
|
||||
|
||||
|
||||
#### Approach
|
||||
* Input N.
|
||||
* While loop will execute till N > 0.
|
||||
* Print N % 10.
|
||||
* In loop update the N by dividing it by 10.
|
||||
|
||||
#### Code
|
||||
```cpp
|
||||
public static void main() {
|
||||
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int N = scn.nextInt();
|
||||
while (N > 0) {
|
||||
System.out.print(N + " ");
|
||||
N /= 10;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Edge Cases
|
||||
**TestCase 1**
|
||||
```plaintext
|
||||
Input :-
|
||||
N = 0
|
||||
```
|
||||
**Solution 1**
|
||||
```plaintext
|
||||
Output = 0
|
||||
```
|
||||
**Approach** to handle edge case -
|
||||
* Input N.
|
||||
* While loop will execute till N >= 0.
|
||||
* Print N % 10.
|
||||
* In loop update the N by dividing it by 10.
|
||||
|
||||
**Code 1**
|
||||
```cpp
|
||||
public static void main() {
|
||||
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int N = scn.nextInt();
|
||||
while (N >= 0) {
|
||||
System.out.print(N + " ");
|
||||
N /= 10;
|
||||
}
|
||||
}
|
||||
```
|
||||
* The above approach leads to **infinite loop**.
|
||||
* We need to handle above case seperately in if else.
|
||||
|
||||
|
||||
**TestCase 2**
|
||||
```plaintext
|
||||
Input :-
|
||||
N = - 6351 (i.e N < 0)
|
||||
```
|
||||
**Solution 2**
|
||||
```plaintext
|
||||
Output : 1 3 5 6
|
||||
```
|
||||
|
||||
* Since answer of N < 0 would be same as that of N > 0.
|
||||
* So we just multiple N with -1 in order to convert it to +ve number .
|
||||
|
||||
#### Code final
|
||||
```cpp
|
||||
public static void main() {
|
||||
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int N = scn.nextInt();
|
||||
if (N == 0) {
|
||||
System.out.print(0);
|
||||
} else {
|
||||
|
||||
if (N < 0) {
|
||||
N *= -1;
|
||||
}
|
||||
while (N > 0) {
|
||||
print(N + " ")
|
||||
N /= 10;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
## Question 8
|
||||
|
||||
|
||||
### Question
|
||||
Given an integer N as input, print sum of it's digits ?
|
||||
> N > 0
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input : N = 6531
|
||||
```
|
||||
#### Solution 1
|
||||
```plaintext
|
||||
Output : 15
|
||||
```
|
||||
|
||||
#### Approach
|
||||
|
||||
* Input N & Intialize sum = 0
|
||||
* While loop will execute till N > 0.
|
||||
* Add N % 10 to sum.
|
||||
* In loop update the N by dividing it by 10.
|
||||
|
||||
#### Pseudeocode
|
||||
```cpp
|
||||
public static void main() {
|
||||
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int N = scn.nextInt();
|
||||
int Sum = 0;
|
||||
while (N > 0) {
|
||||
Sum += (N % 10);
|
||||
N /= 10;
|
||||
}
|
||||
System.out.print(Sum);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Question
|
||||
Which of the following will add the digit `d` to the back of a number `r`
|
||||
|
||||
**Choices**
|
||||
|
||||
- [x] r * 10 + d
|
||||
- [ ] d * r
|
||||
- [ ] d + r
|
||||
- [ ] d * 10 + r
|
||||
|
||||
**Solution**
|
||||
|
||||
```plaintext
|
||||
Let r = 13 & d = 4
|
||||
We want to add d behind r i.e we need number 134
|
||||
So r * 10 = 130
|
||||
r * 10 + d => 130 + 4 = 134
|
||||
```
|
||||
|
||||
---
|
||||
## Question 9
|
||||
|
||||
|
||||
### Question
|
||||
Given an integer N as input, Reverse it ?
|
||||
> N > 0
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```plaintext
|
||||
Input :
|
||||
N = 6531
|
||||
```
|
||||
#### Solution 1
|
||||
`Output : 1356`
|
||||
|
||||
#### Approach
|
||||
* Input N & Intialize reverse = 0
|
||||
* While loop will execute till N > 0.
|
||||
* Set reverse = reverse * 10 + N % 10.
|
||||
* In loop update the N by dividing it by 10.
|
||||
|
||||
#### Code
|
||||
```cpp
|
||||
public static void main() {
|
||||
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int N = scn.nextInt();
|
||||
int reverse = 0;
|
||||
while (N > 0) {
|
||||
d = N % 10;
|
||||
reverse = reverse * 10 + d;
|
||||
N /= 10;
|
||||
}
|
||||
System.out.print(reverse);
|
||||
}
|
||||
```
|
Reference in New Issue
Block a user