I'm trying to generate a random 10-digit code, but even though I use the absolute value of every number in the code, it still sometimes prints a negative value
#include <stdio.h>
int main()
{
int i;
int r;
int barcode[11];
srand(time(NULL));
for(i=0;i <= 10;i++){
r = rand() % 10;
barcode[i] = abs(r);
}
printf("%d",barcode);
return 0;
}
Because you are actually printing the address of an integer array, not a string.
This line:
printf("%d",barcode);
Basically prints the address of barcode as a signed integer instead of the contents of barcode.
You of course could do this:
printf("%d%d%d%d%d%d%d%d%d%d",barcode[0], barcode[1], barcode[2], barcode[3], barcode[4], barcode[5], barcode[6], barcode[7], barcode[8], barcode[9]);
But perhaps a better way is to generate a string of characters instead of an array of integers. Quick mod to your code is to add to '0' to each random value in each interation of the loop and append to a char array.
int main()
{
int i;
int r;
char barcode[11]; // array of chars instead of ints
srand(time(NULL));
for(i=0; i < 10; i++) // loop 10 times, not 11
{
r = rand() % 10;
barcode[i] = '0' + r; // convert the value of r to a printable char
}
barcode[10] = '\0'; // null terminate your string
printf("%s\n",barcode);
return 0;
}
The above will generate a 10 digit code, with a small possibility of the first number being a leading zero. If that's not what you want, that's a simple bug fix. (Which I'll leave up to you...)
Related
I am trying to find the exact match between two numbers and have my counter stop at the first instance when they are not a match. However the code I have written counts the entire string length of my numbers. Is there an alternative way to do this?
Since my counter is starting from the first decimal place and not 0. , it counts to 15 but should stop at 10.
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stdlib.h>
int main(){
char str[100];
char buf[100];
double l,m,a,b;
int c,d,t,u,r,q;
int count =0;
l=59874.141715197809000;
m=59874.141715197817000;
a= (l - (int)l);
b= (m -(int)m);
sprintf(str,"%.15f",a);
sprintf(buf,"%.15f",b);
c = strlen(str);
d = strlen(buf);
for(t=3;t<c;t++){
for(u=3;u<d;u++){
if(str[t]==buf[u]){
count++;
break;
}
}
}
printf("matching decimal places = %d \n",count);
return 0;
}
First, when comparing two strings, you only need to iterate to the length of the smallest string if the two strings differ in length.. That is, if you want to count the amount of sequential character matches in a string.
For example:
A = 0.99997552
B = 0.9999753
would need one for loop to compare.. You would only iterate up to the length of B to determine that 6 decimals match. Why? Because going any further is irrelevant since none of the extra digits would exist in B. Iterating past the end of an array is undefined behaviour anyway.
In your case both buffers are the same length so no worries there, but again, the shorter string won't have the extra digits found in the longer string.. Hence: Iterate up to the smallest length.
The solution can be done as follows:
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int main() {
//Create large enough buffer to hold 100 digits/characters..
char str[100] = {0};
char buf[100] = {0};
//Two doubles to be compared..
double l = 59874.141715197809000;
double m = 59874.141715197817000;
//Counter keeps track of matching digits..
int count = 0;
//Get rid of the base and keep only the decimals..
double a = (l - (int)l);
double b = (m - (int)m);
//Copy a maximum of 15 decimal places to `str` and `buf`
sprintf(str, "%.15f", a);
sprintf(buf,"%.15f", b);
//Get the length of both strings..
int c = strlen(str);
int d = strlen(buf);
//If C is smaller, iterate to length(c) else iterate to length(d).
for (int i = 2; i < (c < d ? c : d); ++i)
{
//If the two characters match, increment the count..
if (str[i] == buf[i])
{
++count;
}
}
//Print the amount of matching decimals..
printf("matching decimal places = %d \n", count);
return 0;
}
This may not be the answer, but do
if (number1 == number2)
{
// do something to stop it
}
Hello I'm writing a program that would generate 10 random characters in order to form a word (it's for a game).
so here's my function:
void GenerateTen(int number)
{
int i;
char abc[30]="abcdefghijklmnopqrstuvwxyz";
char newabc[8];
for (i = 0; i < number; ++i) {
newabc[i] = abc[rand() % (sizeof(abc) - 1)];
printf("%c ", newabc[i]);
}
newabc[number] = 0;
}
the number variable contains 10 and the output is supposed to simply print these 10 characters in the array. There's no error by the compiler however, the program generates the same set of characters. Thank you for your help! :-)
I got your problem. You have to seed it. Seeding it with the time is a good idea: srand()
rand() returns pseudo-random numbers. It generates numbers based on a given algorithm. The starting point of that algorithm is always the same, so you'll see the same sequence generated for each invocation.
You can set the "seed" of the random generator with the srand function(only call srand once in a program). One common way to get different sequences from the rand() generator is to set the seed to the current time or the id of the process:
srand(time(NULL)); or srand(getpid()); at the start of the program.
Reference: https://stackoverflow.com/a/1108810/5352399
You can update your code as follows.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
srand(time(NULL));
for(int i = 0; i < 5; i++){
GenerateTen(8);
}
return 0;
}
void GenerateTen(int number) {
int i;
char abc[26]="abcdefghijklmnopqrstuvwxyz";
char newabc[8];
for (i = 0; i < number; ++i) {
newabc[i] = abc[rand() % (sizeof(abc) - 1)];
printf("%c ", newabc[i]);
}
newabc[number] = 0;
}
It outputs:
r x r a f d a b
f f t i x m l b
r k j e p h d v
s w a c p g v h
e n j l r j n w
You need to initialize the pseudo-random number generator using srand().
Just add this after your main().
srand(time(NULL));
What srand(time(NULL)) actually does is srand() generates pseudo-random numbers using a seed value, and time(NULL) returns the current calendar time.
So theoretically, your srand() function is guaranteed to get a different seed value on every runtime. Hence the values produced by rand() would be different each time.
Apart from calling srand(), you should be very careful that you're actually allocating an array of 8 elements (char newabc[8]) and indexing it up to number, so you should expect a buffer overflow when number >= 8). As you're not returning it you can remove it. If you plan on returning it you should allocate it beforehand: char* newabc = (char*)calloc(number+1, sizeof(char));
You can also remove the char abc[30] by realizing that abc[rand() % (sizeof(abc) - 1)] actually is 'a' + rand() % 26. Unless you want to use a custom dictionary with a subset of letter, in which case it would be better to keep it in global memory (outside of the function, or as static inside the function if you prefer to restrain its scope). And mind that sizeof(abc)might not be the same as strlen(abc) depending on your architecture.
So all in all you could end up with:
char* generate_random(int number) // Better C-style name
{
int i;
char* newabc = (char*)calloc(number, sizeof(char));
if (newabc == NULL)
return NULL;
for (i = 0; i < number; ++i) {
newabc[i] = 'a' + (rand() % 26);
// printf("%c ", newabc[i]); // Not needed anymore, except for debugging
}
// newabc[number] = 0; // Not needed because we used 'calloc()' which zeroes the allocated memory
return newabc;
}
Hi I want to know is there a way to store randnumber without prompting user for input. In this example we want user to store 16 randnumbers in array storerand without prompting the user for randnums for example:
#include<stdio.h>
#include<stdlib.h>
void main() {
int randnum;
int i=0;
int storerand[16]; // storing randnumbers
randnum=rand();
while(i <16){
storerand[i]=randnum; // why is this not storing 16 rand number how can i store 16 randnumbers
i++;
}
return 0;
An easy way to generate random numbers in C is to use the rand() function which comes with <stdlib.h>. Note that if you do not seed with the time library, you will receive the same random numbers every time you run your program.
#include <stdlib.h>
#include <time.h>
int main (void) {
//Uses system time to seed a proper random number.
srand(time(NULL));
//rand() generates a random integer
int a = rand();
//Use mod to restrict range:
int b = rand()%5; //random integer from 0-4
return 0;
}
You also need to make sure to increment your index i within your while loop.
while(i < 16) {
storerand[i] = rand();
i++;
}
You initialise randnum with a random value here:
randnum=rand();
And then you run your loop to put its value into each slot of your array. That means you're putting the same value into each slot.
while(i <16){
storerand[i]=randnum;
i++;
}
The solution is to call rand() each time around the loop:
for( i = 0; i < 16; i++ ) {
storerand[i] = rand();
}
Task is to get int using scanf("%d") then print it again using printf("%с") without standard functions like atoi , itoa .As i understood i need to divide all numbers then add \0 char and print it, however how can i divide it. I thought about loop for dividing number%10 + /0 and number/10 to decrease number for 1 character .
Therefore code should look smoothing like this
#include <conio.h>
#include <stdio.h>
main(void)
{
int number,reserve ;
char Array[50];
scanf_s("%d",&number);
if (number > 0 || number == 0)
{
do
{
reserve = number % 10;
printf("%c", reserve + '/0');
number /= 10;
} while (number != 0);
}
else
{
number *= -1;
printf("-");
do
{
reserve = number % 10;
printf("%c", reserve + '/0');
number /= 10;
} while (number != 0);
}
_getch();
return 0;
}
As well there can be negative number so i need some if statement to check if it is negative and in case it is loop should avoid it it so we won't get smthing like -%10
So i don't know if loop is correct (hope someone will fix it and explain me how it is supposed to be). Waiting for your advices.
One side effect of the line
number = number % 10;
is that you lose the original value of number. So when you go to do
number = number/10;
it would always get the value zero. To fix this, store the original value somewhere else, or use another variable to do your character conversion (modulo 10, then plus \0).
Also, your loop needs to be re-examined. This process of modulo, add \0, divide, repeat, should stop when the result of the division is zero (i.e. there are no more digits to print). Another thing to think about is: in what order are these digits being printed?
I'll leave it to you to to figure out how to determine if the value of an int is greater than or less than zero, since you didn't attempt that in this snippet.
this will help you, adopt for your purposes
#include <stdio.h>
int main() {
int a;
int i = 0;
int str_size = 0;
char str[11] = {};
char tmp;
scanf("%d", &a);
while (a) {
str[str_size++] = a % 10 + '0';
a /= 10;
}
str_size--;
while (i < str_size) { // rewind
tmp = str[i];
str[i++] = str[str_size];
str[str_size--] = tmp;
}
printf("%s", str);
return 0;
}
I basically want to convert a given int number and store individual digits in an array for further processing.
I know I can use % and get each digit and store it. But the thing is if I do not know the number of digits of the int till runtime and hence I cannot allocate the size of the array. So, I cannot work backwards (from the units place).
I also do not want to first store the number backwords in an array and then again reverse the array.
Is there any other way of getting about doing this?
Eg: int num = 12345;
OUTPUT: ar[0] = 1, ar[1] = 2 and so on, where ar[] is an int array.
Convert is probably not the right word. You can take the int, dynamically allocate a new int[], and then store the digits of the int into the int[]. I'm using log base 10 to calculate how many digits num has. Include math.h to use it. The following code is untested, but will give you an idea of what to do.
int num = 12345;
int size = (int)(log10(num)+1);
// allocate array
int *digits = (int*)malloc(sizeof(int) * size);
// get digits
for(int i=size-1; i>=0; --i) {
digits[i] = num%10;
num=num/10; // integer division
}
The easiest way is to calculate number of digits to know the size of an array you need
int input = <input number>; // >= 0
int d, numdigits = 1;
int *arr;
d = input;
while (d /= 10)
numdigits++;
arr = malloc(sizeof(int) * numdigits);
There's even easier way: probably you pass a number to your program as an argument from command line. In this case you receive it as a string in argp[N], so you can just call strlen(argp[N]) to determine number of digits in your number.
If you have a 32-bit integer type, the maximum value will be comprised of 10 digits at the most (excluding the sign for negative numbers). That could be your upper limit.
If you need to dynamically determine the minimum sufficient size, you can determine that with normal comparisons (since calling a logarithmic function is probably more expensive, but a possibility):
size = 10;
if (myint < 1000000000) size--;
if (myint < 100000000) size--;
/* ... */
Declaring the array to be of a dynamic size depends on the C language standard you are using. In C89 dynamic array sizes (based on values calculated during run-time) is not possible. You may need to use dynamically allocated memory.
HTH,
Johan
The following complete program shows one way to do this. It uses unsigned integers so as to not have to worry about converting - you didn't state what should happen for negative numbers so, like any good consultant, I made the problem disappear for my own convenience :-)
It basically works out the required size of an array and allocates it. The array itself has one element at the start specifying how many elements are in the array (a length int).
Each subsequent element is a digit in sequence. The main code below shows how to process it.
If it can't create the array, it'll just give you back NULL - you should also remember to free the memory passed back once you're done with it.
#include <stdio.h>
#include <stdlib.h>
int *convert (unsigned int num) {
unsigned int *ptr;
unsigned int digits = 0;
unsigned int temp = num;
// Figure out how many digits in the number.
if (temp == 0) {
digits = 1;
} else {
while (temp > 0) {
temp /= 10;
digits++;
}
}
// Allocate enough memory for length and digits.
ptr = malloc ((digits + 1) * sizeof (unsigned int));
// Populate array if we got one.
if (ptr != NULL) {
ptr[0] = digits;
for (temp = 0; temp < digits; temp++) {
ptr[digits - temp] = num % 10;
num /= 10;
}
}
return ptr;
}
That convert function above is the "meat" - it allocates an integer array to place the length (index 0) and digits (indexes 1 through N where N is the number of digits). The following was the test program I used.
int main (void) {
int i;
unsigned int num = 12345;
unsigned int *arr = convert (num);
if (arr == NULL) {
printf ("No memory\n");
} else {
// Length is index 0, rest are digits.
for (i = 1; i <= arr[0]; i++)
printf ("arr[%d] = %u\n", i, arr[i]);
free (arr);
}
return 0;
}
The output of this is:
arr[1] = 1
arr[2] = 2
arr[3] = 3
arr[4] = 4
arr[5] = 5
You can find out the number of digits by taking the base-10 logarithm and adding one. For that, you could use the log10 or log10f functions from the standard math library. This may be a bit slower, but it's probably the most exact as long as double has enough bits to exactly represent your number:
int numdigits = 1 + log10(num);
Alternatively, you could repeatedly divide by ten until the result is zero and count the digits that way.
Still another option is just to allocate enough room for the maximum number of digits the type can have. For a 32-bit integer, that'd be 10; for 64-bit, 20 should be enough. You can just zero the extra digits. Since that's not a lot of wasted space even in the worst case, it might be the simplest and fastest option. You'd have to know how many bits are in an int in your setup, though.
You can also estimate fairly well by allocating 3 digits for each 10 bits used, plus one. That should be enough digits unless the number of bits is ridiculously large (way above the number of digits any of the usual int types could have).
int numdigits = 1
unsigned int n = num;
for (n = num; n & 0x03ff; n >>= 10)
numdigits += 3;
/* numdigits is at least the needed number of digits, maybe up to 3 more */
This last one won't work (directly) if the number is negative.
What you basically want to do is to transform your integer to an array of its decimal positions. The printf family of functions perfectly knows how to do this, no need to reinvent the wheel. I am changing the assignment a bit since you didn't say anything about signs, and it simply makes more sense for unsigned values.
unsigned* res = 0;
size_t len = 0;
{
/* temporary array, large enough to hold the representation of any unsigned */
char positions[20] = { 0 };
sprintf(position, "%u", number);
len = strlen(position);
res = malloc(sizeof(unsigned[len]));
for (size_t i = 0; i < len; ++i)
res[i] = position[i] - '0';
}