October 27, 2024
Chicago 12, Melborne City, USA
C#

Why can't I properly divide this array of strings into smaller groups?


I’m a beginner in C programming whose still pretty confused by arrays. I’m trying to create a program where an array of 42 names (alphabetically arranged) is divided into 7 groups each with 5 members. The tricky part is its ordering. The first group consists of the first member, the last member, the second member, the second to the last member, and the third member. Basically it alternates between the first and the last.

This is what I’ve tried so far:

#include <stdio.h>
#include <string.h>

int main() {
    const char students[42][50] = {"Alde", "Amio", "Ande", "Ayuson", "Bacabac", "Bisares", "Caparuzo", "Castro", "Dela Cruz", "Devera", "Frias", "Gailo", "Galvez", "Gamboa", "Geronimo", "Gutierrez", "Hernandez", "Landoy", "Lasay", "Lopez", "Luna", "Manalang", "Maranguis", "Matro", "Mercado", "Millonte", "Morshed", "Naz", "Neri", "Ogbac", "Oredina", "Pardillo", "Pedido", "Perez", "Piedad", "Rodriguez", "Santos", "Sañosa", "Takeuchi", "Uy", "Ventura", "Villavicencio"};
    int numberOfStudents = sizeof(students) / sizeof(students[0]);
    int j = numberOfStudents - 1;
    int numberOfGroups = 7;
    int groupSize = 5;
    char group[7][5][50] = {};
    int m = 0;

    for (int l = 0; l < numberOfGroups; l++) {
        int x = 0;  // Reset x for each group
        for (int i = 0; i < groupSize; i++) {
            if (j >= 0) {
                strcpy(group[l][x], students[m]);  // Use m for the first student
                x++;
                strcpy(group[l][x], students[j]);  // Use j for the second student
                x++;
                j--;
                m++;
            }
        }
    }

    // Print the groups
    for (int y = 0; y < numberOfGroups; y++) {
        printf("Group %d:\n", y + 1);
        for (int k = 0; k < groupSize; k++) {
            printf("\t%s\n", group[y][k]);
        }
        printf("\n");
    }

    return 0;
}

The first groups is correct, but I don’t understand at all why in the other groups there are names that are skipped and names that are repeated.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video