array - initialisierung - ausgabe



  • Hi Leute!

    Ich hab folgendes Programm geschrieben, das mir folgendes Muster ausgibt:

    +-+-+-+-+-+-+-+
    | | | | | | | |
    +-+-+-+-+-+-+-+
    | | | | | | | |
    +-+-+-+-+-+-+-+
    | | | | | | | |
    +-+-+-+-+-+-+-+
    | | | | | | | |
    ...
    

    Der Code macht zwar genau das was er soll, aber bestimmt auf eine sher umständliche art und weise. kann man das verinfachen?

    void array_init(char array[14][15])
    {
    	int i, j, y, x;
    	char zahl = '1';
    
    	y = 0;
    	x = 0;
    	for(i=0; i<7; i=i+1)
    	{
    		array[y][x] = ' ';
    		x = x + 1;
    		array[y][x] = zahl;
    		zahl = zahl + 1;
    		x = x + 1;
    		array[y][x] = ' ';
    	}
    
    	y = 1;
    	x = 0;
    	for(i=0; i<7; i=i+1)
    	{
    		for(j=0; j<7; j=j+1)
    		{
    			array[y][x] = '+';
    			x = x + 1;
    			array[y][x] = '-';
    			x = x + 1;
    			array[y][x] = '+';
    		}
    		y = y + 1;
    		x = x + 1;
    	}
    
    	y = 2;
    	x = 0;
    	for(i=0; i<6; i=i+1)
    	{
    		for(j=0; j<7; j=j+1)
    		{
    			array[y][x] = '|';
    			x = x + 1;
    			array[y][x] = ' ';
    			x = x + 1;
    			array[y][x] = '|';
    		}
    		y = y + 1;
    		x = x + 1;
    	}
    }
    

    Wie würdet ihr das besser machen?



  • Vielleicht so:

    int main()
    {
        const char* fst = "+-+-+-+-+-+-+-+";
        const char* snd = "| | | | | | | |";
        const int lines = 9;
        const char* line;
        int i;
    
        for(i=0;i<lines;++i)
        {
            if(!(i & 1))
                line = fst;
            else
                line = snd;
            puts(line);
        }
        return 0;
    }
    


  • danke für deine hilfe!


  • Mod

    Wie immer gilt: Suche Hilfe in der Abstraktion: Schreibe eine Funktion die dir ein beliebiges Raster initialisiert. Der Code wird dann von ganz alleine einfacher.



  • Übrigens lässt sich a = a + 1 auch als a++ schreiben.


Anmelden zum Antworten