DEV Community

Rattanak Chea
Rattanak Chea

Posted on • Updated on

For Loop in different programming languages

Programming often involves working on redundant tasks. The for loops help shorten the code and reduce tedious tasks. But the way for is used can be different for different languages. This post aims to provide some for loop examples for Java, Javascript and PHP working on String, Array, and Object.

Loop a String

Java

String str = "hello";
for (int i=0; i < str.length(); i++){
    System.out.print(str.charAt(i));
}
//another less optimal solution is to convert the str into an char array
//using str.toCharArray();
//see loop an Array section in Java below
Enter fullscreen mode Exit fullscreen mode

Note:
length() and charAt(index) are methods of String object class.

JavaScript

var str = "hello";
for (var i=0; i < str.length; i++){
    console.log(str.charAt(i));
}
Enter fullscreen mode Exit fullscreen mode

Note:
In JavaScript, we can declare string in two ways:

var str1 = 'primitive';  //datatype is primitive: string
var str2 = new String('string object');  //string as object
Enter fullscreen mode Exit fullscreen mode

Since primitive has no methods and property, str1 was autoboxed to wrapper class String (as in s2). Then str1 becomes a String object with length as property and charAt as its method, and so on.

PHP

It is not as simple as Java, and JavasScript looping a string. One way is to convert the string to an array, then we can loop that array. Another way to use helper method, substr() to get each character of the string.

//method 1: use for loop
for($i=0; $i < count($array); $i++){
    echo $array[$i];
}

//method 2: convert a string to an array first, then we can loop the array
//use str_split() function to split a string by character
$str = "hello";
$array = str_split($str);  //split by character into an array
foreach($array as $value){
    echo $value;
}


Enter fullscreen mode Exit fullscreen mode

Loop an Array

Java

int[] nums = new int[5];
for (int i=0; i < nums.length; i++){
    nums[i] = i; }
    System.out.print(Arrays.toString(nums)); //[0, 1, 2, 3, 4]
    //or use for (:) as for each loop
for(int i : nums){
    System.out.print(i);  //01234
}
//you may compare for(:) loop with foreach loop in PHP and other language.
Enter fullscreen mode Exit fullscreen mode

Note: An array is a container object with a fixed size. The length of an array is established when the array is created. Array has a length property instead of length method in Object. In fact, length is a public final field of Array.
Read more here Chapter 10. Arrays (http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.7)

Javascript

var nums = ["hi", "hello", "you"];
//sequential loop
for (var i=0; i < nums.length; i++){
    console.log(num[i]));   //hihelloyou
}
Enter fullscreen mode Exit fullscreen mode

Note: javascript has another loop for-in which is commonly used in Javascript object loop.

var obj = {  "a": 1,  "b": 2,  "c": 3};
for (var prop in obj) { 
  if (obj.hasOwnProperty(prop)) {
// or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety..
     alert("prop: " + prop + " value: " + obj[prop])  }
}
Enter fullscreen mode Exit fullscreen mode

Read more: Loop through array in JavaScript (http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript)

Loop an Object

Java

In Java, to loop an array of objects, we can use sequential loop or iterator or for (:) loop ##

ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
Iterator<String> itr = list.iterator();
while(itr.hasNext()){
    //do something with itr.next();
    //for example itr.remove();
}
Enter fullscreen mode Exit fullscreen mode
//using foreach loop
for( String s : list){
    //do something with s
    // s is local String variable
    //modify s does not modify the list
}
Enter fullscreen mode Exit fullscreen mode

PHP

In PHP, loop an object use foreach loop like in array.

foreach ($objects as $obj){
    echo $obj->property;
}
//or below
foreach ($obj as $key => $value) {
    echo "$key => $value\n";
}
Enter fullscreen mode Exit fullscreen mode

References
What is the difference between string literals and String objects in JavaScript? (http://stackoverflow.com/questions/17256182/what-is-the-difference-between-string-literals-and-string-objects-in-javascript)

str_split - Manual (http://us.php.net/str_split)
Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics) (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)

Top comments (29)

Collapse
 
ben profile image
Ben Halpern

Love the apples-to-apples comparison.

Here's Ruby:

for num in 0..max_num do
   puts "The number is #{num}"
end

But in practice, nobody uses for loops.

Here's a while:

while num < max_num  do
   puts("The number is #{num}" )
   num +=1
end

But nobody uses those either.

People are way more likely to do

(0..max_num).each do |num|
   puts "The number is is #{num}"
end

Or using a collection of objects, like an array or an ActiveRecord collection.

pizza_toppings.each do |topping|
   puts "The topping is #{topping.name}"
end
Collapse
 
rattanakchea profile image
Rattanak Chea

Thank you for adding Ruby syntax. This post was written a few year ago when I found myself always scrambling to write loop when working with different programming languages. Nowadays, a functional programming approach is preferable. I love Python and Ruby for their clean syntax.

Collapse
 
rattanakchea profile image
Rattanak Chea

Do you mind if I include your Ruby code into the post? I will put credit where it belongs.

Collapse
 
ben profile image
Ben Halpern

Go for it. And no need to credit if it effects the reading in any way. 🙂

Collapse
 
hjfitz profile image
Harry

There's a few other ways to iterate in JavaScript:

for-of

const array = [1,2,3];
for (const num of array) {
  console.log(num);
}

forEach

const array = [1,2,3];
array.forEach(num => {
  console.log(num);
};
// or
array.forEach(console.log);

Functional programming - map

const array = [1,2,3];
array.map(console.log);
Collapse
 
hjfitz profile image
Harry • Edited

Note: forEach(console.log) will print the item, index and the array - developer.mozilla.org/en-US/docs/W...

Array#forEach((item, index, array) => { /*...*/ })
Collapse
 
kind_wizzard profile image
Unknown

There is no need to use breckets in lambda:

const array = [1,2,3];
array.forEach(num => console.log(num));
Collapse
 
antjanus profile image
Antonin J. (they/them)

Here's one for Go:

myStr := "My string"

for i := 0; i < len(myStr); i++ {
  fmt.Printf("%c", myStr[i])
}

You can also use a while loop:

for _, char := range myStr {
  fmt.Printf("%c", char)
} 

Note how a "while loop" is basically the same as a for loop.

Collapse
 
living_syn profile image
Jeremy Mill

Or in rust

let my_str = "Hello World!";    
for c in my_str.chars() { 
    print!("{}",c);
}
Collapse
 
dmulter profile image
David Multer

In Python, this:

for num in range(max_num):
    print "The number is {}".format(num)

or this:

print '\n'.join(["The number is {}".format(num) for num in range(max_num)])
Collapse
 
louissaglio profile image
Louis-Saglio

It's why i use Python.

Collapse
 
danmatakizawa profile image
Dan Ross • Edited

Your PHP string foreach example seems wrong - PHP strings can be referenced like an array. The following works on PHP, for example.

$str = "hello";
for($i = 0; $i < strlen($str); $i++){
    echo $str[$i];
}
Collapse
 
rattanakchea profile image
Rattanak Chea

I did include that too, but it was down. Now i moved it to the top. Thanks man.

Collapse
 
everton profile image
Everton Agner • Edited

Let's be fair with Java. The language has seen quite a few enhancements since Java 8 release, 3 years ago, and very recently on Java 9, both on API and syntax. Now using the new stuff...

Loop a string:

String str = "hello";
str.chars() // Produces a stream of integers... yeah, that's odd
    .mapToObj(i -> (char) i) // Now we have a stream of chars
    .forEach(System.out::println);

Loop a collection:

List<String> list = List.of("a", "b");
list.forEach(System.out::println);
Collapse
 
ssalka profile image
Steven Salka

Nice post! When working with JavaScript/TypeScript, I usually go for the forEach array method, which is pretty convenient for usage with functions:

const fruit = ['apple', 'banana', 'orange'];

fruit.forEach(console.log);
// apple
// banana
// orange

If using a library like lodash, you can also iterate over objects (though iteration order is not guaranteed):

const funcs = {
  square: x => x ** 2,
  abs: x => Math.abs(x),
  reciprocal: x => 1 / x
};

_.forEach(funcs, (fn, fnName) => {
  console.log(`${fnName}(-2) = ${fn(-2)}`);
});
// square(-2) = 4
// abs(-2) = 2
// reciprocal(-2) = -0.5
Collapse
 
miffpengi profile image
Miff • Edited

Here's the ways to loop a string and an array in C# with a for loop, they're pretty much the same as any other language.

    string str = "hello";
    for (int i = 0; i < str.Length; i++){
        Console.WriteLine(str[i]);
    }

    int[] nums = new int[5];
    for (int i = 0; i < nums.length; i++){
        nums[i] = i;
        Console.WriteLine(i);
    }

However, C# really likes iterators, so those tasks are most commonly done with a foreach loop.

    string str = "hello";
    foreach (char c in str){
        Console.WriteLine(c);
    }

    foreach (int num in Enumerable.Range(0, 5)){
        Console.WriteLine(num);
    }

    // Borrowing from Ben Halpern's example for looping over a collection
    foreach (var topping in pizzaToppings){
        Console.WriteLine("The topping is {0}", topping.Name);
    }
Collapse
 
lobsterpants66 profile image
Chris Shepherd

Then resharper tells you that you can replace that with one line of linq... if my experience is anything to go by 😀

Collapse
 
dimpiax profile image
Dmytro Pylypenko • Edited

Swift 2, 3, 4:

// 1
for index in 0..<9 {
    print(index)
}

// 2
(0..<9).forEach { index in
    print(index)
}

// 3
let arr = ["foo", "bar"]
for (index, value) in arr.enumerated() {
    print("index: \(index), value: \(value)")
}
Collapse
 
rattanakchea profile image
Rattanak Chea

I never learn/write Swift. Look interesting. Thanks for sharing.

Collapse
 
codemouse92 profile image
Jason C. McDonald

Very nice, but it's missing my favorite, C++!

std::string str = "hello";
for (int i=0; i < str.length(); ++i)
{
    std::cout << str[i] << std::endl;
}

Note I'm using the prefix increment in my for loop, for pedantic (and habitual) performance reasons. (In reality, your compiler usually optimizes this itself.)

Given more time later, I'll come back and add the other two.

Collapse
 
khophi profile image
KhoPhi

I built a website ago just to keep how different programming languages approach concepts in their different ways.

Like the Fibonacci in 6 languages: code.khophi.co/codes/-KL7i0Vj9WSsh...

code.khophi.co

Collapse
 
rattanakchea profile image
Rattanak Chea

I checked it out. That's a good idea. Keep it up.

Collapse
 
thomas_graf profile image
Thomas Graf • Edited

Java 9 IntStream has a new static method:

iterate​(int seed, IntPredicate hasNext, IntUnaryOperator next)

IntStream.iterate(0, i -> i < 10, i -> i + 1)
            .forEach(System.out::println)

is equivalent to the following for-i loop, but more in a functional style

for(int i = 0; i < 10; i++) {
    System.out.println(i);
}
Collapse
 
inessosa95 profile image
Inés Sosa • Edited

Here's in Smalltalk:

'Hello' do: [:each | Transcript show: each ]

this works for collections, strings, and objects all the same :D

Collapse
 
rattanakchea profile image
Rattanak Chea • Edited

Awesome. One size fits all. :-)

Collapse
 
inessosa95 profile image
Inés Sosa

The wonders of dynamically typed languages 😊

Collapse
 
sayopaul profile image
Sayo Paul

PHP code doesn't have syntax highlighting though 😀

Collapse
 
rattanakchea profile image
Rattanak Chea

I guess it is not support here yet. That's not fair for PHP. :-)

Collapse
 
ben profile image
Ben Halpern

I'm not quite sure why that is. Definitely looking into it.