Pętla while + tablica

0

Cześć.
Mam program z pętlą for i muszę go przerobić, aby działał tak samo jednak zastosować pętlę while.
Nie wiem jak to naprawić, żeby mi nie wywalało po za tablicę.
Wersja początkowa:

public static void Main()
{
int[][] tab = new int[4][];
tab[0] = new int[4];
tab[1] = new int[3];
tab[2] = new int[2];
tab[3] = new int[1];
int licznik = 1;
for(int i = 0; i < tab.Length; i++)
{
for(int j = 0; j < tab[i].Length; j++)
{
tab[i][j] = licznik++;
}
}
for(int i = 0; i < tab.Length; i++)
{
Console.Write("tab[{0}] = ", i);
for(int j = 0; j < tab[i].Length; j++)
{
Console.Write("{0} ", tab[i][j]);
}

Moje wypociny:

    public static void Main()
    {
        int[][] tab = new int[4][];
        tab[0] = new int[4];
        tab[1] = new int[3];
        tab[2] = new int[2];
        tab[3] = new int[1];

        int licznik = 1, i = 0, j = 0;
        while (i < tab.Length)
        {
            i++;
            while (j < tab[i].Length)
            {
                tab[i][j] = licznik++;
                j++;
            }
        }
        while (i < tab.Length)
        {
            Console.Write("tab[{0}] = ", i);
            i++;
            while (j < tab[i].Length)
            {
                j++;
                Console.WriteLine("{0} ", tab[i][j]);
            }
            Console.WriteLine();
        }
2

Powiedz temu, co dał zadanie, ze głupotą jest tu używać while.

Pętle while nie masz tożsame z for'ami. Przed pętlą wewnętrzną nie zerujesz jej indeksu (tfu, tfu, indeks w pętli while, scyzoryk się mi sam otwiera)

0

@AnyKtokolwiek: pewnie i tak jest, ale chcąc nie chcąc muszę to wykonać w takiej formie. Fajnie, gdybyś mógł napisać jak to zrobić z tą while. Szkoły są pełne bzdur :(

2
int licznik = 1, i = 0, j = 0;
while (i < tab.Length)
{
    while (j < tab[i].Length)
    {
        tab[i][j] = licznik++;
        j++;
    }
    i++;
    j = 0;
}
i = 0;
while (i < tab.Length)
{
    Console.Write($"\ntab[{i}] = ");
    while (j < tab[i].Length)
    {
        Console.Write($"{tab[i][j]} ");
        j++;
    }
    i++;
    j = 0;
}
0

@pavarotti:
Program w tej formie wyświetla pustą konsolę.

using System;
public class Program
{
    public static void Main()
    {
        int[][] tab = new int[4][];
        tab[0] = new int[4];
        tab[1] = new int[3];
        tab[2] = new int[2];
        tab[3] = new int[1];
        int licznik = 1, i = 0, j = 0;
        while (i < tab.Length)
        {
            while (j < tab[i].Length)
            {
                tab[i][j] = licznik++;
                j++;
            }
            i++;
        }
        while (i < tab.Length)
        {
            Console.Write($"tab[{i}] = {tab[i]}");
            while (j < tab[i].Length)
            {
                j++;
                Console.WriteLine($"{tab[i][j]}");
            }
            i++;
            Console.WriteLine();
        }
    }
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1