The Variable Types in C

This is what the format looks like when unedited.

#include <studio.h>
#include <stdlib.h>

int main( )
{
printf(“Hello people”);
return 0;
}

When I started learning I was only allowed to edit on the line “printf(“Hello people”);” part. Otherwise it’d crash or not even run properly.

I still don’t know what the function of #include <studio.h> and #include <stdlib.h> yet.


int

There are few of the variable types that I’ve learnt.

The “int” variable type where it can contain only integers (numbers that are not fractional or numbers that don’t contain decimals) which can be positive or negative.

Here’s the code in action :

#include <studio.h>
#include <stdlib.h>

int main( )
{
int CharAge = 76;
printf( “%d”, CharAge);
return 0;
}

Which would output 76.

The %d is used to display the integer variable.


double

The next variable type I’ve learnt about is the “double“. It can store decimal numbers.

int main()
{
double CharAge= 77.99;
printf(“%f”, CharAge);
return 0;
}

Which outputs 77.99

Note that it doesn’t output when the variable is 77 only. It’ll not run/spit out the answer that we want. It simply doesn’t allow integers.

So it has to be decimal, so we have to use 77.0 instead to run the code.

In this case %f is used to display the decimal number variable.


char

The “char” variable type is used to store a single character which can be a letter or an integer( we can technically use a decimal number but it will always print the last “character”.

int main()
{
char CharAge = ‘B’;
printf(“%c”, CharAge);
return 0;
}

Which should output a B.

Note that the character should be enclosed in a single quote not double quotes like we’ve done on other examples.

As I was learning it wasn’t stated anywhere that the char variable type only prints the last “character” if a bunch of characters are given. For example:

int main()
{
char CharAge = ‘Bb’;
printf(“%c”, CharAge);
return 0;
}

It will print out only “b” as it’s the last character in the sequence. Same with numbers.

int main()
{
char CharAge = ‘10.99’;
printf(“%c”, CharAge);
return 0;
}

It will print out only “9”. Not “10.99”.

Even with mixed characters.

int main()
{
char CharAge = ‘10.99A’;
printf(“%c”, CharAge);
return 0;
}

It will print out only “A”. Not “10.99A”.

The %c is a format specifier where it prints out a single character.

To print the whole sequence the “char” variable type can be used with a slight tweak.

char ___ [ ]

With this variable type above we can print out the full sequence.

Here’s how :

int main()
{
char CharAge[ ] = “1098A”;
printf(“%s”, CharAge);
return 0;
}

Which prints out “1098A”. Notice the use of double quotes around the variable.

The 1098A acts as an array or a string of characters, thus using the %s format specifier.



Leave a comment

Design a site like this with WordPress.com
Get started