Hi ,
I am working in a problem in which I have to print elements in array using random number logic.
The logic is that the elements of character should be printed randomly from the array. I have used random function for this.
The logic I implementing is that, I took the random number using function rand() and pick up the last two digit from it and with respect to them , I took the value from char array and print it down.
But the problem is that the array size is 0nly 40 and the number I get from generator some times greater than 40,so in this case repeated iterations will be there,which is not good practice.Also, I have to put the logic whether it from unit place or tens place.
Can anybody help me in implementing this.Actually I want to put the optimized solution.
The code is as follow:
Code:
#include<stdio.h>
#include<conio.h>
#include<time.h>
int main()
{
char alpha[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int count =0,i,mul=0;
int seed = (int)time(NULL);
clrscr();
srand(seed);
i = rand();
printf("%d",i);
while(count!=2)
{
mul*=10;
mul+=i%10;
i = i/10;
count++;
}
printf("\n Value=%c",alpha[mul]);
getch();
}
Thanks