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:
File diff suppressed because it is too large
Load Diff
722
Academy DSA Typed Notes/Beginner Language/Beginner Data Types.md
Normal file
722
Academy DSA Typed Notes/Beginner Language/Beginner Data Types.md
Normal file
@@ -0,0 +1,722 @@
|
||||
# Beginner: Data Types
|
||||
|
||||
---
|
||||
|
||||
# Agenda
|
||||
|
||||
* Quizes to revise the previous session
|
||||
* Rules of Naming a variable
|
||||
* Different categories of Data
|
||||
* Why we need multiple datatype under one category
|
||||
* Int Vs Long
|
||||
* TypeCasting
|
||||
|
||||
:::success
|
||||
There are a lot of quizzes in this session, please take some time to think about the solution on your own before reading further.....
|
||||
:::
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
What will be output for this ?
|
||||
```
|
||||
System.out.print(12 + 4 + "try" + 3 * 4);
|
||||
```
|
||||
# Choices
|
||||
- [ ] Error
|
||||
- [ ] 124try34
|
||||
- [ ] 16try34
|
||||
- [x] 16try12
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
```
|
||||
Declare a int variable with name x and intialize with value 10
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] x int = 10;
|
||||
- [ ] int x = 20
|
||||
- [x] int x = 10;
|
||||
- [ ] None of them
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
```
|
||||
int x = 10;
|
||||
int y = 20;
|
||||
System.out.print(x + y);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] Error
|
||||
- [ ] x + y
|
||||
- [x] 30
|
||||
- [ ] 1020
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
```
|
||||
int x = 10;
|
||||
int y = 20;
|
||||
System.out.print(x + " " + y);
|
||||
```
|
||||
|
||||
# Choices
|
||||
|
||||
- [ ] 1020
|
||||
- [ ] Error
|
||||
- [x] 10 20
|
||||
- [ ] 30
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
```
|
||||
int try = 10;
|
||||
System.out.print(Try);
|
||||
```
|
||||
# Choices
|
||||
|
||||
- [ ] 10
|
||||
- [ ] Try
|
||||
- [x] Error
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
```
|
||||
System.out.print(x);
|
||||
int x = 10;
|
||||
```
|
||||
# Choices
|
||||
- [ ] x
|
||||
- [ ] 10
|
||||
- [x] Error
|
||||
- [ ] None of the above
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Rule:** In order to use a variable we need to declare and initialise it first.
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
```
|
||||
int x = 10;
|
||||
System.out.print(x + y);
|
||||
int y = 20;
|
||||
```
|
||||
# Choices
|
||||
- [ ] 30
|
||||
- [ ] 10y
|
||||
- [x] Error
|
||||
- [ ] None of them
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
```
|
||||
int x = 10;
|
||||
int x = 20;
|
||||
System.out.print(x);
|
||||
```
|
||||
# Choices
|
||||
- [ ] 10
|
||||
- [ ] 20
|
||||
- [x] Error
|
||||
- [ ] None of them
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Explanation:**
|
||||
Here, when we write `int x = 10;`, we are declaring and initialising a variable "x".
|
||||
Now when we write this statement, `int x = 20;`, again a variable is created of type int, and name x with value 20.
|
||||
But this is not possible, we cannot have 2 variables with same name.
|
||||
|
||||
|
||||
## **Rule:** We cannot have 2 variables with same name.
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
```
|
||||
int x = 20;
|
||||
System.out.println(x);
|
||||
x = 40;
|
||||
System.out.print(x);
|
||||
```
|
||||
# Choices
|
||||
- [ ] 2040
|
||||
- [ ] Error
|
||||
- [x] 20 40
|
||||
|
||||
---
|
||||
|
||||
**Explanation:**
|
||||
Here, when we write `int x = 20;` , a variable is created of type int and name x.
|
||||
But `x= 40` means we are not creating the variable, instead changing the value of the variable. This line will change the value of x to 40.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
```
|
||||
int x = 20;
|
||||
int y = 40;
|
||||
x = y + 10;
|
||||
System.out.print(x);
|
||||
```
|
||||
|
||||
# Choices
|
||||
|
||||
- [ ] 70
|
||||
- [ ] 60
|
||||
- [x] 50
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Explanation:**
|
||||
|
||||
With very first line, <img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/248/original/Screenshot_2023-09-23_104216.png?1695445969" height = "40" width = "120"> ;, we are creating a variable of type int and name x. Again <img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/249/original/Screenshot_2023-09-23_104341.png?1695446029" height = "25" width = "120">; another variable is created of type int and name y. Then <img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/250/original/Screenshot_2023-09-23_104437.png?1695446089" height = "25" width = "120">; means update the value of x to 50.
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
```
|
||||
int x = 20,y = 40;
|
||||
System.out.print(x + y);
|
||||
```
|
||||
# Choices
|
||||
- [ ] Error
|
||||
- [ ] x + y
|
||||
- [x] 60
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
**Explanation:**
|
||||
Everytime in Java a statement ends with semicolon.
|
||||
In this line there is a comma so we are trying to create a variable x and y of type int.
|
||||
|
||||
**Rule:** We can create two multiple variables of same type in a single line seperated by comma.
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
```
|
||||
int x = 20;y = 40;
|
||||
System.out.print(x + y);
|
||||
```
|
||||
# Choices
|
||||
- [x] Error
|
||||
- [ ] x + y
|
||||
- [ ] 60
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
**Explanation:**
|
||||
Here semicolon is present after 20. That means with <img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/251/original/Screenshot_2023-09-23_104216.png?1695446171" height = "45" width = "120" style="margin: -10px 0px 0px 0px;" >; we are creating a variable and <img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/252/original/Screenshot_2023-09-23_104656.png?1695446243" height = "25" width = "70" style="margin: 0px 0px 0px 0px;" >; we are not declaring a variable.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
```
|
||||
int x = 20,y = 40,z = 80;
|
||||
System.out.print(x + y + z);
|
||||
```
|
||||
# Choices
|
||||
- [ ] Error
|
||||
- [ ] 150
|
||||
- [x] 140
|
||||
- [ ] None of them
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
**Explanation:**
|
||||
Here we are creating 3 variables which are seperated by commas which is possible.
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
## Rules of Naming a variable:
|
||||
1. Name can only contain lowercase[a - z], uppercase alphabets[A - Z], digits(0 - 9), '\$'{Dollar} or '_' {Underscore}, nothing else
|
||||
2. Name cannot start with a digit
|
||||
3. Cannot use reserve keywords as variable name :
|
||||
Reserve keywords : Words which already have a predefined
|
||||
meaning in java, they have a predefined use for them
|
||||
Ex : public, static, void, int, etc :
|
||||
4. Variable name is also case senstive.
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
```
|
||||
How many of them are correct variable names?
|
||||
int x = 10;
|
||||
int 1y = 20;
|
||||
int x@a = 20;
|
||||
```
|
||||
# Choices
|
||||
- [x] 1
|
||||
- [ ] 2
|
||||
- [ ] 3
|
||||
- [ ] 0
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Explanation:**
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/253/original/Screenshot_2023-09-23_104835.png?1695446325" height = "25" width = "120" style="margin: 0px 0px 0px 0px;" >; here second rule is not followed, we are starting a variable name with a digit. This is a invalid variable name.
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/254/original/Screenshot_2023-09-23_105017.png?1695446427" height = "30" width = "130" style="margin: 0px 0px 0px 0px;" >; this is also invalid because here we are having @ in variable name which is not allowed.
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
```
|
||||
How many of them are correct variable names?
|
||||
int _y = 10;
|
||||
int xxy = 20;
|
||||
int x a = 20;
|
||||
int y$z = 45;
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 1
|
||||
- [ ] 2
|
||||
- [x] 3
|
||||
- [ ] 4
|
||||
- [ ] 0
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Explanation:**
|
||||
_y -> valid,
|
||||
xxy -> valid
|
||||
x a -> cannot have space in name, therefore invalid.
|
||||
y\$z -> valid.
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
```
|
||||
int n = 20;
|
||||
int N = 30;
|
||||
System.out.print(n + N);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 50
|
||||
- [ ] 2030
|
||||
- [ ] Error
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Explanation:**
|
||||
Variables 'n' and 'N' are completely different, Java is case sensitive.
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
```
|
||||
int static = 40;
|
||||
System.out.print(static);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 40
|
||||
- [ ] static
|
||||
- [x] Error
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Explanation:**
|
||||
"static" is reserve keyword.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
## Different categories of Data:
|
||||
There are 3 categories of Data:
|
||||
1. Text:
|
||||
* String: words/sentences.
|
||||
* char: 1 character
|
||||
2. Numbers:
|
||||
a. Decimal:
|
||||
* float
|
||||
* double
|
||||
|
||||
b. Non-Decimal(Integers):
|
||||
* byte: almost never used.
|
||||
* short: almost never used.
|
||||
* int
|
||||
* long
|
||||
3. Boolean:
|
||||
* boolean
|
||||
* True/False
|
||||
|
||||
### Why We Need Multiple Datatype Under One Category:
|
||||
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/244/original/upload_bdc30e4d28acbd24dcec0e8e57749503.png?1695445499"
|
||||
height = "350" width = "700" >
|
||||
|
||||
All of them store water.
|
||||
Difference lies in their storage capacity.
|
||||
|
||||
|
||||
|
||||
| category | small | medium | large |
|
||||
|:--------:|:----------:|:------:|:-----:|
|
||||
| 500ml | yes [ideal] | yes | yes |
|
||||
| 15L | no | no | yes |
|
||||
|
||||
|
||||
---
|
||||
|
||||
### Int Vs Long:
|
||||
They both have different range.
|
||||
|
||||
**int:** <img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/245/original/Screenshot_2023-09-23_103645.png?1695445684"
|
||||
height = "50" width = "200">
|
||||
|
||||
**approx:** <img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/246/original/Screenshot_2023-09-23_103749.png?1695445719"
|
||||
height = "55" width = "200">
|
||||
|
||||
|
||||
**long:**<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/247/original/Screenshot_2023-09-23_104014.png?1695445828"
|
||||
height = "60" width = "200">
|
||||
|
||||
|
||||
**approx:** <img src ="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/255/original/Screenshot_2023-09-23_105318.png?1695446607"
|
||||
height = "30" width = "200">
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
int num = 100000; // 10^5
|
||||
System.out.print(num);
|
||||
```
|
||||
# Choices
|
||||
- [x] 100000
|
||||
- [ ] Error
|
||||
- [ ] No clue!
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Explanation:**
|
||||
Here we are creating a variable of type int, name num and value: 100000.
|
||||
It is in the range if int.
|
||||
Ans = 100000.
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
What will be the output?
|
||||
```
|
||||
int x = 10000000000; //10^10
|
||||
System.out.print(x);
|
||||
```
|
||||
# Choices
|
||||
- [ ] 10000000000
|
||||
- [x] Error
|
||||
- [ ] Too many zeroes!
|
||||
|
||||
---
|
||||
|
||||
**Explanation:**
|
||||
Error, Integer number too large.
|
||||
Because 10^10 is out of range of int.
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
long n = 10000000000; // 10^10
|
||||
System.out.print(n);
|
||||
```
|
||||
# Choices
|
||||
- [x] Error
|
||||
- [ ] 10000000000
|
||||
- [ ] Choose me. I am best!
|
||||
|
||||
---
|
||||
|
||||
**Explanation:**
|
||||
Error: Integer number too large.
|
||||
|
||||
**Rule:** whenever the compiler see a non decimal number it considers it as int.
|
||||
|
||||
Now here, We are storing the value 10000000000 into long, But as soon as compiler see the non decimal digit it consider it as int and which is out of range of int. Therefore we get error.
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
long a = 10000000000L; //10^10
|
||||
System.out.print(a);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] Error
|
||||
- [ ] a
|
||||
- [x] 10000000000
|
||||
- [ ] 10000000000L
|
||||
|
||||
---
|
||||
|
||||
**Explanation:**
|
||||
When we write "L" in front of the number it is telling the compiler that consider this number as long, not int.
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
long a = 10000000000l; //10^10
|
||||
System.out.print(a);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] Error
|
||||
- [ ] 10000000000l
|
||||
- [x] 10000000000
|
||||
- [ ] Too tired to count zeroes!
|
||||
|
||||
---
|
||||
|
||||
**Explanation:**
|
||||
Either use "L" or "l", both will work.
|
||||
|
||||
|
||||
----
|
||||
|
||||
## TypeCasting:
|
||||
Typecasting means converting one datatype to another.
|
||||
Basically, Tranfering data from one container to another.
|
||||
|
||||
**Anology:**
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/256/original/upload_c9d475a202262c1a5c542216c6589737.png?1695446752" height = "280" width = "700" >
|
||||
|
||||
1. We can easily transfer water from 5L bucket to 20; bucket.
|
||||
From smaller storage to higher storage, we can easily do it.
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/257/original/upload_56a679ca68e84294e7fa9897f30e6f94.png?1695446782" height = "280" width = "700" >
|
||||
|
||||
2. We can again transfer water from 20L bucket to 5L bucket, if the water level is less than 5L.
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/050/258/original/upload_6a3bb23eb0715c66bbe4ea20ebe87e2c.png?1695446814" height = "280" width = "700" >
|
||||
|
||||
3. We have 8L of water in 20l bucket, now this time when we try to transfer it to 5L bucket, overflow will happen. Water will flow outside of the bucket as well. It will spill.
|
||||
|
||||
**Replicate the example with data types:**
|
||||
5L bucket: int
|
||||
20L bucket: long.
|
||||
|
||||
4. Easily transfer data from int(smaller) to long(bigger).
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
```
|
||||
int a = 1000;
|
||||
long b = a;
|
||||
System.out.print(b);
|
||||
```
|
||||
# Choices
|
||||
- [x] 1000
|
||||
- [ ] Error
|
||||
|
||||
---
|
||||
|
||||
**Explanation:**
|
||||
Here,`int a = 1000;` we are trying to create a int type variable of name a, value 1000.
|
||||
Now `long b = a;` with this we create a long type variable, name b.
|
||||
b = 1000.
|
||||
And we can easily store 1000 in long.
|
||||
|
||||
**It is Implicit/Widening TypeCasting(automatic).**
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
```
|
||||
long x = 10000;
|
||||
System.out.print(x);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 1000
|
||||
- [ ] Error
|
||||
|
||||
---
|
||||
|
||||
**Explanation:**
|
||||
Java considers non decimal number as int.
|
||||
Therefore, the value 10000 is considered as int and we are trying to store int value into long which is possible.
|
||||
Int to Long is implicit typecasting.
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
```
|
||||
long x = 10000;
|
||||
int y = x;
|
||||
System.out.print(y);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 1000
|
||||
- [x] Error
|
||||
|
||||
---
|
||||
|
||||
**Explanation:**
|
||||
`long x = 10000` It is implicit typecasting.
|
||||
But, `int y = x;` Here we are trying to store long value into int container.
|
||||
Error: Possible lossy conversion.
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
```
|
||||
long x = 1000;
|
||||
int y = (int)x;
|
||||
System.out.print(y);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 1000
|
||||
- [ ] Error
|
||||
|
||||
---
|
||||
|
||||
**Explanation:**
|
||||
|
||||
Here we are doing Explicit/Narrowing Typecasting from long to int.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
```
|
||||
long a = 10^10;
|
||||
int b = (int)a;
|
||||
System.out.print(b);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 10^10
|
||||
- [ ] 10^10L
|
||||
- [x] Error
|
||||
- [ ] Some random value
|
||||
|
||||
---
|
||||
|
||||
**Explanation:**
|
||||
|
||||
Here, value 10^10 is too large for int.
|
||||
Ans = Error, Integer number too large.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
```
|
||||
long a = 10^10L;
|
||||
int b = (int)a;
|
||||
System.out.print(b);
|
||||
```
|
||||
|
||||
|
||||
# Choices
|
||||
- [ ] 10^10
|
||||
- [ ] 10^10L
|
||||
- [ ] Error
|
||||
- [x] Some random value
|
||||
|
||||
---
|
||||
**Explanation:**
|
||||
|
||||
Here, We are specifying L so compiler considers 10^10 as long only and then we are trying to store in a long container only which is possible.
|
||||
After that in next line we are doing explicit typecasting, but then also we know that this number is out of range of int.
|
||||
We are actually forcing the compiler to do it, data loss will happen.
|
||||
|
||||
---
|
||||
Some quizzes to revise
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
```
|
||||
int a = (int)10000000000L;
|
||||
System.out.print(a);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] Some Random Value
|
||||
- [ ] Error
|
||||
- [ ] Very Complicated
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
```
|
||||
int a = (int)10000000000;
|
||||
System.out.print(a);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] Some Random Value
|
||||
- [x] Error
|
||||
- [ ] 10000000000
|
||||
|
597
Academy DSA Typed Notes/Beginner Language/Beginner Patterns 1.md
Normal file
597
Academy DSA Typed Notes/Beginner Language/Beginner Patterns 1.md
Normal file
@@ -0,0 +1,597 @@
|
||||
# Patterns Introduction
|
||||
---
|
||||
|
||||
## Agenda
|
||||
|
||||
**Some abbreviations that will be used in this class:**
|
||||
* System.out.print - SOP
|
||||
* System.out.println - SOPln
|
||||
|
||||
|
||||
|
||||
We will work with patterns today. After this class, the students will feel very comfortable with loops.
|
||||
1. Print stars in a single row
|
||||
2. Print a square
|
||||
3. Print a rectangle
|
||||
4. Print staircase
|
||||
5. Print reverse staircase
|
||||
6. Print special pattern
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Loop to print " * " N times in a single row?
|
||||
Ex: N = 5, print *****
|
||||
N = 9, print *********
|
||||
|
||||
# Choices
|
||||
- [x] for(int i = 1; i <= N; i++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
- [ ] for(int i = 1; i < N; i++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
- [ ] for(int i = 0; i <= N; i++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Explanation
|
||||
|
||||
```java
|
||||
for(int i = 1; i <= N; i++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
```
|
||||
This choice is correct. The code uses a loop to iterate from `i = 1` to `i = N` (both inclusive). In each iteration, it prints the "*" character using the `SOP("*");` statement. This loop will print "*" N times in a single row, as desired.
|
||||
|
||||
|
||||
Certainly, let's take a look at why the other two choices are incorrect:
|
||||
|
||||
1. **Incorrect Choice 2:**
|
||||
```java
|
||||
for (int i = 1; i < N; i++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
```
|
||||
**Explanation:** This code uses a loop that starts from `i = 1` and continues until `i` is less than `N`. In each iteration, it prints an asterisk. However, this loop only iterates `N - 1` times, which means it will print one less asterisk than the desired value. For example, if `N` is 5, this loop will print `****` (4 asterisks) instead of `*****`.
|
||||
|
||||
2. **Incorrect Choice 3:**
|
||||
```java
|
||||
for (int i = 0; i <= N; i++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
```
|
||||
**Explanation:** This code uses a loop that starts from `i = 0` and continues until `i` is less than or equal to `N`. In each iteration, it prints an asterisk. However, this loop iterates `N + 1` times, which means it will print one more asterisk than the desired value. For example, if `N` is 5, this loop will print `******` (6 asterisks) instead of `*****`.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Example 1
|
||||
|
||||
This is the quiz question.
|
||||
Print N starts " * " in a single row.
|
||||
N = 5, *****
|
||||
N = 4, ****
|
||||
N = 2, **
|
||||
|
||||
**Q.** What should be the number of iterations?
|
||||
**A.** "N"
|
||||
|
||||
|
||||
**Code:**
|
||||
|
||||
```
|
||||
public static void main() {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int n = sc.nextInt();
|
||||
for (int i = 1; i <= n; i++) {
|
||||
System.out.print(" * ");
|
||||
}
|
||||
}
|
||||
```
|
||||
Dry run the codes and justify why Option 1 is correct for some values of N.
|
||||
|
||||
---
|
||||
|
||||
### Example 2
|
||||
Print a square (N * N) of stars.
|
||||
|
||||
For example,
|
||||
|
||||
N = 4
|
||||
```plaintext
|
||||
****
|
||||
****
|
||||
****
|
||||
****
|
||||
```
|
||||
|
||||
N = 5
|
||||
```plaintext
|
||||
*****
|
||||
*****
|
||||
*****
|
||||
*****
|
||||
*****
|
||||
```
|
||||
|
||||
**Q.** If you have to repeat a single task N number of tasks, how to do that?
|
||||
**A.** We can write a loop.
|
||||
|
||||
|
||||
Now, this questions is similar to repeating 1st task N number of times.
|
||||
So, the code can be:
|
||||
|
||||
```
|
||||
for (int i = 1; i <= N; i++) {
|
||||
for (int i = 1; i <= N; i++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
SOPln();
|
||||
}
|
||||
```
|
||||
|
||||
Ask students if this code is correct. It's not, because we cannot repeat variable 'i' in java.
|
||||
So, the final correct code is:
|
||||
|
||||
```
|
||||
for (int i = 1; i <= N; i++) {
|
||||
for (int j = 1; j <= N; j++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
SOPln();
|
||||
}
|
||||
```
|
||||
|
||||
Explain why we need `SOPln()` after the 2nd for loop.
|
||||
|
||||
**Explanation:**
|
||||
Without the `SOPln()` statement after the inner loop, all the asterisks would be printed in a single continuous line, and the pattern would not be formed with rows and columns. The `SOPln()` call ensures that each row of asterisks is printed on a new line, creating the desired pattern.
|
||||
|
||||
Dry run the above code for N = 3.
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/810/original/upload_f645c770eeb92640a9f8cc6db03c3cc4.png?1693755503"
|
||||
height = "350" width = "450">
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
### Example 3
|
||||
Print rectangle of N * M having stars.
|
||||
N rows having M stars in each row.
|
||||
|
||||
For example,
|
||||
|
||||
N = 4, M = 3
|
||||
```plaintext
|
||||
***
|
||||
***
|
||||
***
|
||||
***
|
||||
```
|
||||
N = 2, M = 4
|
||||
```plaintext
|
||||
****
|
||||
****
|
||||
```
|
||||
|
||||
Outer loop -> N times
|
||||
Inner loop -> M times
|
||||
|
||||
The correct code is:
|
||||
```
|
||||
for (int i = 1; i <= N; i++) {
|
||||
for (int j = 1; j <= M; j++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
SOPln();
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** Mention that the starting values does not matter. Just that the number of iterations should be N.
|
||||
|
||||
Dry run for N = 2, M = 3.
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/812/original/upload_a445fa2609ea3cf56e1734ba8f432818.png?1693755542"
|
||||
height = "300" width = "6000">
|
||||
|
||||
|
||||
**Observation Table:**
|
||||
|
||||
| Row | Stars |
|
||||
|:---:|:-----:|
|
||||
| 1 | 3 |
|
||||
| 2 | 3 |
|
||||
|
||||
|
||||
ith row => M stars
|
||||
and a total N rows
|
||||
|
||||
|
||||
---
|
||||
|
||||
### Example 4
|
||||
Print staircase pattern.
|
||||
For example,
|
||||
|
||||
N = 4
|
||||
```plaintext
|
||||
*
|
||||
**
|
||||
***
|
||||
****
|
||||
```
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
Observe for each row number i, we have i stars in that row.
|
||||
|
||||
Outer Loop -> N times
|
||||
Inner Loop -> i times
|
||||
Inner loop does not work for constant number of times.
|
||||
|
||||
**Observation Table:**
|
||||
|
||||
| Row | Stars |
|
||||
|:---:|:-----:|
|
||||
| 1 | 1 |
|
||||
| 2 | 2 |
|
||||
| 3 | 3 |
|
||||
| 4 | 4 |
|
||||
| 5 | 5 |
|
||||
|
||||
|
||||
ith row => i stars
|
||||
|
||||
|
||||
The correct code is:
|
||||
```
|
||||
for (int i = 1; i <= N; i++) {
|
||||
|
||||
// Loop to print i stars.
|
||||
for (int j = 1; j <= i; j++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
SOPln();
|
||||
}
|
||||
```
|
||||
|
||||
Dry run this code for N = 4 (Given image is incomplete).
|
||||
You may complete the dry run or stop in-between according to the batch.
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/813/original/upload_210e5f09585ebf945b8091effbbc4957.png?1693755626"
|
||||
height = "350" width = "600">
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Example 5
|
||||
|
||||
> **Note for instructor:** Give some context of why we are learning this approach. Like, as similar approach will work in majority of pattern questions
|
||||
|
||||
Print reverse staircase pattern.
|
||||
For example,
|
||||
N = 4
|
||||
```plaintext
|
||||
****
|
||||
***
|
||||
**
|
||||
*
|
||||
```
|
||||
|
||||
N = 5
|
||||
```plaintext
|
||||
*****
|
||||
****
|
||||
***
|
||||
**
|
||||
*
|
||||
```
|
||||
|
||||
For N = 5, we are printing stars in the following manner.
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/814/original/upload_603a3fffb7a60cb436ec6c3f9cd701d8.png?1693755658"
|
||||
height = "300" width = "450">
|
||||
|
||||
Row + star = N + 1
|
||||
So, star = N + 1 - Row
|
||||
Observe for each row number i, we have N - i + 1 stars in that row.
|
||||
|
||||
Outer Loop -> N times
|
||||
Inner Loop -> N - i + 1 times
|
||||
Inner loop does not work for constant number of times.
|
||||
|
||||
The correct code is:
|
||||
```java
|
||||
for (int i = 1; i <= N; i++) {
|
||||
|
||||
// Loop to print N - i + 1 stars.
|
||||
for (int j = 1; j <= N - i + 1; j++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
SOPln();
|
||||
}
|
||||
```
|
||||
|
||||
Dry run the code for N = 3.
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/815/original/upload_36fc6fad1038306dbbea3e096487fb78.png?1693755708"
|
||||
height = "300" width = "500">
|
||||
|
||||
---
|
||||
|
||||
|
||||
#### Another Approach
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/816/original/upload_9e6e30919023e0f930c7d6a77dbfc12d.png?1693756190"
|
||||
height = "250" width = "500">
|
||||
|
||||
In this approach, we will change the starting value of i itself.
|
||||
|
||||
The correct code is:
|
||||
```
|
||||
for (int i = N; i >= 1; i--) {
|
||||
|
||||
// Loop to print i stars.
|
||||
for (int j = 1; j <= i; j++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
SOPln();
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
### Example 6
|
||||
Print the diamond pattern.
|
||||
|
||||
For example,
|
||||
N = 5
|
||||
|
||||
```plaintext
|
||||
**********
|
||||
****--****
|
||||
***----***
|
||||
**------**
|
||||
*--------*
|
||||
*--------*
|
||||
**------**
|
||||
***----***
|
||||
****--****
|
||||
**********
|
||||
```
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/817/original/upload_52ad209dbb64e8caaea062a196388d88.png?1693756234"
|
||||
height = "300" width = "550">
|
||||
|
||||
You are only supposed to print star " * ", but not underscores (they should be spaces).
|
||||
|
||||
If N = 5, so 10 rows are needed.
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
The pattern can be broken into two halves.
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/820/original/upload_308e046a7c9a3d5a090c91f4bdbeb45c.png?1693756293"
|
||||
height = "400" width = "250">
|
||||
|
||||
Again, we can break this pattern into halves again.
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/821/original/upload_7f1f949912f01d8526b41b664739fcbe.png?1693756327"
|
||||
height = "200" width = "550">
|
||||
|
||||
For the right quarter, we need to print some spaces first and then stars.
|
||||
The table shows for each row, how many spaces and stars need to be printed.
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/822/original/upload_f12e19981999da489adddc4e0116fb84.png?1693756365"
|
||||
height = "300" width = "500">
|
||||
|
||||
Combining everything for the first half, we have the following table.
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/823/original/upload_2eab4eb6d8be0559bd3c33a7aaa316c3.png?1693756386"
|
||||
height = "300" width = "500">
|
||||
|
||||
In one single row,
|
||||
|
||||
print (N + 1 - i) stars + (i - 1) spaces + (i - 1) spaces + (N + 1 - i) stars
|
||||
|
||||
So, print (N + 1 - i) stars + 2 * (i - 1) spaces + (N + 1 - i) stars
|
||||
So, let's write the code for the upper half using the above facts.
|
||||
|
||||
```
|
||||
for (int i = 1; i <= N; i++) {
|
||||
|
||||
// In each row, print N + 1 - i stars.
|
||||
for (int j = 1; j <= N + 1 - i; j++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
|
||||
// In each row, (i - 1) spaces.
|
||||
for (int j = 1; j <= 2 * (i - 1); j++) {
|
||||
SOP(" _ ");
|
||||
}
|
||||
|
||||
// In each row, print N + 1 - i stars.
|
||||
for (int j = 1; j <= N + 1 - i; j++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
SOPln();
|
||||
}
|
||||
```
|
||||
|
||||
**Lower Half:**
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/824/original/upload_de9788a8310b94486706ebd6b69671bb.png?1693756417"
|
||||
height = "200" width = "300">
|
||||
|
||||
For lower part, we can directly write the following table:
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/825/original/upload_17ef3ebc6ea5203765bad9eca9915b17.png?1693756437"
|
||||
height = "310" width = "700">
|
||||
|
||||
|
||||
In one single row,
|
||||
print i stars + print (N - i) spaces + print (N - i) spaces + i stars
|
||||
|
||||
So, print i stars + print 2 * (N - i) spaces + i stars
|
||||
So, let's write the code for the upper half using the above facts.
|
||||
|
||||
```
|
||||
for (int i = 1; i <= N; i++) {
|
||||
|
||||
// In each row, print N + 1 - i stars.
|
||||
for (int j = 1; j <= i; j++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
|
||||
// In each row, (i - 1) spaces.
|
||||
for (int j = 1; j <= 2 * (N - i); j++) {
|
||||
SOP(" _ ");
|
||||
}
|
||||
|
||||
// In each row, print N + 1 - i stars.
|
||||
for (int j = 1; j <= i; j++) {
|
||||
SOP(" * ");
|
||||
}
|
||||
SOPln();
|
||||
}
|
||||
```
|
||||
|
||||
Combining these 2 codes we get, the diamond pattern.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Example 7
|
||||
Print the following pattern:
|
||||
|
||||
For example,
|
||||
|
||||
N = 5
|
||||
```plaintext
|
||||
1
|
||||
2 3
|
||||
4 5 6
|
||||
7 8 9 10
|
||||
11 12 13 14 15
|
||||
```
|
||||
|
||||
N = 4
|
||||
```plaintext
|
||||
1
|
||||
2 3
|
||||
4 5 6
|
||||
7 8 9 10
|
||||
```
|
||||
|
||||
We will create a variable and print that variable. After printing, we increment it.
|
||||
|
||||
```
|
||||
int val = 1;
|
||||
for (int i = 1; i <= N; i++) {
|
||||
for (int j = 1; j <= i; j++) {
|
||||
SOP(val);
|
||||
val++;
|
||||
}
|
||||
SOPln();
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
**Explanation:**
|
||||
|
||||
In the given approach we have initialized a variable `val` to 1. It employs an outer loop that iterates from 1 to N, governing the rows. Within this loop, an inner loop runs from 1 to the current value of the outer loop index, controlling the values within each row. It prints the value of `val`, increments it, and then proceeds with the next iteration of the inner loop. This structure creates a pattern where each row holds an increasing sequence of numbers. The `SOPln()` statement at the end of the outer loop iteration ensures a new line for the subsequent row. By iteratively printing values and managing rows through nested loops, the code systematically generates the desired pattern of numbers.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Example 8
|
||||
Print the following pattern:
|
||||
For example,
|
||||
|
||||
N = 5
|
||||
```plaintext
|
||||
1
|
||||
1 2
|
||||
1 2 3
|
||||
1 2 3 4
|
||||
1 2 3 4 5
|
||||
```
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
**Approach 1:**
|
||||
```
|
||||
for (int i = 1; i <= N; i++) {
|
||||
|
||||
int val = 1;
|
||||
for (int j = 1; j <= i; j++) {
|
||||
SOP(val);
|
||||
val++;
|
||||
}
|
||||
SOPln();
|
||||
}
|
||||
```
|
||||
|
||||
**Approach 2:**
|
||||
In this approach instead of taking an extra variable we can directly print j.
|
||||
```
|
||||
for (int i = 1; i <= N; i++) {
|
||||
for (int j = 1; j <= i; j++) {
|
||||
SOP(j);
|
||||
}
|
||||
SOPln();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Example 9
|
||||
|
||||
Print the following pattern.
|
||||
For example,
|
||||
|
||||
N = 5
|
||||
```plaintext
|
||||
1
|
||||
2 3
|
||||
3 4 5
|
||||
4 5 6 7
|
||||
5 6 7 8 9
|
||||
```
|
||||
|
||||
The pattern now starts at each row with that row number. So, only 1 change is required i.e, in the initial value of val.
|
||||
|
||||
The correct code for this pattern is:
|
||||
```
|
||||
for (int i = 1; i <= N; i++) {
|
||||
|
||||
int val = i;
|
||||
for (int j = 1; j <= i; j++) {
|
||||
SOP(val);
|
||||
val++;
|
||||
}
|
||||
SOPln();
|
||||
}
|
||||
```
|
||||
|
||||
---
|
@@ -0,0 +1,550 @@
|
||||
# Beginner: Patterns 2 & Introduction to Strings
|
||||
|
||||
---
|
||||
|
||||
### Agenda
|
||||
|
||||
1. Print reverse triangle V
|
||||
2. Print numeric triangle /\
|
||||
3. Strings
|
||||
4. next() vs nextLine()
|
||||
5. How to deal with different type of inputs
|
||||
6. Character Pattern
|
||||
|
||||
---
|
||||
|
||||
### Problem Statement
|
||||
Print the following pattern:
|
||||
|
||||
For example,
|
||||
|
||||
N = 5
|
||||
```
|
||||
* * * * *
|
||||
* * * *
|
||||
* * *
|
||||
* *
|
||||
*
|
||||
```
|
||||
|
||||
N = 4
|
||||
```
|
||||
* * * *
|
||||
* * *
|
||||
* *
|
||||
*
|
||||
```
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
### Observation
|
||||
Lets consider the spaces as "_"
|
||||
```
|
||||
* _ * _ * _ * _ * _
|
||||
_ * _ * _ * _ * _
|
||||
_ _ * _ * _ * _
|
||||
_ _ _ * _ * _
|
||||
_ _ _ _ * _
|
||||
```
|
||||
|
||||
Now lets assume we are removing the spaces after every '*', then
|
||||
```
|
||||
* * * * *
|
||||
_ * * * *
|
||||
_ _ * * *
|
||||
_ _ _ * *
|
||||
_ _ _ _ *
|
||||
```
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/588/original/observation.jpg?1706503692" width=600/>
|
||||
|
||||
While printing stars, remember to print a space after every star, to get the our required reverse triangle pattern.
|
||||
|
||||
### Code
|
||||
|
||||
```java
|
||||
for (int i = 0; i < N; i++) {
|
||||
|
||||
//loop to print i spaces
|
||||
for (int j = 1; j <= i; j++) {
|
||||
System.out.print(" ");
|
||||
}
|
||||
|
||||
//loop to print n-i stars
|
||||
for (int j = 1; j <= n - i; j++) {
|
||||
System.out.print("* ");
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
### Problem Statement
|
||||
Print the following pattern:
|
||||
|
||||
For example,
|
||||
|
||||
N = 5
|
||||
```
|
||||
0 0 0 0 1 0 0 0 0
|
||||
0 0 0 2 3 2 0 0 0
|
||||
0 0 3 4 5 4 3 0 0
|
||||
0 4 5 6 7 6 5 4 0
|
||||
5 6 7 8 9 8 7 6 5
|
||||
```
|
||||
N = 4
|
||||
```
|
||||
0 0 0 1 0 0 0
|
||||
0 0 2 3 2 0 0
|
||||
0 3 4 5 4 3 0
|
||||
4 5 6 7 6 5 4
|
||||
```
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
### Approach
|
||||
|
||||
Lets divide the pattern into two halfs,
|
||||
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/063/594/original/patter.png?1706505291" width=500/>
|
||||
|
||||
Lets consider the 2 halves separately,
|
||||
|
||||
### First Half
|
||||
|
||||
| **0** | **0** | **0** | **0** | **1** |
|
||||
|-------|-------|-------|-------|-------|
|
||||
| **0** | **0** | **0** | **2** | **3** |
|
||||
| **0** | **0** | **3** | **4** | **5** |
|
||||
| **0** | **4** | **5** | **6** | **7** |
|
||||
| **5** | **6** | **7** | **8** | **9** |
|
||||
|
||||
Lets create a table, on observing the pattern.
|
||||
| row | zeros | start | end |
|
||||
|-----|---------|-------|-----------|
|
||||
| 1 | 4 [5-1] | 1 | 1 [2\*1-1] |
|
||||
| 2 | 3 [5-2] | 2 | 3 [2\*2-1] |
|
||||
| 3 | 2 [5-3] | 3 | 5 [2\*3-1] |
|
||||
| 4 | 1 [5-4] | 4 | 7 [2\*4-1] |
|
||||
| 5 | 0 [5-5] | 5 | 9 [2\*5-1] |
|
||||
|
||||
We can come up with an generalized pattern on observing the values of the table based on the value i.
|
||||
|
||||
| ith row | (n - i) zeros | starts with i | ends with 2 * i - 1 |
|
||||
|---|---|---|---|
|
||||
|
||||
### Psuedo code for First Half
|
||||
|
||||
```java
|
||||
// Printing (n - i) zeros
|
||||
for (int j = 1; j <= n - i; j++){
|
||||
System.out.print(0 + " ");
|
||||
}
|
||||
|
||||
int lim = 2 *i - 1;
|
||||
// Printing the increasing numbers from i to 2*i-1
|
||||
for (int j = i; j <= lim; j++){
|
||||
System.out.print(j + " ");
|
||||
}
|
||||
```
|
||||
|
||||
### Second Half
|
||||
|
||||
| **0** | **0** | **0** | **0** |
|
||||
|-------|-------|-------|-------|
|
||||
| **2** | **0** | **0** | **0** |
|
||||
| **4** | **3** | **0** | **0** |
|
||||
| **6** | **5** | **4** | **0** |
|
||||
| **8** | **7** | **6** | **5** |
|
||||
|
||||
Lets create a table, on observing the pattern.
|
||||
|
||||
| row | start | end | zeros |
|
||||
|-----|-----------|-----|-------|
|
||||
| 1 | | | 4 |
|
||||
| 2 | 2 [2\*2-2] | 2 | 3 |
|
||||
| 3 | 4 [2\*3-2] | 3 | 2 |
|
||||
| 4 | 6 [2\*4-2] | 4 | 1 |
|
||||
| 5 | 8 [2\*5-2] | 5 | 0 |
|
||||
|
||||
We can come up with an generalized pattern on observing the values of the table based on the value i.
|
||||
|
||||
| ith row | starts with (i * 2 - 2) | ends with i | (n i) zeros |
|
||||
|---|---|---|---|
|
||||
|
||||
Here **starts with (i * 2 - 2)** can be even simplified, by using the end value of the previous calculation as **end - 1**.
|
||||
|
||||
|
||||
### Psuedo code for Second Half
|
||||
|
||||
```java
|
||||
// For the Second Half
|
||||
// Printing the decreasing numbers
|
||||
int lim = 2 *i - 1;
|
||||
for (int j = lim - 1; j >= i; j--){
|
||||
System.out.print(j + " ");
|
||||
}
|
||||
|
||||
//loop to print n - i zeros
|
||||
for (int j = 1; j <= n - i; j++){
|
||||
System.out.print(0 + " ");
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
### Overall Code
|
||||
|
||||
``` java
|
||||
for (int i = 1; i <= n; i++){
|
||||
|
||||
// For the First Half
|
||||
//loop to print n - i zeros
|
||||
for (int j = 1; j <= n - i; j++){
|
||||
System.out.print(0 + " ");
|
||||
}
|
||||
|
||||
int lim = 2 *i - 1;
|
||||
// Printing the increasing numbers from i to 2*i-1
|
||||
for (int j = i; j <= lim; j++){
|
||||
System.out.print(j + " ");
|
||||
}
|
||||
|
||||
// For the Second Half
|
||||
// Printing the decreasing numbers
|
||||
for (int j = lim - 1; j >= i; j--){
|
||||
System.out.print(j + " ");
|
||||
}
|
||||
|
||||
//loop to print n - i zeros
|
||||
for (int j = 1; j <= n - i; j++){
|
||||
System.out.print(0 + " ");
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
### Reading Inputs for Strings
|
||||
|
||||
**1. sc.next()-> cannot take spaces as input**
|
||||
|
||||
Ques1:
|
||||
```java
|
||||
Input: "Hello World"
|
||||
String s1 = sc.next();
|
||||
System.out.println(s1);
|
||||
|
||||
String s2 = sc.next();
|
||||
System.out.println(s2);
|
||||
```
|
||||
Output:
|
||||
```plaintext
|
||||
Hello
|
||||
World
|
||||
```
|
||||
|
||||
Explanation:
|
||||
|
||||
s1 will have first word, Hello
|
||||
s2 will have next word, World
|
||||
|
||||
|
||||
|
||||
|
||||
**2. sc.nextLine() -> can take spaces as well, until next line is encountered.**
|
||||
|
||||
Ques1:
|
||||
```java
|
||||
Input: Hello World
|
||||
String s3 = sc.nextLine();
|
||||
System.out.println(s3);
|
||||
```
|
||||
|
||||
Output:
|
||||
```plaintext
|
||||
Hello World
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Input :
|
||||
|
||||
```
|
||||
Hello World
|
||||
```
|
||||
```
|
||||
Scanner scn = new Scanner(System.in);
|
||||
String str1 = scn.next();
|
||||
String str2 = scn.next();
|
||||
System.out.println(str1);
|
||||
System.out.println(str2);
|
||||
```
|
||||
|
||||
# Choices
|
||||
|
||||
- [x] Hello <br> World
|
||||
- [ ] Hello
|
||||
- [ ] World
|
||||
- [ ] None of the above
|
||||
|
||||
---
|
||||
|
||||
Output:
|
||||
```plaintext
|
||||
Hello
|
||||
World
|
||||
```
|
||||
|
||||
|
||||
Explanation:
|
||||
|
||||
str1 will have, Hello
|
||||
str2 will have next word, World
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
Input:
|
||||
```
|
||||
Hello Welcome in Scaler
|
||||
```
|
||||
|
||||
```
|
||||
Scanner scn = new Scanner(System.in);
|
||||
String str1 = scn.next();
|
||||
String str2 = scn.nextLine();
|
||||
System.out.println(str1);
|
||||
System.out.println(str2);
|
||||
```
|
||||
|
||||
# Choices
|
||||
|
||||
- [ ] Hello
|
||||
- [ ] Error
|
||||
- [x] Hello <br> Welcome in Scaler
|
||||
- [ ] None of the above
|
||||
|
||||
---
|
||||
|
||||
Output:
|
||||
```plaintext
|
||||
Hello
|
||||
Welcome in Scaler
|
||||
```
|
||||
|
||||
Explanation:
|
||||
|
||||
str1 will have first word, Hello
|
||||
str2 will have complete line after hello, Welcome in scaler(including space before welcome).
|
||||
|
||||
---
|
||||
|
||||
**Rule:** When the inputs are given in separate lines, and we take a String input using nextLine() after taking number input[nextInt(), nextLong(), nextFloat(), nextDouble()] or a single word [next()] then we get a empty String.
|
||||
|
||||
### Example
|
||||
|
||||
### Input
|
||||
```
|
||||
45
|
||||
Hello World!
|
||||
```
|
||||
``` java
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int x = sc.nextInt(); // x[45]
|
||||
String st = sc.nextLine(); // st -> Empty String
|
||||
String st2 = sc.nextLine(); // st2 -> "Hello World!"
|
||||
System.out.println(st);
|
||||
System.out.println(s2);
|
||||
```
|
||||
|
||||
### Output
|
||||
```
|
||||
|
||||
Hello World!
|
||||
```
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Predict the output :
|
||||
```
|
||||
Input-
|
||||
11
|
||||
Super Excited!
|
||||
```
|
||||
```
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int x = scn.nextInt();
|
||||
String str = scn.nextLine();
|
||||
System.out.println(x);
|
||||
System.out.println(str);
|
||||
```
|
||||
|
||||
# Choices
|
||||
|
||||
- [ ] 11 Super Excited!
|
||||
- [ ] Error
|
||||
- [ ] 11 <br> Super Excited!
|
||||
- [x] 11
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Predict the output :
|
||||
```
|
||||
Input-
|
||||
11
|
||||
Super Excited!
|
||||
```
|
||||
```
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int x = scn.nextInt();
|
||||
String str = scn.nextLine();
|
||||
System.out.println(x);
|
||||
System.out.println(str);
|
||||
System.out.println("The End");
|
||||
```
|
||||
|
||||
# Choices
|
||||
|
||||
- [ ] 11 Super Excited! The End
|
||||
- [x] 11 <br> <br> The End
|
||||
- [ ] Error
|
||||
- [ ] 11 <br> Super Excited! <br> The End
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Character:
|
||||
A character represent a single symbol.
|
||||
|
||||
There are different types of characters:
|
||||
* Uppercase characters : ['A' - 'Z']
|
||||
* Lowercase characters : ['a' - 'z']
|
||||
* Numeric characters: ['0' - '9']
|
||||
* Special characters: ['@', '#', '\$', '%', '&'...]
|
||||
|
||||
There are a total of 128 characters.
|
||||
|
||||
|
||||
### Syntax
|
||||
|
||||
**Example 1:**
|
||||
```java
|
||||
char ch = 'a';
|
||||
System.out.println(ch);
|
||||
```
|
||||
**Output:**
|
||||
```plaintext
|
||||
a
|
||||
```
|
||||
|
||||
**Example 2:**
|
||||
```java
|
||||
char ch = 'ab';
|
||||
System.out.println(ch);
|
||||
```
|
||||
**Output:**
|
||||
```plaintext
|
||||
Error: Only a single symbol is a character.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Problem Statement
|
||||
Write a program to print all characters from A to Z.
|
||||
|
||||
|
||||
|
||||
### Code
|
||||
```java
|
||||
public static void printCharacters(String str) {
|
||||
for(char i = 'A'; i <= 'Z'; i++) {
|
||||
System.out.println(i);
|
||||
}
|
||||
}
|
||||
```
|
||||
---
|
||||
|
||||
|
||||
### Character Stairacase Pattern
|
||||
|
||||
N = 5
|
||||
```
|
||||
A
|
||||
A B
|
||||
A B C
|
||||
A B C D
|
||||
A B C D E
|
||||
```
|
||||
|
||||
N = 3
|
||||
```
|
||||
A
|
||||
A B
|
||||
A B C
|
||||
```
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
### Approach
|
||||
Consider the spaces as underscores (for better visualization).
|
||||
|
||||
Lets take N = 5,
|
||||
```
|
||||
A _
|
||||
A _ B _
|
||||
A _ B _ C _
|
||||
A _ B _ C _ D _
|
||||
A _ B _ C _ D _ E _
|
||||
```
|
||||
|
||||
Lets assume we are printing the standard stair case pattern,
|
||||
|
||||
```
|
||||
1
|
||||
1 2
|
||||
1 2 3
|
||||
1 2 3 4
|
||||
1 2 3 4 5
|
||||
```
|
||||
|
||||
Now both the patterns is similar. So, instead of printing numbers, we just create a new variable, which starts with **A**, then increment inside the innerloop.
|
||||
|
||||
|
||||
### Code
|
||||
|
||||
``` java
|
||||
for (int i = 1; i <= N; ++i) {
|
||||
char ch = 'A';
|
||||
for (char j = 1; j <= i; j++) {
|
||||
System.out.print(ch + " ");
|
||||
ch++;
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
```
|
||||
---
|
@@ -0,0 +1,688 @@
|
||||
# 1D Arrays 1
|
||||
|
||||
---
|
||||
## Agenda
|
||||
|
||||
1. Introduction to Arrays
|
||||
2. Reading Input
|
||||
3. Indexing and Properties
|
||||
4. Sum of all elements
|
||||
5. Frequency of k in array
|
||||
6. Max of all elements
|
||||
|
||||
|
||||
---
|
||||
|
||||
### Example
|
||||
Let's say we need to read four inputs for our programme. We can use the below approach.
|
||||
|
||||
#### Code
|
||||
```java
|
||||
public static void main(String[] args) {
|
||||
int a, b, c, d;
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
a = scanner.nextInt();
|
||||
b = scanner.nextInt();
|
||||
c = scanner.nextInt();
|
||||
d = scanner.nextInt();
|
||||
}
|
||||
```
|
||||
Some one can suggest that we should use loop to get all four values like :-
|
||||
|
||||
#### Code
|
||||
```cpp
|
||||
public static void main(){
|
||||
for(int i = 1; i <= 4;i ++ ){
|
||||
int a = sc.nextInt();
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
The above provided approach is wrong because what we are doing is updating the value of variable `a` in each iteration due this a would be set to the last input value provided.
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
### Concept of Arrays
|
||||
* In above example what is instead of four there are hundreds of value to store. It would be manually infeasible to declare and set hundreds of variables.
|
||||
* Therefore to overcome above problem we use **arrays**
|
||||
|
||||
#### Array
|
||||
It is a data structure that can hold fixed number of values of same data type.
|
||||
|
||||
#### Syntax
|
||||
```cpp
|
||||
datatype name[] = new datatype[size]
|
||||
|
||||
// example
|
||||
float f[] = new float[10]
|
||||
int arr[] = new int[10]
|
||||
|
||||
// Various ways
|
||||
datatype[] name = new datatype[size]
|
||||
datatype []name = new datatype[size]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Correct way to create an Array containing 5 int values in Java?
|
||||
|
||||
# Choices
|
||||
|
||||
- [x] int[] ar = new int[5]
|
||||
- [ ] int[] ar = new int[4]
|
||||
- [ ] int[] ar = int new[5]
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
## Explanation
|
||||
|
||||
Since size is 5 and datatype is int using above provided syntax rules:
|
||||
int[] ar = new int[5]
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
### Indexing and Properties
|
||||
|
||||
* Indexing in array starts from **0**.
|
||||
|
||||
|
||||
| index | 0 | 1 | 2 | 3 |
|
||||
|:-----:|:---:|:---:|:---:|:---:|
|
||||
|
||||
* Accessing an element at **i<sup>th</sup>** index in an array can be done as follows:-
|
||||
```cpp
|
||||
nameOfArray[i]
|
||||
```
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/869/original/upload_7feaa615de84a0773827cd5f5904fc43.png?1693761847"
|
||||
height = "290" width = "500">
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
`int[] ar = new int[6];`
|
||||
|
||||
How can we access last position element ?
|
||||
|
||||
# Choices
|
||||
- [x] ar[5]
|
||||
- [ ] ar[6]
|
||||
- [ ] ar[4]
|
||||
- [ ] ar[7]
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
## Explanation
|
||||
|
||||
Since size is 6 indexing would be like :-
|
||||
|
||||
| index | 0 | 1 | 2 | 3 | 4 | 5 |
|
||||
|:-----:|:---:|:---:|:---:|:---:|:---:|:---:|
|
||||
| arr | 0 | 0 | 3 | 0 | 0 | 0 |
|
||||
|
||||
last element would be at index 5
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
`int[] ar = new int[10];`
|
||||
|
||||
How can we access last position element ?
|
||||
|
||||
# Choices
|
||||
- [x] ar[9]
|
||||
- [ ] ar[10]
|
||||
- [ ] ar[7]
|
||||
- [ ] ar[8]
|
||||
|
||||
---
|
||||
|
||||
## Explanation
|
||||
|
||||
Since size is 10 indexing would be like :-
|
||||
|
||||
| index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|
||||
|:-----:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|
|
||||
| ar | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
|
||||
last element would be at index 9
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
Say int[] ar = new int[N]
|
||||
How to access first element and last element ?
|
||||
|
||||
# Choices
|
||||
- [x] ar[0] ar[N-1]
|
||||
- [ ] ar[0] ar[N]
|
||||
- [ ] ar[1] ar[N]
|
||||
|
||||
---
|
||||
|
||||
|
||||
## Explanation
|
||||
By observing previous questions we can generalize the idea that :-
|
||||
* Last element in array 'arr' of size 'N' is accessed as `arr[N-1]`.
|
||||
* First element in array 'arr' of size 'N' is accessed as `arr[0]`.
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What is the Output of
|
||||
```java
|
||||
public static void main(String args[]) {
|
||||
int[] arr = new int[10];
|
||||
int n = arr.length;
|
||||
System.out.println(n);
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 10
|
||||
- [ ] 9
|
||||
- [ ] 8
|
||||
|
||||
|
||||
---
|
||||
|
||||
* By default values in an array of type `int` are intialized with **'0'**
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
What will be the output?
|
||||
```java
|
||||
public static void main(String args[]) {
|
||||
int[] arr = new int[5];
|
||||
arr[0] = 10;
|
||||
arr[1] = 20;
|
||||
|
||||
int sum = 0;
|
||||
for(int i = 0; i < 5;i ++ ) {
|
||||
sum += arr[i];
|
||||
}
|
||||
|
||||
System.out.println(sum);
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 30
|
||||
- [ ] error
|
||||
- [ ] 20
|
||||
- [ ] 43
|
||||
|
||||
---
|
||||
|
||||
|
||||
## Explanation
|
||||
By observing previous questions we can generalize the idea that :-
|
||||
* Last element in array 'arr' of size 'N' is accessed as `arr[N-1]`.
|
||||
* First element in array 'arr' of size 'N' is accessed as `arr[0]`.
|
||||
|
||||
|
||||
#### Solution
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/871/original/p17.png?1693762040"
|
||||
height = "290" width = "500">
|
||||
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
```java
|
||||
public static void main(String args[]) {
|
||||
int[] arr = new int[5];
|
||||
System.out.println(arr[0]);
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 0
|
||||
- [ ] error
|
||||
- [ ] random number
|
||||
- [ ] 43
|
||||
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
```java
|
||||
public static void main(String args[]) {
|
||||
int[] ar = new int[3];
|
||||
ar[0] = 10;
|
||||
ar[1] = 20;
|
||||
ar[2] = 30;
|
||||
System.out.print(ar[0] + ar[3]);
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] error
|
||||
- [ ] 0
|
||||
- [ ] 40
|
||||
- [ ] 60
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
```java
|
||||
public static void main(String args[]) {
|
||||
int[] ar = new int[3];
|
||||
ar[0] = 10;
|
||||
ar[1] = 20;
|
||||
ar[2] = 30;
|
||||
System.out.print(ar[0] + ar[2]);
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 40
|
||||
- [ ] 0
|
||||
- [ ] error
|
||||
- [ ] 60
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
```java
|
||||
public static void main(String args[]) {
|
||||
int[] ar = new int[3];
|
||||
ar[0] = 10;
|
||||
ar[1] = 20;
|
||||
ar[2] = 30;
|
||||
System.out.print(ar[-1] + ar[3]);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] error
|
||||
- [ ] 0
|
||||
- [ ] 40
|
||||
- [ ] 60
|
||||
|
||||
---
|
||||
|
||||
|
||||
We can reassign an array to replace the previous value it was referencing.
|
||||
|
||||
|
||||
**Code:**
|
||||
```java
|
||||
public static void main(){
|
||||
int[] ar = new int[6];
|
||||
ar= new int[2];
|
||||
S.O.Pln(arr.length);
|
||||
}
|
||||
```
|
||||
**Output:**
|
||||
```plaintext
|
||||
2
|
||||
```
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
* We can directly store elements into an array
|
||||
|
||||
**Code:**
|
||||
```java
|
||||
int ar[] = {10,20,30};
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
### Creating and Reading an array
|
||||
|
||||
#### Create an array of size 4 and print sum of all it's element :-
|
||||
|
||||
* Let's create an array of size 4 and take input.
|
||||
|
||||
```java
|
||||
public static void main(String[] args) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
|
||||
int[] arr = new int[4];
|
||||
arr[0] = sc.nextInt();
|
||||
arr[1] = sc.nextInt();
|
||||
arr[2] = sc.nextInt();
|
||||
arr[3] = sc.nextInt();
|
||||
}
|
||||
```
|
||||
|
||||
* In above approach we have to take input for each index manually which is not a good idea.
|
||||
* So **How can we take inputs efficiently ?**
|
||||
* **Solution** :- We use a loop.
|
||||
* But **how to apply loop to take array input ?**
|
||||
* On observing above approach we will find that only index changes each time we take an input.
|
||||
* **In each iteration we change the index number.**
|
||||
* We iterate starting from 0 till last index i.e. array size -1.
|
||||
|
||||
```java
|
||||
public static void main(String[] args) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
|
||||
int[] arr = new int[4];
|
||||
for (int i = 0; i < 4; i ++ ) {
|
||||
arr[i] = sc.nextInt();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
### Passing Array to Functions
|
||||
|
||||
#### Create a Function Which Takes arr[] as A Parameter and Print the Array
|
||||
|
||||
* We need to declare a function which takes array as parameter to function.
|
||||
* It can be done like :-
|
||||
`Function nameOfFunction(dataType anyName[]){}`
|
||||
* '`[]`' are important for distinguishing array type parameter from other variable type parameters.
|
||||
* **How can we access the length of array from function ?**
|
||||
* We use `array.length` for this purpose.
|
||||
* We can pass array parameter to function call like:
|
||||
`functionName(arrayName)`
|
||||
* **We only need to pass array name.**
|
||||
|
||||
```java
|
||||
static void printArray(int[] ar) {
|
||||
int n = ar.length;
|
||||
for (int i = 0; i < n; i ++ ) {
|
||||
System.out.print(ar[i] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
|
||||
int[] arr = new int[4];
|
||||
for (int i = 0; i < 4; i ++ ) {
|
||||
arr[i] = sc.nextInt();
|
||||
}
|
||||
printArray(arr);
|
||||
}
|
||||
```
|
||||
We take the sum of all elements of array as follows :-
|
||||
|
||||
```java
|
||||
public static void main(String[] args) {
|
||||
int[] arr = new int[4]; // creates an array of size 4
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
for (int i = 0; i < 4; i ++ ) {
|
||||
arr[i] = scanner.nextInt();
|
||||
}
|
||||
int sum = 0;
|
||||
for (int i = 0; i < 4; i ++ ) {
|
||||
sum += arr[i]; // add element at ith index to sum variable
|
||||
}
|
||||
|
||||
System.out.println(sum);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Problem 1
|
||||
|
||||
Given an array and k. Write a function to return the frequency of k in array?
|
||||
|
||||
#### Testcase
|
||||
|
||||
```java
|
||||
arr[7] = [3,6,7,6,11,6,14]
|
||||
|
||||
k = 6
|
||||
```
|
||||
|
||||
#### solution
|
||||
|
||||
```plaintext
|
||||
ans = 4
|
||||
```
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
|
||||
#### Approach
|
||||
* We need to create a function and pass array and k as parameters to the function.
|
||||
* Inside the function :-
|
||||
* Maintain a count variable which is intialised to 0.
|
||||
* Iterate over the array:-
|
||||
* If element at current index equals k increament count by 1.
|
||||
* Return count.
|
||||
|
||||
#### Trace
|
||||
|
||||
![]()
|
||||
|
||||
|
||||
#### Solution
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/873/original/p22.png?1693762207"
|
||||
height = "200" width = "500">
|
||||
|
||||
|
||||
#### Pseudeocode
|
||||
```cpp
|
||||
static int frequencyK(int[] ar, int k) {
|
||||
int n = ar.length;
|
||||
int count = 0;
|
||||
for (int i = 0; i < n; i ++ ) {
|
||||
if (ar[i] == k) {
|
||||
count ++ ;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Problem 2
|
||||
|
||||
Given an array . Write a function to return the maximum element present in array?
|
||||
|
||||
#### Testcase 1
|
||||
|
||||
```cpp
|
||||
arr[6] = [3,1,7,6,9,11]
|
||||
|
||||
```
|
||||
|
||||
#### solution
|
||||
|
||||
```plaintext
|
||||
ans = 11
|
||||
```
|
||||
#### Testcase 2
|
||||
|
||||
```plaintext
|
||||
arr[6] = [4,2,7,9,12,3]
|
||||
|
||||
```
|
||||
|
||||
#### solution
|
||||
|
||||
```plaintext
|
||||
ans = 12
|
||||
```
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
|
||||
#### Approach 1
|
||||
* We need to create a function and pass array as parameters to the function.
|
||||
* Inside the function :-
|
||||
* Maintain a max variable which is intialised to 0.
|
||||
* Iterate over the array:-
|
||||
* If element at current index is greater than max then set max to current element.
|
||||
* Return max.
|
||||
|
||||
#### Trace 1
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/033/957/original/p23.png?1683759983"
|
||||
height = "150" width = "500">
|
||||
|
||||
|
||||
![]()
|
||||
|
||||
#### Trace 2
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/033/958/original/p24.png?1683760023" height = "150" width = "500">
|
||||
|
||||
|
||||
|
||||
|
||||
#### Code
|
||||
```java
|
||||
static int maxElement(int array[]) {
|
||||
int n = array.length;
|
||||
int max = Integer.MIN_VALUE; // Initialize max with the smallest possible integer value
|
||||
for (int i = 0; i < n; i ++ ) {
|
||||
if (array[i] > max) {
|
||||
max = array[i];
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
```
|
||||
|
||||
**There is a flaw in above code.** Let's see it with help of an testcase.
|
||||
|
||||
#### Testcase 3
|
||||
|
||||
```cpp
|
||||
arr[4] = [ - 8, - 4, - 3, - 5]
|
||||
|
||||
```
|
||||
|
||||
#### solution
|
||||
|
||||
```cpp
|
||||
ans = - 3
|
||||
```
|
||||
|
||||
* Let' apply approach 1 to testcase 3
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/033/959/original/p25.png?1683760451" height = "150" width = "500" >
|
||||
|
||||
|
||||
|
||||
|
||||
* In trace we get the answer as 0 whereas the correact answer is -3. **Why ?**
|
||||
|
||||
#### Issue
|
||||
|
||||
**Since max/ans variable is intialised to 0 which is already greater than all elements in array therefore max/ans is not updated.**
|
||||
|
||||
|
||||
---
|
||||
# Question
|
||||
|
||||
|
||||
For taking sum of N numbers we initialise our sum variable with =
|
||||
|
||||
# Choices
|
||||
- [x] 0
|
||||
- [ ] 9
|
||||
- [ ] 1
|
||||
|
||||
|
||||
|
||||
---
|
||||
title: Quiz 13
|
||||
description:
|
||||
duration: 30
|
||||
card_type : quiz_card
|
||||
---
|
||||
# Question
|
||||
|
||||
For taking product of N numbers we initialise our product variable with `=`
|
||||
|
||||
|
||||
# Choices
|
||||
- [ ] 0
|
||||
- [ ] 9
|
||||
- [x] 1
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
* Based upon observations from above questions we need to intialize max/ans in such a manner that it won't affect the answer.
|
||||
* We intialize the ans/max variable to **- ∞**(negative infinity) so that it does not affect the final answer.
|
||||
* We do this by **Integer.MIN_VALUE**
|
||||
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/033/961/original/p27.png?1683761781" height = "350" width = "500">
|
||||
|
||||
|
||||
|
||||
#### Code
|
||||
|
||||
```java
|
||||
static int maxElement(int[] ar) {
|
||||
int n = ar.length;
|
||||
int max = Integer.MIN_VALUE;
|
||||
|
||||
for (int i = 0; i < n; i ++ ) {
|
||||
if (ar[i] > max) {
|
||||
max = ar[i];
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
```
|
@@ -0,0 +1,606 @@
|
||||
# 1D Array - 2
|
||||
|
||||
# Agenda
|
||||
|
||||
1. Revision
|
||||
2. Implement Function
|
||||
3. Increasing Order [increasing and non-decreasing]
|
||||
4. Drawbacks of Array
|
||||
5. Right shift of the array
|
||||
6. Array List introduction
|
||||
7. Functions [add, get, set, remove, size, sort]
|
||||
8. ArrayList functions via code
|
||||
9. Write a function which takes arrayList as input and update all values by 1
|
||||
10. Return an arraylist with all even numbers
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
## Revision
|
||||
|
||||
Let us revise what we discussed in the last class wit the help of quizzes.
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What will be output for this program ?
|
||||
```java
|
||||
int[] myArray = {1, 2, 3, 4, 5};
|
||||
System.out.println(myArray[2]);
|
||||
```
|
||||
|
||||
|
||||
# Choices
|
||||
- [ ] 2
|
||||
- [x] 3
|
||||
- [ ] 4
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What will be output for this program ?
|
||||
|
||||
```java
|
||||
int[] myArray = new int[3];
|
||||
System.out.println(myArray[1]);
|
||||
```
|
||||
|
||||
|
||||
|
||||
# Choices
|
||||
- [x] 0
|
||||
- [ ] Null
|
||||
- [ ] Error
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What will be output for this program ?
|
||||
```java
|
||||
int[] myArray = {1, 2, 3, 4, 5};
|
||||
System.out.println(myArray.length);
|
||||
```
|
||||
|
||||
|
||||
|
||||
# Choices
|
||||
- [ ] 4
|
||||
- [ ] 0
|
||||
- [x] 5
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What will be output for this program ?
|
||||
```java
|
||||
int[] myArray = {1, 2, 3, 4, 5};
|
||||
myArray[2] = 6;
|
||||
System.out.println(myArray[2]);
|
||||
```
|
||||
|
||||
|
||||
# Choices
|
||||
- [x] 6
|
||||
- [ ] 3
|
||||
- [ ] 3
|
||||
- [ ] Error
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
## Return arr[] Syntax
|
||||
|
||||
### Implement Function
|
||||
|
||||
Given N, create an array of size N, which should contain all elements in increasing order from 1 to N.
|
||||
|
||||
## Example
|
||||
|
||||
```plaintext
|
||||
N = 3
|
||||
arr[3] = { 1, 2, 3 }
|
||||
|
||||
N = 5
|
||||
arr[5] = { 1, 2, 3, 4, 5 }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Given N = 6, create an array of size N containing all elements in increasing order from 1 to N.
|
||||
|
||||
|
||||
|
||||
# Choices
|
||||
- [ ] 0 1 2 3 4 5 6
|
||||
- [x] 1 2 3 4 5 6
|
||||
- [ ] 6 5 4 3 2 1
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Implement Function Code
|
||||
|
||||
|
||||
|
||||
## Pseudocode
|
||||
```java
|
||||
static int[] num(int N){
|
||||
int arr = new int[N];
|
||||
for(int i = 0; i < N; i++){
|
||||
arr[i] = i + 1;
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Increasing Order
|
||||
|
||||
Numbers arranged from smallest to largest.
|
||||
**Note:** If elements are equal then no issues
|
||||
|
||||
## Scritly Increasing Order
|
||||
Arrangement of numbers such that the next number is always greater than the previous number.
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Check whether the given numbers are in increasing order?
|
||||
`3, 4, 4, 4, 4, 5, 5, 7, 9, 18, 18, 26`
|
||||
|
||||
# Choices
|
||||
- [x] yes
|
||||
- [ ] no
|
||||
- [ ] maybe
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Check whether the given numbers are in increasing order?
|
||||
`-1, -2, -3, -4, -5`
|
||||
|
||||
# Choices
|
||||
- [ ] Yes
|
||||
- [x] No
|
||||
- [ ] Maybe
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Check whether the given numbers are in strictly increasing order?
|
||||
|
||||
`3, 9, 16, 24, 29, 29, 34, 50`
|
||||
|
||||
# Choices
|
||||
|
||||
- [ ] Yes
|
||||
- [x] No
|
||||
- [ ] Maybe
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Checking Strictly Increasing Array
|
||||
|
||||
Given an integer N, create an array of size N containing elements in increasing order from 1 to N. Check if the created array is strictly increasing (each element is greater than the previous element).
|
||||
|
||||
#### Example
|
||||
For N = 5, the array `arr` will be `{1, 2, 3, 4, 5}`, and it is strictly increasing.
|
||||
|
||||
For N = 5, the array `arr` will be `{1, 2, 2, 4, 5}`, and it is not strictly increasing.
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
Check whether the given numbers are in strictly increasing order?
|
||||
|
||||
`21, 39, 46, 97, 105`
|
||||
|
||||
|
||||
# Choices
|
||||
- [x] Yes
|
||||
- [ ] No
|
||||
- [ ] Maybe
|
||||
|
||||
---
|
||||
|
||||
|
||||
## If Array Is Strictly Increasing Code
|
||||
|
||||
**Note to instructor:** Explain logic of implementing this in code format here
|
||||
|
||||
|
||||
### Pseudocode
|
||||
```java
|
||||
static boolean isStrictlyIncreasing(int N) {
|
||||
int[] arr = new int[N];
|
||||
for (int i = 0; i < N; i++) {
|
||||
arr[i] = i + 1;
|
||||
}
|
||||
|
||||
for (int i = 1; i < N; i++) {
|
||||
if (arr[i] < arr[i - 1]) {
|
||||
return false; // Array is not strictly increasing
|
||||
}
|
||||
}
|
||||
|
||||
return true; // Array is strictly increasing
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
## Right Shift of An Array
|
||||
Given an array of size N, shift all the elements to the right by 1 and move the last element to the beginning of array
|
||||
|
||||
|
||||
## Example 1
|
||||
|
||||
```plaintext
|
||||
N = 10
|
||||
arr[10] = { 7, 4, 9, 11, 2, 24, -5, 17, 1, 8 }
|
||||
Ans =
|
||||
arr[10] = { 8, 7, 4, 9, 11, 2, 24, -5, 17, 1}
|
||||
```
|
||||
|
||||

|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Right shift the given array
|
||||
|
||||
arr[] = {10, 20, 30, 40, 50, 60}
|
||||
|
||||
|
||||
# Choices
|
||||
- [ ] 60, 50, 40, 30, 20, 10
|
||||
- [ ] 0, 10, 20, 30, 40, 50, 60
|
||||
- [x] 60, 10, 20, 30, 40, 50
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
## Right Shift of An Array Idea and Code
|
||||
|
||||
|
||||
## Idea
|
||||
1. Store last element of original array in a temp variable for future use (`temp = arr[n - 1]`)
|
||||
2. Traverse from end to first index and do
|
||||
`arr[i] = arr[i - 1]`
|
||||
3. Till here all indexes are updated with their new value except 0th index. Finally do
|
||||
`arr[0] = temp`
|
||||
|
||||
|
||||
## Pseudocode
|
||||
```java
|
||||
static int[] rotateByone(int arr[]){
|
||||
int n = arr.length
|
||||
int temp = arr[n - 1]
|
||||
for(int i = n - 1; i >= 1; i--){
|
||||
arr[i] = arr[i - 1]
|
||||
}
|
||||
arr[0] = temp;
|
||||
return ans;
|
||||
}
|
||||
```
|
||||
---
|
||||
## Drawbacks of Arrays
|
||||
|
||||
Once array size is fixed, it cannot be changed.
|
||||
If we want to change, we need to create a new array.
|
||||
|
||||
int[] ar=new int[4];
|
||||
This can only store 4 elements, if we want to store 1 more element we cannot update the size. We have to create a new array only.
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Arraylist
|
||||
|
||||
#### Definition
|
||||
|
||||
ArrayList is a class that provides a resizable array implementation that is similar to an ordinary array, but with the added benefit of being able to resize dynamically as elements are added or removed. An ArrayList can store objects of any type, including primitives.
|
||||
|
||||
#### Syntax
|
||||
|
||||
The general syntax for creating an ArrayList in Java is as follows:
|
||||
```java
|
||||
ArrayList<DataType> listName = new ArrayList<DataType>();
|
||||
```
|
||||
where -
|
||||
* **DataType** is the data type of the elements that will be stored in the list (e.g. Integer, String, Object).
|
||||
* **listName** is the name given to the ArrayList object.
|
||||
|
||||
|
||||
**Note:** There is no need to mention size in Arraylist, an empty Arraylist is created.
|
||||
|
||||
#### Example
|
||||
Here's an example that creates an ArrayList of integers and adds the values 10, 20, 30, and 50 to it:
|
||||
```java
|
||||
// Create an ArrayList of integers
|
||||
ArrayList<Integer> al = new ArrayList<>(); // size = 0
|
||||
|
||||
// Add integers to the list
|
||||
al.add(10); // size = 1
|
||||
al.add(20); // size = 2
|
||||
al.add(30); // size = 3
|
||||
al.add(50); // size = 4
|
||||
```
|
||||
#### Some Methods in Arraylist
|
||||
* **Adding an element at the end** -
|
||||
We can add an element at the end of Arraylist using the add(value) method:
|
||||
```java
|
||||
al.add(10)
|
||||
```
|
||||
|
||||
**Task:** Find out how to add a new value at a particluar index in an ArrayList.
|
||||
|
||||
* **Total elements** -
|
||||
We can get the size of the Arraylist using the size() method:
|
||||
```java
|
||||
int n = al.size(); // Returns the number of elements in the list
|
||||
```
|
||||
|
||||
* **Access ith index element of an Arraylist** -
|
||||
We can access ith index element of an Arraylist using the get(index) method:
|
||||
```java
|
||||
int element = al.get(2); // Returns the element at second index
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
```java
|
||||
ArrayList<Integer> al = new ArrayList<>();
|
||||
al.add(10);
|
||||
al.add(20);
|
||||
al.add(30);
|
||||
al.add(40);
|
||||
System.out.print(al.get(2));
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 10
|
||||
- [ ] 20
|
||||
- [x] 30
|
||||
- [ ] 40
|
||||
- [ ] Error
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
### Explanation:
|
||||
We first created an empty arraylist al. We then added 10, 20, 30 & 40 to it, the list becomes al = [10, 20, 30, 40]. The element at 2nd index is 30. Hence, answer is 30.
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
```java
|
||||
ArrayList<Integer> al = new ArrayList<>();
|
||||
al.add(10);
|
||||
al.add(20);
|
||||
al.add(30);
|
||||
al.add(40);
|
||||
System.out.print(al.get(4));
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 40
|
||||
- [ ] 20
|
||||
- [x] Error
|
||||
- [ ] 10
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Explanation:
|
||||
We first created an empty arraylist al. We then added 10, 20, 30 & 40 to it, the list becomes al = [10, 20, 30, 40]. The size of the array is 4 with indexes from 0 - 3. There is no index 4. Hence, the code gives an error.
|
||||
|
||||
---
|
||||
|
||||
|
||||
## ArrayList
|
||||
* **Update existing element** -
|
||||
We can update the existing element of an Arraylist using the set(index, value) method:
|
||||
```java
|
||||
// myList = [10, 20, 30, 50]
|
||||
myList.set(2, 40); // Updates the element at second index with value 40
|
||||
// updated myList = [10, 20, 40, 50]
|
||||
|
||||
myList.set(6, 60); // Gives error because index 6 does not exist
|
||||
```
|
||||
|
||||
* **Remove an element** -
|
||||
We can remove an element from the Arraylist using the remove(index) method:
|
||||
```java
|
||||
// myList = [10, 20, 40, 50]
|
||||
myList.remove(2); // Removes the element at 2nd index from array
|
||||
// updated myList = [10, 40, 50]
|
||||
```
|
||||
|
||||
* **Sort the arraylist** -
|
||||
We can sort the Arraylist using the Collections.sort(arraylist_name) method:
|
||||
```java
|
||||
// myList = [10, 20, 40, 50]
|
||||
myList.remove(2); // Removes the element at 2nd index from array
|
||||
// updated myList = [10, 40, 50]
|
||||
```
|
||||
|
||||
**Note:** Here is the [link](https://www.interviewbit.com/snippet/aadadab483cbc4a05b04/) to example code snippet for practice.
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What will be the output of the following code?
|
||||
|
||||
```java
|
||||
public static void main(String[] args) {
|
||||
ArrayList<Integer> ar = new ArrayList<>();
|
||||
ar.add(1);
|
||||
ar.add(2);
|
||||
ar.add(3);
|
||||
|
||||
ar.set(1, 5);
|
||||
ar.set(2, ar.get(0) + ar.get(1));
|
||||
|
||||
System.out.println(ar);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] [1, 5, 3]
|
||||
- [x] [1, 7, 3]
|
||||
- [ ] [1, 5, 6]
|
||||
- [ ] [1, 6, 3]
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output
|
||||
|
||||
```java
|
||||
public static void main(String[] args) {
|
||||
ArrayList<Integer> ar = new ArrayList<>();
|
||||
ar.add(-5);
|
||||
ar.add(20);
|
||||
ar.add(19);
|
||||
ar.add(50)
|
||||
|
||||
ar.remove(1);
|
||||
|
||||
System.out.println(ar);
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
|
||||
- [x] [-5, 19, 20]
|
||||
- [ ] [20, 19, 50]
|
||||
- [ ] [-5, 20, 50]
|
||||
- [ ] [-5, 20, 19, 50]
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What will be the output?
|
||||
|
||||
```java
|
||||
public static void main(String[] args) {
|
||||
ArrayList<Integer> ar = new ArrayList<>();
|
||||
ar.add(5);
|
||||
ar.add(2);
|
||||
ar.add(9);
|
||||
ar.add(1);
|
||||
|
||||
Collections.sort(ar);
|
||||
|
||||
System.out.println(ar);
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] [5, 2, 9, 1]
|
||||
- [ ] [9, 5, 2, 1]
|
||||
- [x] [1, 2, 5, 9]
|
||||
- [ ] [2, 1, 5, 9]
|
||||
|
||||
---
|
||||
|
||||
|
||||
#### Problem Statement
|
||||
Write a function which takes arrayList as input and update all values by 1
|
||||
|
||||
#### Example 1
|
||||
```java
|
||||
temp : [20, 15, 8, 25, 21]
|
||||
ans : [21, 16, 9, 26, 22]
|
||||
```
|
||||
|
||||
#### Pseudo Code:
|
||||
```java
|
||||
static ArrayList<Integer> increaseByOne(ArrayList<Integer> al){
|
||||
//iterate over the ArrayList
|
||||
int n = al.size();
|
||||
|
||||
for(int i = 0; i < n; i++){
|
||||
//access ith index element : al.get(i)
|
||||
int num = al.get(i);
|
||||
al.set(i, num + 1);
|
||||
|
||||
}
|
||||
return al;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
#### Problem Statement
|
||||
Given an ArrayList of integers, return all the even numbers in the ArrayList.
|
||||
|
||||
#### Example 1
|
||||
```java
|
||||
Input = 10 13 7 14 16 19 22 9 11
|
||||
Output = 10 14 16 22
|
||||
```
|
||||
#### Example 2
|
||||
```java
|
||||
Input = 4 9 1 10 22 21 45
|
||||
Output = 4 10 22
|
||||
```
|
||||
|
||||
#### Solution
|
||||
Iterate on the arrayList and check if element is even. If yes add it to ans arrayList.
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
public static ArrayList<Integer> getEvenNumbers(ArrayList<Integer> list) {
|
||||
ArrayList<Integer> evenNumbers = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
int num = list.get(i);
|
||||
if (num % 2 == 0) {
|
||||
evenNumbers.add(num);
|
||||
}
|
||||
}
|
||||
|
||||
return evenNumbers;
|
||||
}
|
||||
```
|
||||
|
@@ -0,0 +1,663 @@
|
||||
# 2D Array-1
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Agenda
|
||||
|
||||
|
||||
1. Intro to 2D Arrays
|
||||
2. Indexing and taking Input
|
||||
3. Print matrix row by row and column by column
|
||||
4. print matrix in wave form
|
||||
5. Max of matrix.
|
||||
6. Max of every row
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Introduction
|
||||
|
||||

|
||||
|
||||
Two-dimensional arrays can be defined as arrays within an array. 2D arrays is a collection of 1d Arrays.
|
||||
|
||||
#### Syntax:
|
||||
|
||||
```java
|
||||
datatype name[][] = new datatype[rows][cols]
|
||||
```
|
||||
|
||||
>**Note:** When we create 2D matrix by int default all values are equal to 0.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What is N representing in the line given below?
|
||||
int[][] mat = new int[N][M];
|
||||
|
||||
# Choices
|
||||
- [ ] Number of Column
|
||||
- [x] Number of Row
|
||||
- [ ] Total Element
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What is M representing in the line given below?
|
||||
|
||||
int[][] mat = new int[N][M];
|
||||
|
||||
# Choices
|
||||
- [x] Number of Column
|
||||
- [ ] Number of Row
|
||||
- [ ] Total Element
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
How to create a matrix with 2 rows and 5 columns?
|
||||
|
||||
|
||||
# Choices
|
||||
|
||||
- [x] int[][] mat = new int[2] [5];
|
||||
- [ ] int[] mat = new int[2] [5];
|
||||
- [ ] int[][] mat = new int[5] [2];
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
How to create a matrix with 5 columns and 7 rows?
|
||||
|
||||
# Choices
|
||||
- [x] int mat[ ] [ ] = new int[7] [5];
|
||||
- [ ] int mat[ ] = new int[5] [7];
|
||||
- [ ] int mat[ ] [ ] = new int[5] [7];
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
How to create a matrix with size M * N having M = 5 and N = 7
|
||||
|
||||
# Choices
|
||||
- [ ] int mat[ ] [ ] = new int[7] [5];
|
||||
- [ ] int mat[ ] = new int[5] [7];
|
||||
- [x] int mat[ ] [ ] = new int[5] [7];
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Indexing and Properties:
|
||||
|
||||
* We can access ith row and jth column of matrix `mat[][]` by:
|
||||
mat[i][j]
|
||||
|
||||
|
||||

|
||||
|
||||
* If we iterate on a row, column changes and if we iterate on a column, row changes. For example, in above figure we can see that if we iterate on ith row, column number changes from `[0,M - 1]`.
|
||||
* Similarly, in above figure we can see that if we iterate on jth row, row number changes from `[0,N - 1]`.
|
||||
* In a matrix `mat[][]`, mat.length will be equal to total number of rows in a matrix and `mat[0].length` will be equal to total number of columns.
|
||||
|
||||
**Number of rows =** array.length
|
||||
|
||||
**Number of columns =** array[0].length
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What will be the index of top left cell in a given matrix, mat of size N * M?
|
||||
|
||||
# Choices
|
||||
- [ ] mat[0][M]
|
||||
- [x] mat[0][0]
|
||||
- [ ] mat[top][left]
|
||||
- [ ] mat[N][0]
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
What will be the index of top right cell in a given matrix, mat of size N * M?
|
||||
|
||||
# Choices
|
||||
- [x] mat[0][M-1]
|
||||
- [ ] mat[N - 1][0]
|
||||
- [ ] mat[N][0]
|
||||
- [ ] mat[bottom][left]
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
What will be the index of bottom right cell in a given matrix, mat of size N * M?
|
||||
|
||||
# Choices
|
||||
- [ ] mat[N - 1][0]
|
||||
- [x] mat[N - 1][M - 1]
|
||||
- [ ] mat[N][M]
|
||||
- [ ] mat[bottom][right]
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What will be the index of bottom left cell in a given matrix, mat of size N * M?
|
||||
|
||||
# Choices
|
||||
- [x] mat[N - 1][0]
|
||||
- [ ] mat[N - 1][M - 1]
|
||||
- [ ] mat[N][M]
|
||||
- [ ] mat[bottom][right]
|
||||
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Taking input from user
|
||||
|
||||
|
||||
Create a matrix having N rows and M columns fill the
|
||||
matrix by taking input from the user
|
||||
|
||||
**Input**: rows = 3, columns = 4
|
||||
|
||||

|
||||
|
||||
**Code:**
|
||||
```java
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
// Enter the number of rows
|
||||
int N = scanner.nextInt();
|
||||
|
||||
// Enter the number of columns
|
||||
int M = scanner.nextInt();
|
||||
|
||||
int[][] matrix = new int[N][M];
|
||||
|
||||
for (int i = 0; i < N; i++) {
|
||||
for (int j = 0; j < M; j++) {
|
||||
matrix[i][j] = scanner.nextInt();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Print the 0th index row of the given matrix.
|
||||
|
||||
```plaintext
|
||||
1 2 3 4
|
||||
5 6 7 8
|
||||
9 10 11 12
|
||||
```
|
||||
|
||||
# Choices
|
||||
|
||||
- [x] 1 2 3 4
|
||||
- [ ] 1 5 9
|
||||
- [ ] 1 2 3 4 5 6 7 8 9 10 11 12
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Printing 0th Row
|
||||
|
||||
Given a matrix, you are required to print its 0th row.
|
||||
|
||||
#### Observation
|
||||
|
||||
To print the 0th row of the matrix, we can directly access the elements in the 0th row and print them.
|
||||
|
||||
#### Example
|
||||
|
||||
**mat :**
|
||||
| index | 0 | 1 | 2 | 3 |
|
||||
| ----- | --- | --- | --- | --- |
|
||||
| 0 | 1 | 2 | 3 | 4 |
|
||||
| 1 | 5 | 6 | 7 | 8 |
|
||||
| 2 | 9 | 10 | 11 | 12 |
|
||||
|
||||
The 0th row of the matrix would be: **1 2 3 4**
|
||||
|
||||
#### Pseudocode
|
||||
|
||||
```java
|
||||
void printZeroRow(int mat[][]) {
|
||||
int n = mat.length;
|
||||
|
||||
for (int c = 0; c < n; c++) // columns
|
||||
{
|
||||
System.out.print(mat[0][c] + " ");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Print Matrix Row by Row and Column by Column
|
||||
|
||||
Given a matrix, print every row in new line.
|
||||
|
||||
|
||||
#### Example
|
||||
|
||||
**mat :**
|
||||
| index | 0 | 1 | 2 | 3 |
|
||||
|:-----:|:---:|:---:|:---:|:---:|
|
||||
| 0 | 1 | 2 | 3 | 4 |
|
||||
| 1 | 5 | 6 | 7 | 8 |
|
||||
| 2 | 9 | 10 | 11 | 12 |
|
||||
|
||||
**Output :**
|
||||
```plaintext
|
||||
1 2 3 4
|
||||
5 6 7 8
|
||||
9 10 11 12
|
||||
```
|
||||
|
||||
#### Code
|
||||
```java
|
||||
void printmat(int mat[][]){
|
||||
int n = mat.length;
|
||||
int m = mat[0].length;
|
||||
|
||||
for(int r = 0; r < n; r++)//rows
|
||||
{
|
||||
for(int c = 0; c < m; c++) //columns
|
||||
{
|
||||
System.out.print(mat[r][c] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Printing Row in wave form
|
||||
|
||||
Given a matrix, print rows and column in wave form.
|
||||

|
||||
|
||||
|
||||
#### Observation
|
||||
First we will rum loop for rows from index 0 to n-1 where n is the number of rows. Inside this loop we will run another loop for columns from 0 to m-1, where m is total number of columns. Inside this loop we will print the value at row i and column j.
|
||||
|
||||
#### Example 1
|
||||
**mat :**
|
||||
| index | 0 | 1 | 2 | 3 |
|
||||
|:-----:|:---:|:---:|:---:|:---:|
|
||||
| 0 | 21 | 41 | 17 | 9 |
|
||||
| 1 | 11 | 14 | 24 | 30 |
|
||||
| 2 | 29 | 7 | 35 | 16 |
|
||||
| 3 | 32 | 50 | 6 | 10 |
|
||||
| 4 | 15 | 18 | 49 | 4 |
|
||||
|
||||
|
||||
**Output :**
|
||||
```plaintext
|
||||
21 41 17 30 24 14 11 29 7 35 16 10 6 50 32 15 18 49 4
|
||||
```
|
||||
|
||||
#### Observation
|
||||
* For even rows we will traverse columns from 0 to m - 1 index.
|
||||
* For odd rows we will traverse columns from m - 1 to 0 index.
|
||||
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
void printWaveArray(int mat[][]){
|
||||
int n = mat.length;
|
||||
int m = mat[0].length;
|
||||
|
||||
for(int r = 0; r < n; r++)//rows
|
||||
{
|
||||
if(r % 2 == 0){
|
||||
for(int c = 0; c < m; c++) //columns
|
||||
{
|
||||
System.out.print(mat[r][c] + " ");
|
||||
}
|
||||
}
|
||||
else{
|
||||
for(int c = m - 1; c >= 0; c--) //columns
|
||||
{
|
||||
System.out.print(mat[r][c] + " ");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Print the 0th index column of the given matrix.
|
||||
|
||||
```plaintext
|
||||
1 2 3 4
|
||||
5 6 7 8
|
||||
9 10 11 12
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 1 2 3 4
|
||||
- [x] 1 5 9
|
||||
- [ ] 1 2 3 4 5 6 7 8 9 10 11 12
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
### Print 0th column
|
||||
|
||||
Given a matrix, print 0th column.
|
||||
|
||||
#### Example
|
||||
|
||||
**mat :**
|
||||
| index | 0 | 1 | 2 | 3 |
|
||||
|:-----:|:---:|:---:|:---:|:---:|
|
||||
| 0 | 1 | 2 | 3 | 4 |
|
||||
| 1 | 5 | 6 | 7 | 8 |
|
||||
| 2 | 9 | 10 | 11 | 12 |
|
||||
|
||||
The 0th col of the matrix would be: **1 5 9**
|
||||
|
||||
#### Observation
|
||||
We will run a single loop for i for rows from index 0 to n-1, where n is total number of rows and will print `matrix[i][0]`.
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
void printZeroCol(int mat[][]){
|
||||
int n = mat.length;
|
||||
int m = mat[0].length;
|
||||
|
||||
for(int r = 0; r < n; r++)//rows
|
||||
{
|
||||
System.out.print(mat[r][0] + " ");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Print every column
|
||||
Given a matrix, print every column in new line.
|
||||
|
||||
#### Exmaple 1
|
||||
```java
|
||||
mat[4][3] = {
|
||||
{21,16,17,14},rows
|
||||
{7,8,10,1},
|
||||
{6,11,13,21}
|
||||
}
|
||||
|
||||
Ans = {
|
||||
{21, 7, 6}
|
||||
{16, 8, 11}
|
||||
{17, 10, 13}
|
||||
{14, 1, 21}
|
||||
}
|
||||
```
|
||||
|
||||
| 21 | 16 | 17 | 14 |
|
||||
|:---:|:---:|:---:|:---:|
|
||||
| 7 | 8 | 10 | 1 |
|
||||
| 6 | 11 | 13 | 21 |
|
||||
|
||||
|
||||
#### Observation
|
||||
First we will rum loop for columns from index 0 to m - 1 where m is the number of columns. Inside this loop we will run another loop for rows from 0 to n - 1, where n is thw total number of columns. Inside this loop we will print the value at row i and column j.
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
void printmat(int mat[][]){
|
||||
int n = mat.length;
|
||||
int m = mat[0].length;
|
||||
|
||||
for(int c = 0; c < m; c++)//rows
|
||||
{
|
||||
for(int r = 0; c < n; c++) //columns
|
||||
{
|
||||
System.out.print(mat[r][c] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Printing Column in Wave Form
|
||||
|
||||
Given a matrix, you are required to print its elements in wave form by columns.
|
||||
|
||||

|
||||
|
||||
#### Observation
|
||||
To print the matrix in wave form by columns, we can iterate through the columns of the matrix. For even columns, we start from the top and move downward; for odd columns, we start from the bottom and move upward. This way, we print the elements in a zigzag pattern along the columns.
|
||||
|
||||
#### Example
|
||||
Consider the following matrix:
|
||||
|
||||
**mat :**
|
||||
|
||||
| index | 0 | 1 | 2 | 3 |
|
||||
|:-----:|:---:|:---:|:---:|:---:|
|
||||
| 0 | 21 | 16 | 17 | 14 |
|
||||
| 1 | 7 | 8 | 10 | 1 |
|
||||
| 2 | 6 | 11 | 13 | 21 |
|
||||
| 3 | 32 | 50 | 6 | 10 |
|
||||
| 4 | 15 | 18 | 49 | 4 |
|
||||
|
||||
|
||||
The elements in wave form by columns would be: `21 7 6 32 15 18 50 11 8 16 17 10 13 6 49`.
|
||||
|
||||
|
||||
|
||||
#### Pseudocode
|
||||
|
||||
```java
|
||||
void printWaveArrayByColumn(int mat[][]) {
|
||||
int n = mat.length;
|
||||
int m = mat[0].length;
|
||||
|
||||
for (int c = 0; c < m; c++){ // columns
|
||||
if (c % 2 == 0) {
|
||||
for (int r = 0; r < n; r++){ // rows
|
||||
print(mat[r][c] + " ");
|
||||
}
|
||||
} else {
|
||||
for (int r = n - 1; r >= 0; r--){ // rows
|
||||
print(mat[r][c] + " ");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Max of matrix
|
||||
Given a 2D Array A[][], return max element from this matrix.
|
||||
|
||||
### Example:
|
||||
|
||||
**mat :**
|
||||
| index | 0 | 1 | 2 | 3 |
|
||||
|:-----:|:---:|:---:|:---:|:---:|
|
||||
| 0 | 12 | 65 | 89 | 74 |
|
||||
| 1 | 22 | 44 | 12 | 30 |
|
||||
| 2 | 10 | 12 | 97 | 19 |
|
||||
|
||||
|
||||
**Output:**
|
||||
Max element of matrix is 97
|
||||
|
||||
### Idea:
|
||||
1. Iterate on every element of row and column.
|
||||
2. compare mat[i][j] with max element.
|
||||
3. return max element.
|
||||
|
||||
### Psuedo Code:
|
||||
```java
|
||||
public class Solution {
|
||||
public int solve(int[][] A) {
|
||||
int max = Integer.MIN_VALUE;
|
||||
for(int i = 0; i < A.length; i++) {
|
||||
for(int j = 0; j < A[0].length; j++) {
|
||||
if(max < A[i][j]) {
|
||||
max = A[i][j];
|
||||
}
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
### Max of Every Row
|
||||
Given a matrix and row number, return an array containing max of all elements in that row.
|
||||
|
||||

|
||||
|
||||
#### Example 1
|
||||
|
||||
**mat :**
|
||||
| index | 0 | 1 | 2 | 3 | max |
|
||||
|:-----:|:---:|:---:|:---:|:---:|:---:|
|
||||
| 0 | 21 | 16 | 17 | 14 | 21 |
|
||||
| 1 | 7 | 8 | 10 | 1 | 10 |
|
||||
| 2 | 6 | 11 | 13 | 21 | 21 |
|
||||
| 3 | 32 | 50 | 6 | 10 | 50 |
|
||||
| 4 | 15 | 18 | 49 | 4 | 49 |
|
||||
|
||||
|
||||
**ans :**
|
||||
| index | 0 | 1 | 2 | 3 | 4 |
|
||||
|:-----:|:---:|:---:|:---:|:---:|:---:|
|
||||
| ans | 21 | 10 | 21 | 50 | 49 |
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
What will be the max of every row for the given matrix?
|
||||
|
||||
```plaintext
|
||||
1 2 3 13 4
|
||||
5 6 17 8 9
|
||||
19 0 1 2 21
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 15 19
|
||||
- [ ] 4 9 21
|
||||
- [x] 13 17 21
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
What should be the size of array to store max in every row for a matrix of size N * m
|
||||
|
||||
# Choices
|
||||
- [ ] N + M
|
||||
- [x] N
|
||||
- [ ] M
|
||||
- [ ] N * M
|
||||
|
||||
---
|
||||
|
||||
#### Observation
|
||||
|
||||
Size of ans array = total no of Rows
|
||||
|
||||
1. Create ans array
|
||||
2. Iterate on every row and find max
|
||||
3. Store the max of ith row at ans[i]
|
||||
|
||||
Dry Run wrt Above Example:
|
||||
|
||||
|
||||
|
||||
| i | Initial MAX | Iterate on ith row: j -> 0 to m-1 | Max in Row | ans[i] = max |
|
||||
|:---:|:-----------:|:---------------------------------:|:----------:|:------------:|
|
||||
| 0 | - INF | Iterate on 0th row: j -> 0 to m-1 | 21 | ans[0] = 21 |
|
||||
| 1 | -INF | Iterate on 1st row: j -> 0 to m-1 | 10 | ans[1] = 10 |
|
||||
| 2 | -INF | Iterate on 2nd row: j -> 0 to m-1 | 21 | ans[2] = 21 |
|
||||
| 3 | -INF | Iterate on 3rd row: j -> 0 to m-1 | 50 | ans[3] = 50 |
|
||||
| 4 | -INF | Iterate on 4th row: j -> 0 to m-1 | 49 | ans[4] = 49 |
|
||||
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
int prinRowMax(int mat[][], int r){
|
||||
int n = mat.length;
|
||||
int m = mat[0].length;
|
||||
int[] ans = new int[n];
|
||||
|
||||
int sum = 0;
|
||||
for(int i = 0; i < n; i++)//rows
|
||||
{
|
||||
int max = Integer.MIN_VALUE;
|
||||
for(int j = 0; j < m; j++){
|
||||
if(mat[i][j] > max)
|
||||
{
|
||||
max = mat[i][j];
|
||||
}
|
||||
}
|
||||
ans[i] = max;
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
```
|
@@ -0,0 +1,745 @@
|
||||
# 2D arrays 2
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Agenda
|
||||
- Revision
|
||||
- Transpose
|
||||
- Reverse every row in the given matrix
|
||||
- Rotate by 90
|
||||
- Intro to 2D ArrayList
|
||||
- Syntax
|
||||
- Functions
|
||||
- Return even elements from everyrow.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
|
||||
How do you declare an int 2D array in Java?
|
||||
|
||||
|
||||
# Choices
|
||||
- [x] int[][] mat = new int[rows][cols]
|
||||
- [ ] int[][] mat = new int[cols][rows]
|
||||
- [ ] int[][] mat = new int[rows][rows]
|
||||
- [ ] int[][] mat = new int[cols][cols]
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
How do you get the no. of rows in a 2D matrix mat?
|
||||
|
||||
# Choices
|
||||
- [x] mat.length
|
||||
- [ ] mat.length()
|
||||
- [ ] mat.size
|
||||
- [ ] mat.size()
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
How do you get the number of columns in a 2D matrix for row index x?
|
||||
|
||||
|
||||
# Choices
|
||||
- [ ] mat[x].length()
|
||||
- [x] mat[x].length
|
||||
- [ ] mat[x].size
|
||||
- [ ] mat[x].size()
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
```java
|
||||
int[][] nums = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
|
||||
1 2 3
|
||||
4 5 6
|
||||
7 8 9
|
||||
System.out.println(nums[1][2]);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 4
|
||||
- [ ] 5
|
||||
- [x] 6
|
||||
- [ ] ArrayIndexOutOfBoundsException
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Transpose
|
||||
|
||||
#### Given an rectangular matrix return the transpose of the matrix
|
||||
|
||||
> Rectangular matrix is matrix having number of rows not equal to number of columns
|
||||
|
||||
> Transpose of the matrix is new matrix in which the row of certain number in old matrix is converted to column of that particular number in new matrix like -
|
||||
> >Row 1 of old matrix ---> column 1 of new matrix
|
||||
> > Row 2 of old matrix ---> column 2 of new matrix
|
||||
> > and so on...
|
||||
|
||||
#### Example 1
|
||||
|
||||
`mat[3][5]`
|
||||
|
||||
| 1 | 2 | 3 | 4 | 5 |
|
||||
|:---:|:---:|:---:|:---:|:---:|
|
||||
| 6 | 7 | 8 | 9 | 10 |
|
||||
| 11 | 12 | 13 | 14 | 15 |
|
||||
|
||||
#### Explaination and solution
|
||||
|
||||
Intial matrix :-
|
||||
|
||||
`mat[3][5]`
|
||||
|
||||
| 1 | 2 | 3 | 4 | 5 |
|
||||
|:---:|:---:|:---:|:---:|:---:|
|
||||
| 6 | 7 | 8 | 9 | 10 |
|
||||
| 11 | 12 | 13 | 14 | 15 |
|
||||
|
||||
|
||||
Step 1 :- convert row 1 of intial to column 1
|
||||
|
||||
| 1 |
|
||||
|:---:|
|
||||
| 2 |
|
||||
| 3 |
|
||||
| 4 |
|
||||
| 5 |
|
||||
|
||||
Step 2:- convert row 2 of intial to column 2
|
||||
| 1 | 6 |
|
||||
|:---:|:---:|
|
||||
| 2 | 7 |
|
||||
| 3 | 8 |
|
||||
| 4 | 9 |
|
||||
| 5 | 10 |
|
||||
|
||||
Step 3 :- convert row 3 of intial to column 3
|
||||
|
||||
| 1 | 6 | 11 |
|
||||
|:---:|:---:|:---:|
|
||||
| 2 | 7 | 12 |
|
||||
| 3 | 8 | 13 |
|
||||
| 4 | 9 | 14 |
|
||||
| 5 | 10 | 15 |
|
||||
|
||||
Transpose of matrix is :-
|
||||
|
||||
| 1 | 6 | 11 |
|
||||
|:---:|:---:|:---:|
|
||||
| 2 | 7 | 12 |
|
||||
| 3 | 8 | 13 |
|
||||
| 4 | 9 | 14 |
|
||||
| 5 | 10 | 15 |
|
||||
|
||||
#### Example 2
|
||||
|
||||
`mat[3][4]`
|
||||
|
||||
| 1 | 2 | 3 | 4 |
|
||||
|:---:|:---:|:---:|:---:|
|
||||
| 6 | 7 | 8 | 9 |
|
||||
| 11 | 12 | 13 | 14 |
|
||||
|
||||
#### Explanation and solution
|
||||
Transpose of matrix is :-
|
||||
|
||||
| 1 | 6 | 11 |
|
||||
|:---:|:---:|:---:|
|
||||
| 2 | 7 | 12 |
|
||||
| 3 | 8 | 13 |
|
||||
| 4 | 9 | 14 |
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
For a rectangular matrix, can we have the transpose in the same matrix?
|
||||
|
||||
# Choices
|
||||
- [ ] Yes
|
||||
- [x] No we need new matrix
|
||||
- [ ] Maybe
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
If dimensions of a matrix A is ( N x M ), and it is declared as int mat[][] = new int[N][M];
|
||||
How will the transpose be declared?
|
||||
|
||||
# Choices
|
||||
- [ ] int transpose[] = new int[N][M];
|
||||
- [ ] int transpose[][] = new int[N][M];
|
||||
- [x] int transpose[][] = new int[M][N];
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
What will be the transpose of this matrix?
|
||||
```java
|
||||
10, 20, 30
|
||||
14, 15, 18
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 10,14<br>20,15<br>30,18
|
||||
- [ ] 10,20<br>30,14<br>15,18
|
||||
- [ ] I am confused about what is transpose :(
|
||||
|
||||
---
|
||||
|
||||
|
||||
#### Observations :-
|
||||
|
||||
* if we observe example 1
|
||||
* Element at row 0 and column 1 in matrix mat becomes Element at column 0 and row 1 in transpose.
|
||||
* similarly mat[2][3] ---> newMat[3][2]
|
||||
* mat[1][4] ---> newMat[4][1]
|
||||
* Is there any pattern between the position of element in intial matrix and tranpose matrix ?
|
||||
* On observing we can say that :-
|
||||
|
||||
<div class="alert alert-block alert-warning">
|
||||
Transpose[i][j] = Mat[j][i]
|
||||
</div>
|
||||
|
||||
<div class="alert alert-block alert-warning">
|
||||
|
||||
**If dimensions of Mat are MxN then dimensions of transpose would be NxM**
|
||||
</div>
|
||||
|
||||
#### Code
|
||||
```java
|
||||
static int[][] transposeMatrix(int[][] Mat) {
|
||||
int m = Mat.length;
|
||||
int n = Mat[0].length;
|
||||
int[][] ans = new int[n][m];
|
||||
for (int i = 0; i < m; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
ans[j][i] = Mat[i][j];
|
||||
}
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Reverse every row
|
||||
Given a matrix reverse every row of matrix and return the same matrix
|
||||
|
||||
#### Example 1
|
||||
|
||||
`mat[3][5]`
|
||||
|
||||
| 3 | 2 | 6 | 1 | 9 |
|
||||
|:---:|:---:|:---:|:---:|:---:|
|
||||
| 14 | 18 | 2 | 4 | 10 |
|
||||
| 5 | 6 | 3 | 9 | 8 |
|
||||
|
||||
#### Explanation and solution
|
||||
|
||||
Initial matrix :-
|
||||
|
||||
`mat[3][5]`
|
||||
|
||||
| 3 | 2 | 6 | 1 | 9 |
|
||||
|:---:|:---:|:---:|:---:|:---:|
|
||||
| 14 | 18 | 2 | 4 | 10 |
|
||||
| 5 | 6 | 3 | 9 | 8 |
|
||||
|
||||
|
||||
Step 1 :- Reverse row 1 of matrix
|
||||
|
||||
| 9 | 1 | 6 | 2 | 3 |
|
||||
|:---:|:---:|:---:|:---:|:---:|
|
||||
| 14 | 18 | 2 | 4 | 10 |
|
||||
| 5 | 6 | 3 | 9 | 8 |
|
||||
|
||||
|
||||
Step 2 :- Reverse row 2 of matrix
|
||||
|
||||
| 9 | 1 | 6 | 2 | 3 |
|
||||
|:---:|:---:|:---:|:---:|:---:|
|
||||
| 10 | 4 | 2 | 18 | 14 |
|
||||
| 5 | 6 | 3 | 9 | 8 |
|
||||
|
||||
|
||||
|
||||
Step 4 :- Reverse row 3 of matrix
|
||||
|
||||
|
||||
| 9 | 1 | 6 | 2 | 3 |
|
||||
|:---:|:---:|:---:|:---:|:---:|
|
||||
| 10 | 4 | 2 | 18 | 14 |
|
||||
| 8 | 9 | 3 | 6 | 5 |
|
||||
|
||||
|
||||
#### Example 2
|
||||
|
||||
`mat[3][4]`
|
||||
|
||||
| 1 | 2 | 3 | 4 |
|
||||
|:---:|:---:|:---:|:---:|
|
||||
| 6 | 7 | 8 | 9 |
|
||||
| 11 | 12 | 13 | 14 |
|
||||
|
||||
#### Explanation and solution
|
||||
|
||||
| 4 | 3 | 2 | 1 |
|
||||
|:---:|:---:|:---:|:---:|
|
||||
| 9 | 8 | 7 | 6 |
|
||||
| 14 | 13 | 12 | 11 |
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
What will be result if we reverse each row of this matrix?
|
||||
|
||||
```java
|
||||
10, 20, 30
|
||||
14, 15, 18
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 10, 20, 30<br>14, 15, 18
|
||||
|
||||
- [ ] 20, 10, 30<br>14, 15, 18
|
||||
|
||||
- [ ] 10, 20, 30<br>18, 15, 14
|
||||
|
||||
- [x] 30, 20, 10<br>18, 15, 14
|
||||
|
||||
---
|
||||
|
||||
|
||||
#### Approach
|
||||
* Our approach should be to traverse each row reverse it.
|
||||
* But how to reverse a row ?
|
||||
**Reversing a single row:-**
|
||||
* First element of the row is swapped with the last element of the row. Similarly, the second element of the array is swapped with the second last element of the array and so on.
|
||||
* 
|
||||
* But if keep on swapping we would end up with intial configuartion again
|
||||
* So **we swap till e>s**
|
||||
This way at the end of traversal, we will have the entire row reversed.
|
||||
|
||||
### Code
|
||||
|
||||
```java
|
||||
static int[][] reverseEachRow(int[][] Mat) {
|
||||
int m = Mat[0].length;
|
||||
int n = Mat.length;
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
int s = 0;
|
||||
int e = m - 1;
|
||||
|
||||
while (e > s) {
|
||||
// Swap elements in the current row
|
||||
int temp = Mat[i][s];
|
||||
Mat[i][s] = Mat[i][e];
|
||||
Mat[i][e] = temp;
|
||||
|
||||
e--;
|
||||
s++;
|
||||
}
|
||||
}
|
||||
|
||||
return Mat;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Rotate by 90
|
||||
|
||||
Given a matrix rotate it by 90<sup>o</sup> in clockwise direction ?
|
||||
#### Testcase
|
||||
|
||||

|
||||
|
||||
#### Solution
|
||||

|
||||
|
||||
|
||||
#### Example
|
||||
|
||||

|
||||
|
||||
#### Approach
|
||||
* **First we take transpose of matrix. On taking transpose:-**
|
||||

|
||||
|
||||
* **Reverse each row of transpose to get the solution**.
|
||||

|
||||
|
||||
|
||||
|
||||
|
||||
**Code**
|
||||
```java
|
||||
import java.util.*;
|
||||
|
||||
public class Main {
|
||||
static int[][] transposeMatrix(int Mat[][]) {
|
||||
int m = Mat.length;
|
||||
int n = Mat[0].length;
|
||||
int transposeMat[][] = new int[n][m];
|
||||
for (int i = 0; i < m; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
transposeMat[j][i] = Mat[i][j];
|
||||
}
|
||||
}
|
||||
return transposeMat;
|
||||
}
|
||||
|
||||
static int[][] reverseEachRow(int Mat[][]) {
|
||||
int m = Mat[0].length;
|
||||
int n = Mat.length;
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
int s = 0;
|
||||
int e = m - 1;
|
||||
|
||||
while (e > s) {
|
||||
int temp = Mat[i][s];
|
||||
Mat[i][s] = Mat[i][e];
|
||||
Mat[i][e] = temp;
|
||||
|
||||
e--;
|
||||
s++;
|
||||
}
|
||||
}
|
||||
|
||||
return Mat;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int Mat[][] = new int[3][4];
|
||||
for (int i = 0; i < 3; i++) {
|
||||
for (int j = 0; j < 4; j++) {
|
||||
Mat[i][j] = sc.nextInt();
|
||||
}
|
||||
}
|
||||
int transpose[][] = transposeMatrix(Mat);
|
||||
int matRotatedClockwise90Degree[][] = reverseEachRow(transpose);
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Syntax
|
||||
```java
|
||||
ArrayList<Integer> l = new ArrayList<>();
|
||||
```
|
||||
Here each element in l is an integer.
|
||||
|
||||
|
||||
### Properties
|
||||
|
||||
#### 1. add(element)
|
||||
It is used to insert elements in ArrayList.
|
||||
```java
|
||||
l.add(20);
|
||||
l.add(30);
|
||||
l.add(40);
|
||||
l.add(35);
|
||||
```
|
||||
ArrayList :-
|
||||
|
||||
| 20 | 30 | 40 | 35 |
|
||||
|:---:|:---:|:---:|:---:|
|
||||
|
||||
#### 2. set(element)
|
||||
It is used to update values at particular index in ArrayList.
|
||||
```java
|
||||
l.set(1, 80);
|
||||
l.set(0, 90);
|
||||
```
|
||||
ArrayList :-
|
||||
|
||||
| 90 | 80 | 40 | 35 |
|
||||
|:---:|:---:|:---:|:---:|
|
||||
|
||||
#### 3. get(index)
|
||||
It is used to get values at particular index in ArrayList.
|
||||
```java
|
||||
print(l.get(2));
|
||||
print(l.get(3));
|
||||
```
|
||||
|
||||
Output :
|
||||
```plaintext
|
||||
40
|
||||
50
|
||||
```
|
||||
#### 4. remove(index)
|
||||
It is used to remove value at particular index in ArrayList.
|
||||
```plaintext
|
||||
l.remove(2);
|
||||
```
|
||||
|
||||
ArrayList :-
|
||||
|
||||
| 90 | 80 | 35 |
|
||||
|:---:|:---:|:---:|
|
||||
|
||||
**Note:**
|
||||
```java
|
||||
ArrayList<Integer> l = new ArrayList<>();
|
||||
```
|
||||
Each element in this ArrayList is of **Integer** type.
|
||||
|
||||
---
|
||||
|
||||
|
||||
### 2D ArrayList
|
||||
|
||||
ArrayList of ArrayLists
|
||||
|
||||
### Syntax for 2D ArrayList
|
||||
|
||||
```java
|
||||
ArrayList<ArrayList< Datatype>> a = new ArrayList<>();
|
||||
```
|
||||
Each element in this 2D ArrayList is of **ArrayList< Datatype>**
|
||||
|
||||
### How to add elememts in 2D ArrayList
|
||||
|
||||
```java
|
||||
ArrayList<ArrayList<Integer>> arr = new ArrayList<>();
|
||||
```
|
||||
|
||||
Here each Arraylist in arr is of type **ArrayList<Integer>**.
|
||||
|
||||
#### Pseudocode
|
||||
|
||||
```java
|
||||
ArrayList<ArrayList<Integer>> arr = new ArrayList<>();
|
||||
ArrayList<Integer> d1 = new ArrayList<>();
|
||||
d1.add(10);
|
||||
d1.add(20);
|
||||
d1.add(30);
|
||||
d1.add(40);
|
||||
|
||||
ArrayList<Integer> d2 = new ArrayList<>();
|
||||
d2.add(-1);
|
||||
d2.add(4);
|
||||
d2.add(8);
|
||||
|
||||
ArrayList<Integer> d3 = new ArrayList<>();
|
||||
d1.add(50);
|
||||
d1.add(60);
|
||||
d1.add(70);
|
||||
d1.add(80);
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
|
||||
```plaintext
|
||||
{
|
||||
{10,20,30,40},
|
||||
arr : {-1,4,8},
|
||||
{50,60,70,80}
|
||||
}
|
||||
```
|
||||
|
||||
### How to get elememts in 2D ArrayList
|
||||
|
||||
>Note: arr.get(i) = element at ith index.
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
System.out.println(arr.get(1));
|
||||
System.out.println(arr.get(2));
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```plaintext
|
||||
{-1,4,8}
|
||||
{50,60,70,80}
|
||||
```
|
||||
|
||||
### How to access element from ith ArrayList at jth index
|
||||
|
||||
>Note: arr.get(i).get(j) = element at ith ArrayList and jth index.
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
System.out.println(arr.get(0).get(0));
|
||||
System.out.println(arr.get(1).get(2));
|
||||
System.out.println(arr.get(2).get(1));
|
||||
```
|
||||
Output:
|
||||
|
||||
```plaintext
|
||||
10
|
||||
8
|
||||
60
|
||||
```
|
||||
### How to return no. of elements in ArrayList
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
System.out.println(arr.size());
|
||||
System.out.println(arr.get(0).size());
|
||||
System.out.println(arr.get(1).size());
|
||||
```
|
||||
Output:
|
||||
|
||||
```plaintext
|
||||
3
|
||||
4
|
||||
3
|
||||
```
|
||||
|
||||
### How to modify elements in ArrayList
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
System.out.println(arr.get(0).set(0,14));
|
||||
System.out.println(arr.get(1).set(2,-9));
|
||||
System.out.println(arr.get(2).set(0,20));
|
||||
```
|
||||
Output:
|
||||
|
||||
```plaintext
|
||||
{
|
||||
{14,20,30,40},
|
||||
arr : {-1,4,-9},
|
||||
{20,60,70,80}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Problem 1
|
||||
|
||||
Print 2D ArrayList.
|
||||
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
void print(ArrayList< ArrayList< Integer>> arr) {
|
||||
|
||||
int n = arr.size(); // Get the number of rows in the ArrayList
|
||||
|
||||
// Iterate through each row
|
||||
for (int i = 0; i < n; i++) {
|
||||
// Get the number of columns in the current row
|
||||
int m = arr.get(i).size();
|
||||
|
||||
// Iterate through each element in the current row
|
||||
for (int j = 0; j < m; j++) {
|
||||
|
||||
System.out.print(arr.get(i).get(j) + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Dry run
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
|
||||
### Even numbers
|
||||
Given a 2D ArrayList, return a 2D ArrayList which contains even number from every row.
|
||||
|
||||
|
||||
#### Example 1
|
||||
```java
|
||||
arr = {
|
||||
{3,10,2},
|
||||
{2,7,6,9,4},
|
||||
{18,20,11,6}
|
||||
}
|
||||
|
||||
Ans = {
|
||||
{10, 2}
|
||||
{2,6,4}
|
||||
{18,20,6}
|
||||
}
|
||||
```
|
||||
|
||||
#### Example 2
|
||||
```java
|
||||
arr = {
|
||||
{3,6,2,9},
|
||||
{2,4,8,10},
|
||||
{3,9,7,15},
|
||||
8,3,2,14,19},
|
||||
}
|
||||
|
||||
Ans = {
|
||||
{6,2}
|
||||
{2,4,8,10}
|
||||
{}
|
||||
{8,2,14}
|
||||
}
|
||||
```
|
||||
|
||||
#### Observation
|
||||
|
||||
We will traverse every element in ArrayList and insert even numbers in output.
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
ArrayList<ArrayList<Integer>> even(ArrayList<>> arr){
|
||||
|
||||
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
|
||||
int n = arr.size();
|
||||
for(int i = 0; i < n; i++) {
|
||||
ArrayList<Integer> l = new ArrayList<>();
|
||||
int m = arr[i].get(i).size();
|
||||
for(int j = 0; j < m; j++){
|
||||
if( arr.get(i).get(j) % 2 == 0){
|
||||
l.add(arr.get(i).get(j));
|
||||
}
|
||||
}
|
||||
ans.add(l);
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
Binary file not shown.
Binary file not shown.
720
Academy DSA Typed Notes/Beginner Language/Beginner If-Else 1.md
Normal file
720
Academy DSA Typed Notes/Beginner Language/Beginner If-Else 1.md
Normal file
@@ -0,0 +1,720 @@
|
||||
# If Else 1
|
||||
---
|
||||
## Agenda
|
||||
* Contest Details
|
||||
* Introduction to If
|
||||
* If Examples
|
||||
* If / Else examples
|
||||
* If / Else if examples
|
||||
|
||||
**Some abbreviations that will be used in this class:**
|
||||
* System.out.print - SOP
|
||||
* System.out.println - SOPln
|
||||
|
||||
:::success
|
||||
There are a lot of quizzes in this session, please take some time to think about the solution on your own before reading further.....
|
||||
:::
|
||||
|
||||
---
|
||||
|
||||
The following questions serve as an introduction to the topic.
|
||||
|
||||
**Q1.** Sravan loves drinking tea. But he is out of sugar. Sravan is asking his neighbour Karthik?
|
||||
|
||||
|
||||
|
||||
**A1.** Look at the following diagram:
|
||||
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/259/original/Screenshot_2023-10-04_at_2.25.30_PM.png?1696409763" alt= “” width ="500" height="200">
|
||||
|
||||
|
||||
|
||||
|
||||
**Q2.** Eligibility criteria for voting.
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Correct logic to check whether you are eligible to vote.
|
||||
|
||||
# Choices
|
||||
- [ ] age > 180
|
||||
- [ ] age != 17
|
||||
- [ ] age == 18
|
||||
- [x] age >= 18
|
||||
|
||||
---
|
||||
|
||||
# Explanation
|
||||
|
||||
Look at the following diagram.
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/260/original/Screenshot_2023-10-04_at_2.27.12_PM.png?1696409843" alt= “” width ="400" height="200">
|
||||
|
||||
|
||||
|
||||
**Note:** Some students may ask why are we drawing diagrams. Just mention that it's easy to visualize.
|
||||
|
||||
---
|
||||
**Q3.** Check person is senior citizen or not.
|
||||
If age >= 65, then they can collect pension.
|
||||
|
||||
**A.** Look at the following diagram.
|
||||
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/261/original/Screenshot_2023-10-04_at_2.31.03_PM.png?1696410084" alt= “” width ="400" height="200">
|
||||
|
||||
|
||||
|
||||
**Q4.** Check whether person is suffering from fever or not.
|
||||
|
||||
**A.**
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/262/original/Screenshot_2023-10-04_at_2.32.31_PM.png?1696410182" alt= “” width ="400" height="200">
|
||||
|
||||
|
||||
|
||||
|
||||
### Syntax of If
|
||||
**Idea:** When we want to do something when condition is True.
|
||||
|
||||
**Syntax:**
|
||||
```
|
||||
if (condition) {
|
||||
// Statements we want to be executed
|
||||
// if above condition is True.
|
||||
}
|
||||
```
|
||||
|
||||
**Imp point:** `condition` should be a boolean expression. A boolean expression is an expression whose value can only be true or false.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Which of the following is NOT a boolean expression?
|
||||
|
||||
# Choices
|
||||
- [ ] true
|
||||
- [ ] 4 == 5
|
||||
- [x] 4 + 5
|
||||
- [ ] 4 < 5
|
||||
- [ ] false
|
||||
|
||||
|
||||
---
|
||||
|
||||
1. Read a number and If person is eligible, print "eligible to vote".
|
||||
|
||||
Run the below code on IDE and explain.
|
||||
```
|
||||
public static void main() {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int age = sc.nextInt();
|
||||
if (age >= 18) {
|
||||
System.out.print("Eligible to vote");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Which data type should be used to store temperature of a patient?
|
||||
|
||||
# Choices
|
||||
- [ ] int
|
||||
- [x] double
|
||||
- [ ] boolean
|
||||
- [ ] String
|
||||
|
||||
---
|
||||
|
||||
# Explanation
|
||||
Explain with the following code:
|
||||
|
||||
```
|
||||
psv main() {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
double temp = sc.nextDouble();
|
||||
if (temp >= 98.6) {
|
||||
System.out.print("Go to doctor!");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
int a = 10;
|
||||
if(a >= 10){
|
||||
System.out.println("Yo");
|
||||
}
|
||||
System.out.println("Yo");
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] YoYo
|
||||
- [x] Yo<br>Yo
|
||||
- [ ] Error
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
int a = 18,b = 16;
|
||||
if(a >= 18){
|
||||
System.out.println("a is major");
|
||||
}
|
||||
if(b >= 18){
|
||||
System.out.println("b is major");
|
||||
}
|
||||
System.out.println("Blab");
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] a is major<br>b is major<br>Blab
|
||||
- [ ] a is major<br>b is major
|
||||
- [ ] b is major<br>Blab
|
||||
- [x] a is major<br>Blab
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
int a = 50,b = 50;
|
||||
if(a >= 50){
|
||||
System.out.println("a scored half");
|
||||
a = a + 1;
|
||||
}
|
||||
if(b >= 50){
|
||||
System.out.println("b scored half");
|
||||
b = b + 1;
|
||||
}
|
||||
System.out.print(a + b);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] a scored half<br>101
|
||||
- [ ] a scored half<br>b scored half<br>101
|
||||
- [ ] b scored half<br>102
|
||||
- [x] a scored half<br>b scored half<br>102
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
if(5 > 4) {
|
||||
System.out.println("First if");
|
||||
}
|
||||
if(10 >= 6) {
|
||||
System.out.println("Second if");
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] First if<br>Second if
|
||||
- [ ] First if
|
||||
- [ ] Second if
|
||||
- [ ] Error
|
||||
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
if(5 > 10) {
|
||||
System.out.println("First if");
|
||||
}
|
||||
if(10 >= 16) {
|
||||
System.out.println("Second if");
|
||||
}
|
||||
System.out.println("Oops!! Nothing will get printed..");
|
||||
```
|
||||
|
||||
|
||||
# Choices
|
||||
- [ ] First if
|
||||
- [ ] Second if
|
||||
- [ ] First if<br>Second if<br>Oops!! Nothing will get printed..
|
||||
- [x] Oops!! Nothing will get printed..
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
if(true) {
|
||||
System.out.println("1");
|
||||
}
|
||||
if(true) {
|
||||
System.out.println("2");
|
||||
}
|
||||
if(true) {
|
||||
System.out.println("3");
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
# Choices
|
||||
- [x] 1<br>2<br>3
|
||||
- [ ] 1
|
||||
- [ ] 2
|
||||
- [ ] Error
|
||||
|
||||
|
||||
---
|
||||
|
||||
Check if someone has normal temperature: Normal temp = [98.0 to 98.9]
|
||||
|
||||
Ex:
|
||||
* 98.1 -> Normal temperature
|
||||
* 99 -> Not normal temperature
|
||||
* 97.9 -> Not normal temperature
|
||||
|
||||
Explain -> _______98.0________98.9_______
|
||||
* 96.8 -> Not normal temperature
|
||||
* 98.5 -> Normal temperature
|
||||
|
||||
**Q.** What is the Java code for this?
|
||||
|
||||
|
||||
|
||||
```
|
||||
Scanner sc = new Scanner(System.in);
|
||||
double temp = sc.nextDouble();
|
||||
if (temp >= 98.0 && temp >= 98.9) {
|
||||
System.out.println("Normal temperature");
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** Logical operators are used to combine conditions.
|
||||
|
||||
|
||||
---
|
||||
|
||||
Now, we want to do something or the other accordingly when the condition is true or false.
|
||||
|
||||
### Syntax of If / Else
|
||||
```
|
||||
if (condition) {
|
||||
// Statements to run, when above condition True
|
||||
}
|
||||
else {
|
||||
// Statements to run, when above condition False
|
||||
}
|
||||
```
|
||||
|
||||
### Flow 1
|
||||
```
|
||||
if (condition) {
|
||||
Statement 1
|
||||
}else{
|
||||
Statement 2
|
||||
}
|
||||
```
|
||||
Q1: Condition True: Statement 1
|
||||
Q2: Condition False: Statement 2
|
||||
|
||||
### Flow 2
|
||||
```
|
||||
Statement 1
|
||||
if (condition) {
|
||||
Statement 2
|
||||
}else{
|
||||
Statement 3
|
||||
}
|
||||
Statement 4
|
||||
```
|
||||
**Q.** What all statements will be executed?
|
||||
**A.** Condition True: Statement 1, 2 4
|
||||
Condition False: Statement 1, 3, 4
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Example 1
|
||||
Read age of a person, check if person is at retirement age, or still have few years left to work. Retirement age is 65.
|
||||
|
||||
```
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int age = sc.nextInt();
|
||||
if (age > 65) {
|
||||
System.out.println("Retired");
|
||||
}else{
|
||||
System.out.println("Few more years of service.");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
if(9 > 5){
|
||||
System.out.println("If block");
|
||||
}
|
||||
else{
|
||||
System.out.println("Else block");
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] If block
|
||||
- [ ] If block<br>Else block
|
||||
- [ ] Error
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
if(false){
|
||||
System.out.println("Line 1");
|
||||
} else {
|
||||
System.out.println("Line 2");
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] Line 1
|
||||
- [x] Line 2
|
||||
- [ ] Line 1<br>Line 2
|
||||
- [ ] Error
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Modulus Operator
|
||||
|
||||
Modulus operator (%) -> Gives remainder
|
||||
|
||||
```
|
||||
System.out.println(17 % 4) -> Remainder = 1
|
||||
System.out.println(24 % 2) -> Remainder = 0
|
||||
System.out.println(97 % 2) -> Remainder = 1
|
||||
System.out.println(82 % 2) -> Remainder = 0
|
||||
```
|
||||
|
||||
Explain even and odd numbers.
|
||||
**Even numbers:** Numbers which are divisible by 2.
|
||||
Eg: 2, 4, 6, 8, 10, 12..
|
||||
When we divide the number with 2, remainder = 0
|
||||
**Odd numbers:** Numbers which are not divisible 2.
|
||||
Eg: 1, 3, 5, 7, 9, 11..
|
||||
When we divide the number with 2, remainder = 1
|
||||
|
||||
|
||||
---
|
||||
|
||||
### Example 1
|
||||
|
||||
Read a number and check if number is odd or even.
|
||||
|
||||
```
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int a = sc.nextInt();
|
||||
if (a % 2 == 0) {
|
||||
System.out.println("Number is even");
|
||||
}else{
|
||||
System.out.println("Number is odd");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Example 2
|
||||
|
||||
Check if a number is divisible by 5.
|
||||
|
||||
```
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int a = sc.nextInt();
|
||||
if (a % 5 == 0) {
|
||||
System.out.println("Number is divisible by 5");
|
||||
}else{
|
||||
System.out.println("Number is not divisible by 5");
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Example 3
|
||||
|
||||
Check if a number is divisible by 2 or 3.
|
||||
|
||||
```java
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int a = sc.nextInt();
|
||||
if (a % 2 == 0 || a % 3 == 0) {
|
||||
System.out.println("Number is divisible by 2 or 3");
|
||||
}else{
|
||||
System.out.println("Number is not divisible by 2 and 3 both");
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
Can we have if without an else block?
|
||||
|
||||
# Choices
|
||||
- [x] Yup!!
|
||||
- [ ] Nope!!
|
||||
- [ ] Don't know
|
||||
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
Can we have else without an if block?
|
||||
|
||||
# Choices
|
||||
- [ ] Yup!!
|
||||
- [x] Nooo!!
|
||||
- [ ] Maybe
|
||||
|
||||
---
|
||||
|
||||
Read 2 numbers and print max of 2 numbers.
|
||||
|
||||
**Examples:**
|
||||
```plaintext
|
||||
a = 5 , b = 10
|
||||
Max of a and b = 10
|
||||
```
|
||||
|
||||
|
||||
```plaintext
|
||||
a = 15 , b = 10
|
||||
Max of a and b = 15
|
||||
```
|
||||
|
||||
|
||||
```
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int a = sc.nextInt();
|
||||
int b = sc.nextInt();
|
||||
if (a > b) {
|
||||
System.out.println(a);
|
||||
}else{
|
||||
System.out.println(b);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
For input: 45 45
|
||||
|
||||
```
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int a = sc.nextInt();
|
||||
int b = sc.nextInt();
|
||||
if(a > b){
|
||||
System.out.print(a);
|
||||
}
|
||||
else{
|
||||
System.out.print(b);
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] Error
|
||||
- [ ] 45<br>45
|
||||
- [x] 45
|
||||
|
||||
|
||||
|
||||
|
||||
### Categorize Number
|
||||
Given an integer n0, categorize it into positive, negative or zero.
|
||||
|
||||
Category:
|
||||
n = 10: n > 0: print "positive number"
|
||||
n = -27: n < 0: print "negative number"
|
||||
n = 0: n == 0: print "zero"
|
||||
|
||||
Give some more examples.
|
||||
|
||||
Idea:
|
||||
```
|
||||
public static void main() {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int a = scn.nextInt();
|
||||
if (a > 0) {
|
||||
System.out.println("positive number");
|
||||
}
|
||||
if (a < 0) {
|
||||
System.out.println("negative number");
|
||||
}
|
||||
if (a == 0) {
|
||||
System.out.println("zero");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Q.** Is the above logic correct?
|
||||
**A.** Yes
|
||||
|
||||
Dry run the above code for some examples.
|
||||
|
||||
Explain the problem in the above approach.
|
||||
It's the wastage of comparisions.
|
||||
|
||||
|
||||
|
||||
**Syntax:**
|
||||
|
||||
```
|
||||
if (cond_1) {
|
||||
// Statements if cond_1 is true
|
||||
}
|
||||
else if (cond_2) {
|
||||
// Statements if cond_1 is false and cond_2 is true
|
||||
}else{
|
||||
// Statements if cond_1 is false and cond_2 is false
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** "else" is optional.
|
||||
|
||||
### Flow
|
||||
```
|
||||
Statement 1
|
||||
if (cond_1) {
|
||||
Statement 2
|
||||
}
|
||||
else if (cond_2) {
|
||||
Statement 3
|
||||
}
|
||||
else{
|
||||
Statement 4
|
||||
}
|
||||
Statement 5
|
||||
```
|
||||
|
||||
Explain the above flow according to below table.
|
||||
| Conditions which are true | Statements executed |
|
||||
|:-------------------------:|:-------------------:|
|
||||
| 1 | 1 2 5 |
|
||||
| 2 | 1 3 5 |
|
||||
| All false | 1 4 5 |
|
||||
| 1 2 | 1 2 4 |
|
||||
|
||||
**Note:** If a condition is true, it will execute and will come out of If/Else block and execute remaining statements.
|
||||
**Note:** We can have multiple "else if()" blocks.
|
||||
|
||||
Back to Categorize number problem,
|
||||
|
||||
|
||||
```
|
||||
public static void main() {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
int a = scn.nextInt();
|
||||
if (a > 0) {
|
||||
System.out.println("positive number");
|
||||
}
|
||||
else if (a < 0) {
|
||||
System.out.println("negative number");
|
||||
}
|
||||
else{
|
||||
System.out.println("zero");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Example
|
||||
|
||||
Is the below code correct or not?
|
||||
```
|
||||
int a = 10;
|
||||
else if (a > 5) {
|
||||
System.out.println("Number is more than 5");
|
||||
}
|
||||
else{
|
||||
System.out.println("Number is not more than 5");
|
||||
}
|
||||
```
|
||||
Correct Answer: Compilation error.
|
||||
|
||||
We cannot write any `else if()` without `if()` block.
|
||||
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What will be the output of the following:
|
||||
```
|
||||
if(true) {
|
||||
System.out.println("1");
|
||||
}
|
||||
else if(true) {
|
||||
System.out.println("2");
|
||||
}
|
||||
else if(true) {
|
||||
System.out.println("3");
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
# Choices
|
||||
- [x] 1
|
||||
- [ ] 1<br>2<br>3
|
||||
- [ ] 2
|
||||
- [ ] 3
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Can there be an else if block without a if block
|
||||
|
||||
|
||||
|
||||
# Choices
|
||||
- [ ] Yes
|
||||
- [x] No
|
||||
- [ ] Maybe
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Can there be an else if block without an else block
|
||||
|
||||
|
||||
|
||||
# Choices
|
||||
- [x] Yes
|
||||
- [ ] No
|
||||
- [ ] Maybe
|
||||
|
||||
|
||||
|
||||
|
||||
---
|
666
Academy DSA Typed Notes/Beginner Language/Beginner If-Else 2.md
Normal file
666
Academy DSA Typed Notes/Beginner Language/Beginner If-Else 2.md
Normal file
@@ -0,0 +1,666 @@
|
||||
### If Else : 2
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Content
|
||||
- Revision Quizzes
|
||||
- Categorize triangle
|
||||
- Max of three
|
||||
- Fizz Buzz
|
||||
- Nested If Else
|
||||
- Categorize into positive, negative and zero
|
||||
|
||||
:::success
|
||||
There are a lot of quizzes in this session, please take some time to think about the solution on your own before reading further.....
|
||||
:::
|
||||
|
||||
---
|
||||
|
||||
## Recap
|
||||
**Some abbreviations that will be used in this class:**
|
||||
* System.out.print - SOP
|
||||
* System.out.println - SOPln
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What will be the output of the following code?
|
||||
```java
|
||||
int a = 10,b = 10;
|
||||
if(a >= 10 && b >= 10){
|
||||
System.out.print(a+b);
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 10
|
||||
- [x] 20
|
||||
- [ ] 30
|
||||
- [ ] None
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What will be the output of the following code?
|
||||
```java
|
||||
int a = 10;
|
||||
int b = 10;
|
||||
if( ++ a >= 12 && ++ b >= 12 ){
|
||||
System.out.println("Hello");
|
||||
}
|
||||
System.out.println(a + b);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] Hello<br>10
|
||||
- [ ] 22
|
||||
- [x] 21
|
||||
- [ ] None
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What will be the output of the following code?
|
||||
```java
|
||||
int a = 10;
|
||||
int b = 10;
|
||||
if( ++ a >= 11 || ++ b >= 12 ){
|
||||
System.out.println("Hello");
|
||||
}
|
||||
System.out.println(a + b)
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 20
|
||||
- [ ] 22
|
||||
- [x] Hello<br>21
|
||||
- [ ] None
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What will be the output of the following code?
|
||||
```java
|
||||
int a = 10;
|
||||
int b = 10;
|
||||
if( ++ a >= 12 || ++ b >= 12 ){
|
||||
System.out.println("Hello");
|
||||
}
|
||||
System.out.println(a + b);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 20
|
||||
- [ ] 21
|
||||
- [x] 22
|
||||
- [ ] None
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What will be the output of the following code?
|
||||
```java
|
||||
int N = 5;
|
||||
if(N > 2)
|
||||
System.out.println("Yayay");
|
||||
else
|
||||
System.out.println("Blahblah!!");
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] Yayay
|
||||
- [ ] Blahblah!!
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What will be the output of the following code?
|
||||
```java
|
||||
int N = 5;
|
||||
if(N > 2)
|
||||
System.out.println("Yayay");
|
||||
System.out.println("Hmmmm");
|
||||
else
|
||||
System.out.println("Blahblah!!");
|
||||
System.out.println("Blahblah!!");
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] Error :(
|
||||
- [ ] No Error, this code rocks! :D
|
||||
- [ ] Yayay Hmmmm
|
||||
- [ ] Blahblah!!
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What will be the output of the following code?
|
||||
```java
|
||||
int marks = 80;
|
||||
if(marks > 70) {
|
||||
System.out.print("Distinction ");
|
||||
System.out.print("Congrats ");
|
||||
} else if(marks > 35) {
|
||||
System.out.print("Pass ");
|
||||
} else
|
||||
System.out.print("Fail ");
|
||||
System.out.print("Good luck");
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] Distinction Congrats Good luck
|
||||
- [ ] Good luck
|
||||
- [ ] Error
|
||||
- [ ] Distinction Congrats
|
||||
|
||||
|
||||
---
|
||||
# Categorize Triangles
|
||||
|
||||
Categorize triangle on the basis of the length of the sides
|
||||
|
||||
**Equilateral:** When the length of the all the sides are equal.
|
||||
**Isosceles:** When the length of any two sides are equal.
|
||||
**Scalene:** When the length of all sides are different.
|
||||
|
||||
Let `a`, `b`, `c` be the length of the three sides of a triangle. Given in each case they take some values, tell the category of the triangle. It is the given that the input values for a, b, c are positive integer values.
|
||||
|
||||
```plaintext
|
||||
a = 20, b = 20, c = 20
|
||||
-- Output = Equilaterial
|
||||
```
|
||||
|
||||
```plaintext
|
||||
a = 7, b = 12, c = 9
|
||||
-- Output = Scalene
|
||||
```
|
||||
|
||||
```plaintext
|
||||
a = 5, b = 13, c = 5
|
||||
-- Output = Isosceles
|
||||
```
|
||||
|
||||
```plaintext
|
||||
a = 12, b = 7, c = 7
|
||||
-- Output = Isosceles
|
||||
```
|
||||
|
||||
The equivalent code for implementing the above logic is as follows:
|
||||
|
||||
```java
|
||||
if(a == b && b == c){
|
||||
SOPln("Equilateral");
|
||||
}
|
||||
else if(a == b || b == c || a == c){
|
||||
SOPln("Isosceles");
|
||||
}
|
||||
else{
|
||||
SOPln("Scalene");
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
# Max of three
|
||||
**Ques:** Given three numbers, print the maximum among them.
|
||||
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/724/original/upload_a249488f4da0204e8671e22d85267672.png?1693733958" alt= “” width ="700" height="600">
|
||||
|
||||
|
||||
|
||||
Note that `a`, `b`, `c` can take any integer values.
|
||||
Stress on the point that `a`, `b`, `c` can also take equal values. The three test case demonstrates this point.
|
||||
|
||||
For example,
|
||||
* a = 7, b = 20, c = 50 ==> max = 50
|
||||
* a = 10, b = 9, c = 10 ==> max = 10
|
||||
* a = 3, b = 3, c = 3 ==> max = 3
|
||||
|
||||
The equivalent code for implementing the above logic is as follows:
|
||||
|
||||
```java
|
||||
if(a >= b && a >= c){
|
||||
SOPln("a");
|
||||
}
|
||||
else if(b >= c){
|
||||
SOPln("b");
|
||||
}
|
||||
else{
|
||||
SOPln("c");
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
# Fizz-Buzz
|
||||
**Ques:** Given a number,
|
||||
* print "Fizz" if the number is divisible by 3.
|
||||
* print "Buzz" if the number is divisible by 5.
|
||||
* print "Fizz-Buzz" if the number is divisble by both 3 and 5.
|
||||
|
||||
For example,
|
||||
|
||||
* n = 39, O/p = Fizz
|
||||
* n = 25, O/p = Buzz
|
||||
* n = 15, O/p = Fizz-Buzz
|
||||
* n = 13, O/p = `No output`
|
||||
|
||||
**How to implement this? **
|
||||
|
||||
The following code shows a **wrong implementation** of the above logic:
|
||||
|
||||
```java
|
||||
if(n % 3 == 0){
|
||||
SOPln("Fizz");
|
||||
}
|
||||
else if(n % 5 == 0){
|
||||
SOPln("Buzz");
|
||||
}
|
||||
else{
|
||||
SOPln("Fizz-Buzz");
|
||||
}
|
||||
```
|
||||
|
||||
The above code prints "Fizz-Buzz" for n = 11, but this is wrong as n is neither divisble by 3 nor 5. So there should have no output for this number.
|
||||
|
||||
**Another wrong implementation is as follows:**
|
||||
|
||||
```java
|
||||
if(n % 3 == 0){
|
||||
SOPln("Fizz");
|
||||
}
|
||||
else if(n % 5 == 0){
|
||||
SOPln("Buzz");
|
||||
}
|
||||
else if(n % 3 == 0 && n % 5 == 0){
|
||||
SOPln("Fizz-Buzz");
|
||||
}
|
||||
```
|
||||
|
||||
The above code prints "Fizz" for n = 15, but this is wrong as n is divisble by 3 and 5 both. So the correct output should be "Fizz-Buzz".
|
||||
|
||||
So finally, the **correct implementation** of this logic is as follows:
|
||||
|
||||
```java
|
||||
if(n % 3 == 0 && n % 5 == 0){
|
||||
SOPln("Fizz-Buzz");
|
||||
}
|
||||
else if(n % 3 == 0){
|
||||
SOPln("Fizz");
|
||||
}
|
||||
else if(n % 5 == 0){
|
||||
SOPln("Buzz");
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
# Nested If Else
|
||||
**Syntax:**
|
||||
```java
|
||||
|
||||
Statement 1
|
||||
if(cond1){
|
||||
Statement 2
|
||||
if(cond2){
|
||||
Statement 3
|
||||
}
|
||||
else{
|
||||
Statement 4
|
||||
}
|
||||
Statement 5
|
||||
}
|
||||
else{
|
||||
Statement 6
|
||||
if(cond3){
|
||||
Statement 7
|
||||
}
|
||||
else{
|
||||
Statement 8
|
||||
}
|
||||
Statement 9
|
||||
}
|
||||
```
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/725/original/upload_a7f4d3e8fb808f6475963859c4aed00c.png?1693734037" alt= “” width ="400" height="400">
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output of the following code?
|
||||
```java
|
||||
int a = 10, b = 15;
|
||||
if(a > 8) {
|
||||
if(a < b || b == 9) {
|
||||
System.out.println("Hi");
|
||||
}
|
||||
else {
|
||||
System.out.println("Bye");
|
||||
}
|
||||
}
|
||||
else {
|
||||
System.out.println("Good Bye");
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] Hi
|
||||
- [ ] Bye
|
||||
- [ ] Good Bye
|
||||
- [ ] None
|
||||
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output of the following code?
|
||||
```java
|
||||
int a = 10, b = 15;
|
||||
if(a > 8) {
|
||||
if(a == b || b < a) {
|
||||
System.out.println("Hi");
|
||||
}
|
||||
else {
|
||||
System.out.println("Bye");
|
||||
}
|
||||
}
|
||||
else {
|
||||
System.out.println("Got it");
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] Hi
|
||||
- [x] Bye
|
||||
- [ ] Got it
|
||||
- [ ] None
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output of the following code?
|
||||
```java
|
||||
if(true) {
|
||||
if(true) {
|
||||
if(false) {
|
||||
System.out.println("Hey there");
|
||||
}
|
||||
}
|
||||
else {
|
||||
System.out.println("Hello");
|
||||
}
|
||||
}
|
||||
else {
|
||||
System.out.println(10 / 0);
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] Hey there
|
||||
- [ ] Hello
|
||||
- [x] No output
|
||||
- [ ] Error
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
**Explanation:**
|
||||
We are not getting an error because the inner if statement with the false condition is not executed due to the if condition being false. Therefore, the else block following it is also not executed. The program simply moves on to the next line, which is outside of any control structures and executes the statement `System.out.println("Hello");` as expected.
|
||||
|
||||
The else block following the outer if statement is also not executed since the condition of the outer if statement is true, and the program again moves to the next line and executes the statement `System.out.println("Hello");`
|
||||
|
||||
|
||||
---
|
||||
## Categorise the number
|
||||
**Ques:** Given a number, classify it as follows:
|
||||
|
||||
* +ve and even
|
||||
* +ve and odd
|
||||
* -ve and even
|
||||
* -ve and odd
|
||||
|
||||
## Example :
|
||||
|
||||
**Input:**
|
||||
|
||||
|
||||
|
||||
```java
|
||||
public static void main(){
|
||||
Scanner scn = new Scanner(System.in);
|
||||
int n = scn.nextInt();
|
||||
if(num > 0){
|
||||
if(num % 2 == 0){
|
||||
SOPln("Positive and even");
|
||||
}
|
||||
else{
|
||||
SOPln("Positive and odd");
|
||||
}
|
||||
}
|
||||
else{
|
||||
if(num % 2 == 0){
|
||||
SOPln("Negative and even");
|
||||
}
|
||||
else{
|
||||
SOPln("Negative and odd");
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Scope of a Variable
|
||||
|
||||
It defines the point till where you can use the variable. You can only use a variable till the closing bracket of the block in which it was created.
|
||||
|
||||
**Example 1:**
|
||||
|
||||
```java=
|
||||
public static void main(){
|
||||
|
||||
|
||||
int x;
|
||||
x = 5;
|
||||
|
||||
int y;
|
||||
y = 20
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
Scope of variable `x`: Line 4 to 10
|
||||
Scope of variable `y`: Line 7 to 10
|
||||
|
||||
**Example 2:**
|
||||
|
||||
```java=
|
||||
public static void main(){
|
||||
|
||||
int x = 10;
|
||||
if(x == 10){
|
||||
int y = 5;
|
||||
SOP(y);
|
||||
}
|
||||
int z = 9;
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
Scope of variable `x`: Line 3 to 10
|
||||
Scope of variable `y`: Line 5 to 7
|
||||
Scope of variable `z`: Line 8 to 10
|
||||
|
||||
**Example 3:**
|
||||
|
||||
```java=
|
||||
public static void main(){
|
||||
int a = 10;
|
||||
{
|
||||
a = 20;
|
||||
}
|
||||
SOP(a);
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
Scope of variable `a`: Line 2 to 8
|
||||
Also the code will print 20 as the changes done in the variable values are not restricted to that block in which the change is done. But the life of the variable is restricted to the block in which it was created.
|
||||
|
||||
**Example 4:**
|
||||
|
||||
```java=
|
||||
public static void main(){
|
||||
int x = 10;
|
||||
{
|
||||
int y = 20;
|
||||
SOP(x + " " + y);
|
||||
}
|
||||
{
|
||||
SOP(x + " " + y); // This line will give error as y is not present in its scope
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
**Example 5:** Redefining variable error
|
||||
|
||||
```java=
|
||||
public static void main(){
|
||||
int a = 90;
|
||||
{
|
||||
int a = 7; // This line will give error as variable a is already defined in this scope
|
||||
SOPln(a);
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output of the following code:
|
||||
```java
|
||||
public static void main(String args[]) {
|
||||
int x = 10;
|
||||
{
|
||||
int y = 20;
|
||||
System.out.println(x + " " + y);
|
||||
}
|
||||
{
|
||||
System.out.println(x + " " + y);
|
||||
}
|
||||
System.out.println(x + " " + y);
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] Error
|
||||
- [ ] 10 20<br>10 20<br>10 20
|
||||
- [ ] 10 20 10 20 10 20
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output of the following code:
|
||||
```java
|
||||
public static void main(){
|
||||
int x = 10, y = 20;
|
||||
{
|
||||
SOP(x + " " + y);
|
||||
}
|
||||
{
|
||||
x = 15;
|
||||
SOPln(x + " " + y);
|
||||
}
|
||||
SOPln(x + " " + y);
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 10 20<br>15 20<br>10 20
|
||||
- [ ] Error
|
||||
- [x] 10 20<br>15 20<br>15 20
|
||||
- [ ] inky pinky ponky
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output of the following code:
|
||||
```java
|
||||
if(true){
|
||||
int x = 10;
|
||||
SOPln("Value of x is " + x);
|
||||
x ++ ;
|
||||
}
|
||||
SOPln("Value of x is " + x);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] Value of x is 10<br>Value of x is 11
|
||||
- [ ] Value of x is 10<br>Value of x is 0
|
||||
- [ ] Value of x is 10<br>Value of x is 10
|
||||
- [x] Error
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output of the following code:
|
||||
```java
|
||||
int a = 0;
|
||||
{
|
||||
int b = 10;
|
||||
SOPln("b = " + b);
|
||||
int c = a + b;
|
||||
SOPln("c = " + c);
|
||||
}
|
||||
a = c + b;
|
||||
SOPln("a = " + a);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] a = 20<br>b = 10<br>c = 10
|
||||
- [ ] b = 10<br>c = 10<br>a = 20
|
||||
- [x] Error
|
||||
---
|
||||
**Explanation:** Error b and c are out of the scope
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output of the following code:
|
||||
```java
|
||||
int a = 10, b = 5;
|
||||
if(true){
|
||||
int c = a * b;
|
||||
}
|
||||
SOPln(c);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 50
|
||||
- [x] Error
|
||||
- [ ] Need Coffee!!
|
||||
|
||||
---
|
||||
**Explanation:** Error the variable c is out of the scope
|
Binary file not shown.
628
Academy DSA Typed Notes/Beginner Language/Beginner Loop - 1.md
Normal file
628
Academy DSA Typed Notes/Beginner Language/Beginner Loop - 1.md
Normal file
@@ -0,0 +1,628 @@
|
||||
# While Loop
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Agenda
|
||||
- Intro of Loops
|
||||
- Print numbers from 1 to 5
|
||||
- Structure and Syntax of while loop
|
||||
- Even numbers from 1 to n
|
||||
- Print multiples of 4
|
||||
- Print numbers from n to 1
|
||||
- Find last digit
|
||||
- Remove last digit
|
||||
|
||||
|
||||
:::success
|
||||
There are a lot of quizzes in this session, please take some time to think about the solution on your own before reading further.....
|
||||
:::
|
||||
|
||||
---
|
||||
|
||||
**Ques:** Print natural numbers from 1 to 5.
|
||||
|
||||
**Method 1:**
|
||||
```
|
||||
System.out.println(1);
|
||||
System.out.println(2);
|
||||
System.out.println(3);
|
||||
System.out.println(4);
|
||||
System.out.println(5);
|
||||
```
|
||||
|
||||
**Method 2:**
|
||||
```
|
||||
int i = 1;
|
||||
System.out.println(i);
|
||||
i ++ ;
|
||||
System.out.println(i);
|
||||
i ++ ;
|
||||
System.out.println(i);
|
||||
i ++ ;
|
||||
System.out.println(i);
|
||||
i ++ ;
|
||||
System.out.println(i);
|
||||
```
|
||||
|
||||
**Comparison of Method 1 and Method 2:**
|
||||
Both **Method 1** and **Method 2** output the numbers 1, 2, 3, 4, and 5 in order. The only difference between the two methods is the way the code is written.
|
||||
* Issues In **Method 1** : Since we are updating the values as well along with copy pasting the lines.
|
||||
Possibility of Human Error
|
||||
* Issues In **Method 2** : We are repeating the same lines again and again.
|
||||
|
||||
## Loops
|
||||
Repeat a task multiple times
|
||||
|
||||
- For Loop
|
||||
- While Loop
|
||||
- Do while Loop
|
||||
|
||||
**Method 3:**
|
||||
```
|
||||
int i = 1;
|
||||
while(i <= 5){
|
||||
SOPln(i);
|
||||
i = i + 1;
|
||||
}
|
||||
```
|
||||
|
||||
| i | i<=5 | Output | i + 1 |
|
||||
|:---:|:-----:|:------:|:---------:|
|
||||
| 1 | true | 1 | 2 |
|
||||
| 2 | true | 2 | 3 |
|
||||
| 3 | true | 3 | 4 |
|
||||
| 4 | true | 4 | 5 |
|
||||
| 5 | true | 5 | 6 |
|
||||
| 6 | false | | **Break** |
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Structure of While loop
|
||||
|
||||
**Step 1:** Initialization of a loop variable.
|
||||
**Step 2:** Write while with condition.
|
||||
**Step 3:** Write the task you want to repeat.
|
||||
**Step 4:** Updation of loop variable.
|
||||
|
||||
## Syntax of while loop
|
||||
|
||||
```
|
||||
initialize
|
||||
while(condition){
|
||||
// task to be repeated
|
||||
// updation
|
||||
}
|
||||
```
|
||||
|
||||
**Flow chart of while loop:**
|
||||
|
||||
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/265/original/Screenshot_2023-10-04_at_3.00.22_PM.png?1696411919" alt= “” width ="400" height="300">
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What is the output of the following code?
|
||||
```
|
||||
int i = 5;
|
||||
while(i <= 10){
|
||||
System.out.println(i);
|
||||
i = i * 2;
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 5<br>10
|
||||
- [ ] 0
|
||||
- [ ] Error
|
||||
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What is the output of the following code?
|
||||
```
|
||||
int i = 1;
|
||||
while(i < 5){
|
||||
System.out.print(i + " ");
|
||||
i = i + 1;
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 1 2 3 4 5
|
||||
- [x] 1 2 3 4
|
||||
- [ ] 5 4 3 2 1
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What is the output of the following code?
|
||||
```
|
||||
int i = 0;
|
||||
while(i <= 10){
|
||||
System.out.print(i + " ");
|
||||
i++;
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 0 1 2 3 4 5 6 7 8 9 10
|
||||
- [ ] 1 2 3 4 5 6 7 8 9 10
|
||||
- [ ] Error
|
||||
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
What is the output of the following code?
|
||||
|
||||
```
|
||||
int i = 1;
|
||||
while(i >= 10){
|
||||
System.out.print(i + " ");
|
||||
i = i + 1;
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] Error
|
||||
- [ ] 1 2 3 4 5 6 7 8 9 10
|
||||
- [x] Nothing will get printed
|
||||
- [ ] 10 9 8 7 6 5 4 3 2 1
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What is the output of the following code?
|
||||
|
||||
```
|
||||
int i = 1;
|
||||
while(i <= 10){
|
||||
System.out.print(i + " ");
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 1 2 3 4 5 6 7 8 9 10
|
||||
- [x] 1 1 1 1 1 1 ... Infinite times
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What is the output of the following code?
|
||||
|
||||
```
|
||||
int i = 0;
|
||||
while(i <= 10){
|
||||
System.out.print(i + " ");
|
||||
i = i * 2;
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 5 10
|
||||
- [ ] 0
|
||||
- [x] Infinite loop
|
||||
- [ ] 0 2 4
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What is the output of the following code?
|
||||
|
||||
```
|
||||
int i = 1;
|
||||
while(i <= 5){
|
||||
System.out.print(i + " ");
|
||||
i = i - 1;
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 1 2 3 4 5
|
||||
- [ ] 5 4 3 2 1
|
||||
- [x] Infinite loop
|
||||
- [ ] Inki pinky ponky
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
How many times `Hi` will be printed in the output?
|
||||
|
||||
```
|
||||
int i = 0;
|
||||
while(i <= 5){
|
||||
System.out.println("Hi");
|
||||
i = i + 1;
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 5
|
||||
- [x] 6
|
||||
- [ ] 4
|
||||
- [ ] Infinite times
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
How many times `Inki Pinki Ponki` will be printed in the output?
|
||||
|
||||
```
|
||||
int i = 1;
|
||||
while(i <= n){
|
||||
System.out.println("Inki Pinki Ponki");
|
||||
i = i + 1;
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] n
|
||||
- [ ] (n+1)
|
||||
- [ ] Only once
|
||||
- [ ] Too many times
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Ques:** Print even numbers from 1 to n
|
||||
|
||||
```
|
||||
int n = scn.nextInt();
|
||||
int i = 1;
|
||||
while(i <= n){
|
||||
if(i % 2 == 0){
|
||||
System.out.println(i);
|
||||
}
|
||||
i = i + 1;
|
||||
}
|
||||
```
|
||||
|
||||
> Explain dry run of the above code for more clarity
|
||||
> Example of how to dry run the above code:
|
||||
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/266/original/Screenshot_2023-10-04_at_3.26.15_PM.png?1696413386" alt= “” width ="500" height="300">
|
||||
|
||||
|
||||
|
||||
Another way to implement the above task is as follows:
|
||||
|
||||
```
|
||||
int i = 2;
|
||||
while(i <= n){
|
||||
System.out.println(i);
|
||||
i = i + 2;
|
||||
}
|
||||
```
|
||||
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/052/267/original/Screenshot_2023-10-04_at_3.27.52_PM.png?1696413482
|
||||
" alt= “” width ="500" height="300">
|
||||
|
||||
|
||||
Note that the number of iterations are reduced from 6 to 3.
|
||||
|
||||
Let us take some test cases to test our code.
|
||||
Consider `n = 17`
|
||||
The output should be `2 4 6 8 10 12 14 16`
|
||||
> **Instruction for Instructor:** Run the code on editor to verify the same and show to the students.
|
||||
|
||||
|
||||
In the range 1 - 17, the total number of even numbers are 8.
|
||||
|
||||
In the range 1 - 10, the total number of even numbers are 5.
|
||||
|
||||
> Based on the above observation, ask the following question to the students?
|
||||
**How to calculate the total number of multiples of x between 1 and n?**
|
||||
**Ans:** `n/x`
|
||||
|
||||
Total number of multiples of 2 from 1 to 40 is = 
|
||||
|
||||
Total number of multiples of 2 from 1 to 51 is = 
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# Question
|
||||
What will be the total number of iterations in the following code?
|
||||
|
||||
```
|
||||
int i = 1;
|
||||
while(i <= 20){
|
||||
System.out.println(i);
|
||||
i = i + 1;
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 20
|
||||
- [ ] 10
|
||||
- [ ] 15
|
||||
- [ ] No clue
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What will be the total number of iterations in the following code?
|
||||
|
||||
```
|
||||
int i = 2;
|
||||
while(i <= n){
|
||||
System.out.println(i);
|
||||
i = i + 2;
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] n
|
||||
- [x] n/2
|
||||
- [ ] n+1
|
||||
- [ ] Infinite
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What will be the total number of iterations in the following code?
|
||||
|
||||
```
|
||||
int i = 3;
|
||||
while(i <= n){
|
||||
System.out.println(i);
|
||||
i = i + 3;
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] n / 3
|
||||
- [ ] 3 * n
|
||||
- [ ] n+3
|
||||
- [ ] n
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What are all the multiples of 4 between 1 to 18 ?
|
||||
|
||||
# Choices
|
||||
- [ ] 4 8 12 16 20 24
|
||||
- [ ] 4 6 8 10 12 14
|
||||
- [x] 4 8 12 16
|
||||
- [ ] 1 4 8 12 16
|
||||
|
||||
|
||||
---
|
||||
|
||||
**Ques:** Print multiples of 4 till n.
|
||||
|
||||
**Approach 1:**
|
||||
In this approach, the code takes an input from the user and stores it in the variable n. Then, it uses a `while` loop to iterate from 1 to n. During each iteration, if the value of i is divisible by 4, it prints the value of i using `System.out.println()`.
|
||||
|
||||
```
|
||||
int n = scn.nextInt();
|
||||
int i = 1;
|
||||
while(i <= n){
|
||||
if(i % 4 == 0){
|
||||
System.out.println(i);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
```
|
||||
|
||||
If n is taken as 10, the output of the above code would be: `4 8`
|
||||
|
||||
|
||||
**Approach 2:** **Number of instructions executed are reduced**
|
||||
In this approach, the code initializes the variable $i$ to $4$ and then uses a `while` loop to print the value of $i$ in each iteration. The value of $i$ is incremented by $4$ during each iteration until it becomes greater than $n$.
|
||||
|
||||
**Code:**
|
||||
```
|
||||
int i = 4;
|
||||
while(i <= n){
|
||||
System.out.println(i);
|
||||
i = i + 4;
|
||||
}
|
||||
```
|
||||
|
||||
> Explain using dry run as follows:
|
||||
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/733/original/upload_908acb233760adf812b6c04b41b24ff1.png?1693736372" alt= “” width ="500" height="200">
|
||||
|
||||
|
||||
> Contrast both the dry runs and stress on the fact that the number of iterations are reduced from 10 to 2.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What are the total number of iterations of the following code?
|
||||
```
|
||||
int i = 4;
|
||||
while(i <= n){
|
||||
System.out.println(i);
|
||||
i = i + 4;
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] n
|
||||
- [ ] n + 4
|
||||
- [x] n / 4
|
||||
- [ ] Easy Peesy
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Ques:** Print numbers from n to 1.
|
||||
|
||||
```
|
||||
int n = 5;
|
||||
while(i >= 1){
|
||||
System.out.println(i);
|
||||
i--;
|
||||
}
|
||||
```
|
||||
|
||||
> Explain using dry run as follows:
|
||||
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/734/original/upload_f0f8b93644bb7df8f81fe127ed7302cd.png?1693736416" alt= “” width ="600" height="300">
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
|
||||
```
|
||||
int i = 10;
|
||||
while(i >= 0){
|
||||
System.out.print(i + " ");
|
||||
i = i - 2;
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 10 9 8 7 6 5 4 3 2 1 0
|
||||
- [ ] 10 8 6 4 2
|
||||
- [x] 10 8 6 4 2 0
|
||||
- [ ] 0 2 4 6 8 10
|
||||
|
||||
---
|
||||
|
||||
**Dry Run:**
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/735/original/upload_41d0c4493836a10e847050314b6fa548.png?1693736449" alt= “” width ="450" height="400">
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
## Modulus operator (%)
|
||||
It is used to find the remainder. When we take modulus by 10, we get the last digit of that number.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output of the following code:
|
||||
|
||||
```
|
||||
int x = 7185;
|
||||
System.out.println(x % 10);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 8
|
||||
- [ ] 578
|
||||
- [ ] 718.5
|
||||
- [x] 5
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output of the following code:
|
||||
|
||||
```
|
||||
int x = 4578;
|
||||
System.out.println(x % 10);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 8
|
||||
- [ ] 578
|
||||
- [ ] 78
|
||||
- [ ] None
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output of the following code:
|
||||
|
||||
```
|
||||
int x = 99576;
|
||||
System.out.println(x % 10);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 6
|
||||
- [ ] 576
|
||||
- [ ] 995
|
||||
- [ ] None
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output of the following code:
|
||||
|
||||
```
|
||||
int x = 7248;
|
||||
System.out.println(x / 10);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 724.8
|
||||
- [ ] 725
|
||||
- [x] 724
|
||||
- [ ] Inky pinky ponky
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Ques:** Given a positive integer, write code to find it's last digit.
|
||||
|
||||
**Code:**
|
||||
```
|
||||
int n = scn.nextInt();
|
||||
System.out.println(n % 10);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Ques:** Given a positive integer, write code to remove it's last digit.
|
||||
|
||||
**Code:**
|
||||
```
|
||||
int n = scn.nextInt();
|
||||
n = n / 10;
|
||||
System.out.println(n);
|
||||
```
|
||||
---
|
||||
|
599
Academy DSA Typed Notes/Beginner Language/Beginner Loop - 2.md
Normal file
599
Academy DSA Typed Notes/Beginner Language/Beginner Loop - 2.md
Normal file
@@ -0,0 +1,599 @@
|
||||
# Loops 2
|
||||
|
||||
---
|
||||
|
||||
> Quick revision
|
||||
|
||||
**Step 1:** Initialization of a loop variable.
|
||||
**Step 2:** Write while with condition.
|
||||
**Step 3:** Write the task you want to repeat.
|
||||
**Step 4:** Updation of loop variable.
|
||||
|
||||
## Syntax of while loop
|
||||
|
||||
```
|
||||
initialize
|
||||
while(condition){ // loop stops when the condition fails
|
||||
// task to be repeated
|
||||
// updation
|
||||
}
|
||||
```
|
||||
|
||||
**Flow chart of while loop:**
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/748/original/beginner-iterations-loop-2-image-1.png?1693749426" height = "350" width = "350">
|
||||
|
||||
|
||||
**Question:**
|
||||
|
||||
How to find the last digit of a number N?
|
||||
|
||||
**Answer:** Use the modulus operator as `N%10`.
|
||||
|
||||
> Give an example
|
||||
|
||||
**Question:** How to delete the last digit of N?
|
||||
|
||||
**Answer:**
|
||||
```
|
||||
N = N / 10;
|
||||
SOP(N);
|
||||
```
|
||||
|
||||
---
|
||||
title: Printing all digits
|
||||
description: Print all the digits of that number from right to left
|
||||
duration: 480
|
||||
card_type: cue_card
|
||||
---
|
||||
|
||||
**Ques:** Given a integer number, print all the digits of that number from right to left.
|
||||
|
||||
Example, if `n = 6397` the correct output should be `7 9 3 6`
|
||||
|
||||
> Give the students, an intuition to solve the problem as follows:
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/746/original/upload_c997251ad272ffb9708ce7c8a5bf1411.png?1693748957" alt= “” width ="450" height="350">
|
||||
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
**Approach:**
|
||||
* Find the last digit.
|
||||
* Print the digit.
|
||||
* Remove last digit.
|
||||
|
||||
**Code:**
|
||||
```
|
||||
int n = scn.nextInt();
|
||||
while(n > 0){
|
||||
int digit = n % 10;
|
||||
SOPln(digit);
|
||||
n = n / 10;
|
||||
}
|
||||
```
|
||||
|
||||
> To figure out the condition in the while loop expression (i.e., `n > 0`), give the students an intuition as follows:
|
||||
<img src="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/747/original/upload_a7b3a344d33b1e78a66ba64c1ae9b4a0.png?1693748996" alt= “” width ="400" height="450">
|
||||
|
||||
**How to handle negative numbers?**
|
||||
**Ans:** Convert negative numbers to positive numbers.
|
||||
|
||||
> Take an example of a negative number, dry run the code. Tell the students that the code exits from the while loop condition since `n < 0`. Then give the solution.
|
||||
|
||||
**The updated code is as follows:**
|
||||
```
|
||||
int n = scn.nextInt();
|
||||
if(n < 0){
|
||||
n = n * -1;
|
||||
}
|
||||
while(n > 0){
|
||||
int digit = n % 10;
|
||||
SOPln(digit);
|
||||
n = n / 10;
|
||||
}
|
||||
```
|
||||
|
||||
**Next corner test case:** What if `n == 0`?
|
||||
In this case, the output should be $0$, but according to the code this will print nothing. So we need to handle this case as well.
|
||||
|
||||
**The updated code is as follows:**
|
||||
```
|
||||
int n = scn.nextInt();
|
||||
if(n < 0){
|
||||
n = n * -1;
|
||||
return;
|
||||
}
|
||||
else if(n == 0){
|
||||
SOPln(0);
|
||||
return;
|
||||
}
|
||||
while(n > 0){
|
||||
int digit = n % 10;
|
||||
SOPln(digit);
|
||||
n = n / 10;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
**Dry Run:**
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/749/original/beginner-iterations-loop-2-image-2.png?1693749460" height = "450" width = "450">
|
||||
|
||||
|
||||
---
|
||||
title: Find sum of digits of a given number
|
||||
description: Take examples to explain how to use while loops
|
||||
duration: 900
|
||||
card_type: cue_card
|
||||
---
|
||||
|
||||
## Find Sum of Digits of A Given Number
|
||||
**Question:**
|
||||
|
||||
Find the sum of digits of a given number.
|
||||
|
||||
Give examples -> 1274, 1004, -512
|
||||
|
||||
```
|
||||
1274 -> 1 + 2 + 7 + 4 = 14
|
||||
1004 -> 1 + 0 + 0 + 4 = 5
|
||||
-512 -> 5 + 1 + 2 = 8
|
||||
```
|
||||
|
||||
|
||||
Note: Negative sign (**-**) is not a digit.
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
**Approach:**
|
||||
To discuss the approach take an example.
|
||||
|
||||
```
|
||||
// Initialization
|
||||
n = 2748
|
||||
s = 0
|
||||
```
|
||||
|
||||
| n | n > 0 | d = n % 10 | s = s + d | n = n / 10 |
|
||||
|:----:|:-----:|:----------:|:---------:|:----------:|
|
||||
| 2748 | true | 8 | 8 | 274 |
|
||||
| 274 | true | 4 | 12 | 27 |
|
||||
| 27 | true | 7 | 19 | 2 |
|
||||
| 2 | true | 2 | 21 | 0 |
|
||||
| 0 | false | - | - | - |
|
||||
|
||||
```
|
||||
int n = scn.nextInt();
|
||||
|
||||
if (n < 0) {
|
||||
n = n * - 1;
|
||||
}
|
||||
|
||||
int s = 0;
|
||||
while (n > 0) {
|
||||
int d = n % 10;
|
||||
s = s + d;
|
||||
n = n / 10;
|
||||
}
|
||||
|
||||
SOPln(s);
|
||||
```
|
||||
|
||||
---
|
||||
title: Add a given digit to the back of a given number N.
|
||||
description: Take examples to explain how to use while loops
|
||||
duration: 800
|
||||
card_type: cue_card
|
||||
---
|
||||
|
||||
### Example 1
|
||||
**Question:**
|
||||
|
||||
Given a positive integer N and a single digit d, add d to the back of N.
|
||||
|
||||
**Example:**
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/751/original/beginner-iterations-loop-2-image-3.png?1693749757" height = "350" width = "500">
|
||||
|
||||
Formula to add d to the back of N:
|
||||
|
||||
```
|
||||
n = n * 10 + d;
|
||||
```
|
||||
|
||||
---
|
||||
title: Find the reverse of a given number
|
||||
description: Take examples to explain how to use while loops
|
||||
duration: 1100
|
||||
card_type: cue_card
|
||||
---
|
||||
|
||||
### Example 2
|
||||
**Question:**
|
||||
|
||||
Given a number N, store it's reverse in another variable and print it.
|
||||
|
||||
**Examples:**
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/752/original/beginner-iterations-loop-2-image-4.png?1693749809" height = "350" width = "220">
|
||||
|
||||
**Idea/Approach:**
|
||||
Initialize a variable rev = 0 and one by one take the last digit of N and add it to rev as shown below.
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/754/original/beginner-iterations-loop-2-image-5.png?1693749853" height = "350" width = "350">
|
||||
|
||||
**Steps:**
|
||||
* Get last digit
|
||||
* Add last digit to the back of rev
|
||||
* Remove last digit
|
||||
* Repeat the above three steps till the number is greater than zero
|
||||
|
||||
**Dry run:**
|
||||
| n | n > 0 | d = n % 10 | rev = rev * 10 + d | n = n / 10 |
|
||||
|:----:|:-----:|:----------:|:------------------:|:----------:|
|
||||
| 1456 | true | 6 | 6 | 145 |
|
||||
| 145 | true | 5 | 65 | 14 |
|
||||
| 14 | true | 4 | 654 | 1 |
|
||||
| 1 | true | 1 | 6541 | 0 |
|
||||
| 0 | false | - | - | - |
|
||||
|
||||
```
|
||||
int n = scn.nextInt();
|
||||
int copy = n;
|
||||
|
||||
if (n < 0) {
|
||||
n = n * - 1;
|
||||
}
|
||||
|
||||
int rev = 0;
|
||||
while (n > 0) {
|
||||
int d = n % 10;
|
||||
rev = rev * 10 + d;
|
||||
n = n / 10;
|
||||
}
|
||||
|
||||
if (copy < 0) {
|
||||
rev = rev * - 1;
|
||||
}
|
||||
|
||||
SOPln(s);
|
||||
```
|
||||
|
||||
> Dry run with n = 2400 and show that the output will be 42 and not 0042.
|
||||
|
||||
Tell them that if you want to print 0042, print the digits of n from right to left. It is not possible for an integer variable to store 0042.
|
||||
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/755/original/beginner-iterations-loop-2-image-6.png?1693750025" height = "350" width = "650">
|
||||
|
||||
> Show dry run with - 417 as n.
|
||||
|
||||
---
|
||||
title: Check if a given number is palindrome or not
|
||||
description: Take examples to explain how to use while loops
|
||||
duration: 720
|
||||
card_type: cue_card
|
||||
---
|
||||
|
||||
### Example 3
|
||||
**Question:**
|
||||
|
||||
Given a number N, check if number if palindrome or not.
|
||||
A number is said to a palindrome if it remains the same when its digits are reversed. Ex- 1221, 1551, 131, etc.
|
||||
|
||||
**Exercise for students:**
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/756/original/beginner-iterations-loop-2-image-7.png?1693750061" height = "400" width = "430">
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
**Approach:**
|
||||
Find the reverse of the number using what we discussed in the last quiz and compare it with the original number. It it is the same, then the number is palindromic, otherwise not.
|
||||
|
||||
```
|
||||
int n = scn.nextInt();
|
||||
int copy = n;
|
||||
|
||||
if (n < 0) {
|
||||
n = n * - 1;
|
||||
}
|
||||
|
||||
int rev = 0;
|
||||
while (n > 0) {
|
||||
int d = n % 10;
|
||||
rev = rev * 10 + d;
|
||||
n = n / 10;
|
||||
}
|
||||
|
||||
if (copy < 0) {
|
||||
rev = rev * - 1;
|
||||
}
|
||||
|
||||
if (rev == copy) {
|
||||
SOPln("PALINDROME");
|
||||
}
|
||||
else {
|
||||
SOPln("NOT PALINDROME")
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
title: For loop basics
|
||||
description: Quick recap of the syntax and flow of for loops
|
||||
duration: 120
|
||||
card_type: cue_card
|
||||
---
|
||||
|
||||
## For loop Basics
|
||||
|
||||
Every for loop question can be done using a while loop. The difference lies in the syntax.
|
||||
|
||||
**Syntax:**
|
||||
```
|
||||
for(Initialization; Condition; update) {
|
||||
// Statements to be executed
|
||||
}
|
||||
```
|
||||
|
||||
> Explain the syntax.
|
||||
|
||||
|
||||
**Flow:**
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/757/original/beginner-iterations-loop-2-image-8.png?1693750115" height = "400" width = "380">
|
||||
|
||||
---
|
||||
title: Print numbers from 1 to 5 using for loops
|
||||
description: Take examples to explain how to use for loops
|
||||
duration: 180
|
||||
card_type: cue_card
|
||||
---
|
||||
### Example 4
|
||||
**Question:**
|
||||
|
||||
Print all numbers from 1 to 5.
|
||||
|
||||
```
|
||||
for(int i = 1; i <= 5; i ++ ) {
|
||||
SOPln(i);
|
||||
}
|
||||
```
|
||||
|
||||
> Explain the logic behind initialization, condition and update statements.
|
||||
|
||||
**Dry Run:**
|
||||
| i | i <= 5 | print(i) | i++ |
|
||||
|:---:|:------:|:--------:|:---:|
|
||||
| 1 | true | 1 | 2 |
|
||||
| 2 | true | 2 | 3 |
|
||||
| 3 | true | 3 | 4 |
|
||||
| 4 | true | 4 | 5 |
|
||||
| 5 | true | 5 | 6 |
|
||||
| 6 | false | - | - |
|
||||
|
||||
---
|
||||
title: Quiz 1
|
||||
description: Quiz 1
|
||||
duration: 60
|
||||
card_type: quiz_card
|
||||
---
|
||||
|
||||
# Question
|
||||
Expected output for following code :
|
||||
|
||||
```
|
||||
for(int i = 1; i <= 10; i = i + 2) {
|
||||
System.out.println(i);
|
||||
}
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] All Numbers from 1 to 10
|
||||
- [ ] All Even Numbers from 1 to 10
|
||||
- [x] All Odd Numbers from 1 to 10
|
||||
- [ ] All Numbers from 1 to 9
|
||||
|
||||
---
|
||||
title: Explain the quiz answer
|
||||
description: Perform a dry run to explain the quiz question
|
||||
duration: 240
|
||||
card_type: cue_card
|
||||
---
|
||||
|
||||
### Explaination
|
||||
|
||||
**Dry Run:**
|
||||
| i | i <= 10 | print(i) | i += 2 |
|
||||
|:---:|:-------:|:--------:|:------:|
|
||||
| 1 | true | 1 | 3 |
|
||||
| 3 | true | 3 | 5 |
|
||||
| 5 | true | 5 | 7 |
|
||||
| 7 | true | 7 | 9 |
|
||||
| 9 | true | 9 | 11 |
|
||||
| 11 | false | - | - |
|
||||
|
||||
---
|
||||
title: Print the count of digits of a number
|
||||
description: Take examples to explain how to use for loops
|
||||
duration: 600
|
||||
card_type: cue_card
|
||||
---
|
||||
|
||||
### Example 5
|
||||
**Question:**
|
||||
|
||||
Given a positive number, print the count of digits.
|
||||
|
||||
> Give examples such as 5164, 121700, 9, etc.
|
||||
|
||||
**Approach/Intuition:**
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/045/767/original/beginner-iterations-loop-2-image-9.png?1693751819" height = "400" width = "380">
|
||||
|
||||
```
|
||||
int count = 0;
|
||||
for(int i = n; i > 0; i = i / 10) {
|
||||
count += 1;
|
||||
}
|
||||
|
||||
SOPln(count);
|
||||
```
|
||||
|
||||
> Show that the above code does not work for n = 0 and make the following change.
|
||||
|
||||
```
|
||||
int count = 0;
|
||||
if (n == 0) count = 1;
|
||||
|
||||
for(int i = n; i > 0; i = i / 10) {
|
||||
count += 1;
|
||||
}
|
||||
|
||||
SOPln(count);
|
||||
```
|
||||
|
||||
---
|
||||
title: Read 5 numbers and for every number print last digit of the number.
|
||||
description: Explain the need of for loops
|
||||
duration: 780
|
||||
card_type: cue_card
|
||||
---
|
||||
### Example 6
|
||||
|
||||
**Question:**
|
||||
|
||||
Read 5 numbers and for every number print last digit of the number.
|
||||
|
||||
**Example:**
|
||||
Input:
|
||||
34
|
||||
45
|
||||
378
|
||||
980
|
||||
456
|
||||
|
||||
**Output:**
|
||||
4
|
||||
5
|
||||
8
|
||||
0
|
||||
6
|
||||
|
||||
:::warning
|
||||
Please take some time to think about the solution approach on your own before reading further.....
|
||||
:::
|
||||
|
||||
**Approach 1:**
|
||||
|
||||
```
|
||||
int a = scn.nextInt();
|
||||
int b = scn.nextInt();
|
||||
int c = scn.nextInt();
|
||||
int d = scn.nextInt();
|
||||
int e = scn.nextInt();
|
||||
|
||||
SOPln(a % 10);
|
||||
SOPln(b % 10);
|
||||
SOPln(c % 10);
|
||||
SOPln(d % 10);
|
||||
SOPln(e % 10);
|
||||
```
|
||||
|
||||
**Approach 2:**
|
||||
```
|
||||
for(int i = 0; i < 5; i ++ ) {
|
||||
int n = scn.nextInt();
|
||||
SOPln(n % 10);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
title: Read T numbers and for every number print last digit of the number.
|
||||
description: Show examples to explain how to use for loops
|
||||
duration: 360
|
||||
card_type: cue_card
|
||||
---
|
||||
### Example 7
|
||||
|
||||
**Question:**
|
||||
|
||||
Read T numbers and for every number print the last digit.
|
||||
|
||||
**Input Format:**
|
||||
1st Line: Contains T
|
||||
Followed by T lines containing the T numbers
|
||||
|
||||
```
|
||||
int T = scn.nextInt();
|
||||
|
||||
for(int i = 0; i < T; i ++ ) {
|
||||
int n = scn.nextInt();
|
||||
SOPln(n % 10);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
title: Read T numbers and for every number print the sum of digits of the number.
|
||||
description: Show examples to explain how to use for loops
|
||||
duration: 420
|
||||
card_type: cue_card
|
||||
---
|
||||
### Example 8
|
||||
**Question:**
|
||||
|
||||
Read T numbers and for each number, print the sum of digits of the number.
|
||||
|
||||
**Input:**
|
||||
3
|
||||
566
|
||||
4130
|
||||
162
|
||||
|
||||
**Output:**
|
||||
17
|
||||
8
|
||||
9
|
||||
|
||||
```
|
||||
int T = scn.nextInt();
|
||||
|
||||
for(int i = 0; i < T; i ++ ) {
|
||||
int n = scn.nextInt();
|
||||
|
||||
if (n < 0) {
|
||||
n = n * - 1;
|
||||
}
|
||||
|
||||
int s = 0;
|
||||
while (n > 0) {
|
||||
int d = n % 10;
|
||||
s = s + d;
|
||||
n = n / 10;
|
||||
}
|
||||
|
||||
SOPln(s);
|
||||
}
|
||||
```
|
||||
|
||||
> Show dry run for the example above.
|
||||
|
||||
Same question using for loop -
|
||||
```
|
||||
int T = scn.nextInt();
|
||||
|
||||
for(int i = 0; i < T; i ++ ) {
|
||||
int n = scn.nextInt();
|
||||
|
||||
if (n < 0) {
|
||||
n = n * -1;
|
||||
}
|
||||
|
||||
int s = 0;
|
||||
for(int x = n; x > 0; x ++ ) {
|
||||
int d = x % 10;
|
||||
s = s + d;
|
||||
}
|
||||
|
||||
SOPln(s);
|
||||
}
|
||||
```
|
||||
|
Binary file not shown.
958
Academy DSA Typed Notes/Beginner Language/Beginner Operators.md
Normal file
958
Academy DSA Typed Notes/Beginner Language/Beginner Operators.md
Normal file
@@ -0,0 +1,958 @@
|
||||
# Beginner: Operators
|
||||
---
|
||||
## Agenda
|
||||
|
||||
* Typecasting Revision
|
||||
* Rules doing basic operations
|
||||
* Integer Overflow
|
||||
* Operators (Logical, Unary)
|
||||
|
||||
:::success
|
||||
There are a lot of quizzes in this session, please take some time to think about the solution on your own before reading further.....
|
||||
:::
|
||||
|
||||
---
|
||||
|
||||
## Rules
|
||||
1. While type casting, if no chance of data loss, then we get no error -> Implicit / Widening Typecasting (Happens automatically).
|
||||
2. If there may be a data loss, then we will get some error. If we still want to typecast, we forcefully have to do it -> Explicit / Narrowing (forcefully).
|
||||
|
||||
**Note:** If students are not able to understand, run the corresponding quiz code in IDE, and then clarify any questions.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
int abc = 400;
|
||||
long x = abc;
|
||||
System.out.print(x);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 400
|
||||
- [ ] Error
|
||||
- [ ] Random Value
|
||||
- [ ] Good Morning!
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Explanation
|
||||
When we store int into long, there is no data loss, hence 400 is the answer. Explain more if necessary.
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Predict the output:
|
||||
```
|
||||
long a = 100000; // 10^5
|
||||
System.out.print(a);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] Error
|
||||
- [x] 100000
|
||||
- [ ] a
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Explanation
|
||||
**Mistake:** Some students may think that we need a L after the number but its not necessary. Because implicity typecasting is going on. Explain more, if needed.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Predict the output:
|
||||
```
|
||||
long x = 500000;
|
||||
int y = x;
|
||||
System.out.print(y);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] Error
|
||||
- [ ] 500000
|
||||
- [ ] Some random value
|
||||
---
|
||||
|
||||
|
||||
# Explanation
|
||||
|
||||
```
|
||||
long x = 500000; // This line is correct (Implcity typecasting)
|
||||
int y = x; // Possible data loss.
|
||||
System.out.print(y);
|
||||
```
|
||||
We cannot store a long into int, because of possible data loss. Hence, the error.
|
||||
|
||||
**Q.** Ask students on how to correct this?
|
||||
**A.** Explicit typecasting
|
||||
|
||||
Move on to the next quiz which is based on this.
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
long n = 60000;
|
||||
int a = (int)n;
|
||||
System.out.print(a);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] Random Value
|
||||
- [ ] Error
|
||||
- [x] 60000
|
||||
- [ ] How would I know?
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Explanation
|
||||
The 2nd line is forcing the compiler to change the long to int which is correct.
|
||||
|
||||
**Mistake:** Some students may ask why we won't get any random value. Because, 60000 is within the range of int data type, and hence no loss.
|
||||
|
||||
Range of int -> -2 * 10^9 to 2 * 10^9
|
||||
|
||||
Give the following example:
|
||||
long x = 100000000000 // 10^11
|
||||
This number is too large and so we need to mention explicity that:
|
||||
long x = 100000000000L.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
long a = 100000000000L; // 10^11
|
||||
int b = (int)a;
|
||||
System.out.println(b);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 100000000000
|
||||
- [ ] Error
|
||||
- [x] Random Value
|
||||
- [ ] Too many zeroes
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Explanation
|
||||
|
||||
Since 10^11 cannot be stored in int, and we are forcing. So, data loss (Overflow) is happening, and some value is getting lost, we are getting random value.
|
||||
|
||||
|
||||
---
|
||||
title: Quiz 6
|
||||
description: Quiz 6
|
||||
duration: 30
|
||||
card_type: quiz_card
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
double x = 7.89;
|
||||
System.out.print(x);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 7
|
||||
- [x] 7.89
|
||||
- [ ] Error
|
||||
- [ ] Ex is not texting back.
|
||||
|
||||
---
|
||||
|
||||
# Explanation
|
||||
|
||||
Since the right value is of type double. We can store double into double without any issues.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
float val = 10.78;
|
||||
System.out.print(val);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 10.78
|
||||
- [ ] 10
|
||||
- [x] Error
|
||||
- [ ] I am sleeping
|
||||
|
||||
---
|
||||
|
||||
# Explanation
|
||||
|
||||
Any decimal number is of double type, while the type of val is float.
|
||||
**Q.** Can we store double into float type?
|
||||
**A.** No, as there can be possible data loss.
|
||||
|
||||
Hence, we get an error.
|
||||
**Q.** Ask students into how to fix this?
|
||||
**A.** Explicit typecasting to float.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
Predict the output:
|
||||
```
|
||||
float x = 15.88f;
|
||||
System.out.print(x);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 15.88
|
||||
- [ ] 15
|
||||
- [ ] Error
|
||||
|
||||
---
|
||||
|
||||
# Explanation
|
||||
Since, we explicitly typecasted to float, hence we will not get any error.
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
|
||||
Predict the output:
|
||||
```java
|
||||
double y = 4.78;
|
||||
float a = y;
|
||||
System.out.println(a);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 4.78
|
||||
- [x] Error
|
||||
- [ ] Missed the lectures
|
||||
|
||||
---
|
||||
|
||||
# Explanation
|
||||
|
||||
Since, we are storing a double type into float, we have possible data loss. Hence, we get an error.
|
||||
|
||||
|
||||
---
|
||||
## Rules doing Basic Operations
|
||||
|
||||
|
||||
## Rule 1
|
||||
When we do operation between a decimal and a non-decimal number, the output is always decimal.
|
||||
|
||||
* int op double --> double
|
||||
* long op float --> float
|
||||
|
||||
**Note:** Run each of the following example codes in the compiler, and show the output to students.
|
||||
|
||||
## Example 1
|
||||
|
||||
### Incorrect Code
|
||||
Don't let the students know that the code is incorrect. Ask them if it's correct and if not, how is it violating the Rule 1.
|
||||
|
||||
```
|
||||
class Scaler {
|
||||
public static void main(String[] args) {
|
||||
int x = 10;
|
||||
double y = 10.25;
|
||||
int z = x + y;
|
||||
System.out.println(z);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Output
|
||||
```
|
||||
error: incompatible types: possible lossy conversion from double to int
|
||||
int z = x + y;
|
||||
^
|
||||
1 error
|
||||
```
|
||||
|
||||
Explain why their is a possible lossy conversion if we store the sum in an integer.
|
||||
A. (x + y) is of double type.
|
||||
|
||||
Ask students on how to remove the error?
|
||||
|
||||
### Correct Code
|
||||
```
|
||||
class Scaler {
|
||||
public static void main(String[] args) {
|
||||
int x = 10;
|
||||
double y = 10.25;
|
||||
double z = x + y;
|
||||
System.out.println(z);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Output
|
||||
```
|
||||
20.25
|
||||
```
|
||||
|
||||
Q. Ask students on how to store the result into an integer i.e, we don't want to store into a double.
|
||||
|
||||
A. Typecasting
|
||||
|
||||
### Correct Code
|
||||
```
|
||||
class Scaler {
|
||||
public static void main(String[] args) {
|
||||
int x = 10;
|
||||
double y = 10.25;
|
||||
int z = (int)(x + y);
|
||||
System.out.println(z);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Rule 2
|
||||
When we do operation between two operands of same category, the result is of bigger type.
|
||||
|
||||
* int op long --> long
|
||||
* float op double --> double
|
||||
* int op int --> int
|
||||
* long op long --> long
|
||||
|
||||
**Note:** Run each of the following example codes in the compiler, and show the output to students.
|
||||
|
||||
## Example 1
|
||||
|
||||
### Incorrect Code
|
||||
Don't let the students know that the code is incorrect. Ask them if it's correct and if not, how is it violating the Rule 2.
|
||||
|
||||
```
|
||||
class Scaler {
|
||||
public static void main(String[] args) {
|
||||
int x = 20;
|
||||
long y = 150L;
|
||||
int z = x + y;
|
||||
System.out.println(z);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Output
|
||||
```
|
||||
/tmp/thqSRPUchr/Scaler.java:6: error: incompatible types: possible lossy conversion from long to int
|
||||
int z = x + y;
|
||||
^
|
||||
1 error
|
||||
```
|
||||
|
||||
Explain why their is a possible lossy conversion if we store the sum in an integer.
|
||||
A. (x + y) is of long type.
|
||||
|
||||
Ask students on how to remove the error?
|
||||
|
||||
### Correct Code
|
||||
|
||||
```
|
||||
class Scaler {
|
||||
public static void main(String[] args) {
|
||||
int x = 20;
|
||||
long y = 150L;
|
||||
long z = x + y;
|
||||
System.out.println(z);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Output
|
||||
```
|
||||
170
|
||||
```
|
||||
|
||||
---
|
||||
## Integer Overflow
|
||||
|
||||
|
||||
**Note:** For better clarity of quizzes, please run the codes in the compiler as well.
|
||||
Explain the integer overflow concept after giving the following quiz.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Predict the output:
|
||||
```
|
||||
int a = 100000;
|
||||
int b = 400000;
|
||||
int c = a * b;
|
||||
System.out.print(c);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 40000000000
|
||||
- [x] Some random Value
|
||||
- [ ] Error
|
||||
|
||||
|
||||
---
|
||||
## CPU and its components
|
||||
|
||||
|
||||
Before explaining the quiz's answer, we need to understand some more information.
|
||||
|
||||
**Q.** Where are these variables stored and where are these operations carried out?
|
||||
|
||||
We have two major components:
|
||||
* Central Processing Unit (CPU)
|
||||
* ALU - Arithmetic Logic Unit
|
||||
* Control Unit
|
||||
* Registers
|
||||
* Random Access Memory (RAM)
|
||||
|
||||
Look at the following diagram.
|
||||
<img src ="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/048/460/original/upload_d26c363818f0ecae906193eac45751b9.png?1694708166"
|
||||
width = "600" height = "300">
|
||||
|
||||
Explain the use of the two components using the code for the quiz.
|
||||
|
||||
int a = 100000;
|
||||
int b = 400000;
|
||||
Populate the RAM with these two variables.
|
||||
int c = a * b;
|
||||
We want to store c into RAM. But we need to compute a * b first.
|
||||
|
||||
**Q.** Where will the computation happen?
|
||||
**A.** ALU
|
||||
Values will be transferred to CPU's registers via buses, and then computation will be performed. The values are then written back to c's location in RAM.
|
||||
|
||||
The result would look something like this:
|
||||
<img src ="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/048/461/original/upload_84a6994f462551877ec0827f0a75b961.png?1694708288"
|
||||
width = "700" height = "300">
|
||||
|
||||
|
||||
If the inputs are integers, the ALU will assume that the output is also integer, which cannot be stored.
|
||||
**Note:** The compiler has no control over this.
|
||||
|
||||
So, the output will be some random value.
|
||||
|
||||
Now, formally define what is **Integer Overflow**?
|
||||
* When we attempt to store a value that cannot be represented correctly by a data type, an Integer Overflow.
|
||||
* Integer Overflow occurs when the value is more than the maximum representable value
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Predict the output:
|
||||
```
|
||||
int a = 100000;
|
||||
int b = 400000;
|
||||
long c = a * b;
|
||||
System.out.print(c);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 40000000000
|
||||
- [ ] 2147483647
|
||||
- [x] Some random Value
|
||||
- [ ] Error: product of integers can't be stored in long
|
||||
|
||||
# Explanation
|
||||
|
||||
Explain why this is the correct answer. If we store an integer in a long, we don't have any issues. So, according to the compiler, there's nothing wrong.
|
||||
|
||||
Explain it in the following way:
|
||||
|
||||
|
||||
<img src ="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/048/462/original/upload_6ee7d0a207336c303f89d6aab64cbaaa.png?1694708350"
|
||||
width = "700" height = "250">
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Predict the output:
|
||||
```
|
||||
long a = 100000;
|
||||
long b = 400000;
|
||||
int c = a * b;
|
||||
System.out.print(c);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 40000000000
|
||||
- [ ] Some random Value
|
||||
- [x] Error
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Explanation
|
||||
Explain why we are getting error in this case.
|
||||
long * long --> long
|
||||
Q. Can we store long into an integer?
|
||||
A. No, we can't. So, there is a possible lossy conversion.
|
||||
|
||||
**Reminder:** Remind the students to focus on the two rules, and all the questions would be easy.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Predict the output:
|
||||
```
|
||||
long a = 100000;
|
||||
int b = 400000;
|
||||
long c = a * b;
|
||||
System.out.print(c);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 40000000000
|
||||
- [ ] Compilation Error
|
||||
- [ ] Some random Value
|
||||
|
||||
---
|
||||
|
||||
# Explanation
|
||||
long * int --> long
|
||||
Q. Can we store long into a long type?
|
||||
A. Yes.
|
||||
|
||||
Explain this again in RAM and ALU in the following way:
|
||||
<img src ="https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/048/463/original/upload_7581c0b9de5fd1dad5e7fc79cea74dd8.png?1694708442"
|
||||
width = "700" height = "250">
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Predict the output:
|
||||
```
|
||||
int a = 100000;
|
||||
int b = 400000;
|
||||
long c = (long)(a * b);
|
||||
System.out.println(c);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [ ] 40000000000
|
||||
- [ ] Compilation Error
|
||||
- [x] Some random Value
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Explanation
|
||||
|
||||
int * int --> int
|
||||
Q. Ask if we are typecasting individual variables or (a * b)?
|
||||
A. We are typecasting (a * b) which is a random value to long.
|
||||
|
||||
Explain this again in RAM and ALU in the following way:
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/048/464/original/upload_aa2768e0525d6a8622f5133220bdcee4.png?1694708474" width = "700" height = "300">
|
||||
|
||||
Let the students know that this is not the correct way to multiply two integers.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
What will be the output?
|
||||
```
|
||||
int a = 100000;
|
||||
int b = 400000;
|
||||
long c = (long)a * b;
|
||||
System.out.println(c);
|
||||
```
|
||||
|
||||
# Choices
|
||||
- [x] 40000000000
|
||||
- [ ] Compilation Error
|
||||
- [ ] Some random Value
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Explanation
|
||||
|
||||
Typecast the value of a to long, and then multiply it with the integer b.
|
||||
Q. What will be the output of the multiplication of a long and an integer?
|
||||
A. According to Rule 2, it will be long.
|
||||
|
||||
We can store a long into a long variable.
|
||||
Explain this again in RAM and ALU in the following way:
|
||||
<img src = "https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/048/465/original/upload_ff5e95b19bb73ea5f469d0c89ba91411.png?1694708553" height = "250" width = "600">
|
||||
|
||||
|
||||
**Clarification:**
|
||||
|
||||
Some students get confused between the following 2 things:
|
||||
* long c = (long) (a * b)
|
||||
* long c = (long)a * b
|
||||
|
||||
Explain that in the 1st case, we are typecasting the product of two integers to a long, and in the 2nd case, we are first typecasting a into long, and then multiplying it with an integer.
|
||||
|
||||
---
|
||||
|
||||
In this section, we will study different types of operators namely:
|
||||
* Arithmetic Operators
|
||||
* Relational Operators
|
||||
* Logical Operators
|
||||
* Unary Operators
|
||||
* Assignment Operators
|
||||
|
||||
---
|
||||
|
||||
|
||||
**Q.** What are Logical Operators?
|
||||
**A.** Logical operators can be defined as a type of operators that help us to combine multiple conditional statements. There are three types of logical operators: **AND (&&), OR (||) and Logical NOT (!) operators**.
|
||||
|
||||
To better understand AND(&&) operator, give the students the following analogy.
|
||||
|
||||
1. Driver's License
|
||||
* age >= 18
|
||||
* Know how to drive
|
||||
|
||||
In which of the following 4 scenarios the person should get their driver's license.
|
||||
|
||||
|
||||
|
||||
$\begin{array}{|c:c:c:c:c:c|}
|
||||
\hline
|
||||
age >= 18 & Know\ how\ to\ drive & Driver's\ License\ received \\ \hline
|
||||
True & True & True \\ \hline
|
||||
True & False & False \\ \hline
|
||||
False & True & False \\ \hline
|
||||
False & False & False \\ \hline
|
||||
\end{array}$
|
||||
|
||||
|
||||
So, we get the drivers's license when both the conditions are true.
|
||||
AND [&&] -> Both conditions need to be true to get true as answer.
|
||||
|
||||
To better understand Logical OR (||) operator, give the students the following analogy.
|
||||
|
||||
2. Eligibility Criterion for Exam
|
||||
* Should have a diploma
|
||||
* Should have a degree
|
||||
|
||||
If they have either diploma or degree, they will be allowed to sit in the exam.
|
||||
|
||||
In which of the following 4 scenarios the person should be allowed to sit in the exam.
|
||||
|
||||
|
||||
|
||||
$\begin{array}{|c:c:c:c:c:c|}
|
||||
\hline
|
||||
Have\ a\ diploma? & Have\ a\ degree? &Allowed\ to\ sit\ in\ exam \\ \hline
|
||||
True & True & True \\ \hline
|
||||
True & False & True \\ \hline
|
||||
False & True & True \\ \hline
|
||||
False & False & False \\ \hline
|
||||
\end{array}$
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
OR [||] -> Even if one of the conditions is true, we get true as an answer.
|
||||
|
||||
### Important Observation of AND and OR Operator
|
||||
|
||||
* In case of AND, if the 1st condition is false, does the 2nd value have any effect? No, so the compiler would skip the 2nd check if the 1st condition is false.
|
||||
* Similarly, if the 1st condition is true, does the 2nd value have any effect? No, so the compiler would skip the 2nd check if the 1st condition is true.
|
||||
|
||||
|
||||
To better understand Logical Not (!) operator, let us look into following analogy.
|
||||
|
||||
3. To purchase milk, it shouldn't be raining outside. How to check for this condition?
|
||||
|
||||
If it's not raining outside, purchase milk.
|
||||
|
||||
|
||||
|
||||
$\begin{array}{|c:c:c:c:c:c|}
|
||||
\hline
|
||||
Raining\ outside & Can\ purchase\ Milk? \\ \hline
|
||||
True & False \\ \hline
|
||||
False & True \\ \hline
|
||||
\end{array}$
|
||||
|
||||
|
||||
Meaning, whatever is the case, just invert it.
|
||||
|
||||
### Examples
|
||||
|
||||
Discuss the following examples related to both arithmetic and logical operators.
|
||||
1. Given two scores, check if they made a 50 partnership i.e, their combined score is 50 or not.
|
||||
* a = 15, b = 30 -> False
|
||||
* a = 25, b = 25 -> True
|
||||
* a = 10, b = 60 -> False
|
||||
How to write the code for it in java?
|
||||
```
|
||||
a + b == 50
|
||||
```
|
||||
|
||||
Q. What type of operator are we using here?
|
||||
A. Relational Operator
|
||||
|
||||
2. Read 2 scores, check if both of them passes. The passing score is 35.
|
||||
* a = 35, b = 40 -> True
|
||||
* a = 34, b = 40 -> False
|
||||
* a = 50, b = 14 -> False
|
||||
|
||||
Q. How to check if a score is passed?
|
||||
A. Use the >= operator.
|
||||
|
||||
Q. How to check if both the scores are passed?
|
||||
A. Use the AND (&&) operator.
|
||||
|
||||
How to write the code for it in java?
|
||||
```
|
||||
a >= 35 && b >= 35
|
||||
```
|
||||
|
||||
3. Read 2 scores and check if atleast one of them passed. The passing score is 35.
|
||||
|
||||
Ask students to do it themselves.
|
||||
**Answer:**
|
||||
```
|
||||
a >= 35 || b >= 35
|
||||
```
|
||||
|
||||
**Note:** If students ask about the Logical NOT (!) operator, let them know that this will be discussed in unary operators section.
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Assignment Operators
|
||||
|
||||
It is used to assign value.
|
||||
They are : =, +=, -=, * =, /= etc.
|
||||
|
||||
```java
|
||||
int a = 10;
|
||||
a = a+5;
|
||||
System.out.println(a);
|
||||
```
|
||||
>Explanation: This will increase the value of a by 5.
|
||||
|
||||
Same thing can be done using "+=".
|
||||
```java
|
||||
int b = 10;
|
||||
b += 5; // increment the value of b by 5
|
||||
System.out.println(b);
|
||||
```
|
||||
|
||||
```java
|
||||
int c = 20;
|
||||
c -= 4; // decrement the value of c by 4
|
||||
System.out.println(b);
|
||||
```
|
||||
Similarly, /= and * = works
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
Q. What are unary operators?
|
||||
A. Unary operators work on a single operand only.
|
||||
|
||||
Give them a little bit idea of the following:
|
||||
* What are Pre operators -> ++a, --a
|
||||
* What are Post operators -> a++, a--
|
||||
|
||||
Run the following codes on IDE:
|
||||
```
|
||||
int a = 10;
|
||||
a ++ ;
|
||||
System.out.println(a);
|
||||
```
|
||||
|
||||
```
|
||||
int b = 10;
|
||||
++ b;
|
||||
System.out.println(b);
|
||||
```
|
||||
|
||||
Both the codes give 11 as output.
|
||||
Ask the students what is happening here, and why are we getting the same result.
|
||||
|
||||
Now, to show the difference, use the following codes.
|
||||
|
||||
```
|
||||
int a = 10;
|
||||
System.out.println(a ++ );
|
||||
```
|
||||
|
||||
```
|
||||
int b = 10;
|
||||
System.out.println( ++ b);
|
||||
```
|
||||
|
||||
The first code will give 10 as output, while the 2nd code gives 11 as output.
|
||||
To explain the reason for this behaviour, show them the following table and ask them to focus on the first 4 rows.
|
||||
|
||||
|
||||
$\begin{array}{|c:c:c:c:c:c|}
|
||||
\hline
|
||||
Operator & Name \\ \hline
|
||||
a++ & Post-Increment\ Operator \\ \hline
|
||||
++a & Pre-Increment\ Operator \\ \hline
|
||||
a-- & Post-Decrement\ Operator \\ \hline
|
||||
--a & Pre-Decrement\ Operator \\ \hline
|
||||
! & Logical\ Not\ Operator \\ \hline
|
||||
\end{array}$
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Coming back to the original question,
|
||||
|
||||
**Post-Increment**
|
||||
```
|
||||
int a = 10;
|
||||
System.out.println(a ++ );
|
||||
```
|
||||
|
||||
The last line is broken down into the following two lines.
|
||||
```
|
||||
System.out.println(a);
|
||||
a ++ ;
|
||||
```
|
||||
|
||||
**Pre-Increment**
|
||||
```
|
||||
int a = 10;
|
||||
System.out.println(++ a);
|
||||
```
|
||||
|
||||
The last line is broken down into the following two lines.
|
||||
```
|
||||
++a;
|
||||
System.out.println(a);
|
||||
```
|
||||
|
||||
Now, ask students if they can figure out the reason why the 1st code is printing 10, while the 2nd code is printing 11.
|
||||
|
||||
|
||||
Mention that similar is the case with pre-decrement and post-decrement operators.
|
||||
|
||||
# Examples
|
||||
|
||||
## Example 1
|
||||
```
|
||||
int a = 10;
|
||||
int b = 20;
|
||||
int c = a ++ + b ++ ;
|
||||
System.out.println(a + b + c);
|
||||
```
|
||||
|
||||
Ask the following questions along with explanation, wherever necessary.
|
||||
**Q.** What is the value of c?
|
||||
**A.** 30
|
||||
|
||||
**Q.** What is the current value of a after 3rd line?
|
||||
**A.** 11
|
||||
|
||||
**Q.** What is the current value of b after 3rd line?
|
||||
**A.** 21
|
||||
|
||||
**Q.** What will be the output?
|
||||
**A.** 62
|
||||
|
||||
|
||||
## Example 2
|
||||
```
|
||||
int a = 10;
|
||||
int b = a ++ + a ++ ;
|
||||
System.out.println(a);
|
||||
System.out.println(b);
|
||||
```
|
||||
|
||||
**Output:**
|
||||
```
|
||||
12
|
||||
21
|
||||
```
|
||||
|
||||
Explanation: First we will solve left "a++", that will give b = 10 + a++, and now a will be 11.
|
||||
Then again, we solve 2nd "a++", b = 10 + 11, and now a will be 12 after this.
|
||||
So, finally a = 12, b = 21.
|
||||
|
||||
Q. Suppose, we add the following statement in the above code, what would be the value of c?
|
||||
|
||||
```
|
||||
int c = b ++ ;
|
||||
```
|
||||
|
||||
A. There are 2 things happening -> Assignment and Post-Increment.
|
||||
But since its post-increment, we will use the value of b first, and then increment the value of b.
|
||||
So, value of c = 21.
|
||||
|
||||
Q. What if we add the following statement instead?
|
||||
|
||||
```
|
||||
int c = ++ b;
|
||||
```
|
||||
A. There are 2 things happening -> Assignment and Pre-Increment.
|
||||
But since its pre-increment, we will increment the value of b and then use the value of b.
|
||||
So, value of c = 22.
|
||||
|
||||
|
||||
## Example 3
|
||||
```
|
||||
int a = 10;
|
||||
int b = a-- ;
|
||||
System.out.println(a);
|
||||
System.out.println(b);
|
||||
```
|
||||
|
||||
**Output:**
|
||||
```plaintext
|
||||
9
|
||||
10
|
||||
```
|
||||
|
||||
Explain the reason for the above output accordingly if the students understood or not.
|
||||
|
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,412 @@
|
||||
# Problems on Arrays:
|
||||
|
||||
---
|
||||
|
||||
## Agenda
|
||||
|
||||
1. Count of Pairs with sum = K
|
||||
2. Elements having at least 1 element greater than it
|
||||
3. Given a mat[][] and row num, return sum of that row
|
||||
4. Given a mat[][] and col num, return sum of that col"
|
||||
5. Given two matrices and return sum of mat[][]
|
||||
6. Return an arraylist with all unique element
|
||||
7. Return unique of elements from every row
|
||||
|
||||
---
|
||||
|
||||
|
||||
#### Problem Statement
|
||||
Given an array arr and a value k, find the count of pairs (i, j) such that `arr[i] + arr[j] == k` where i != j.
|
||||
**Note 1:** i & j are indices of array.
|
||||
**Note 2:** (i, j) is the same as (j, i).
|
||||
|
||||
#### Example 1
|
||||
```cpp
|
||||
Input: arr = [2, 4, 2, 5, 1, 3], k = 6
|
||||
Output: 3
|
||||
```
|
||||
**Explanation:** Following pairs satisfy the condition-
|
||||
(0, 1) -> arr[0] + arr[1] = 2 + 4 = 6
|
||||
(1, 2) -> arr[1] + arr[2] = 4 + 2 = 6
|
||||
(3, 4) -> arr[3] + arr[4] = 5 + 1 = 6
|
||||
Hence, the answer is 3.
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Given ar[5] = {5 3 2 3 6} k = 8
|
||||
no of pairs (i , j) are there such that ar[i] + ar[j] = k ?
|
||||
|
||||
# Choices
|
||||
- [x] 3
|
||||
- [ ] 4
|
||||
- [ ] 5
|
||||
- [ ] 6
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Explanation
|
||||
|
||||
Following pairs satisfy the condition-
|
||||
(0, 1) -> arr[0] + arr[1] = 5 + 3 = 8
|
||||
(0, 3) -> arr[0] + arr[3] = 5 + 3 = 8
|
||||
(2, 4) -> arr[2] + arr[4] = 2 + 6 = 8
|
||||
Hence, the answer is 3.
|
||||
|
||||
---
|
||||
|
||||
|
||||
#### Solution 1
|
||||
|
||||

|
||||
|
||||
One way to solve this problem is to use a brute force approach, which involves checking every possible pair of elements in the array to see if their sum is equal to k. Here are the steps involved in this approach:
|
||||
* Initialize a variable count to 0 to keep track of the count of pairs.
|
||||
* Traverse the array arr using two nested loops, comparing each pair of elements in the array to see if their sum is equal to k.
|
||||
* Return count/2, since (i, j) & (j, i) are considered as same.
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
public static int countPairs(int[] arr, int k) {
|
||||
int count = 0;
|
||||
|
||||
for (int i = 0; i < arr.length; i++) {
|
||||
for (int j = 0; j < arr.length; j++) {
|
||||
if (i!=j && arr[i] + arr[j] == k) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count / 2;
|
||||
}
|
||||
```
|
||||
|
||||
#### Solution 2
|
||||
|
||||

|
||||
|
||||
If we notice, in the above solution we are counting (i, j) & (j, i) both. If we not consider one of the pair initially only, then it will not get added to the count. To achieve this, we will always start the inner loop from one index greater than the outer loop.
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
public static int countPairs(int[] arr, int k){
|
||||
int count = 0;
|
||||
|
||||
for (int i = 0; i < arr.length; i++){
|
||||
for (int j = i+1; j < arr.length; j++){
|
||||
if (arr[i] + arr[j] == k){
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Problem:
|
||||
Given a 2D array and a row index, return sum of that particular row.
|
||||
|
||||
|
||||
| 0 | 1 | 2 | 3 |
|
||||
|:--- | --- | --- | --- |
|
||||
| 1 | 2 | 3 | 4 |
|
||||
| 5 | 6 | 7 | 8 |
|
||||
| 9 | 10 | 11 | 12 |
|
||||
|
||||
row index =1,
|
||||
5 + 6 + 7 + 8, output=26
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Given a matrix, row index =0, return sum of that particular row.
|
||||
|
||||
```plaintext
|
||||
1 2 3 4
|
||||
5 6 7 8
|
||||
9 10 11 12
|
||||
```
|
||||
# Choices
|
||||
- [x] 10
|
||||
- [ ] 4
|
||||
- [ ] 26
|
||||
- [ ] 6
|
||||
|
||||
---
|
||||
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
static int rowSum(int[] mat, int i){
|
||||
int n = mat.length;
|
||||
int m = mat[0].length;
|
||||
|
||||
int sum=0;
|
||||
for (int j = 0; j < m; j++){
|
||||
sum=sum+mar[i][j];
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
```
|
||||
---
|
||||
|
||||
|
||||
### Problem:
|
||||
Given a 2D array and a column index, return sum of that particular column.
|
||||
|
||||
|
||||
| 0 | 1 | 2 | 3 |
|
||||
|:--- | --- | --- | --- |
|
||||
| 1 | 2 | 3 | 4 |
|
||||
| 5 | 6 | 7 | 8 |
|
||||
| 9 | 10 | 11 | 12 |
|
||||
|
||||
column index =2,
|
||||
3 + 7 + 11, output=21
|
||||
|
||||
Ask the students to do it yourself.
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Add two matrices
|
||||
Write a function to add two matrix of same dimension and return the resultant
|
||||
|
||||
#### Testcase 1
|
||||

|
||||
|
||||
#### Solution with explaination
|
||||
|
||||

|
||||
|
||||
* Matrix are of same dimension i.e. they have same number of rows and columns.
|
||||
* The values that are present at same row number and same column number in both matrix are to be added together inorder to get the resultant.
|
||||
* In above solution number with same colors are present at same row number and same column number in both matrix.
|
||||
* So inorder to get element at c[0][0] we add A[0][0] i.e 7 and B[0][0] i.e. 3 and so on.
|
||||
|
||||
#### Testcase 2
|
||||

|
||||
#### Solution
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Can we add a 3x4 matrix with a 3x4 matrix?
|
||||
|
||||
# Choices
|
||||
- [x] Yes
|
||||
- [ ] No
|
||||
- [ ] Maybe
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
|
||||
Can we add a 3x4 matrix with a 3x3 matrix ?
|
||||
|
||||
# Choices
|
||||
- [ ] Yes
|
||||
- [x] No
|
||||
- [ ] Maybe
|
||||
|
||||
---
|
||||
|
||||
|
||||
#### Observation
|
||||
* On oberserving both the cases we can give generalized formula for sum of matrix having same dimensions as:-
|
||||
|
||||
<div class="alert alert-block alert-warning">
|
||||
SumMat[i][j] = Mat1[i][j] + Mat2[i][j]
|
||||
</div>
|
||||
|
||||
|
||||
#### Code
|
||||
```java
|
||||
static int[][] addMatrix(int[][] A, int[][] B) {
|
||||
int m = A.length;
|
||||
int n = A[0].length;
|
||||
int[][] ans = new int[m][n];
|
||||
|
||||
for (int i = 0; i < m; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
ans[i][j] = A[i][j] + B[i][j];
|
||||
}
|
||||
}
|
||||
|
||||
return ans;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
#### Problem Statement
|
||||
Given an ArrayList of integers, return all the unique numbers in the ArrayList.
|
||||
|
||||
**Note:** An element with frequency 1 is known as unique element.
|
||||
|
||||
#### Example 1
|
||||
```java
|
||||
Input = 10 7 32 10 32 48 56 12 48 19 11 32
|
||||
Output = 7 56 12 19 11
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
ar[] = {6 10 8 2 8 10 11}
|
||||
Return all unique elements
|
||||
|
||||
# Choices
|
||||
- [x] 6 2 11
|
||||
- [ ] 6 2 10
|
||||
- [ ] 10 8 11
|
||||
- [ ] None of the above
|
||||
|
||||
---
|
||||
|
||||
|
||||
#### Solution
|
||||
Iterate on each element, check if frequency is 1 then add element to ans arrayList.
|
||||

|
||||
|
||||
|
||||
|
||||
|
||||
#### Pseudocode
|
||||
|
||||
```java
|
||||
static ArrayList<Integer> getUniqueNumbers(ArrayList<Integer> list) {
|
||||
ArrayList<Integer> ans = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
int num = list.get(i);
|
||||
int freq = 0;
|
||||
for (int j = 0; j < list.size(); j++) {
|
||||
if (num == list.get(j)) {
|
||||
freq++;
|
||||
}
|
||||
}
|
||||
if (freq == 1) {
|
||||
ans.add(num);
|
||||
}
|
||||
}
|
||||
|
||||
return ans;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Even numbers
|
||||
Given a 2D ArrayList, return a 2D ArrayList which contains unique elements from every row.
|
||||
|
||||
|
||||
#### Example 1
|
||||
```java
|
||||
A =[ [1, 2, 3, 4, 1],
|
||||
[5, 8, 7, 8, 8],
|
||||
[9, 4, 3, 2, 4] ]
|
||||
|
||||
ans= [ [2, 3, 4],
|
||||
[5, 7],
|
||||
[9, 3, 2] ]
|
||||
```
|
||||
|
||||
#### Example 2
|
||||
```java
|
||||
A = [ [3, 2],
|
||||
[2, 4] ]
|
||||
|
||||
ans= [ [3, 2],
|
||||
[2, 4] ]
|
||||
|
||||
```
|
||||
|
||||
#### Observation
|
||||
|
||||
We will traverse every element in ArrayList and insert unique elements in output.
|
||||
|
||||
#### Pseudocode
|
||||
```java
|
||||
public int freq(ArrayList<Integer>list,int k) {
|
||||
int count = 0;
|
||||
|
||||
for(int i=0; i < list.size();i++) {
|
||||
if(list.get(i) == k) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
public ArrayList<ArrayList<Integer>> solve(ArrayList<ArrayList<Integer>> A) {
|
||||
int n = A.size();
|
||||
int m = A.get(0).size();
|
||||
|
||||
ArrayList<ArrayList<Integer>>ans = new ArrayList<>();
|
||||
|
||||
for(int i=0; i < n;i++) {
|
||||
ArrayList<Integer>temp = new ArrayList<>();
|
||||
for(int j=0; j < m;j++) {
|
||||
int ele = A.get(i).get(j);
|
||||
if(freq(A.get(i),ele) == 1) {
|
||||
temp.add(ele);
|
||||
}
|
||||
}
|
||||
|
||||
ans.add(temp);
|
||||
}
|
||||
|
||||
return ans;
|
||||
}
|
||||
```
|
||||
---
|
||||
|
||||
### Problem:
|
||||
Given an array A of N integers.
|
||||
Count the number of elements that have at least 1 elements greater than itself.
|
||||
|
||||
### Example1:
|
||||
```java
|
||||
A = [3, 1, 2]
|
||||
```
|
||||
```java
|
||||
Output:
|
||||
2
|
||||
```
|
||||
|
||||
### Example 2:
|
||||
```java
|
||||
A = [-17, 15, 6, 3, 15, 7, -19, 15]
|
||||
```
|
||||
|
||||
```java
|
||||
Output:
|
||||
8-3 = 5
|
||||
```
|
||||
---
|
||||
|
||||
|
||||
TODO:
|
||||
|
||||
1. Find the max in array using 1 loop.
|
||||
2. Count the frequency of max in array using 1 loop.
|
||||
3. ans= total no of elements(ar.length)- count
|
||||
|
||||
---
|
||||
|
@@ -0,0 +1,379 @@
|
||||
# String Implementation
|
||||
|
||||
|
||||
---
|
||||
|
||||
1. Introduction to Characters
|
||||
2. ASCII Introduction
|
||||
3. Sum of digits in the string with characters and digits
|
||||
4. Replace all the characters 'x' with '$'
|
||||
5. Count uppercase and lower case characters
|
||||
6. Count number of characters of first string present in the second string
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
### Character:
|
||||
A character represent a single symbol.
|
||||
|
||||
There are different types of characters:
|
||||
* Uppercase characters : ['A' - 'Z']
|
||||
* Lowercase characters : ['a' - 'z']
|
||||
* Numeric characters: ['0' - '9']
|
||||
* Special characters: ['@', '#', '\$', '%', '&'...]
|
||||
|
||||
There are a total of 128 characters.
|
||||
|
||||
## Syntax
|
||||
|
||||
**Example 1:**
|
||||
```java
|
||||
char ch = 'a';
|
||||
System.out.println(ch);
|
||||
```
|
||||
**Output:**
|
||||
```plaintext
|
||||
a
|
||||
```
|
||||
|
||||
**Example 2:**
|
||||
```java
|
||||
char ch = 'ab';
|
||||
System.out.println(ch);
|
||||
```
|
||||
**Output:**
|
||||
```plaintext
|
||||
Error: Only a single symbol is a character.
|
||||
```
|
||||
---
|
||||
|
||||
|
||||
## Why do we need ASCII Codes?
|
||||
|
||||

|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
## ASCII Codes
|
||||
ASCII stands for **American Standard Code for Information Interchange.**
|
||||
|
||||
These codes are a standardized system of assigning a unique numeric value to each character in the English language and other common characters, such as punctuation marks and symbols.
|
||||
|
||||
|
||||
|
||||

|
||||
|
||||
|
||||
|
||||
|
||||
## Show the ASCII table in the class
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
#### Definition
|
||||
In programming, a string is a data type used to represent a sequence of characters.
|
||||
|
||||
#### Syntax
|
||||
The syntax for declaring and initializing a string variable in Java is:
|
||||
```java
|
||||
String str = "Hello World!"; // Double quotes are used to define a string
|
||||
```
|
||||
|
||||
|
||||
#### Example -
|
||||
```java
|
||||
String str = "How are you?"
|
||||
print(str) // How are you? will be printed
|
||||
```
|
||||
|
||||
#### Indexing
|
||||
String indexing starts from 0, where the first character is at index 0, the second character is at index 1, and so on.
|
||||
|
||||
**Example -**
|
||||
```java
|
||||
String str = "Hello, World!";
|
||||
System.out.println(str.charAt(0)); // Output: 'H'
|
||||
System.out.println(str.charAt(7)); // Output: 'W'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Properties of a String
|
||||
Some of the most commonly used properties of a string include:
|
||||
|
||||
* **Length:** The length() method of the String class returns the number of characters in a string. For example,
|
||||
```java
|
||||
String str = "Priyanshi";
|
||||
int n = str1.length(); // assigns 9 to variable n as str has 9 characters.
|
||||
System.out.println(str.length()); // 9
|
||||
```
|
||||
|
||||
* **Access a character:** The charAt(index) method of the String class returns the character at that index in a string. Indexing in string is same as that in array and starts from 0. For example,
|
||||
```java
|
||||
String str = "Priyanshi";
|
||||
System.out.println(str.charAt(5)); // output will be 'n'.
|
||||
```
|
||||
|
||||
* **Iterate a string:** We can iterate over the characters of a string using a loop. One way to do this is to use a for loop that iterates over the index positions of the string, and then use the charAt() method to retrieve the character at each position. For example,
|
||||
```java
|
||||
String str = "Priyanshi";
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
System.out.println(i + " -> " + str.charAt(i));
|
||||
}
|
||||
```
|
||||
|
||||
* **Update a string:** In Java, strings are immutable, meaning that their contents cannot be changed after they are created.
|
||||
* **Concatenating characters to String:** In Java, a character can be concatenated after a string by using the + or += operator, or through the concat() method, defined in the java. lang. String class.
|
||||
|
||||
```java
|
||||
// Concatentaion example
|
||||
|
||||
String s1 = "Hello";
|
||||
String s2 = s1 + "Everyone";
|
||||
System.out.println(s2); // Output will be "Hello Everyone"
|
||||
|
||||
|
||||
String s3 = "Hi";
|
||||
s3 = s3 + 'i';
|
||||
System.out.println(s3); // Output will be "Hii"
|
||||
|
||||
s3 = 'e' + s3;
|
||||
System.out.println(s3); // Output will be "eHii"
|
||||
|
||||
s3 = "Bye " + s3;
|
||||
System.out.println(s3); // Output will be "Bye eHii"
|
||||
```
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
#### Problem statement:
|
||||
Given a string s, you have to find the length of the longest word in the input string.
|
||||
|
||||
### Exanple 1:
|
||||
|
||||
Input:
|
||||
hi hello bye
|
||||
|
||||
Output:
|
||||
5
|
||||
|
||||
Explanation:
|
||||
In the sentence "hi hello bye", hello is the longest word, whose length is 5.
|
||||
|
||||
---
|
||||
|
||||
# Question
|
||||
Given string A, "coding is awesome"
|
||||
find the length of the longest word in the given string.
|
||||
|
||||
# Choices
|
||||
- [x] 7
|
||||
- [ ] 6
|
||||
- [ ] 5
|
||||
- [ ] I dont know
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Explanation
|
||||
|
||||
In the sentence "coding is awesome", awesome is the longest word, whose length is 7.
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
```java
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
String line = scanner.nextLine();
|
||||
|
||||
int maxLength = 0;
|
||||
int currentLength = 0;
|
||||
|
||||
for (int i = 0; i < line.length(); i++) {
|
||||
char currentChar = line.charAt(i);
|
||||
|
||||
if (currentChar != ' ') {
|
||||
currentLength++;
|
||||
} else {
|
||||
if (currentLength > maxLength) {
|
||||
maxLength = currentLength;
|
||||
}
|
||||
currentLength = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentLength > maxLength) {
|
||||
maxLength = currentLength;
|
||||
}
|
||||
System.out.println(maxLength);
|
||||
scanner.close();
|
||||
}
|
||||
```
|
||||
---
|
||||
|
||||
|
||||
### Problem
|
||||
Given a string A of length N and a character B, replace all occurrences of B in string A with character '@'.
|
||||
|
||||
**Input Format**
|
||||
|
||||
First line is String A
|
||||
Second line is Character B
|
||||
|
||||
**Example:**
|
||||
abcad
|
||||
a
|
||||
|
||||
**Output:**
|
||||
@bc@d
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Given string A,"interviewbit"
|
||||
String B= "i"
|
||||
replace all occurrences of B in string A with character '@'.
|
||||
|
||||
# Choices
|
||||
- [x] @nterv@ewb@t
|
||||
- [ ] i@terv@ewb@t
|
||||
- [ ] @ntervewb@t
|
||||
- [ ] I dont know
|
||||
|
||||
---
|
||||
|
||||
### Explanation
|
||||
|
||||
Modified string after Replacement of i at 1st, 7th, and 11th position is @nterv@ewb@t
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Idea:
|
||||
1. Initialization: Create an empty string result.
|
||||
2. Iterate: Loop through each character in the input string.
|
||||
3. Check and Replace: If the current character matches the target character, append '@' to the result; otherwise, append the current character.
|
||||
4. Final Result: Return the modified string (result).
|
||||
|
||||
|
||||
### Psuedo code
|
||||
```java
|
||||
static String replaceCharacter(String str, char targetChar) {
|
||||
String result = "";
|
||||
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
char currentChar = str.charAt(i);
|
||||
if (currentChar == targetChar) {
|
||||
result += '@';
|
||||
} else {
|
||||
result += currentChar;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
```
|
||||
---
|
||||
|
||||
|
||||
### Problem:
|
||||
Given a string, Count uppercase and lower case characters and print the values.
|
||||
|
||||
|
||||
### Example:
|
||||
String str="Hello World"
|
||||
|
||||
**Output:**
|
||||
Uppercase: 2
|
||||
Lowercase: 8
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# Question
|
||||
Given string ElePHant
|
||||
Count number of Uppercase character first, then lowercase characters.
|
||||
|
||||
# Choices
|
||||
- [ ] 3 lowercase<br>5 uppercase
|
||||
- [x] 3 uppercase<br>5 lowercase
|
||||
- [ ] 5 uppercase<br>9 lowercase
|
||||
- [ ] I dont know
|
||||
|
||||
---
|
||||
|
||||
|
||||
```java
|
||||
public static void main(String args[]) {
|
||||
Scanner scn = new Scanner(System.in);
|
||||
String str = scn.next();
|
||||
|
||||
int c1 = 0;
|
||||
int c2 = 0;
|
||||
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
char ch = str.charAt(i);
|
||||
|
||||
if (ch >= 'A' && ch <= 'Z') {
|
||||
c1++;
|
||||
} else if (ch >= 'a' && ch <= 'z') {
|
||||
c2++;
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println(c1);
|
||||
System.out.println(c2);
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Problem:
|
||||
|
||||
Count number of characters of first string present in the second string.
|
||||
|
||||
### Example:
|
||||
String A=abbd
|
||||
String B=aabb
|
||||
|
||||
Output:
|
||||
Number of common characters: 3(a,b,b)
|
||||
|
||||
### Pseudo Code
|
||||
|
||||
```java
|
||||
static int countCommonCharacters(String str1, String str2) {
|
||||
int count = 0;
|
||||
|
||||
for (int i = 0; i < str1.length(); i++) {
|
||||
char currentChar = str1.charAt(i);
|
||||
|
||||
for (int j = 0; j < str2.length(); j++) {
|
||||
if (currentChar == str2.charAt(j)) {
|
||||
count++;
|
||||
break; // Break the inner loop once a common character is found
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
```
|
||||
|
||||
------
|
Reference in New Issue
Block a user