ayman almuti ayman almuti - 7 months ago 46
C Question

I am trying to make the for loop iterate once so it does not give me multiple errors just one in c but don't know how?

So here is my code

#include <iso646.h>
#include <cs50.h>
#include <stdio.h>

int main(void)
{
int arr [6] = {1,2,3,4,5};
printf("please enter an number to search in the array \n");
int arri = get_int();
printf("Okay Searching Seaquence Activing (SSA) Now... \n");
for(int i = 0; i < arr[i]; i++)
{
if (arri == arr[i])
{
printf("Found Number in array \n");
}
if (arri != arr[i])
{
printf("Number not found \n");
}
}
}


and the output is this when I give the number 10

please enter an number to search in the array
10
Okay Searching Seaquence Activing (SSA) Now...
Number not found
Number not found
Number not found
Number not found
Number not found


Make it say the error only once not multiple times for each character in the array

Answer Source

There is a really obvious solution - just move the logic for printing that message outside of the for loop.

Track whether you've found the value with a separate variable which starts off being set to 0 and only gets set to 1 when you have a match. You should also ensure that the loop definitely ends when it's finished searching it by adding a condition to check that i isn't more than the size of the array you've defined.

int found = 0;
for(int i = 0; (i < arr[i]) && (i < sizeof(arr)/sizeof(arr[0])); i++)
{
    if(arri==arr[i])
    {
       found=1;
    }
}

if (found)
{
    found = 1;
    printf("Found Number in array \n");
} 
else
{
    printf("Number not found \n");
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download