RockJumpwa22
RockJumpwa22

Reputation: 21

How to insert output into an array in c

My code:

// DICE ROLL PROGRAM
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>


int main()
{
    // defining variables until "till here" comment
    int i;
    int rollDice;
    int firInp;
    int secInp;
    int flag = 1; // flag variable set to 1 which will later be set to zero
    srand (time(NULL)); // seeding rand so that we get different values every time

    // till here

    while(flag) // while loop runs as long as flag variable has a value
    {

    printf("Enter the amount of faces you want your dice to have (MAX=24, MIN=2): "); // prints the message
    scanf("%d", &firInp); // user input stored into firInp
    printf("Enter the amount of throws you want(MAX=499, MIN=2): "); // this message is printed after the users first input
    scanf("%d", &secInp); // user input stored into secInp



    if (((firInp < 25)&&(firInp > 1))&&((secInp < 500)&&(secInp > 1))){ // if statement to check parameters met
    for(i = 0; i < secInp; i++){
        rollDice = (rand()%firInp) + 1; // added 1 to rand because if the value is ever zero, you will get an error
        printf("%d \n", rollDice);

    }
    flag = 0; // now the flag variable is set to zero, exiting the while loop
    }
    else{
        printf("Sorry, these numbers don't meet the parameters\nPlease enter a number in the right parameters.\n");
    }
    }

   return 0;
}

I want to input the values I obtain from "rollDice" into an array. for example: If the user enters firInp and secInp as 6, and they get the following values: 1 2 2 3 1 6 I want these numbers to be stored in an array like so: arrayA = [1,2,2,3,1,6]

Upvotes: 0

Views: 644

Answers (1)

Emily-TTG
Emily-TTG

Reputation: 604

Well it really depends on the particular codebase - my example uses stack frame allocation but it could easily be done using the malloc/calloc method suggested in the comments

(The following is pseudocode, you wil need to integrate it into your application)

int main() {
    int dice_rolls[6];
    for(int i = 0; i < 6 i++) {
        roll = rollTheDice(); // In your program you have your own method for getting this number - the point still stands
        dice_rolls[i] = roll;
    }
}

Upvotes: 1

Related Questions