How do I make the code read a new value if the condition is not met? - C

Asked

Viewed 48 times

0

The code is this, it’s in C

#include <stdio.h>
int main(void){
int i;

printf("digite um inteiro");
scanf("%d",&i);



 while(i>=1){
  
printf("%d\n",i);
i=i-1; 
}
}

But I want you to enter an invalid value like -1 for example ,it asks for a new value and perform the while instructions. How can I do that? Thanks for your attention.

  • If he should ask again, why not use the function scanf again? I don’t understand why it displays the value of i and then it goes down.

  • Substitute printf("digite um inteiro"); scanf("%d",&i); for printf("digite um inteiro"); scanf("%d",&i); while (i < 1) { printf("Valor inválido. Redigite um inteiro"); scanf("%d",&i);}.

1 answer

2

You have many options! 1st Validate the entry:

int main(void){
  int i;
  do{
    printf("Digite um inteiro: ");
    scanf("%d", &i);
    if(i<1) printf("Entrada invalida\n");
  }while(i<1);
  
  while(i>=1){
     printf("%d\n",i);
     i=i-1; 
  }
}

2nd Use the scanf within another type of repeating structure:

int main(void){
 int i;

 do{
   printf("digite um inteiro");
   scanf("%d",&i);

   while(i>=1){
  
     printf("%d\n",i);
     i=i-1; 
   }
  }while(i!=0); //Esta condição diz que se a entrada for 0 ele irá parar de pedir entradas
}

3rd Give the "kick start" to the i:

int main(void){
  int i = 1;//Aqui dou o chute inicial

  while(i!=0){//Não irá executar novamente caso o 'i' seja 0
    printf("digite um inteiro");
    scanf("%d",&i);

    while(i>=1){
      printf("%d\n",i);
      i=i-1; 
    }
  }
}

Browser other questions tagged

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