Here I am comparing two array element , If array element are equal SETPASSWORD=1;
else SETPASSWORD=0;
But Here It is always printing password set status 1 even array are not equal
#include <stdio.h>
#define ARY_SIZE 4
int password_set;
int main (void)
{
//Local Declarations
int numbersA[ARY_SIZE];
int numbersB[ARY_SIZE];
int i;
int j;
//Statements
printf("Please Enter 10 Integers For Array A\n");
for (int i = 0; i < ARY_SIZE; i++)
scanf("%d", &numbersA[i]);
printf("\nPlease Enter 10 Integers For Array B\n");
for (int j = 0; j < ARY_SIZE; j++)
scanf("%d", &numbersB[j]);
for (int i = 0; i < ARY_SIZE; i++)
{
for (int j = 0; j < ARY_SIZE; j++)
{
if (numbersA[i] == numbersB[j])
password_set=1;
else
password_set=0;
}
}
printf(" password setstaus =%d",password_set);
return 0;
}
Your logic is wrong. You must exit the loop as soon as one pair of numbers is non equal.
And you also need only one loop :
password_set = 1 ;
for (int j = 0; j < ARY_SIZE; j++)
{
if (numbersA[j] != numbersB[j])
{
password_set = 0;
break ;
}
}
Your compare each value of the array in your for (if (numbersA[i] == numbersB[j])
It resets the value of password_set at each iterations. It means that the result printed will be the last index of your array.
And btw you need only one loop
Actually, you comparison is wrong. Because you want to test two arrays is equal or not, you just test each number of these two arrays.
like this:
password_set = 1;
for (int i = 0; i < ARY_SIZE; i++) {
if (numbersA[i] != numbersB[i]) {
password_set=0;
break;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.