Code to calculate the probability of sum of 2 dices using Monte Carlo Simulation method :
#include <stdio.h>Output :
#include <stdlib.h>
#include <time.h>
#define SIDES 6
#define R_SIDE (rand() % SIDES + 1)
int main(void)
{
int trials;
int d1, d2;
int outcomes[13] = {0};
const int n_dice = 2;
srand(clock());
printf("Enter number of trials: ");
scanf("%d", &trials);
for (int j = 0; j < trials; ++j)
outcomes[(d1 = R_SIDE) + (d2 = R_SIDE)]++;
printf("Probability:\n");
for (int j = 2; j < n_dice * SIDES + 1; ++j)
printf("j=%d p=%lf\n", j, (double)(outcomes[j]) / trials);
return 0;
}
Enter number of trials: 10
Probability:
Sum=2 P=0.000
Sum=3 P=0.100
Sum=4 P=0.200
Sum=5 P=0.100
Sum=6 P=0.300
Sum=7 P=0.000
Sum=8 P=0.100
Sum=9 P=0.000
Sum=10 P=0.100
Sum=11 P=0.000
Sum=12 P=0.100⚡2❤2👍2
Code to print x pattern (twitter new logo xd) in c :
#include <stdio.h>Output :
int main(void){
int n;
printf("Enter no. of lines:");
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(i==j)
printf("\\\\");
else if(i==n+1-j)
printf("/");
else
printf(" ");
}
printf("\n");
}
return 0;
}
Enter no. of lines:5
\\ /
\\ /
\\
/ \\
/ \\👍2❤1
A program that replaces tabs in the input file with the proper number of
blanks to the next tab stop ( A problem from the book C by K&R):
blanks to the next tab stop ( A problem from the book C by K&R):
#include <stdio.h>
#include <stdlib.h>
void tab_to_space(FILE *ifp, FILE *ofp) {
int c;
int space = 0,
count = 0;
rewind(ifp);
while((c = getc(ifp)) != EOF) {
if(c == '\t') {
space = (8-(count%8));
while(space != 0) {
putc(' ', ofp);
space--;
count++;
}
} else {
putc(c, ofp);
++count;
}
if(c == '\n')
count = 0;
}
}
int main(int argc, char *argv[]) {
FILE *ifp,
*ofp;
if(argc != 3) {
printf("Need ifp,ofp files");
exit(1);
}
ifp = fopen(argv[1], "r");
ofp = fopen(argv[2], "w");
tab_to_space(ifp, ofp);
fclose(ifp);
fclose(ofp);
return 0;
}
👍5 4👀1