Daniel Camilleri Daniel Camilleri - 19 days ago 5
C Question

unique element/s for array in every row

I have a question on how to show unique elements in an array. The program consists of two nested loops. The first counter is for rows and the other is for the letters, and the second counter outputs the letters in the array in the order.

The issue I am having, is that after the first and second row some elements start to repeat themselves(C primer plus 6th edition 241pg num 4)

#include <stdio.h>

int main(void){

char lets[29] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


for(int i =0; i<6; i++)
{
for(int j=0; j<=i; j++)
{
printf("%c", lets[j+i]);
}


printf("\n");
}
}


My Output

A
BC
CDE
DEFG
EFGHI
FGHIJK


Required Output

A
BC
DEF
GHIJ
KLMNO
PQRSTU

Answer

You need an extra offset or you never reach the end of the alphabet:

char lets[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // no need to give array size, automatic size is OK

int start = 0;

for(int i =0; i<6; i++)
{
    for(int j=0; j<=i; j++)
    {
        printf("%c", lets[j+i+start]);
    }
    start += i;  # shift letters

    printf("\n");
}

result:

A
BC
DEF
GHIJ
KLMNO
PQRSTU