How to analyze the input in the while condition?

1

I'm learning C, and as the language in which I was "literate" is Python, I usually make associations to assimilate better.

In Python, I can get a direct value in the while condition. Ex.:

while int(input()) != 0:
    faça isso

It is also possible (in Python and C) to declare a variable before the while, to receive a new value at the end of each loop, and then to parse. Ex (in Python).:

n = 1
while n != 0:
    faça isso

    n = int(input)

But I wanted to know if there is any way to do it as in the first example, but in C.

I tried the following way (in C):

int n;

while(scanf("%d", &n) != 0){
    faça isso
}

But it runs the loop even though I type 0.

Thank you in advance.

    
asked by anonymous 24.12.2017 / 05:25

2 answers

1

When you run scanf("%d", &n) it will store the read value at address n . Then just add && n != 0 to parse the input.

int n;
while(scanf("%d", &n) && n != 0){
  printf("Não é zero! :)\n");
}
printf("Ops :(\n");
  

Example working on repl.it .

    
24.12.2017 / 08:04
0

Just add the "& &" between scanf("%d", &n) and n != 0 for the compiler to analyze the two conditions. It looks like this:

int n;

while(scanf("%d", &n) && n != 0) {
  faca tal coisa;
}
    
31.12.2017 / 00:52