Is the following use of "return 0;" correct?

1

Within a C programming course that I am taking, enter the loop section (while, do-while, for, etc ...).

And within one of the practices had as goal to achieve that in the last printf in which prints the numbers entered by the user, when you reach the last number, print it with a final point.

But I needed to figure out how to get to that part of the loop and if the if condition were fulfilled, the program would stop. So consider, since it was the final part of the program, place the return 0; to stop it when the if is fulfilled.

What I did, even if it worked, is considered correct? and otherwise how to do it the right way?

#include <stdio.h>

#define LIMITE 10

int main() {
int tabla[LIMITE], total, suma = 0, i = 0;

  do {
      printf("¿Cuantos numeros quieres sumar (entre 0 y %d)?: ", LIMITE);
      scanf("%d", &total);

      if (total < 0 || total > LIMITE)
          printf("Error. Debes introducir un numero entre 0 y %d.\n\n", LIMITE);

     } while (total < 0 || total > LIMITE);

  while (i < total) {
      printf("\nIntroduce un numero: ");
      scanf("%d", &tabla[i]);
      suma += tabla[i];
      i++;
  }

  printf("La suma de los numeros: ");

  i = 0;
  while (i < total){

      if (i + 1 == total) {
          printf(" %d. es %d", tabla[i], suma);
          return 0;
      }

      printf(" %d,", tabla[i]);
      i++;
  }

}
    
asked by Jeremy Jasiel 02.01.2019 в 22:45
source

1 answer

1

I would have used break instead of return 0 .

While it is true that with return you leave the function main and, with it, the program ends, with break the code would be more natural since you really want is not to leave the main but only the loop ... that there is no more code after the loop is secondary.

So, what I said, I would replace return 0 with break :

if (i + 1 == total) {
    printf(" %d. es %d", tabla[i], suma);
    break;
}

And the code might even be cleaner if the printf were moved out of the loop. To taste the colors:

while (i < total){

    if (i + 1 == total) break;

    printf(" %d,", tabla[i]);
    i++;
}

printf(" %d. es %d", tabla[i], suma);
    
answered by 02.01.2019 / 22:50
source