Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats possible in a for loop

So today I went to an interview and one of the questions was the following (C# context).

//Print the output for the following code:
for (int i = 10, j = 0; j <= 10; j++, i--)
{
    if (i > j)
        Console.WriteLine(j.ToString());
}

I have never seen such a construct before and having asked my colleagues, 4 of 5 at my workplace didn't know either (Perhaps more a reflection on us but I digress). Using some basic logic, I was able to answer the question correctly but this knowledge has radically altered my understanding of how for loops can be structured.

So I guess my question boils down to this.

  1. Do all C syntax based languages implement this functionality? IE: C, C++, Java, javascript etc.
  2. Where does this syntax stem from?
  3. Are there any other "not well known" structures that a for loop can take?
  4. Is writing code like above considered bad practice given how hard it is to read?
  5. Are there any good real world examples where such a structure is required?
like image 497
Maxim Gershkovich Avatar asked Jun 02 '11 07:06

Maxim Gershkovich


3 Answers

for (statement1; statement2; statement3)
{
     /* body */
}

(1) First the statement1 is executed.

(2) Next statement2 is executed.

(3) If the evaluation of statement2 is true then the body is executed

(4) Then statement3 is executed.

(5) Repeat from step (2)

          |                  +<-----------------+
          |                  |                  ^
          V                  V                  |
 for (  (s1); -------->(s2 true? | false?);    (s3) )
 {                           |       |          ^
                             |       |          |
                             |       |          |
                             V       |          |
                          (body)-----|--------->+
 }                                   |
                                     |
                                     V
                                 (come out)

The structure you have shown is the same normal structure as above. The statement n could be any statement. In your example, you have separated by comma operators in statement1 and statement3. You can separate any number of statements by comma operators.

Generally for loops are used with the statement1 with initialization as it is executed only once. The statement2 is used for the loop termination condition checking, because the evaluation value of this statement is used to decide if to enter the body of break out. And the statement3 is used for update of the loop termination variable as it is executed after the body. But generally they could be used in any way.

First statement1 is i=10, j=0; this initializes the variables. Next in the statement2 is j <= 10 if this is true then the body is executed. After the body is executed, statement3 which is i--,j++ is executed. The loop will iterate 11 times 0 to 10. But will print 5 times, as at one point i and j will become same and the if (i > j) will evaluate false.

EDIT Here is an example where it might be used, not much practical but a sample use, to check for a palindrome string.

  int i, j, n, flag;
  char str[128];

  printf ("\nEnter string: ");
  scanf ("%s", &str);
  n = strlen (str);


for (flag=1, i=n-1, j=0; j<n/2; j++, i--)
{
  if (str[i] != str[j])
  {
    flag = 0;
    break;
  }
}

if (flag)
 printf ("\n\"%s\" is a palindrome");
else
 printf ("\n\"%s\" is not a palindrome");

We should always try to write code which is easy to read and which does not create confusion. This helps the code writer as well as others who read the code.

like image 131
phoxis Avatar answered Sep 23 '22 22:09

phoxis


  1. Java & C# both share this same syntax
  2. The syntax probably stems from C/C++ which is the 'root' of Java & C#
  3. Yes, you can also have zero initializers and end conditions for your for loop.
  4. Whether or not it is bad practice really depends on how it is used. You can create quite cryptic code using this technique, however, it does not mean that when used correctly it is perfectly acceptable.
  5. I doubt it!
like image 43
ColinE Avatar answered Sep 21 '22 22:09

ColinE


In C and Java for loops you may specify an unlimited (or zero) number of comma separated initialisers (of the same data type) and end-of-loop actions.

The initializer section is really just one java statement; java variable definitions may be grouped if they are of the same type, ie:

int i = 0;
int j = 0;

is equivalent to:

int i = 0, j = 0;

You can do what you like in the end-of-loop section - any number of statements separated by commas.

Since java 5, there is also the foreach syntax, eg:

List<String> list;
for (String element : list) {
    // do something with the variable element
}

The syntax works with Iterable types, which includes arrays and Collections.

like image 40
Bohemian Avatar answered Sep 23 '22 22:09

Bohemian