I am trying to let children to process different random value EVERYTIME. If there is 3 children, I want them to generate 3 different random value each, so in total 3*3=9 different number. I've tried many srand(), if I go srand(time(NULL)) , all the children produces three same random number(123, 123, 123), and if I put getpid() into srand(), each child produces a random number three times(111,222,333). But I can't find something that produces 9 different random values. Here are my codes.
int main(int argc, char const *argv[]){
int pid[6];
for (int i = 0; i < 3; i++) {
pid[i] = fork();
if (pid < 0) {
printf("Fork Failed\n");
exit(0);
}
if (pid[i] == 0) {
time_t t;
srand((int)time(&t) % getpid());
int r = rand() % 30;
int count = 0;
while (count < 3){
printf("Child %d: %d\n",i+1,r);
count++;
}
exit(0);
}
}
return 0;
}
You only call rand() once in each child (outside the while (count < 3) loop, and then you print out that same number three times in a loop. Note that you do not assign any new value to r between loop iterations, so naturally its value hasn't changed when you print it again.
If you want three different numbers, call rand() three times (inside the loop). Replace
int r = rand() % 30;
int count = 0;
while (count < 3){
printf("Child %d: %d\n",i+1,r);
count++;
}
with
int count = 0;
while (count < 3){
int r = rand() % 30;
printf("Child %d: %d\n",i+1,r);
count++;
}
Related
// C Program to Print Prime Numbers From 1 to 100
#include
int main() {
int i, num, count;
// Checking for prime numbers
for (num = 1; num <= 100; num++) {
count = 0;
for (i = 2; i <= num/2; i++) {
if (num % i == 0) {
count++;
break;
}
}
// Checking and Printing Prime Numbers
if (count == 0 && num != 1) {
printf("%d \n", num);
}
}
return 0;
}
I don't understand, if I put 0 at the start of the count variable (i.e., int i, num, count=0; like this) the code is not working. But if you put count=0 inside the for loop it is working. Why is this happening?
I wonder if you wrote that code yourself.
Why did you add count variable to start with if you do not seem to know how it works?
I don't understand, if I put 0 at the start of the count variable (i.e., int i, num, count=0; like this) the code is not working. But if you put count=0 inside the for loop it is working. Why is this happening?
That variable is used to detect if any value of i is found where num is a multiple of i. If that is the case (count != 0 it is not a prime.
Of course you need to do this for each number num which means you must reset count for each iteration of the outer loop.
If you only do it once where you define the variable, it will never find any prime number any more after you saw the first none-prime number.
Working code:
// C Program to Print Prime Numbers From 1 to 100
#include
int main(void) {
int i, num, count;
// Checking for prime numbers
for (num = 2; num <= 100; num++) {
count = 0; // This is the indicator whether a number is prime
// We must reset it here for each number we check.
for (i = 2; i <= num/2; i++) {
if (num % i == 0) {
count++;
break;
}
}
// Checking and Printing Prime Numbers
if (count == 0) {
printf("%d \n", num);
}
}
return 0;
}
Broken code:
// C Program to Print Prime Numbers From 1 to 100
#include
int main(void) {
int i, num, count = 0; // This is only set to 0 once for all numbers we check.
// Checking for prime numbers
for (num = 2; num <= 100; num++) {
for (i = 2; i <= num/2; i++) {
if (num % i == 0) {
count++; // count will never become 0 again.
// We will not be able to detect any prime number after this.
break;
}
}
// Checking and Printing Prime Numbers
if (count == 0) {
printf("%d \n", num);
}
}
return 0;
}
Not related to your problem but some detail to improve the code:
Why do you start with num=1 if you later check num != 1?
Instead start at num=2.
Or print 2 before you start the loop. Then run the loop from num=3 and increment num+=2 to only check the odd numbers.
I have this code in which I need to find all prime numbers from 2 to 1000 and need to print them out in groups of 5 in each line. How can I do that?
#include <stdio.h>
int main() {
int i, a, count;
printf("Prime numbers between 2 and 1000 are : \n");
for (i = 2; i < 1000; i++) {
count = 0;
for (a = 1; a <= i; a++) {
if (i % a == 0)
count++;
}
if (count == 2)
printf("%d\t", i);
}
return 0;
}
You can add a new counter to count the number of prime numbers printed until the current loop. If this counter value is divisable by 5, print a new line.
int main()
{
int i,a,count;
printf("Prime numbers between 2 and 1000 are : \n");
int cnt_prime = 0; // count the number of prime numbers until this loop
for (i=2;i<1000;i++)
{
count=0;
for (a=1;a<=i;a++)
{
if (i%a==0)
count++;
}
if (count==2) {
printf("%d\t", i);
cnt_prime++;
if (cnt_prime % 5 == 0) // print new line after each five numbers
printf("\n");
}
}
return 0;
}
There is another faster approach to find the prime numbers in a range. You can read about sieve of eratosthenes from here: https://www.geeksforgeeks.org/sieve-of-eratosthenes/
Maybe not the best answer, but you could add another counter-variable called prime_count and initialize it with value 0. Then each time you print a prime, you increment that variable. After printing a prime you then check wether prime_count is equal to 4. If that's the case you print a newline-character and reset prime_counter to 0.
The code could look something like this:
int main()
{
int i,a,count,prime_count=0;
printf("Prime numbers between 2 and 1000 are : \n");
for (i=2;i<1000;i++)
{
count=0;
for (a=1;a<=i;a++)
{
if (i%a==0)
count++;
}
if (count==2)
{
printf("%d\t",i);
prime_count++;
if (prime_count == 4)
{
printf("\n");
prime_count = 0;
}
}
}
return 0;
}
You can check till square root of N to verify prime no need to check till N it makes your code O(sqrt(n)) refer this for more info about the algorithm.You can have a variable called printCounter to check total elements printed on console when it become a multiple of 5 we can print a new line.
int main() {
int i, a, printCount = 0 ;
printf("Prime numbers between 2 and 1000 are : \n");
for (i = 2; i < 1000; i++) {
int isPrime = 1;
for (a = 2; a * a <= i; a++) {
if (i % a == 0){
isPrime = 0;
break;
}
}
if (isPrime == 1) {
printf("%d\t", i);
printCount++;
}
if(printCount%5 == 0){
printf("\n");
}
}
return 0;
}
I am learning about fork and pipe but have a problem with the following: My aim was to build a program with 3 processes and I did that but my question is: Why does printf("Sum of first half: %d\n", sum); get executed twice?
I checked the code for any logical errors that I made but couldn't find anything.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int size = sizeof(arr) / sizeof(int);
int sum;
int fd[2];
pipe(fd);
int id = fork();
if (id == 0) // Child process
{
for (int i = 0; i < size / 2; i++)
sum = sum + arr[i];
int j = fork();
if (j == 0)
{
printf("Hello I'm the grandchild\n");
}
}
else // Parent process
{
for (int i = size / 2; i < size; i++)
sum = sum + arr[i];
}
if (id == 0) // Child process writing to the pipe
{
close(fd[0]);
write(fd[1], &sum, sizeof(sum));
close(fd[0]);
printf("Sum of first half: %d\n", sum);
}
else // Parent process reading from the pipe
{
int x;
close(fd[1]);
read(fd[0], &x, sizeof(sum));
close(fd[1]);
printf("Sum of second half: %d\n", sum);
printf("Total sum: %d\n", x + sum);
}
}
Your code simplified:
int main()
{
int id = fork();
if (id == 0)
fork();
if (id == 0)
printf("Sum of first half\n");
else
printf("Sum of second half\n");
}
And the explanation:
code
Parent
Child
Granchild
fork()
fork
N/A
N/A
id value
id != 0
id==0
N/A
if (id == 0) fork()
then not executed
fork
N/A
id value
id != 0
id == 0
id == 0
if (id == 0) printf("sum first")
then not executed
printf
printf
else printf("sum second half")
printf
else not executed
else not executed
So from the numbers from 1 to n, I have to compute how much the '1' digit occurs. For example: if n is 11, the total numbers is 4 (1, 10, 11). My assignment is saying that i have to use threads for this. This is what I've wrote so far:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
typedef struct {
int from;
int to;
} th_struct;
void *thread_function(void *param){
th_struct *st = (th_struct *) param;
int count = 0;
int nr;
for(int i = st->from; i <= st->to; i++){
nr = i + 1;
while(nr != 0 ){
if (nr % 10 == 1)
count++;
nr /= 10;
}
}
return (void *) (long) count;
}
int main(int argc, char **argv)
{
int threads, n, count = 0, result;
sscanf(argv[1], "%d", &n);
sscanf(argv[2], "%d", &threads);
th_struct info[threads];
pthread_t tid[threads];
for(int i = 0; i < threads; i++){
if(i == 0)
info[0].from = 0;
else
info[i].from = info[i - 1].to + 1;
info[i].to = info[i].from + n / threads - 1;
if(i < n / threads)
info[i].to++;
pthread_create(&tid[i], NULL, thread_function, &info[i]);
}
for(int i = 0; i < threads; i++){
pthread_join(tid[i], (void**)&result);
count += (int) (long) result;
}
printf("%d\n", count);
}
First command line argument is n, and the second is the number of threads. For n equal to 11, the output should be 4. But if I plug in 11 1 (n=11, nr of threads=1) the output is 5 (instead of 4). If i plug in 11 2 (two threads), the output is 9. The output should be the same, no matter how many threads I have.
I have tested the following code, and it works. It computes the number of '1' correctly (the following is the same as in the funcion "thread_function_ above", just adapted for testing):
int function(int n){
int count = 0;
int nr;
for(int i = 0; i <= n; i++){
nr = i + 1;
while(nr != 0 ){
if (nr % 10 == 1)
count++;
nr /= 10;
}
}
return count;
}
So the problem is thread related (I guess). Since this is my first program with threads, I don't know what the problem is. Thanks!
You have a few problems:
Incorrect input ranges:
info[0].from = 0;
...
if(i < n / threads)
info[i].to++;
Should be:
info[i].from = 1;
...
if (n % 2 == 1 && i + 1 == threads)
info[i].to++;
Invalid range processing:
nr = i + 1;
Should be:
nr = i;
Invalid result receiving.i changes its value while iterating for joining threads and for loop executes more times than intended:
pthread_join(tid[i], (void**)&result);
Should be:
void* result;
pthread_join(tid[i], &result);
I have to return which digit in a number occurs the most frequently ( though not how many times it occurs )
So far I can only get this, I don't know how to isolate the digit, only to show how many times each digit occurs.
#include <stdio.h>
int frequentDigit(int);
int main()
{
frequentDigit(123032333);
return 0;
}
int frequentDigit(int arg)
{
int tmp; int i; int myArr[9] = { 0 };
tmp = (arg < 0) ? -arg : arg;
do
{
myArr[tmp % 10]++;
tmp /= 10;
} while (tmp != 0);
for (i = 0; i < 9; i++) { printf("\nThere are %d occurances of digit %d", myArr[i], i); }
}
The array where you are storing the frequency of the digits, i.e myArr[]. Its suppose to hold the frequency of all the number from 0...9. And since there are 10 numbers, you would need an array of lenght 10.
int myArr[10];
Later, you need to traverse through the array once, checking for the max element, and saving the index accordingly, to find which number has occured most number of times.
To traverse, the for loop should go till 9
for (i = 0; i <= 9; i++)
Edited
As someone commented, you can find the max value while you are computing the frequencies itself.
int max = -1, max_num = -1;
do
{
myArr[tmp % 10]++;
if( myArr[tmp % 10] > max)
{
max = myArr[tmp % 10];
max_num = tmp % 10;
}
tmp /= 10;
} while (tmp != 0);
printf("%d", max_num);
Its simple. At the end of your code you have an array of frequencies, if you find the max of that you get the most common element
Just use a loop to find the max and print that:
int max = myArr[0]; // start with max = first element
int max_position=0;
for(int i = 1; i<9; i++)
{
if(myArr[i] > max){
max = myArr[i];
max_position=i;
}
}
printf("\The max is %d occuring %d times ", max_position, max_position)