In: Computer Science
hi! I have this code. when I run it, it works but in
the print(the number we are searching for is ) it prints the number
twice. ex. for 5 it prints 55 etc. apart from this, it
works
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int n,i;
printf("Give me the size of the table : \n");
scanf("%d", &n);
int A[n],x,y;
for (i=0;i<n;i++)
A[i]=rand() % n;
for (i=0;i<n;i++)
printf("%d\n", A[i]);
srand(time(NULL));
y=rand()% n ;
printf("The number we are searching for is %d", y);
for (i=0;i<n;i++)
{
if (A[i]==y)
{
printf("%d is present at location
%d.\n", y,i+1);
break;
}
}
if (i == n)
printf("%d isn't present in the array.\n",
y);
return 0;
}
The code is working fine. but displaying two times of the number searching so that it is displaying two times.
please take a look on the code corrected code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int n,i;
srand(time(0));
printf("Give me the size of the table : \n");
scanf("%d", &n);
int A[n];
int x,y;
for (i=0;i<n;i++)
A[i] = rand()%n;
for (i=0;i<n;i++)
printf("%d\n", A[i]);
srand(time(NULL));
y=rand()%n; //random generate number upto n
numbers
//do not have to display here the y value if display
then
//not display in the inside for loop in print
statement
printf("The number we are searching for is ");
for (i=0;i<n;i++) //loop to the n times
{
if (A[i]==y) //check for the
index value is same as y value
{
//here is printed
again the y value so that it is displaying two times the value
corrected
printf("%d is
present at location %d.\n", y,i+1); //prints the found with the
index
break; //breaks
the loop
}
}
if (i == n) //if not found
printf("%d isn't present in
the array.\n", y);
return 0;
}
sample output: