c programming
hello,
Im trying to define the variable in C programming.
Does anyone how to do it and the difference of data type while defining it?
Hey!
Defining a variable in C is quite straightforward, all you need to do is follow these steps:
- Decide what you're going to put in the variable, and choose the appropriate datatype.
- Decide a name for your variable.
- Assign a value to the variable.
For example, to store your age, you would approach defining your variable like so:
-
We know the age is going to be an integer, which means it is a whole number having no decimal value. In C, the datatype for storing integers is called
int
, so that's our data type. -
Our variable stores an age, so we might as well call it
age
. -
We can now store any number we want in our
age
variable (shh, C won't know).
Once you've done those 3 things, you can write out your declaration like so
int age = 42;
(Notice that ;
in the end, that's something you can't forget)
And there you have it, You've just declared your variable!
Here are some other data types you can use:
float pi = 3.14; char grade = 'A';
If you wanted to store a string, or a sequence of characters, you would use a 'character array' (you don't have to worry about what this means, you'll learn what arrays are later)
char[] username = "zeno99";
You can find dozens of great C tutorials that will make learning it easier, here are a couple ones I found
Hope this helped!
@JustARatherRidi Love this answer! Wish I could up vote it twice! Very well put together and a lot of explanation.
@EchoCoding Thank you! That means a lot :)
Almost just like any other programming language.
For example.
int foo = 22;
string Da = "Hello World!";
Remember google is a good resource for this as well!
@ryanhallihan I've got news for you buddy, there is no 'string' datatype in C, what you should do is use a character array, like so
char[] name = "ryan";
@JustARatherRidi Oops! Sorry!
@ryanhallihan No problem, but try and be a bit more careful when you're posting an answer to someone relatively newer than you are. They might think they're doing something wrong, which might confuse them further.
int - number values only, no letters
int a = 5;
char - letters or numbers, but only 1 at a time
char a = 'b';
int array - number values only, no letters
int a[5] = {1,2,3,4,5};
char array - aka string, letters or numbers, one per array slot
char a[5] = {'a','b','c','d','e'};
(there are other ways of defining arrays but these should do for now)
how about your OWN type?
Now we have a hotel room type made up of char arrays and ints
Now we have set the data values of our special type variable