How this Java for loop should look like in pseudocode?

20,612

Solution 1

PseudoCode can be whatever you want. Since you or other people can understand what the lines mean.

You can turn it simple as FOR (your variable value start) TO (your end desired) i++ -

Basically something that makes people and you mostly understand that it is a For Loop

Solution 2

For example:

getNonDup(listA, listB):
    nonDup = listA + listB
    dup    = an empty list
    for each object i in listB do:
        if listA contains i do:
            add i to dup
            remove i from nonDup
    return nonDup

(my pseudocode style is somehow similar to Python...)

In Java, to have only unique values, you can simply put all of them in a set:

Set<Integer> nonDup = new HashSet<Integer>(listA.addAll(listB));

Solution 3

It's just plain English:

Initialize "check" as an empty (array-backed) list of integers.
Initialize "dup" as an empty (array-backed) list of integers.
Initialize "nonDup" as an empty (array-backed) list of integers.

For each integer in listA:
    Add the integer to "nonDup".
End of loop.

For each integer in listB:
    Add the integer to "nonDup".
End of loop.

For each integer in listA:
    Add the integer to "check".
End of loop.

For each integer in listB:
    If "check" contains the integer:
        Add the integer to "dup".
        Remove all integers in "dup" from "nonDup".
    End of if.
End of loop.

Normally you don't need to bother with pseudocodes. They really don't have much use (other than bragging rights... I mean, helping your peers understand your code) and they are not executable.

Solution 4

How about something like this:

for each element in list A
    add element to list nonDup

Its basically just plain text which can be read by anyone. You could choose more speaking names for the variables. You could also choose begin loop and end loop to show the scope of the loop instead of indentication.

Share:
20,612
user3116280
Author by

user3116280

Updated on July 18, 2022

Comments

  • user3116280
    user3116280 almost 2 years

    How should I proceed to turn this piece of code into pseudocode?

    ArrayList<Integer> check = new ArrayList<Integer>();
    ArrayList<Integer> dup = new ArrayList <Integer> ();
    ArrayList<Integer> nonDup = new ArrayList <Integer> ();
    
    for (int i : listA) {
        nonDup.add(i);
    }
    for (int i : listB) {
        nonDup.add(i);
    }
    for (int i : listA) {
        check.add(i);
    }
    for (int i : listB) {
        if (check.contains(i)) {
            dup.add(i);
            nonDup.removeAll(duplicates);                   
        }
    }
    

    I have no idea how to turn the for loops, add(), contains() and removeAll() methods into pseudocode.