Examples of Algorithms: Part 1
Explore how to apply algorithms in Java through practical coding examples. Learn to count specific elements in data, perform iterative arithmetic operations, and sort arrays. This lesson helps build foundational problem-solving techniques using algorithms in Java programming.
We'll cover the following...
Coding example: 69
In this example, we have an input like 1122322 and we will try to find how many times 2 appears in this number.
Coding example: 70
The following example is easier than the one before. We will raise the value of 1 by adding 3. And this iteration will stop when the number of steps is less than 5.
Code explanation
The loop starts from 1, as usual. After that, it starts to increment the value by 3 and stops after incrementing four times.
Coding example: 71
In the following example, let’s do some weird things like taking an array of values from the user and sorting them in ascending order. If you want to rerun the code, write java main in the terminal:
/*
Enter any number of array elements and get them in ascending order
*/
import java.util.Scanner;
public class main {
public static void main(String[] args)
{
int count, temp;
//User inputs the array size
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of elements you want in the array: ");
count = scan.nextInt();
int num[] = new int[count];
System.out.println("Enter array elements:");
for (int i = 0; i < count; i++)
{
num[i] = scan.nextInt();
}
scan.close();
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++) {
if (num[i] > num[j])
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
System.out.print("Array Elements in Ascending Order: ");
for (int i = 0; i < count - 1; i++)
{
System.out.print(num[i] + ", ");
}
System.out.print(num[count - 1]);
}
}Code explanation
Try to read the code and then write it from your memory. While doing so, follow the logical steps that we maintained in the code.