It's a simple task, you do not have to use a boolean variable for this. Simply fill in the vector and read it again.
Try to identify and organize your code more and use correct programming practices. Do not use main()
without a method, we usually declare int main()
or if you want use int main(int argc, char const *argv[])
arguments. Always use a return for main
, we usually use return 0
to indicate success and return 1
to indicate a failure.
The use of fflush(stdin)
was to clear the input buffer to prevent getchar()
from "sucking" the last value entered by the user and passing blank, without pausing execution.
I gave a rephrase in your code, take a look:
#include <stdio.h>
int main()
{
int i;
int A[5];
for(i = 0; i < 5; i++)
{
printf("Digite o numero inteiro para o vetor A[%d]: ", i);
scanf("%d", &A[i]);
fflush(stdin);
}
for(i = 0; i < 5; i++)
{
if(A[i] < 0)
{
printf("O indice do primeiro numero negativo e: A[%d]", A[i]);
getchar();
return 0;
}
}
printf("Nao tem numero negativo.");
getchar();
return 0;
}
As you can see, the first negative number it finds it will display and exit the program. If it does not find any negative numbers it will continue execution and will display the final message.
Simply a comparison to know if the number is less than 0.
But if you still want to use the Boolean method:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int i;
int A[5], N;
bool isNegative = false;
for(i = 0; i < 5; i++)
{
printf("Digite o numero inteiro para o vetor A[%d]: ", i);
scanf("%d", &A[i]);
fflush(stdin);
}
for(i = 0; i < 5; i++)
{
if(A[i] < 0)
{
N = A[i];
isNegative = true;
break;
}
}
if(isNegative == true)
{
printf("O indice do primeiro numero negativo e: A[%d]", N);
}
else
{
printf("Nao tem numero negativo.");
}
getchar();
return 0;
}
With the Boolean method, a isNegative
variable is declared that initially receives the value false
and if a negative number is detected it becomes true
, the integer N
takes the value of the negative index and breaks the execution loop with break
because it will not be necessary to go through the rest of the vector.
After this it checks whether the isNegative
variable is true or false and gives the answer to the user based on that.
I hope you have helped.