Dice Programm in C - c

I'm having some trouble with my homework and I hope someone can help me with it.
They want me to create a dice game with the following requests:
5 dice are rolled.
Grand is what you get by rolling 5x the same number
Poker for 4x the same number
Full House for getting 3x the same number and another 2 with the same number aswell. example:(5,5,5,2,2)
I have written a code in which i can get some of the requests done. But I also have to save the values as an array which causes me alot of trouble. Can someone please show me how it is done? and explain it aswell? This is my code so far:
#include <stdio.h>
#include <stdlib.h>
int main () {
srand (time(0));
int dice[5];
int i;
printf ("Program dice\n");
for (i=0; i<5; i++)
dice [1] = (rand ()%6 )+ 1;
printf ("Würfel 1: %d \n", dice [1]);
dice [2] = (rand ()%6 )+ 1;
printf ("Würfel 2: %d \n", dice [2]);
dice [3] = (rand ()%6 )+ 1;
printf ("Würfel 3: %d \n", dice [3]);
dice [4] = (rand ()%6 )+ 1;
printf ("Würfel 4: %d \n", dice [4]);
dice [5] = (rand ()%6 )+ 1;
printf ("Würfel 5: %d \n", dice [5]);
for(i = 0; i < 6; i++)
if (dice [i] == 5)
{
printf ("You've won! Grand!");
return (0);
}
else
{
printf ("You lost.");
return (0);
}
return 0;
}

First, let's take a look on how you generate the numbers... consider you are using an array, you can access it using the [] operator, it means that if you have an array, and you want to access the first element, considering that array index start from 0, you can do it by doing array[0] and since we are inside a for loop with a i that get values from 0 to 5, you can generate your dice roll with this
int dice[5];
for (int i=0; i<5; i++){
dice [i] = (rand ()%6 )+ 1;
printf ("Würfel %d: %d \n", i, dice [i]);
}
than, you have to create the logic behind each possible game win

I think it is better to restructure the code.
You should store the count for each dice roll. For example, (5,5,5,3,3) should generate (0,0,2,0,3,0).
Now just use these instead.
Try this:
#include <stdio.h>
#include <stdlib.h>
const int DICE_ROLLS = 5;
int main()
{
srand(time(0));
int number_of_rolls[6] = {0};
// Simulate the random rolls
for(int i = 0; i < DICE_ROLLS; ++i)
{
// Get a new roll ( from 1 to 6)
int dice_value = rand() % 6 + 1;
// If it is 1, increment rolls for number_of_rolls[0]
++number_of_rolls[ dice_value - 1 ];
}
// Now it is simple. To check for all five, do
for(int i = 0; i < DICE_ROLLS; ++i)
{
if(number_of_rolls[i] == 5)
{
printf("You've won! Grand!");
}
}
return 0;
}
Hopefully you get the gist now. :-)

I gave my students a similar question a while back. My solution can be found here, although I only implemented checking for the same values (yahtzee/kniffel).
The code is written to be pseudo object orientated in that you have a struct cup that is initialized to store an array of pointers to dice object. The cup is then filled with a specified number of struct dict, found here. Following that you can roll the cup which uses the rand() function to randomize values for each die in your cup.
int max_value = 0, dice_count = 0, ret;
struct cup *my_cup = NULL;
prompt_int("Please enter the max value of each die", &max_value);
prompt_int("Please enter the number of die in the cup", &dice_count);
my_cup = create_cup(dice_count);
fill_cup(my_cup, max_value);
roll_cup(my_cup);
ret = check_cup(my_cup)
switch(ret){
//Respond[ to combinations
}
In the main.c you will find a function called check_cup in which you can put checking logic to check for certain combinations of dice, at the moment it just checks if all the dice are the same and returns 0, this could be modified to return certain values for certain.

Related

Checking dice roll combinations in C

I try to code a little dice game in C. I am a beginner in C and still have to learn a lot. The user inserts the numbers of 5 dices. The program puts every number into an array and then prints out one of 4 cases:
Grand = same number on all 5 dices
Poker = same number on 4 dices
Full House = 3 equal and 2 equal numbers
Lose = No Grand, Poker or Full House
I just could write an if-statement-block that checks every possible combination and then prints the right case into the console. But that would take me quite a while. So I wanted to ask if there is an easier way to achieve that.
I coded the Grand and Lose so far:
#include <stdio.h>
int main() {
int dices[5];
printf("Program Dice game \n\n");
for(int i=0; i < 5; i++) {
printf("dice %i: ", i+1);
scanf("%i", &dices[i]);
}
printf("dice \t");
printf("1 \t");
printf("2 \t");
printf("3 \t");
printf("4 \t");
printf("5 \n");
printf("number \t");
for(int i=0; i < 5; i++) {
printf("%i \t", dices[i]);
}
printf("\n\n");
if(dices[0] == dices[1] && dices[0] == dices[2]
&& dices[0] == dices[3] && dices[0] == dices[4]) {
printf("Win! Grand!");
} else {
printf("Lose!");
}
return 0;
}
One solution could be to sort your dice array. This way, you'll have a lot fewer comparaisons to do. here's an exemple:
int cmp_func (const void *a, const void *b)
{
return (*(int*)a - *(int*)b);
}
int main() {
int dice[5] = {2, 3, 2, 3, 3}; //arbitrary dice combination
qsort(dice, 5, sizeof(int), cmp_func);
if (dice[0] == dice[4])
{
printf("Grand\n");
}
else if (dice[1] == dice[4] || dice[0] == dice[3])
{
printf("Poker\n");
}
else if ((dice[0] == dice[2] && dice[3] == dice[4]) || (dice[0] == dice[1] && dice[2] == dice[4]))
{
printf("Full House\n");
}
else
{
printf("Lose\n");
}
return (0);
}
Once your dice are sorted, if the first one is equal to the last one, you can assume they're all equals. If the first one is equal to the fouth one OR the second one is equal to the last one, you can assume you have 4 same dice, etc...
Note that if the initial order of your dice array matters, you'll have to duplicate it and use the other array to sort / test.

(Lotto 6/49 simulation) Calculate how many draws will take place until a user-entered combination hits the jackpot

I have my code and data for my Lotto 6/49 simulation. I just don't know how to create a simple mathematical expression to calculate how many draws will take place until the user hits the jackpot
Code:
#include <stdio.h>
#include <stdlib.h> //need this library to use srand and rand without warnings
#include <time.h> //need this library to use time function
int main(void) {
int i, j, k , temp, count1=0;
unsigned int count2=1;
int select[6];
int jackpot[6];
printf("Welcome to Lotto 6/49! The 6 numbers you choose must match the 6 randomly chosen numbers in the lottery in order to win the jackpot. Select your 6 numbers!\n\n");
for(i=0; i<6; i++)
{
printf("Enter a number between 1-49: ");
scanf("%d", &select[i]);
}
srand(time(NULL));
for(;;){
for(i=0; i!= 6 ; ) //This loop produces the winning number combination
{
temp= (rand() %49)+1; //produce a random number between 1 and 49
for( k =0 ; k<i && (temp!=jackpot[k]) ; k++); //make sure we do not have duplicate
if (k==i){ //only write to the array if we do not have a duplicate
jackpot[i] = temp;
i++; //only increment the loop if we write a value to the array
}
}
printf("\nThe winning numbers are: "); //displays the winning numbers
for(i=0;i<6;i++)
printf("\t%d\t",jackpot[i]);
printf("\n");
// This loop will check the user array with the jackpot array to determine if it is a winning combination
for(i=0; i<6 && i ==count1; i++){ //if we do not match the first element, we skip the rest
for(j=0; j<6 ; j++)
{
if(select[i]==jackpot[j]){
count1+=1; // only increment if we match
}
}
}
if(count1==6){ //all 6 numbers matched
printf("\n\nYou win the JACKPOT! Congratulations! \nIt took you %d draws to win", count2);
break;
}
else{
count2+=1;
count1=0; //reset match count
}
}
return 0;
}
Data (number range limited to 8 numbers for easier recording, eg temp= (rand() %8)+1 instead of temp= (rand() %49)+1 # line 19.)
Count1 = user input matched
Count2 = # of draws
↑
I have no clue how to calculate this

I'm trying to get the counter to work, how many months have a higher income than the same month from last year

The line of code I'm having trouble with has to do with counting a number of months, I'm passing a value up from a function that I thought would work but I'm not getting a proper readout from it. I'm sure I'm missing something stupid or the mistake I made is very basic but I can't seem to get it right. I would greatly appreciate any help I can get. please excuse the many printf statements, I was trying to find where the error was.
#include <stdio.h>
#include <stdlib.h>
void DisplayInstructions();//function 1
void HigherSales(float yearOne, float yearTwo, int k);//fuction 2
int months (float yearOne, float yearTwo);//function 3
void main()
{
float yearOne[12];//variables
float yearTwo[12];
int i = 0;
int j = 0;
int k = 0;
int count = 0;
DisplayInstructions();//calling first function
printf(" \n");
for (i = 0; i<12; i++)//scanf for entering sales values
{
j= i+1;
printf("enter the sales figures for month %d in year one \n",j);
scanf_s("%f",&yearOne[i]);
}
for (i = 0; i<12; i++)
{
j= i+1;
printf("enter the sales figures for month %d in year two \n",j);
scanf_s("%f",&yearTwo[i]);
} //end of entering sales
k=0;
for (i = 0; i<12; i++)//populating function 2
{
k++;
HigherSales(yearOne[i], yearTwo[i], k);
}
printf("\n count before going into the for loop is %d \n",count);
for (i = 0; i<12; i++)
{
months(yearOne[i], yearTwo[i]);//populating function 3
printf("before going into count calculation months is reading %f",months(yearOne[12], yearTwo[12]));
count = count + months(yearOne[12], yearTwo[12]); //calling function 3 so that i get the sum of times y1 < y2
printf(" \n after calc count is %d \n after calc monts is returning %f", count, months(yearOne[12], yearTwo[12]));
}
printf(" \n the number of months in year two where sales have increased is %d \n", count);
system("pause");
}
void DisplayInstructions() //function 1 printf's
{
printf("\n");
printf("this program consists of one function called 'DisplayInstructions' \n");
printf("the function takes no arguments and simply dispays this message \n");
printf("it is innitalised above main, called inside main and described below main \n");
}
void HigherSales(float yOne, float yTwo, int g)
{
if(yOne < yTwo) //function 2 comparing logic
{
printf("month %d in year two had higher sales than the same month the year prior \n", g);
}
}
int months(float monthOne, float monthTwo)
{
int m = 0;
if(monthOne < monthTwo )
{
m = m + 1;
printf("\n in the mothhs function, m loop, m is %d \n", m);
return m;
}
}
The function int months(float monthOne, float monthTwo) does not work as you probably expect.
With int m = 0; the variable m always is initialized with 0 every time this function is called, therefore m = m + 1 won't count up how often the condition is true - its either 0 or 1
To make the function remember the value of m from its last call you need to declare it static int m = 0;
But in your case this wouldn't be the best idea either because you would only want to know the last return value (when all months are iterated).
Furthermore function months only has a return value if the condition is true - your compiler should have complained about that.
So if you want to make this simple comparison within a function which is called within a loop:
int months(float monthOne, float monthTwo)
{
if (monthOne < monthTwo)
return 1;
else
return 0;
}
for (i = 0; i<12; i++)
{
count += months(yearOne[i], yearTwo[i]);
}
In your context I cant figure out the purpose of count = count + months(yearOne[12], yearTwo[12]); - beside the fact that you are accessing the 13th element of your array which is invalid, it makes no sense to increment your counter by the same comparison every loop.
The modified code below addresses the errors I commented under your post as well as some others (see comments in code.) I automated inputs using rand() to speed up testing, but left all your original code. Comment out the auto populate sections for your purposes.
Note: Not all logic errors are addressed, but enough to get you started. Read the comments left in the code.:
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
void DisplayInstructions();//function 1
void HigherSales(float yearOne, float yearTwo, int k);//fuction 2
int months (float yearOne, float yearTwo);//function 3
const char month[][4] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
void main()
{
float yearOne[12];//variables
float yearTwo[12];
int i = 0;
int j = 0;
int k = 0;
int count = 0;
srand(clock());//seed pseudo random number generator
DisplayInstructions();//calling first function
printf(" \n");
for (i = 0; i<12; i++)//scanf for entering sales values
{
j= i+1;
printf("enter the sales figures for month %d in year one \n",j);
yearOne[i] = rand();//Added to automate populating monthly sales numbers...
while(yearOne[i] < 500)
{
yearOne[i] = rand()%10000;//Added to automate populating monthly sales numbers...
Sleep(100);//pause execution for 0.1 seconds
}
printf("YearOne - %s: %lf\n", month[i], yearOne[i]);
//scanf("%f",&yearOne[i]);
}
for (i = 0; i<12; i++)
{
j= i+1;
printf("enter the sales figures for month %d in year two \n",j);
yearTwo[i] = rand();//Added to automate populating monthly sales numbers...
while(yearTwo[i] < 500)
{
yearOne[i] = rand()%10000;//Added to automate populating monthly sales numbers...
Sleep(100);//pause execution for 0.1 seconds
}
printf("YearTwo - %s: %lf\n", month[i], yearOne[i]);
//scanf("%f",&yearTwo[i]);
} //end of entering sales
k=0;
for (i = 0; i<12; i++)//populating function 2
{
k++;
HigherSales(yearOne[i], yearTwo[i], k);
}
printf("\n count before going into the for loop is %d \n",count);
for (i = 0; i<12; i++)
{ //Hint: In this for loop, you are calling months function more
//than you want to. Consider assigning a variable to read it's
//output, then use that variable in the printf statements.
months(yearOne[i], yearTwo[i]);//populating function 3
// printf("before going into count calculation months is reading %f",months(yearOne[i], yearTwo[i]));
printf("before going into count calculation months is reading %d",months(yearOne[i], yearTwo[i]));//changed format type to match variable type
count = count + months(yearOne[i], yearTwo[i]); //calling function 3 so that i get the sum of times y1 < y2
//printf(" \n after calc count is %d \n after calc monts is returning %f", count, months(yearOne[i], yearTwo[i]));
printf(" \n after calc count is %d \n after calc monts is returning %d", count, months(yearOne[i], yearTwo[i]));//changed format type to match variable type
}
printf(" \n the number of months in year two where sales have increased is %d \n", count);
// system("pause");
printf("hit any key to continue.");
getchar(); //this method is more idomatic and portable to pause code
}
void DisplayInstructions() //function 1 printf's
{
printf("\n");
printf("this program consists of one function called 'DisplayInstructions' \n");
printf("the function takes no arguments and simply dispays this message \n");
printf("it is innitalised above main, called inside main and described below main \n");
}
void HigherSales(float yOne, float yTwo, int g)
{
if(yOne < yTwo) //function 2 comparing logic
{
printf("month %d in year two had higher sales than the same month the year prior \n", g);
}
}
int months(float monthOne, float monthTwo)
{
static int m = 0;//use static here to allow m to keep value from call to call.
//static extends life of variable until program ends.
if(monthOne < monthTwo )
{
m = m + 1;
printf("\n in the mothhs function, m loop, m is %d \n", m);
}
return m;//moved from inside loop, otherwise return will not occur
//for some evaluations.
//Perhaps you would prefer an else statement
}

For loop "<" vs "<=" print format issues in program

I am learning C on my own with a book and I cannot for the life of me figure out how to solve this exercise. I'm obviously looking at it in the wrong way or something. Here is an explanation below.
Listed below are some functions and the main function at the bottom. This program is compiled to generate a certain number of random numbers and determine the min and the max of the random numbers. If you copy and paste this code, you will see how it works. Anyways, an exercise asks me to go to the function "prn_random_numbers()" and change the for loop from "for (i = 1; i < k; ++i)" to for (i = 2; i <= k; ++i). This causes the first line format to print incorrectly. The exercise is to further modify the program in the body of the for loop to get the output to be formatted correctly.
To sum it up, the "prn_random_numbers()" function is written to print out 5 random numbers before moving to the next line. Hence the" i % 5" if statement. Now, for some reason, when you make the slight adjustment to the for loop, as the exercise asks above, it causes the first line to only print 4 numbers before moving to the next line. I have tried a number of things, including trying to force it to print the 5th number, but it only duplicated one of the random numbers. I even tried "i % 4" to see if it would print 4 numbers for each row, but it only prints 3 numbers for the first row instead of 4! So it always prints one less number on the first line than it is supposed to. I have n clue why it is doing that and the book does not give an exercise. Do you have any idea?
Bear with me if you think this is a stupid question. I am just learning on my own and I want to make sure I have a good foundation and understand everything as I learn it, before moving forward. I appreciate any help or advice!
prn_random_numbers(k) /* print k random numbers */
int k;
{
int i, r, smallest, biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for (i = 1; i < k; ++i)
{
if (i % 5 == 0)
printf("\n");
r = rand();
smallest = min(r, smallest);
biggest = max(r, biggest);
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}
int main()
{
int n;
printf("Some random numbers are to be printed.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
while (n < 1)
{
printf("ERROR! Please enter a positive integer.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
}
prn_random_numbers(n);
return (EXIT_SUCCESS);
}
the following proposed code:
properly initializes the random number generator
cleanly compiles
properly checks for and handles errors
performs the desired functionality
avoids having to list instructions twice
follows the axiom: Only one statement per line and (at most) one variable declaration per statement.
does not use undefined functions like: max() and min()
and now the proposed code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void prn_random_numbers(int k)
{
int count = 1;
int r;
int smallest;
int biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for ( int i = 2; i <= k; i++, count++)
{
if (count % 5 == 0)
{
count = 0;
printf("\n");
}
r = rand();
smallest = (r < smallest)? r : smallest;
biggest = (r > biggest)? r : biggest;
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}
int main( void )
{
int n;
srand( (unsigned)time( NULL ) );
do
{
printf("Please enter a positive integer, greater than 0.\n");
printf("How many would you like to see? ");
if( scanf("%d", &n) != 1 )
{
fprintf( stderr, "scanf for number of random numbers failed\n" );
exit( EXIT_FAILURE );
}
} while( n < 1 );
prn_random_numbers(n);
// in modern C, if the returned value from `main()` is 0 then no `return 0;` statement needed
}
a typical run, no input problems is:
Please enter a positive integer, greater than 0.
How many would you like to see? 20
98697066 2110217332 1247184349 421403769 1643589269
1440322693 985220171 1915371488 1920726601 1637143133
2070012356 541419813 1708523311 1237437366 1058236022
926434075 1422865093 2113527574 626328197 1618571881
20 random numbers printed.
Minimum: 98697066
Maximum: 2113527574
Try to use a debugger to solve your problem, it's easy to use and really helpfull :)
SOLUTION:
Your i variable don't count the number of numbers because it is initialize at 1 (in the for statement), so you need to declare a new variable to count properly.
If you have still a problem:
void prn_random_numbers(int k)
{
int count = 1;
int i, r, smallest, biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for (i = 2; i <= k; i++, count++) {
if (count % 5 == 0) {
count = 0;
printf("\n");
}
r = rand();
smallest = min(r, smallest);
biggest = max(r, biggest);
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}

How to select multiple elements in an array with C?

Is there a way to select multiple elements in array using one line of code in C? For instance, say I had the following code (assuming I already asked the user for twenty numbers, the first ten I asked to be positive and the last ten I asked to be negative):
if (myArray[0 through 9] > 0)
{
printf("Thank you for providing positive numbers!");
}
else
{
printf("Sorry, please try again!");
}
if (myArray[10 through 19] < 0)
{
printf("Thank you for providing negative numbers!");
}
else
{
printf("Sorry, please try again!");
}
What code could I substitute for "through"? I am fairly new to this language, and have never heard of a way of doing so. I know that with this particular code I could make two arrays, one for the positive numbers and one for the negative numbers, but I am curious to know for other programming projects.
Thank you for reading and answering!
There's nothing built-in that does it, you need to write a loop. Don't forget that array indexes start at 0.
int all_positive = 1;
int i;
for (i = 0; i < 10; i++) {
if (myArray[i] <= 0) {
all_positive = 0;
break;
}
}
if (all_positive) {
printf("Thank you for providing positive numbers!\n");
}
int a[20];
// entering values for the array
_Bool first_positive = 1;
for ( size_t i = 0; i < 10 && first_positive; i++ )
{
first_positive = 0 < a[i];
}
if ( first_positive ) puts( "Hura, first 10 elements are positive" );
_Bool last_negative = 1;
for ( size_t i = 10; i < 20 && last_negative; i++ )
{
last_negative = a[i] < 0;
}
if ( last_negative ) puts( "Hura, last 10 elements are negative" );
Instead of type name _Bool you can use type int if your compiler does not support _Bool
The program requests number of rows (1D array).
Then asks for 2 integers, whole numbers.
Then asks user to select 2 rows.
The sum of the 2 selected rows is then added.
#include <stdio.h>
int main ()
//1D_Array. Load Element and Add Sumline .
//KHO2016.no5. mingw (TDM-GCC-32) . c-ansi .
{
//declare
int a,b,c,d,e,sum1=0;
int array[50];
int i,j,elm1,elm2;
//valuate
printf ("Plot a number of elements [1 - 20]: ");
scanf ("%d",&a);
printf ("Plot a value : ");
scanf ("%d",&b);
printf ("Plot an increment value : ");
scanf ("%d",&c);
//calculate
{for (i<0;i<=a;i++)
{array[i] =(b+(++c)); // set value for variable [i], inside the array subscript. the vairable [i] must have an INT, and an increment to function !
sum1 = (sum1 + array[i]);
printf ("Row [%.2d] : %.2d + %.2d = %d\n",i,b,c,array[i]);}
printf ("\nSum total = %d\n",sum1);}
printf ("\nRow [%.2d] = %d\n",b,array[b]);
printf ("Row [%.2d] = %d\n",a,array[a]);
printf ("Select 2 Rows :\n");
scanf ("%d%d",&elm1,&elm2);
d=elm1;
e=elm2;
printf ("You selected Row [%.2d] = %d\n",d,array[d]);
printf ("You selected Row [%.2d] = %d\n",e,array[e]);
printf ("The sum of two selected Rows [%d]+[%d] : %d + %d = %d\n",d,e,array[d],array[e],array[d]+array[e]);
//terminate
return 0;
}

Resources