Lesson 5: Data Types Part 2

In the last lesson I discussed about integer (int) type data. In today’s lesson I am going to discuss more about character, float and double type data.

Character (char) Type Data

What is a character constant? Anything that is enclosed within single quote is a character constant. For example ‘A’, ‘B’, ‘a’ these all are character constants in C.  Again, if you put 1, 2, 3 within single quotes it will be character constants too. To declare a character type variable we need to follow the following syntax:

char variable_name;

To print character we need to use %c in the printf statement as I mentioned it in the previous lesson.

Lets see a C Programming Example of with character:

#include <stdio.h>

int main()
{
    char ch;
    ch = 'A';
    printf("%c\n",ch );
    ch = '5';
    printf("%c\n",ch );
    return 0;
}

Floating Point Data (float)

Did you try floating point values in a int type data? If not then try the following program.

#include <stdio.h>

int main()
{
    int pi = 3.1416;
    printf("The value of PI is %d",pi);
    return 0;
}

What is the output? I am sure it is not 3.1416. The output is 3. Isn’t it? It is because a int type data can only hold integer part of a number. So if we want to print we need float type data. To print any float type data we need to use %f. So the above example will be:

#include <stdio.h>

int main()
{
    double pi = 3.1416;
    printf("The value of PI is %lf",pi);
    return 0;
}

Double type data

Double type data are same as float type data. The difference is it can hold more digits than a float type data after the decimal point. To print a double we need to use %lf. Lets have an example of double.
#include <stdio.h> 

int main() 
{ 
    double x; 
    x = 4.4544454; 
    printf(“%lf”,x); 
    return 0; 
}

1 comments :

Spam comments will be deleted. :)

 
Loading...
TOP