# Can anybody let me know how to solve this.

• 02-24-2009
Farhan
Can anybody let me know how to solve this.
Question Follows:

Twenty-five numbers are entered from the keyboard into anarray. The number to be searched is entered through the keyboard by the user. Write a program to find if the number to be searched is present in the array and if it is present, displaythe number of times it appears in the array.

My Coding is this:
Code:

#include <stdio.h>

main()
{
int nos[2];
int a,i,f;
for(a=1;a<=3;a++)
{
printf("Enter Numbers:");
scanf("%d",&nos[a]);
}
printf("\nEnter a Number to be Found:");
scanf("%d", &f);
/*for(a=1;a<=3;a++)
printf("%d",nos[a]);*/
if(nos[a]==f)
printf("\nNumber found");
else

}

what is wrong with above programme.
• 02-24-2009
Meldreth
array indexes start at 0 and end at the size of the array minus 1. your loops should be
Code:

for (a = 0; a < 2; a++)
• 02-24-2009
MK27
Use an extra variable to keep track of the finds:
Code:

#include <stdio.h>

int main()    /* the proper way */
{
int nos[4];
int a,f, total=0;      /* our new variable */
for(a=0;a<=3;a++)
{
printf("Enter Numbers:");
scanf("%d",&nos[a]);
}
printf("\nEnter a Number to be Found:");
scanf("%d", &f);

for(a=0;a<=3;a++) if(nos[a]==f) total++;
if (total>0) printf("Number found %d times.\n",total);

return 0;
}

You also had an overwrite in your last code, because you assign 2 elements to nos, then you count thru them 1,2,3! You actually overflow by 2, because the 2 elements of nos are numbered 0 and 1 (2 and 3 do not exist). Always remember the first element of an array is 0, not 1.

So here the numbers match up: nos has 4 elements and we count thru them 0, 1, 2, and 3.
• 02-24-2009
Farhan
Thank you verymuch guys.
• 02-24-2009
Farhan
ok the programme works fine but want to know how this total++ does the work of getting the input of the variables in it.Can you please explain so that i will know the programme more detail.Thanks in advance
• 02-24-2009
Subsonics
Quote:

Originally Posted by Farhan
ok the programme works fine but want to know how this total++ does the work of getting the input of the variables in it.Can you please explain so that i will know the programme more detail.Thanks in advance

It means that if an occurance of the number is found 1 is added to total. Itīs the same a writing total = total + 1;