I'm trying to create a program which randomly decides how many cards you have, then randomly allocates a value to each of those cards.
I have managed to randomise the amount of cards, and I know how to randomise their values using an array and a for loop, but the problem is that this method only works when I manually choose a value for the number of elements in the array, but I want the number of elements to be the random amount of cards.
How do I go about this?
Here's my code so far to show what I mean. And yes, I'm aware the code probably could be done better but this is my first C assignment and I'm a complete beginner.
Thanks :)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main(void)
{
system("cls"); /* Clears output to start */
srand(time(NULL)); /* Sets seed for random number generator */
int player1_amount = rand() %9 + 2; /*Generates random number for player 1's amount of cards */
int player2_amount = rand() %9 + 2; /*Generates random number for player 2's amount of cards */
int a = 1; /* For loop purposes */
while(a <= 1) /* While loop to print out each player's amount of cards once */
{
printf("Player 1 you have %d cards! \n", player1_amount);
Sleep(500);
printf("Player 2 you have %d cards! \n", player2_amount);
a++;
}
Sleep(1000); /* Delays for 1 second before printing card values */
int values[3]; /* Creates an array with 3 elements, but I want the number of elements to be player1_amount from above */
int b; /* Random variable for the loop */
int size = sizeof(values) / sizeof(values[0]); /* Gets length of array */
for (b = 0; b < size; b++) /* For loop randomises 3 values and then stops */
{
values[b] = rand() % 10 +1;
}
printf("Player 1 your cards are"); /* For loop to print out the values one after the other */
for(b = 0; b < size; b++)
{
printf(" %d, ", values[b]);
}
getch();
return 0;
}
I believe you will want to use malloc or calloc for that with a pointer.
int *values = (int *)calloc(player1_amount, sizeof(int));
Just make sure you free your allocation when done:
free(values);
C allows you to declare variable sized array. If you are not interested in using functions like malloc or calloc you can simply use variable to declare array as I've done here :
#include <stdio.h>
void main()
{
int x;
printf("\nEnter the value of x : ");
scanf("%d" , &x);
int array[x];
for(i = 0 ; i < x ; i++)
{
printf("Enter the element : ");
scanf("%d" , &array[i]);
}
for(i = 0 ; i < x ; i++)
{
printf("%d " , array[i]);
}
}
This program runs correctly without any error. So your problem is solved here itself without using malloc or calloc. But just make sure you declare your array after scanning or giving value to your variable which will represent the size of your array(here : x is the variable) and in your case I guess : player1_amount.
But still if you want to use malloc then here it goes :
#include <stdio.h>
#include <stdlib.h>
void main()
{
int x , i;
int * array;
printf("\nEnter the value of x : ");
scanf("%d" , &x);
array = (int *) malloc(x * sizeof(int));
for(i = 0 ; i < x ; i++)
{
printf("Enter the element : ");
scanf("%d" , &array[i]);
}
for(i = 0 ; i < x ; i++)
{
printf("%d " , array[i]);
}
}
Both the codes will give you same output.
A little explanation ...
Malloc will take input parameter as the amount of memory you wish to allocate to given variable(like 'array' in our case) in bytes and will output the pointer to that block of memory.
Since here we are working with integer array the return type is cast as : (int *), had it been a character array we would type cast it as : (char *).
Related
Just getting to learn C better and I'm playing with arrays.
I would like to enter my phone number into an array like this:
#include <stdio.h>
int main()
{
int phoneNum[10];
for (int i = 0; i < sizeof(phoneNum); i++) {
printf("Insert digit %d of your phone number: \n", i + 1);
scanf("%d", &phoneNum[i]);
}
return 0;
}
This seems to fail as it keeps asking me for a new digit. So I tried to print the size of the array:
int phoneNum[10];
printf("%lu", sizeof(phoneNum));
which incredibly gives me the result of 40 even though I initialized it to be 10 (?).
I have three questions:
Why is the result 40 and not 10 in sizeof(phoneNum) ?
How can I add elements in an array successfully with scanf in the above manner?
If the above manner is silly, is there a better, more efficient way to do this? For example directly enter 10 digits into an array? I can of course use scanf("%d%d%d...", digit1, digit2, digit3, ...) but I would like a generalized way, using the size of the array (say I don't know it and it's passed from another function)
sizeof(phoneNum) returns 10 * sizeof(int). The sizeof(int) value appears to be 4 for your system.
#include <stdio.h>
int main()
{
int phoneNum[10] = {0};
const size_t size = sizeof(phoneNum) / sizeof(int);
for (int i = 0; i < size; i++) {
printf("Insert digit %d of your phone number: \n", i + 1);
scanf("%d", &phoneNum[i]);
}
for(int i = 0; i < size; ++i)
{
printf("\r\n %i \n", phoneNum[i]);
}
return 0;
}
sizeof(phoneNum) will return number in bytes, not length of array.
after the includes you could make a define like #define SIZE 10 and use SIZE like if it was a constant.
#include <stdio.h>
#define SIZE 10
int main()
{
int phoneNum[SIZE];
for (int i = 0; i < SIZE; i++)
{
//Do Something
}
}
Take into account the fact that strings should end with null terminated character (\0) so the size of the string have that space available.
This a dot_product function of 2 vectors of the same length.
I don't understand how to build the array because how the machine will know which input goes to which input (for example i want a={1,2,3} but the input of 123 will come a[0]= 123)...
How do I make end of array[index] input and how do I make end of the whole array.
#include <stdio.h>
#include <stdlib.h>
#define MAXINPUT 100
int dot_product(int v[], int u[], int n)
{
int result = 0;
int i;
for (i=0; i < n; i++)
result += v[i]*u[i];
return result;
}
int main(){
int v1[MAXINPUT];
int v2[MAXINPUT];
int count = 0
int i,print;
printf(" first vector:");
for(i=0;i<MAXINPUT;i++){
scanf("%d", &v1[i]);
count +=1;
}
printf(" second vector:");
for(i=0;i<MAXINPUT;i++)
scanf("%d", &v2[i]);
print = dot_product(v1, v2, count);
printf("v1*v2:%d",print);
return 0;
}
The first problem I observe here is with
count +=1;
where count is an uninitialized automatic local variable, which makes it's initial value indeterminate. Attempt to use that value invokes undefined behavior.
You should be initializing count to 0.
That said, here, you're depending on the user to input the second array with exact same dimension of that of the first one. In case that does not happen, your program will blow up, as you did not initialize the arrays, again.
I am trying to create a simple program where the user will have to enter a series of numbers and the program should output the square and the cube of the given number. However, when I try to use an array, it prints some random numbers I didn't even input. Any help would be appreciated to eliminate the unecessary input. Thank you.
#include <stdio.h>
int main()
{
char *value;
value = malloc(sizeof(20));
float answer;
int x;
int y;
scanf("%s" , value);
for(x=0; x < 20; x++)
{
y = value[x] - '0';
printf("\nThe square of %d is: %d" , y , y*y);
printf("\nThe cube of %d is: %d \n" , y , y*y*y);
}
return 0;
}
You are taking input in char and doing arithmetic operations on it.
Use this code, it will give you correct output.
#include <stdio.h>
int main()
{
int *value;
value = (int *)malloc(20 * sizeof(int));
//float answer;
int x;
int y;
for(x=0; x < 20; x++)
{
scanf("%d" , value + i);
}
for(x=0; x < 20; x++)
{
y = value[x];
printf("\nThe square of %d is: %d" , y , y*y);
printf("\nThe cube of %d is: %d \n" , y , y*y*y);
}
return 0;
}
The problem is with your malloc statement.
sizeof is used to determine the parameter size - in your case a hard-coded integer. The generated array is of size 4, which is exactly sizeof(20) instead of 20 integers which is 20*sizeof(int). It will be best to allocate the array statically if you know what size you need, see code below:
#include <stdio.h>
int main()
{
// This line sets value to an array of 20 ints
int value[20];
// Another, less favorable option, but still works:
// char *value = malloc(20 * sizeof(int))
float answer;
int x;
int y;
scanf("%s" , value);
for(x=0; x < 20; x++)
{
y = value[x] - '0';
printf("\nThe square of %d is: %d" , y , y*y);
printf("\nThe cube of %d is: %d \n" , y , y*y*y);
}
return 0;
}
The expression sizeof(20) returns the size of an int (the literal 20 is an int), which is typically only 4 bytes. In other words, you are only allocating a single integer for your array. All access outside of that single integer will result in undefined behavior.
You need to allocate sizeof(int) times the number of elements, if you want to dynamically allocate the memory. Or (which I recommend) use a normal array:
int value[20];
There is also another problem, in that you only read a single value from the user. You should probably be reading in the loop too.
But if you read in the loop, then there is really no need to even have an array to begin with, only a single int Variable which you read into, and then print its value as squared and cubed.
So the code could be simplified as
#include <stdio.h>
int main(void)
{
int value;
for (unsigned i = 0; i < 20 && scanf("%d", &value) == 1; ++i)
{
printf("The square of %d is: %d\n", value, value * value);
printf("The cube of %d is: %d\n", value, value * value * value);
}
return 0;
}
You also need to be careful of overflows when multiplying.
This is an activity given by my instructor.
Create a program that accepts numeric input from the user. If the user enters an even number, store it to an array for even numbers. If the user enters an odd number, store it to another array for odd numbers. Input terminates if the user entered 10 numbers already. Display the size of each array and their elements.
Example:
Input: 5, 6, 12, 10, 0, 3, 4, 100, -1, 7
Even numbers (6): 6 12 10 0 4 100
Odd numbers (4): 5 3 -1 7
and this is the code I've come up with.
#include <stdio.h>
int sort(int);
int main(){
int input, count;
for(count=0;count!=10;count++){
printf("Enter 10 digits: ");
scanf("%d", &input);
sort(input);
}
printf("%d", input);
return 0;
}
int sort(int inp){
int odd[10];
int even[10];
if(inp%2==0){
odd[]=inp;
}
else
even[]=inp;
return 0;
}
Please help me on how to store the numbers into two separate arrays. Any tips will be greatly appreciated.
Check the below code. It's self-explaining.
#include <stdio.h>
#include <stdlib.h>
#define NUM 10
int main()
{
int input, i;
int oddcounter = 0, evencounter =0;
int oddarr[NUM];
int evenarr[NUM];
printf("Enter 10 integers\n");
for (i = 0; i < NUM; i++)
{
if ( scanf("%d", &input) == 1 )
{
if ((input % 2) == 0)
{
evenarr[evencounter++] = input;
}
else
{
oddarr[oddcounter++] = input;
}
}
}
printf("Number of elem in oddarray : %d, evenarray : %d\n\n", oddcounter, evencounter);
printf("Odd elements are :");
for (i = 0; i < oddcounter ; i++) printf("%d\t", oddarr[i]);
printf("\n");
printf("Even elements are :");
for (i = 0; i < evencounter; i++) printf("%d\t", evenarr[i]);
printf("\n");
return 0;
}
In addition to Sourav's comment which indicates that you shouldn't have the int[] arrays be local to sort, this syntax isn't correct for assigning to arrays in C:
odd[]=inp;
On my compiler, it generates the following error:
24:9: error: expected expression
odd[]=inp;
To store to odd, you need to indicate the index at which you'd like to store, for example:
odd[1]=inp;
which also means you'll need to keep track the latest index you wrote to for each array!
You need to tell the compiler which index of the array you are storing your data to. In sort:
if(inp%2==0){
odd[]=inp;
}
else
even[]=inp;
return 0;
}
Should look something like:
if(inp%2==0){
odd[endofoddindex]=inp;
}
else
even[endofevenindex]=inp;
return 0;
}
That said, you won't get much use out of the arrays being local variables, since they are deallocated on each call. Your best bet is to declare the arrays in main and pass them in.
Your even and odd arrays are both local. This means that they exist as long as the function exists. So you won't be retrieve the data you have stored(You also don't store it correctly).
So you need both the arrays in main and also two other variables for using as the index of both the array(i and j in the below program). The modified program is given below:
#include <stdio.h>
int sort(int);
int main(){
int input, count,i=0,j=0; //i and j to be used as array indices
int odd[10];
int even[10]; //arrays in main
for(count=0;count!=10;count++){
printf("Enter 10 digits: ");
scanf("%d", &input);
if(sort(input)) //if odd number was found
odd[i++]=input;
else //even number found
even[j++]=input;
}
printf("%d", input);
//print even and odd arrays here
return 0;
}
int sort(int inp){
if(inp%2==0)
return 0; //if number is even,return 0
return 1; //else return 1
}
You need to either have your arrays as globals or pass them into your sort function. Where they are they currently they get recreated every time the sort function is called and are inaccessible to the rest of your program.
You will also need to keep track of the max number of ints in each array and the current number.
Your test in sort would be something like this:
if( inp % 2 == 0)
{
//TODO check that currentEvenCount < maxEvenCount
even[ currentEvenCount ] = inp;
currentEvenCount++
}
else
{
//TODO check that currentOddCount < maxOddCount
odd[ currentOddCount ] = inp;
currentOddCount++;
}
To declare your arrays as globals just move the declaration outside of any function above anywhere they are referenced
int even[10];
int odd[10];
int main() ...
To pass them as parameters to sort function you could declare sort like this:
sort( int inp, int even[], int maxEvenCount, int* currentEvenCount, int odd[]. int maxOddCount, int* currentOddCount)
{
...
if( inp % 2 == 0)
{
//TODO check that currentEvenCount < maxEvenCount
even[ *currentEvenCount ] = inp;
(*currentEvenCount)++
}
}
The * in front of currentEventCount is dereferencing the pointer and getting/setting the actual value pointed to.
You would then call sort like so:
int main()
{
int evenArray[10];
int oddArray[10];
int currentEvenCount = 0;
int currentOddCount = 0;
...
sort( input, evenArray, 10, ¤tEvenCount, oddArray, 10, ¤tOddCount);
}
There is no any sense to define the arrays as local variables of function sort because each time the function is called the arrays are created anew.
The program could look the following way
#include <stdio.h>
#define N 10
enum Type { Even, Odd };
enum Type sort( int x )
{
return x % 2 == 0 ? Even : Odd;
}
int main( void )
{
int odd[N];
int even[N];
int odd_count = 0;
int even_count = 0;
int i;
printf( "Enter %d numbers: ", N );
for( i = 0; i < N; i++ )
{
int num;
scanf( "%d", &num );
switch ( sort( num ) )
{
case Even:
even[even_count++] = num;
break;
case Odd:
odd[odd_count++] = num;
break;
}
}
printf( "Even numbers (%d):", even_count );
for ( i = 0; i < even_count; i++ ) printf( " %d", even[i] );
printf( "\n" );
printf( "Odd numbers (%d):", odd_count );
for ( i = 0; i < odd_count; i++ ) printf( " %d", odd[i] );
printf( "\n" );
return 0;
}
If to enter
5 6 12 10 0 3 4 100 -1 7
then the output will be
Even numbers (6): 6 12 10 0 4 100
Odd numbers (4): 5 3 -1 7
Simply copy, paste and investigate the program.:)
Hope this program will solve you issue. Here is the working code.
#include <stdio.h>
int sort(int[]);
int main(){
int input[10], count;
printf("Enter 10 digits: ");
for(count=0;count<10;count++){
scanf("%d", &input[count]);
}
sort(input);
return 0;
}
int sort(int inp[]){
int odd[10];
int even[10];
int oddCount=0, evenCount=0;
int i;
for(i=0; i<10;i++)
{
if(inp[i]%2==0){
even[evenCount]=inp[i];
evenCount++;
}
else
{
odd[oddCount]=inp[i];
oddCount++;
}
}
printf("ODD COUNT is %d \n", oddCount);
for(i=0; i<oddCount;i++)
{
printf("ODD VALUE %d \n", odd[i]);
}
printf("EVEN COUNT is %d \n", evenCount);
for(i=0; i<evenCount;i++)
{
printf("EVEN VALUE %d \n", even[i]);
}
return 0;
}
Your variable input is just an int, it's not an array. You need two arrays:
int even[10], odd[10];
Then you need to keep track of the number of numbers you've read so far, and for each number check which array to store it in.
I don't see a need to do sorting, so not sure why you have a function called sort().
It should just be something like:
int even[10], odd[10];
int oddindex = 0, evenindex = 0;
while(scanf(" %d", &x) == 1)
{
if(x % 2 == 0)
even[evenindex++] = x;
else
odd[oddindex++] = x;
if((evenindex + oddindex) >= 10)
break;
}
/* Loop here to print numbers. */
An answer suitable for an assignment question:
int main()
{
int i,c,o[10],e[10];int oc=0;int ec=0;int*pc;for(c=0;c<10;c++){scanf("%d",&i);pc=(i&1)?&o[oc++]:&e[ec++];*pc=i;}
// Now print out the values as requested in oc, o, ec and e.
}
I'm trying to calculate the size of the file . The process I've followed is to read the file and store it in an array and calculate its size. However,I really don't know ... I tried n number of ways..I've to pass this size as an attribute to the frequency function.along with the name of the array.
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int ??????, int x)
{
int count = 0;
int u;
for (u = 0; u < ??????; u++)
{
if ( theArray[u]==x)
{
count = count + 1 ;
/*printf("\n%d",theArray[u]);*/
}
else
{
count = count ;
}
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int r = 0;
int num;
int theArray[100];
int there[100];
int n;
int g;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",(integers[i]));
there[r] = integers[i];
i++;
}
//printf("%d",there[r]);
//printf("\n%d",file);
//fclose(file);
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf("\n%d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,????????,x);
getch();
fclose(file);
}
?????? is the size of the integer array from where i read the file and stored it.
I could not find a way to calculate the size of the array into which i copied my file. My idea is to calculate the frequency of a number in that file and calculate the probability of it's occurrence and thereby calculating entropy..Suggestions please!
I don't know why you are initializing so many variables and some of them with awkward names like ??????.
Your main problem is that the call to function should be
frequency(integers, i, x);
Your code with the awkward irrelevant parts removed will look like
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int number, int x)
{
int count = 0;
int u;
for (u = 0; u < number; u++)
{
if ( theArray[u]==x)
count++;
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int num;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",integers[i]);
i++;
}
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf(" %d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,i,x);
getch();
fclose(file);
}
There are a lot of parts of this code that don't make sense, but I assume it is your debugging trying to figure out what is wrong. The answer to your specific question is:
For each value read from the file you set integers[i] to the value and then increment i. Thus i is the count of items in integers. You then pass integers to frequency(), so i should be passed to the second parameter as the count.
Note that if there are more than 100 values in the file, you will over index integers and cause unpredictable behavior.
To calculate length of array:
int len= sizeof(arr)/sizeof(arr[0]);
It will give length of array without looping.