This question already has answers here:
Generating random numbers in C
(7 answers)
Closed 9 years ago.
So basically i wrote this function in C to generate 5 random numbers from 1 to 50:
#include <stdio.h>
#include <stdlib.h>
int main() {
int c, n;
printf("Five random numbers from 1 to 50 \n");
for (c = 1; c <= 5; c++) {
n = rand()%50 + 1;
printf("%d\n", n);
}
return 0;
}
and i'd like to know how can i be sure that the numbers generated by this code are all different from each other.
Any help ?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int i, c, n, size = 50;
int data[size];
srand(time(NULL));
for(i=0;i<size;++i)
data[i] = i+1;
printf("Five random numbers from 1 to 50 \n");
for (c = 1; c <= 5; c++) {
n = rand()%size;
printf("%d\n", data[n]);
swap(&data[--size], &data[n]);
}
return 0;
}
Store each number in an array and check each new random number against the existing entries.
You should check all numbers like this:
#include <time.h>
int randomNumbers[5];
int c, d, n;
bool itIsNew;
//current time as random seed
srand(time(0));
for (c = 1; c <= 5;)
{
n = rand() % 50 + 1;
itIsNew = true;
for(d = 1; d <= c; d++)
{
if(n == randomNumbers[d - 1])
{
itIsNew = false;
break;
}
}
if(itIsNew)
{
randomNumbers[c - 1] = n;
c++;
}
}
Related
I have to print the pascal's triangle given a certain number of levels desired. The max levels that will be asked for is 28. I am able to print the some of the rows correctly but then it starts printing negative numbers in the rest of my rows. I can't figure out why, help would be much appreciated!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printTriangle() {
int numLevels;
printf("Please enter how many levels of Pascal's Triangle you would like to see: ");
scanf("%d", &numLevels);
char pascalTriangle[28][28];
for (int k = 1; k <= numLevels; ++k) {
for (int i = 0; i < k; ++i) {
int val = (i == 0) || (i == k - 1) ? 1 : (pascalTriangle[k-1][i-1] + pascalTriangle[k-1][i]);
pascalTriangle[k][i] = val;
printf(" %d", val);
}
printf("\n");
}
}
int main() {
printTriangle();
}
Change char pascalTriangle[28][28]; to int pascalTriangle[28][28];. You're going over the max char value so it goes to negative.
There is no "array" type, only a collection of pointers. You can also change char to short, long, etc.
Also, change k <= numLevels to k < numLevels. This prevents the segmentation fault. To fix the logic, you have to change for(int i = 0; to for(int i = -1;
The fixed code is:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printTriangle() {
int numLevels;
printf("Please enter how many levels of Pascal's Triangle you would like to see: ");
scanf("%d", &numLevels);
long long pascalTriangle[28][28];
for (int k = 0; k < numLevels; ++k) {
for (int i = -1; i < k; ++i) {
long long val = (i == 0) || (i == k - 1) ? 1 : (pascalTriangle[k-1][i-1] + pascalTriangle[k-1][i]);
pascalTriangle[k][i] = val;
printf(" %lld", val);
}
printf("\n");
}
}
int main() {
printTriangle();
}
The program should just print out the elements of the array, which stores random integers between 10 and 30. I wanted the numbers to be different from each other, but my program isn't working, what is wrong with it? thanks
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0; i<N; i++)
arr[i]=10+rand()%20;
for(i=0; i<N; i++)
{
for(j=N-1; j == 0; j--)
{
do
{
arr[i]=10+rand()%20;
if(arr[i]!=arr[j])
break;
}
while(arr[i]==arr[j]);
}
printf(">>%d\n",arr[i]);
}
return 0;
}
The fact that the numbers need to be different from one another means that they are not truly random. You can create another set of numbers with elements 10 through 30 in them. Randomize that list and pull them into your array.
C++ version:
const int begin = 10;
const int end = 30;
// creates a vector of 30-10 zeroes
std::vector<int> v(begin-end);
// fill vector with 10, 11, ..., 30.
std::iota (std::begin(v), std::end(v), begin);
// a source for random seed
std::random_device rd;
// seed this generator with 32-bit number
std::mt19937 g(rd());
// randomly shuffle a vector
std::shuffle(std::begin(v), std::end(v), g);
const int N = 12;
std::vector<int> result(v.begin(), v.begin() + N);
C version:
#include <stdio.h>
#include <stdlib.h>
// https://stackoverflow.com/a/6127606/1953079
void shuffle(int *array, size_t n)
{
if (n <= 1) { return; }
size_t i;
for (i = 0; i < n - 1; i++)
{
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
int main(){
const int begin = 10;
const int end = 30;
const int N = 12;
srand(time(0));
// array that contains elements 10, 11...30
int nums[end-begin];
for(int i=0;i<end-begin; i++){
nums[i] = begin+i;
}
// randomly shuffle array
shuffle(nums, end-begin);
// take first N elements
int result[N];
for(int i=0;i<N;i++){
result[i] = nums[i];
printf("%d ", result[i]);
}
}
Thanks for the help but after some more looking I found what I was doing wrong and now works.
code :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0;i<N;i++)
{
arr[i]=10+rand()%30;
}
for(i=0;i<N;i++)
{
for(j=i+1;j<N;j++)
{
if(arr[i]==arr[j])
{
do
{
arr[i]=10+rand()%30;
}
while(arr[i]==arr[j]);
}
}
printf(">>%d\t",arr[i]);
}
return 0;
}
I want to produce different numbers with C.
We can generate a random number using the stdlib library and the srand function.
For example; I want to produce a random number between 0 and 5.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void)
{
int i;
int n = 4;
int array[3];
srand(time(NULL));
for(i = 0; i < n; i++)
{
array[i] = rand() % 5;
printf("%d\n", array[i]);
}
return 0;
But the same numbers may coincide here.Like this:
2
4
4
1
How can I prevent this?
Maybe you can use something like this:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(void)
{
int i;
int n = 4;
int array[4];
// Fill an array with possible values
int values[5] = {0, 1, 2, 3, 4};
srand(time(NULL));
for(i = 0; i < n; i++)
{
int t1 = rand() % (5-i); // Generate next index while making the
// possible value one lesser for each
// loop
array[i] = values[t1]; // Assign value
printf("%d\n", array[i]);
values[t1] = values[4-i]; // Get rid of the used value by
// replacing it with an unused value
}
return 0;
}
Instead of random number you can generate random non-zero shift from the previous number:
#include <stdio.h>
#include <stdlib.h>
int myrand() {
static int prev = -1;
if (prev < 0)
prev = rand() % 5;
prev = (prev + 1 + rand() % 4) % 5;
return prev;
}
int main(void) {
int i;
for (i = 0; i < 20; i++)
printf("%d\n", myrand());
}
This code is designed to find the sum of digits of 100!. I get the correct ouput in ideone but the wrong one in codeblocks. Please help.
#include <stdio.h>
#include <stdlib.h>
#define size_of_number 160
#define question 100
//Function Prototypes
void initialise(int[]);
int sum_of_digits(int[]);
void factorial(int[],int);
int main()
{
int number[size_of_number];
int sum;
initialise(number);
factorial(number, question);
//Getting the sum of the digits of the number
sum = sum_of_digits(number);
printf("The sum of the digits of %d! is %d.\n",question, sum);
return 0;
}
//Initially, the number is 0 so all it's digits are set to zero.
void initialise(int number[])
{
int i;
for(i = 0; i < size_of_number; i++)
{
number[i] = 0;
}
}
//Finding the factorial by multiplying the digits
void factorial(int number[], int num)
{
int i, first_digit;
int carry, replace, product;
first_digit = 0;
number[first_digit] = 1;
while(num != 1)
{
carry = 0;
for(i = 0; i <= first_digit; i++)
{
product = num*number[i] + carry;
replace = product%10;
carry = product/10;
number[i] = replace;
if( (i == first_digit) && (carry > 0) )
{
first_digit++;
}
}
num--;
}
}
//Finding the sum of all digits
int sum_of_digits(int number[])
{
int i, sum;
for(i = 0; i < size_of_number; i++)
{
sum = sum + number[i];
}
return sum;
}
I had problems with some other programs too. Why s Codeblocks not giving the correct output which is 648 ?
You don't initialize sum in the function sum_of_digits. Normal local variables don't automatically get a starting value in C, so your program has what the C standard calls undefined behaviour. Anything can happen, but what typically does happen is that the variable starts with whatever data happened to be in the place in memory where the variable happened to be located.
The random function is not working in the parameters set and I do not know why. Can anyone help? I need random numbers between 18 and 38 and I can't seem to get that and I do not know why.
Here's my code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct tires
{
char Manufacturer[40];
int tire_pressure[2];
int pressure_change;
}typedef tires;
void getTireInformation(tires*, int);
void tirePressure(tires*, int);
int main()
{
tires tire[4];
tires* ptire = &tire[0];
getTireInformation(ptire, 4);
tirePressure(ptire, 4);
return 0;
}
void getTireInformation(tires* ptire, int size)
{
int i = 0;
for (i = 0; i < size; i++)
{
printf("please enter Make for the tire: \n");
scanf("%s", &(ptire + i) ->Manufacturer);
}
printf("all tire make you entered ...just for verification:\n");
for(i = 0; i < size; i++)
printf("%s\n",(ptire +i) ->Manufacturer);
}
void tirePressure(tires* ptire, int size)
{
int i = 0;
int min = 18;
int max = 38;
for (i = 0; i < size; i++)
{
srand(time(NULL));
ptire = rand()%(max - min)-min;
printf("%d\n", (ptire + i) -> tire_pressure);
}
}
Edit: Here's my updated function after making the suggested fixes
void tirePressure(tires* ptire, int size)
{
int i = 0;
int min = 18;
int max = 38;
for (i = 0; i < size; i++)
{
ptire = rand()%(max - min + 1) + min;
printf("%d\n", (ptire + i) -> tire_pressure);
}
}
It's not necessary to call srand(time(NULL)); every time it generates a random number. Put that in main(), before any function call.
Then change
rand() % (max - min) - min;
to
rand() % (max - min + 1) + min;
Say max = 3 and min = 1, you need rand() % 3 + 1 to generate a random number from 1 to 3 inclusively.
There is another problem, which have nothing to do with random number generating: The random numbers generated is assigned to ptire, that is, you are assigning a tires* with an int!
I've refined your code. Hope it will work:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct tires
{
char Manufacturer[40];
int tire_pressure[2];
int pressure_change;
} typedef tires;
// Prototypes
void getTireInformation(tires*, size_t);
void tirePressure(tires*, size_t);
int main()
{
tires tire[4];
tires* ptire = &tire[0];
srand(time(NULL));
getTireInformation(ptire, 4);
tirePressure(ptire, 4);
return 0;
}
void getTireInformation(tires* ptire, size_t size)
{
size_t i = 0;
for (i = 0; i < size; i++)
{
printf("Please enter the maker of the tire: \n");
scanf("%s", (ptire + i) -> Manufacturer); // just use str. &str actually causes undefined bahavior
}
printf("All tire make you entered ...just for verification:\n");
for(i = 0; i < size; i++)
printf("%s\n", (ptire +i) -> Manufacturer);
}
void tirePressure(tires* ptire, size_t size)
{
int i = 0;
int min = 18;
int max = 38;
for (i = 0; i < size; i++)
{
(ptire + i) ->tire_pressure[0] = rand() % (max - min + 1) + min;
printf("%d\n", (ptire + i) -> tire_pressure[0]);
}
}
And here is the result when I run it:
Please enter the maker of the tire:
qwert
Please enter the maker of the tire:
fewqwe
Please enter the maker of the tire:
hcgexf
Please enter the maker of the tire:
zrbghcr
All tire make you entered ...just for verification:
qwert
fewqwe
hcgexf
zrbghcr
22
34
31
31
All numbers are between 18 to 38 now. Note that tire_pressure is an array containing two ints. Without knowing your purpose, I just gave random numbers to its first element.