Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to code a for loop so that it doesn't increment through a sequence?

Tags:

c#

I have this loop:

  for (int i = 1; i < 10; i++)

But instead I would like to have i for just numbers 1,2,4,5 and 7 and I will hardcode this.

Is there a way I can do this with something like an array?

like image 233
Alan2 Avatar asked Nov 13 '19 11:11

Alan2


People also ask

Can you increment i in a for loop?

A for loop doesn't increment anything. Your code used in the for statement does. It's entirely up to you how/if/where/when you want to modify i or any other variable for that matter.

Can the loop body of a for loop never get executed in Python?

No, the for loop will perform an exit condition in order to break the loop.


2 Answers

You could use an array to give the numbers you want like this

int[] loop = new int[] {1,2,4,5,7};
foreach(int i in loop)
    Console.WriteLine(i);

Or do it inline which is not as clean when the list of values grows in my opinion

foreach(int i in new int[] {1,2,4,5,7})
    Console.WriteLine(i);
like image 105
Joost K Avatar answered Oct 03 '22 10:10

Joost K


foreach (int i in new[] { 1, 2, 4, 5, 7 })
{

}
like image 26
Johnathan Barclay Avatar answered Oct 03 '22 08:10

Johnathan Barclay