Convert for to while

Asked

Viewed 80 times

0

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


int main(void) {

   int X[10], cont;
   cont=0;
   while(cont<10){
        printf("Digite um numero inteiro: ");
        scanf("%d",&X[cont]);
        if(X[cont] %2 == 0){
            X[cont]=0;
        }else{
            X[cont]=1;

        }
        cont++;
    }
    
   while(cont<10){
        printf(" %d ", X[cont]);
        cont++;
   }

    
}

This code is not working, but when I do for works:

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


int main(void) {

   int X[10], cont;
   for(cont=0;cont<10;cont++){
        printf("Digite um numero inteiro: ");
        scanf("%d",&X[cont]);
        if(X[cont] %2 == 0){
            X[cont]=0;
        }else{
            X[cont]=1;

        }
    }
    
   for(cont=0;cont<10;cont++){
        printf(" %d ", X[cont]);
   }

    
}
  • Note that at the end of the first while the variable cont will be set to 10 and therefore will not enter the second loop. Restart the variable before entering the second loop.

  • Okay, thanks. It worked!

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

The main problem is that it is not zeroing the counter when going to do the second loop, as the variable was ditching 10 at the output of the first it will pick wrong positions of memory in the sequence. I took the opportunity to organize and simplify the code.

Note that the result of the account to find out if it is even or odd already gives exactly the required number, so there is no reason to make a if.

#include <stdio.h>

int main(void) {
   int X[10];
   int cont = 0;
   while (cont < 10) {
        printf("Digite um numero inteiro: ");
        scanf("%d", &X[cont]);
        X[cont] = X[cont] % 2;
        cont++;
    }
    cont = 0;
    while (cont < 10) printf(" %d ", X[cont++]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • It worked out! Thank you!!

  • How do I check the position of a vector?

  • Test do, if you have any problem ask a new question with all the necessary details.

  • See the [tour] best way to say thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.