user2850602
user2850602

Reputation: 35

Trying to find if the element of an int array is equal to a number entered in C

I'm trying to use a for loop to iterate over the elements of an integer array and find out if a particular element in that array is equal to some other integer.

Here's what I've got, and it doesn't seem to work:

int squaresArray[1000];
int numberOfSquares = 1000;
int i = 0;

for (i; i<=numberOfSquares; i++)
{
    squaresArray[i] = i*i;
    if (number == squaresArray[i]){
        printf("%d is a perfect square\n", number);}
        break;
}

According to what I know about for loops this should work, but it prints nothing even when the number should be equal to some element of the array.

Upvotes: 1

Views: 100

Answers (1)

arshajii
arshajii

Reputation: 129587

You're breaking on the first iteration due to misplaced brackets (i.e. break is not in the scope of the if-statement). Change it to:

if (number == squaresArray[i]) {
        printf("%d is a perfect square\n", number);  // no closing bracket here
        break;
} // <--

Also, your loop condition should probably be i < numberOfSquares. After all, numberOfSquares (1000) is an out of bounds index for an array of length 1000. Moreover, you don't need a loop initialization statement if you've already declared/initialized i in the loop's enclosing scope. Hence, we're left with

int i = 0;

for (; i < numberOfSquares; i++)

If you're using C99 and above, you can limit the scope of i to only the loop, which should be preferred:

for (int i = 0; i < numberOfSquares; i++)

Upvotes: 3

Related Questions