Home > front end >  Use of "while" instead of "for" in C
Use of "while" instead of "for" in C

Time:12-25

Hello I'm new to programming, and would want to return an array in a "while" condition (not use "for"), any tips to make my program working please? Thanks

int numberPlayer=0;
    int *listPlayers= NULL;
    int i;

    printf("How many players");
    scanf("%d",&numberPlayer);

    listPlayers= malloc(sizeof(int) * numberPlayer);

    if (listPlayers==NULL){
        exit(1);
    }

    i=0;
    while(i<numberPlayer){
         printf("Joueur n° %d", i*3);
         listPlayers[i]= i*3;
         i  ;

    }

    while(i<numberPlayer){
        printf("%d", listPlayers[i]); 
        i  ;
    }

CodePudding user response:

I think you should learn how to use function. return array pointer is available for function not for commands like while, for. you can check this https://www.tutorialspoint.com/cprogramming/c_return_arrays_from_function.htm

CodePudding user response:

Your example is a perfect illustration of the superiority of the for loop over the while loop. It is a shame some schools insist on students using only while loops (42, Epita, Epitech...)

You forgot to initialize i = 0 before the second while loop. A classical for loop combines initialization, test and increment in the for clauses, making it easy to read and verify.

For proper output, you should use a separator between the numbers and output a newline.

Here is a modified version:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int numberPlayers = 0;
    int *listPlayers = NULL;
    int i;

    printf("How many players? ");
    if (scanf("%d", &numberPlayers) != 1) {
        return 1;
    }

    listPlayers = malloc(sizeof(int) * numberPlayers);
    if (listPlayers == NULL) {
        return 1;
    }

    i = 0;
    while (i < numberPlayers) {
         printf("Joueur n° %d? ", i * 3);
         if (scanf("%d", &listPlayers[i]) != 1)
             return 1;
         i  ;
    }

    printf("Liste des joueurs: ");
    i = 0;
    while (i < numberPlayers) {
        printf("[%d]", numberPlayers[i]); 
        i  ;
    }
    printf("\n");
    free(listPlayers);
    return 0;
}
  • Related