Hi so I have this code but it says I can't use the enum in the for loop... and I dont know why.
Can someone help ? :)
#include <stdio.h>
typedef enum kuloer {spar, kloer, rudder, hjerte} kuloer;
typedef enum vaerdi {one, two, three, four, five, six, seven, eight, nine, ten, knaegt, dronning, konge} vaerdi;
typedef struct kort
{
kuloer k;
vaerdi v;
} kort;
int main(void){
int i;
kort kort[52];
for (i = 0; i < 52; i++)
{
kort[i].k = kuloer[i % 4];
kort[i].v = vaerdi[i % 13];
printf("Kort %d %c", i , kort[i].k);
printf("Kort %d %c", i , kort[i].v);
}
return(0);
}
Enumerations doesn't work like variables. The name kuloer is a type alias. Also, enumeration defines a set of named integer constants, nothing else.
With that said, because enumerations are just named integer constants, you can use any integer value really, and treat it as an enumeration value. So e.g.
kort[i].k = i % 4;
will work fine.
Related
Goodevening everyone, i'm learning now to loop an array of numbers, and i'm just wondering,
how can i square the numbers in my array depending on the input of how many times i should square it
int main() {
int nums[5] = {1, 2, 3, 4, 5};
int loop;
int a;`enter code here`
int pro,pro1,pro2,pro3,pro4;
int spacing = 3;
int i = 0
scanf("%d", &a);
do{
pro = pow(nums[0],2);
pro1 = pow(nums[1],2);
pro2 = pow(nums[2],2);
pro3 = pow(nums[3],2);
pro4 = pow(nums[4],2);
i++
}while (i != a);
printf("%0*d\n", spacing, pro);
printf("%0*d\n", spacing, pro1);
printf("%0*d\n", spacing, pro2);
printf("%0*d\n", spacing, pro3);
printf("%0*d\n", spacing, pro4);
return 0;
}
this is my code so far, i wanted to loop it, and get the results like this:
001
016
081
256
625
or like this
001
256
6561
65536
390625
but i always get this:
001
004
009
016
025
please help me understand thank you
There is a strong error and a number of possible improvements in your code.
The error has already be identified by #SylvainChaugny and is that you re-use original nums value on each and every iteration. The improvements are:
you are using 5 variables pro to pro5 and process them the same. Better to make an array for them, or even better re-use the nums array.
if you want to later extend your program to 6 values, you would have to consistently look through the code to search what needs to be changed: better to use a constant or as you have a literal initialization ask the size to the compiler
you are using pow to process integer values. This is not efficient because as pow takes and returns double values you force a conversion from int to double and back. In addition it might be dangerous for large values: a double has less precision than an int on 64 bits architectures (48 mantissa bits for a double, 64 bits for an int). So it can lead to incorrect results.
So your code could become:
#include <stdio.h>
int main() {
int nums[] = {1, 2, 3, 4, 5};
int len = sizeof (nums) / sizeof (*nums); // idiomatic way for the length of an array
int a;
int spacing = 3;
scanf("%d", &a);
for (int i=0; i<a; i++) {
for (int j=0; j<len; j++) {
nums[j] = nums[j] * nums[j];
}
}
for (int i=0; i<len; i++) {
printf("%0*d\n", spacing, nums[i]);
}
return 0;
}
It is shorter to type (not only laziness but also less sensitive to typos) and it gives the expected result ;-). In addition, if you want to add a value to the array, it can be done be changing one single line.
Your problem is that you always reassign your pro variables to the exact same value (pow(nums[0], 2), pow(nuws[1], 2), ....
So no matter what the value of a is, you always will have your pro3 variable to be equal to pow(nums[3], 2).
You first have to assign the initial values to your pro variables, then use them in the calls to pow(), to be able to square your previous result.
I am currently trying to make a small game in the c programing language for a portfolio. I am new to c so I don't know all of the ticks. Currently, I am trying to assign values to enum's though I don't know if that is correct.
// C program for generating a
// random number in a given range.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "Test.h"
enum mods{
Cha, Str, Dex, Con, Int, Wis // <-this line is the only line that is my code (of this document I have more that will reference this document) the rest I learned from others
};
// Generates and prints 'count' random
// numbers in range [lower, upper].
void printRandoms(int lower, int upper,
int count)
{
int i;
for (i = 0; i < count; i++) {
int num = (rand() %
(upper - lower + 1)) + lower;
printf("%d ", num);
}
}
// Driver code
int main(enum mods Str)
{
int lower = 6, upper = 18, count = 1;
// Use current time as
// seed for random generator
srand(time(0));
printRandoms(lower, upper, count);
printf("My enum Value : %d\n", (int)Str);
return 0;
*edit Sorry for the confusion. I want to be able to reference this product of this line of code over and over again in the main sheet/program. I want it to be a random start so it isn't the same game every time. How do I do that? (for an example of the end product:
if (Str >= 10)
printf("pass skill check to lift the log\n");
else
printf("you drop the log on your foot and take 1d4 damage\n");
enum (health -1d4[will make actual code for this but not yet])
what I need answered
how to make each of the enum mods = a random number at the start of the program to be referenced in the main program
)
If I understood you correctly, you want the mod values to be randomly generated.
Use the enum values as array indices into an array big enough to hold all your mod attributes. Like this, for example:
enum mods = { Cha, Str, Dex, Con, Int, Wis, Mod_Max };
int mod_values[Mod_Max];
Keeping Mod_Max (or whatever you'd like to call it) as the last element of the enum, this will give you simple way to refer to the size of the array. Populating the array with values:
for (int i = 0; i < Mod_Max; i++) {
mod_values[i] = ...;
}
And getting a value of a given "mod" would simply be (for example Str):
mod_values[Str];
EDIT: This way, lets you further modify the mod values down the line, rather than having them as constants
I believe you're asking how to have values for each element in your enum. Well all you have to do is simply assign said value-
enum mods { foo = 77, bar = 42, baz = 3 };
Then you can access said values like so-
enum mods mod_enum = foo;
printf("%d", mod_enum);
The above will print 77
You can also directly use the value of one of the elements from said enum
printf("%d\n", bar);
The above prints 42
Read more about enums
That code will run on a payment device (POS). I have to use legacy C (not C# or C++) for that purpose.
I am trying to prepare a simple Mifare card read/write software data. Below document is my reference and I am trying to achieve what is on page 9, 8.6.2.1 Value blocks explains.
http://www.nxp.com/documents/data_sheet/MF1S50YYX_V1.pdf
I just know very basics of C. All my searches in The Internet have failed. According to document:
1- There is integer variable with value of 1234567.
2- There is char array[4] which should have hex of above value which is 0x0012D687
3- I am supposed to invert that char array[4] and reach value of 0xFFED2978
I need to do some other things but I have stuck in number 3 above. What I have tried lastly is
int value = 1234567;
char valuebuffer[4];
char invertbuffer[4];
sprintf(valuebuffer, "%04x", value);
for(i = 0; i < sizeof(valuebuffer); i++ )
{
invertbuffer[i] ^= valuebuffer[i];
}
When I print, I read some other value in invertbuffer and not 0xFFED2978
Seems like you're making it more complicated than it needs to be. You can do the binary inversion on the int variable rather than messing around with individual bytes.
int value = 1234567;
int inverted= ~ value;
printf("%x\n",value);
printf("%x\n",inverted);
gives you output of
12d687
ffed2978
First of all, you must use the types from stdint.h and not char, because the latter has implementation-defined signedness and is therefore overall unsuitable for holding raw binary data.
With that sorted, you can use a union for maximum flexibility:
#include <stdint.h>
#include <stdio.h>
typedef union
{
uint32_t u32;
uint8_t u8 [4];
} uint32_union_t;
int main (void)
{
uint32_union_t x;
x.u32 = 1234567;
for(size_t i=0; i<4; i++)
{
printf("%X ", x.u8[i]);
}
printf("\n");
x.u32 = ~x.u32;
for(size_t i=0; i<4; i++)
{
printf("%X ", x.u8[i]);
}
printf("\n");
}
Notably, the access order of the u8 is endianess dependent. This might be handy when dealing with something like RFID, which doesn't necessarily have the same network endianess as your MCU.
Can I declare an int array, then initialize it with chars? I'm trying to print out the state of a game after each move, therefore initially the array will be full of chars, then each move an entry will be updated to an int.
I think the answer is yes, this is permitted and will work because an int is 32 bits and a char is 8 bits. I suppose that each of the chars will be offset by 24 bits in memory from each other, since the address of the n+1'th position in the array will be n+32 bits and a char will only make use of the first 8.
It's not a homework question, just something that came up while I was working on homework. Maybe I'm completely wrong and it won't even compile the way I've set everything up?
EDIT: I don't have to represent them in a single array, as per the title of this post. I just couldn't think of an easier way to do it.
You can also make an array of unions, where each element is a union of either char or int. That way you can avoid having to do some type-casting to treat one as the other and you don't need to worry about the sizes of things.
int and char are numeric types and char is guaranteed smaller than int (therefore supplying a char where an int is expected is safe), so in a nutshell yes you can do that.
Yes it would work, because a char is implicitly convertible to an int.
"I think the answer is yes, this is permitted and will work because an int is 32 bits and a char is 8 bits." this is wrong, an int is not always 32 bits. Also, sizeof(char) is 1, but not necessarily 8 bits.
As explained, char is an int compatible type.
From your explanation, you might initially start with an array of int who's values are char, Then as the game progresses, the char values will no longer be relevant, and become int values. Yes?
IMHO the problem is not putting char into an int, that works and is built into the language.
IMHO using a union to allow the same piece of space to be used to store either type, helps but is not important. Unless you are using an amazingly small microcontroller, the saving in space is not likely relevant.
I can understand why you might want to make it easy to write out the board, but I think that is a tiny part of writing a game, and it is best to keep things simple for the rest of the game, rather than focus on the first few lines of code.
Let's think about the program; consider how to print the board.
At the start it could be:
for (int i=0; i<states; ++i) {
printf("%c ", game_state[i]);
}
Then as the game progresses, some of those values will be int.
The issue to consider is "which format is needed to print the value in the 'cell'?".
The %c format prints a single char.
I presume you would like to see the int values printed differently from ordinary printed characters? For example, you want to see the int values as integers, i.e. strings of decimal (or hex) digits? That needs a '%d' format.
On my Mac I did this:
#include <stdio.h>
#define MAX_STATE (90)
int main (int argc, const char * argv[]) {
int game_state[MAX_STATE];
int state;
int states;
for (states=0; states<MAX_STATE; ++states) {
game_state[states] = states+256+32;
}
for (int i=0; i<states; ++i) {
printf("%c ", game_state[i]);
}
return 0;
}
The expression states+256+32 guarantees the output character codes are not ASCII, or even ISO-8859-1 and they are not control codes. They are just integers. The output is:
! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? # A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y
I think you'd like the original character to be printed (no data conversion) when the value is the initial character (%c format), but you do want to see data conversion, from a binary number to a string of digit-characters (%d or a relative format). Yes?
So how would the program tell which is which?
You could ensure the int values are not characters (as my program did). Typically, this become a pain, because you are restricted on values, and end up using funny expressions everywhere else just to make that one job easier.
I think it is easier to use a flag which says "the value is still a char" or "the value is an int"
The small saving of space from using a union is rarely worth while, and their are advantages to having the initial state and the current move available.
So I think you end up with something like:
#include <stdio.h>
#define MAX_STATE (90)
int main (int argc, const char * argv[]) {
struct GAME { int cell_state; int move; char start_value } game_state[MAX_STATE];
enum CELL_STATE_ENUM { start_cell, move_cell };
int state;
int states;
for (states=0; (state=getchar())!= EOF && states<MAX_STATE; ++states) {
game_state[states].start_value = state;
game_state[states].cell_state = start_cell;
}
// should be some error checking ...
// ... make some moves ... this is nonsense but shows an idea
for (int i=0; i<states; ++i ) {
if (can_make_move(i)) {
game_state[states].cell_state = move_cell;
game_state[states].move = new_move(i);
}
}
// print the board
for (int i=0; i<states; ++i) {
if (game_state[i].cell_state == start_cell) {
printf("'%c' ", game_state[i].start_value);
} else if (game_state[i].cell_state == move_cell) {
printf("%d ", game_state[i].move);
} else {
fprintf(stderr, "Error, the state of the cell is broken ...\n");
}
}
return 0;
}
The move can be any convenient value, there is nothing to complicate the rest of the program.
Your intent can be made a little more clear my using int8_t or uint8_t from the stdint.h header. This way you say "I'm using a eight bit integer, and I intend for it to be a number."
It's possible and very simple. Here is an example:
int main()
{
// int array initialized with chars
int arr[5] = {'A', 'B', 'C', 'D', 'E'};
int i; // loop counter
for (i = 0; i < 5; i++) {
printf("Element %d id %d/%c\n", i, arr[i], arr[i]);
}
return 0;
}
The output is:
Element 0 is 65/A
Element 1 is 66/B
Element 2 is 67/C
Element 3 is 68/D
Element 4 is 69/E
this is an integer array:
int values[] = { 75, '*', 5,'-' };
for(i=0 ; i<size ; i++){
// Here
}
how to check if the values[i] is an integer or an operation ??
maybe the value equals the Ascii of an operation,, how to deal with it in this case??
You can't. As for as the compiler is concerned, the constants 42 an '*' are one and the same. In the compiled object code, they're both represented as the integer 42.
If you need to differentiate between integers and characters, either use a boolean flag or enum indicating the type of the value, or keep your integers and characters in separate arrays.
Note that in C++, but not in C, there is a slight difference: 42 has the type int, whereas '*' has the type char, so you can differentiate this fact using overloaded functions or templates.
That's a dangerous road to go down. The array in your example will translate (during compilation) into:
int values[] = {75, 42, 5, 45};
So when you see the number 42... what is it? Is it the '*' character, or did you actually mean the number 42?
You can't rely on typecasting, either, because all your values will be cast to ints, since they're stored in an integer array. Your best bet is to make a struct that holds both type and value, like so:
typedef struct
{
int type; //0 for int, 1 for operator, and so forth.
int value; //holds either a character code or an integer value
//you could use a union here, if you felt it would make things cleaner...
} Token;
Then checking to see what type a token is is simply a matter of looking at token.type.
Hope this helps!
PS: The cheating answer would be to use a dynamically typed language. Lots less work on your part, but slower, and I don't know if it's an option for you.
Your array elements cannot be simple integers.
Try this instead:
enum ElementType {INTEGER, OPERATION};
struct ArrayElement {
enum ElementType etype;
int evalue;
};
struct ArrayElement values[] = {
{INTEGER, 75}, {OPERATION, '*'}, {INTEGER, 5}, {OPERATION, '-'}
};
for (i = 0; i < sizeof values / sizeof *values; i++) {
/* Here */
switch (values[i].etype) {
default: printf("unrecognized type. value is %d.\n", values[i].value);
break;
case INTEGER: printf("INTEGER with value %d.\n", values[i].value);
break;
case OPERATION: printf("OPERATION with value '%c'.\n", values[i].value);
break;
}
}