Generate three random character in c
String and Generate three random character in C. The string should have a termination character if we don’t add it to a 2d array then it will act as an array of chars, we add it to inform the compiler that it is a string so terminate.
Before understanding this code you need to learn about array. I’m trying to generate three random characters and lengths of Strings.
How to generate random string in C
#include<stdio.h> #include<time.h> #define N 20 int main() { const char pool[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int poolsize=sizeof(pool)-1; char name[N][4]; srand(time(0)); int i,j; for (i=0;i<N;i++) { for(j=0;j<4;j++) { if(j<=2) name[i][j]=pool[(rand()%poolsize+0)]; // assign random chars else name[i][j]='\0'; } } //print random string for (i=0;i<N;i++) { printf("%s\n",name[i]); } return 0; }
The char array when you encounter ‘\0’ symbol in the array. and we should have 1 char more than the required length of the array so instead of name[N][3];.
I made it name[N][4] so it can accommodate termination character which we can’t see but it is for the compiler to terminate the string properly. some compilers add it automatically.

You can try this code it will do the same as above, then try to remove the line name[i][3]=’\0′, and see what happens. Try it 1st Yourself.
Generate random number in C
#include<stdio.h> #include<time.h> #define N 20 int main() { const char pool[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int poolsize=sizeof(pool)-1; char name[N][4]; srand(time(0)); int i,j; for (i=0;i<N;i++) { for(j=0;j<3;j++) { //if(j<=2) name[i][j]=pool[(rand()%poolsize)]; // assign random chars //else //name[i][j]='\0'; } name[i][3]='\0'; } //print random string for (i=0;i<N;i++) { printf("%s\n",name[i]); } return 0; }