How do i use foreach/for loops properly?

Hello, I’m currently starting to expand my skills in the gui side of scripting, I’ve seen that foreach/for loops can be used to give each i in a list the same property or do something * the amount of things in the list,
but how do i use it properly? the script at the bottom of this thread currently loops forever, do i have to move it to its own function or perhaps add a bool? so it only loops when the bool is true? any help would be greatly appreciated, thanks!
the script

     Delcaring
	public Rect slotRect;					
	public Rect slotRectoffset;
	public List<string> TestList= new List<string>();


void start
TestList.Add("0");
TestList.Add("1");

	void OnGUI() 
foreach(string i in TestList)
{
             GUI.Button (new Rect (slotRect.x + slotRectoffset.x, slotRect.y + slotRectoffset.y, slotRect.width, slotRect.height), i);
			slotRectoffset.x += 50;

}

The code posted has some errors (“start” instead of “Start()”, curly brackets missing in Start and OnGUI), but the basic problem is that slotRectoffset is being incremented every OnGUI, thus the button will move horizontally every frame. You should reset the offset before the foreach, so that the buttons would be placed in the right places every time - like this:

public Rect slotRect;            
public Rect slotRectoffset;
public List<string> TestList= new List<string>();

void Start(){ // enclose the whole function in curly brackets
    TestList.Add("0");
    TestList.Add("1");
}

void OnGUI(){
    float offsetX = slotRectoffset.x; // reset the offsets every OnGUI
    float offsetY = slotRectoffset.y;
    foreach(string i in TestList){
        GUI.Button (new Rect (slotRect.x + offsetX, slotRect.y + offsetY, slotRect.width, slotRect.height), i);
        offsetX += 50;
    }
}