Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Starting to reformat loops into a unified concept #2773

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 61 additions & 3 deletions concepts/loops/about.md
manumafe98 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
# About

In Java there are four looping constructs, two that are condition centric: `while` and `do-while` and the other two are iteration centric: `for` and `for-each`.
In Java there are four looping constructs, two that are iteration centric: [`For`] and [`For-each`] and the other two are condition centric: [`While`] and [`Do-while`].

## For

A for loop provides a mechanism to execute a group of statements repeatedly until some condition is met.
A for loop is a control flow statement that allows you to efficiently execute a block of code multiple times.
It achieves this repetition through a concept called iteration, where a variable (often called a loop counter) takes on different values within a specified range. This loop continues executing the code block until the iteration reaches its end.

```java
for (initialization; test; update) {
Expand All @@ -24,6 +25,7 @@ The `test` expression tests if the loop should end.
If it evaluates to `true`, the body and then the update expression will be executed.
If it evaluates to `false`, neither the body nor the update statement will be executed and execution resumes after the loop's closing bracket.
Typically it checks the variable assigned in the initialization block.

For example:

```java
Expand Down Expand Up @@ -55,7 +57,7 @@ square of 3 is 9
square of 4 is 16
```

If iterating through every element in a collection, a `for-each` loop is preferred, but it can be done with a `for` loop like this:
Iterating through every element in a collection is usually performed using a `for-each`, but it can be done with a `for` loop like this:

```java
for (int i = 0; i < array.length; i++) {
Expand Down Expand Up @@ -176,3 +178,59 @@ which outputs:
```text
1
```

## Break
manumafe98 marked this conversation as resolved.
Show resolved Hide resolved

The break statement acts as an "exit door" for a looping construct.
When encountered within the loop's body, `break` immediately terminates the loop's execution.

For example:

```java
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}

System.out.println(i);
}
```

which outputs:

```text
0
1
2
3
4
```

## Continue

The continue statement in the other hand acts similar to a "skip button" in a looping construct.
manumafe98 marked this conversation as resolved.
Show resolved Hide resolved
When encountered within a loop's body, `continue` skips the remaining statements in the current iteration.

For exmaple:

```java
for (int i = 0; i < 5; i++) {
if (i < 3) {
continue;
}

System.out.println(i);
}
```

which outputs:

```text
3
4
```

[`For`]: #for
[`For-each`]: #for-each
[`While`]: #while
[`Do-while`]: #do-while
179 changes: 3 additions & 176 deletions concepts/loops/introduction.md
manumafe98 marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whoa, I know I said to trim down the contents of the introduction but I think we need to give at least some information 😂

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤣 What do you suggest to add then ? hahaha

Original file line number Diff line number Diff line change
@@ -1,178 +1,5 @@
# Introduction

In Java there are four looping constructs, two that are condition centric: `while` and `do-while` and the other two are iteration centric: `for` and `for-each`.

## For

A for loop provides a mechanism to execute a group of statements repeatedly until some condition is met.

```java
for (initialization; test; update) {
body;
}
```

The `initialization` sets an initial state for the loop and is executed exactly once at the start of the loop.
Typically it declares and assigns a variable used in the test expression and update statement.
For example:

```java
int i = 1
```

The `test` expression tests if the loop should end.
If it evaluates to `true`, the body and then the update expression will be executed.
If it evaluates to `false`, neither the body nor the update statement will be executed and execution resumes after the loop's closing bracket.
Typically it checks the variable assigned in the initialization block.
For example:

```java
i <= 10
```

After executing the loop body, the `update` expression is executed.
Typically it increments or decrements the loop variable by some value.
For example:

```java
i++
```

A `for` loop printing out the first four squares would look like this:

```java
for (int i = 1; i <= 4; i++) {
System.out.println("square of " + i + " is " + i * i);
}
```

The output would be:

```text
square of 1 is 1
square of 2 is 4
square of 3 is 9
square of 4 is 16
```

If iterating through every element in a collection, a `for-each` loop is preferred, but it can be done with a `for` loop like this:

```java
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
```

A `for` loop does have some advantages over a `for-each` loop:

- You can start or stop at the index you want.
- You can use any (boolean) termination condition you want.
- You can skip elements by customizing the incrementing of the loop variable.
- You can process collections from back to front by counting down.
- You can use `for` loops in scenarios that do not involve collections.

## For-each

A for-each loop provides a mechanism for executing a block of code for each element in a collection.

```java
for (declaration: collection) {
body;
}
```

The `declaration` declares the variable used to hold the values assigned from the collection.

The `collection` is an array or collection holding the values that will be assigned to the loop variable.

The `body` contains the statements that will be executed once for each value in the collection.

For example:

```java
char[] vowels = {'a', 'e', 'i', 'o', 'u'};

for(char vowel: vowels) {
System.out.println(vowel);
}
```

which outputs:

```text
a
e
i
o
u
```

Generally a `for-each` loop is preferrable over a `for` loop for the following reasons:

- A `for-each` loop is guaranteed to iterate over _all_ values.
- A `for-each` loop is more _declarative_ meaning the code is communicating _what_ it is doing, instead of _how_ it is doing it.
- A `for-each` loop is foolproof, whereas with `for` loops it is easy to have an off-by-one error (think of using `<` versus `<=`).
- A `for-each` loop works on all collection types, including those that do not support using an index to access elements (eg. a `Set`).

## While

The `while` loop continually executes a block of statements while a particular condition is true.

```java
while (condition) {
body;
}
```

The `condition` It's a statement that can be true or false. As long as the condition is true, the loop keeps running.
The `body` it's the code that gets executed repeatedly until the condition becomes false.

For example:

```java
int counter = 1;

while (counter <= 5) {
System.out.println(counter);
counter++;
}
```

which outputs:

```text
1
2
3
4
5
```

Generally good rule of thumb is to use a `while` loops when you don't know exactly how many times you need to loop beforehand.

## Do-while

As `while` loops `do-while` loops are condition centric loops, but unlike a regular `while` loop, a `do-while` loop guarantees that the code inside the loop will run at least once, no matter what.

```java
do {
body;
} while (condition);
```

For example:

```java
int counter = 1;

do {
System.out.println(counter);
counter++;
} while (counter < 2);
```

which outputs:

```text
1
```
Programming is full of tasks that need to be done over and over again.
To handle these repetitive actions efficiently, Java offers special control flow statements called looping constructs.
This concept will guide you through exploring these constructs and how to use them to your advantage.
13 changes: 12 additions & 1 deletion exercises/concept/making-the-grade/.docs/hints.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

## 2. Get the average grade of students

- Try using one of the loops that is condition centric using numberOfStudents as one of the core conditions.
- Try using one of the loops that is condition centric using `numberOfStudents` as one of the core conditions.

## 3. Calculating letter grades

Expand All @@ -15,3 +15,14 @@
## 4. Matching Names to Scores

- Try using a iteration centric loop that allow you to work with indexes.

## 5. Count Odd Scores

- Remember that you could use the modulus operator `%` to check if a division has a certain reminder.
- Try using a iteration centric loop
- Check the statements/keywords covered in the concept an use one of them.

## 6. Challenging Exam

- Try using a iteration centric loop
- Check the statements/keywords covered in the concept an use one of them.
29 changes: 28 additions & 1 deletion exercises/concept/making-the-grade/.docs/instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ MakingTheGrade.countFailedStudents(List.of(40, 70, 80, 20, 39));

As your second task of the day the professor asks you to get the average score of a certain number of students.

Create the method `getAverageScoreOfStudents(List<Integer> studentScores, int numberOfStudents)` that takes a `List<Integer>` of studentScores and a `int` of numberOfStudents. This method should get the average score of the number of students passed. numberOfStudents it's guaranteed to be lower than the size of the list of scores.
Create the method `getAverageScoreOfStudents(List<Integer> studentScores, int numberOfStudents)` that takes a `List<Integer>` of studentScores and a `int` of numberOfStudents.
This method should get the average score of the number of students passed.
The number of students is guaranteed to be lower than the size of the list of scores.

```java
MakingTheGrade.getAverageScoreOfStudents(List.of(40, 70, 80, 20, 39, 50, 100, 90, 66, 15, 79), 10);
Expand Down Expand Up @@ -58,3 +60,28 @@ List<String> studentNames = List.of("Joci", "Sara", "Kora", "Jan", "John", "Bern
MakingTheGrade.studentRanking(studentScores, studentNames);
// => ["1. Joci: 100", "2. Sara: 99", "3. Kora: 90", "4. Jan: 84", "5. John: 66", "6. Bern: 53", "7. Fred: 47"]
```

## 5. Count Odd Scores

As an investigation, the principal asked the teacher to count how many scores of the math exam result being odd scores, and since you want to help him handle it efficiently.

We are going to create the method `countOddScores(List<Integer> studentScores)` with the parameter `List<integer>` of studentScores.
This method should count up the number of odd students scores and return that count as an integer.

```java
MakingTheGrade.countOddScores(List.of(20, 35, 40, 10, 39, 77));
// => 3
```

## 6. Challenging Exam

The teacher has prepared a challenging exam and wants to analyze the results. As his assistant you'll evaluate the exams in the same order students handed them in. The teacher is particularly interested in knowing how many students passed the exam before the first non-passing student.
manumafe98 marked this conversation as resolved.
Show resolved Hide resolved
As you know a student needs a score greater than **40** to achieve a passing grade on the exam.

Create the method `evaluateChallengingExam(List<Integer> studentScores)` that takes a `List<Integer>` of students scores in the handed order.
This method should count up the number of passing student scores until the first non-passing score and return that count as an integer.

```java
MakingTheGrade.evaluateChallengingExam(List.of(45, 90, 15, 100, 70));
// => 2
```
Loading