It is a very simple task, it is not necessary to use a boolean variable for this. Simply fill in the vector and read it again.
Try to find and organize your code more and use correct programming practices. Do not use the main()
without a method, we usually declare as int main()
or if you want arguments use int main(int argc, char const *argv[])
. Always use a return to the main
, we usually use the return 0
to indicate success and the return 1
to indicate a fault.
The use of fflush(stdin)
was to clear the input buffer to prevent the getchar()
"sugue" the last value entered by the user and pass blank, without pausing the execution.
I reworked 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 he finds will display and exit the program. If it does not find any negative number it will continue running and will display the final message.
Simply a comparison to see 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 variable was declared isNegative
that initially receives the value false
and if a negative number is detected it turns into true
, the whole N
takes the value of the negative index and breaks the execution loop with the break
because it will not be necessary to go through the rest of the vector.
After that it checks whether the variable isNegative
is true or false and gives the answer to the user based on this.
I hope it helped.
edit the issue and add the code you’re trying to...
– MagicHat
edited the question and put the code to see if you can help me
– Gabriel