Repeat loop is not running

1

I am making a code where you have a vector (with 15 positions) with predetermined values (10 any values and 5 times the value 0), and where the user will enter a new value to go to the end of the list ( substituting 0).

It seems to me that everything is right here, but the vector does not "get" the typed value. It performs everything right, with no error, just does not replace 0 with the new value.

The code (as part of a larger code, a switch with 7 options, I'm going to put this part with error not to get too big and with unnecessary parts):

    case 1 : printf("Qual valor voce quer inserir no final? ");
               scanf ("%d",&x1);
  n1 = 15;//posições do vetor
  num = 1;
  x2 = 1;
            printf("lista atual:\n"); //Exibe como está a lista
            while (num <= n1)
            {
                printf ("%d ", vet[num]);
                num++;
            }
            while (num <= n1) //roda o laço e caso encontre uma posição do vetor igual a zero, subtitui
            {
                if (vet[num] == 0)
                {
                    vet[num] = x1;
                }
               num++;
            }
            printf ("\n\nNova lista:\n");
            while (num <= n1)
            {
                printf ("%d", vet[num]);
                num++;
            }
    
asked by anonymous 22.03.2015 / 17:59

2 answers

2

You are not restarting the num variable that is used as the count. has two solutions:

    while (num < n1) {
        printf ("%d ", vet[num]);
        num++;
    }
    num = 0;
    while (num < n1) {
        if (vet[num] == 0) {
            vet[num] = x1;
        }
       num++;
    }

You could also do the same with for , then avoid this confusion:

   for (int num = 0; num < n1; num++) {
        printf ("%d ", vet[num]);
   }
   for (int num = 0; num < n1; num++) {
        if (vet[num] == 0) {
            vet[num] = x1;
        }
   }

Note that I am starting num with 0, seems to me to be the most correct but I can not guarantee without seeing the rest. If the right is 1, just change.

But to avoid this problem you can also enjoy and do everything in one loop:

   for (int num = 0; num < n1; num++) {
        printf ("%d ", vet[num]);
        if (vet[num] == 0) {
            vet[num] = x1;
        }
   }
    
22.03.2015 / 18:09
0
        while (num <= n1)
        {
            printf ("%d ", vet[num]);
            num++;
        }

At the end of this first cycle, the value of num will be n1 + 1

        while (num <= n1) //roda o laço e caso encontre uma posição do vetor igual a zero, subtitui

This cycle will never run, because the first time the condition is false ( num == n1 + 1 ).

    
22.03.2015 / 18:03