C Data Types

Data Types

C Data Types
C Data Types 

As the explained in the Variables chapter, a variable in C must be a specified the data type, and you must use a format specifier to inside the printf() function to display it:


Example

#include <stdio.h>

int main() {

  // the Create variables

  int myNum = 5;               //the Integer (whole number)

  float myFloatNum = 5.99;     // the Floating point number

  char myLetter = 'D';         //the Character

    //the Print variables

  printf("%d\n", myNum);

  printf("%f\n", myFloatNum);

  printf("%c\n", myLetter);

  return 0;

}

OUTPUT:

Basic Data Types.

The data type to specifies the size and type of information the variable will store.

In this Post, we will be focus on the most basic ones:

Data Type

Size

Description

int

2 or 4 bytes

The Stores whole numbers, without the decimals

float

4 bytes

The Stores fractional numbers, To the containing one or more decimals. The Sufficient for storing 6-7 decimal digits

double

8 bytes

The Stores fractional numbers, To the containing one or more decimals. The Sufficient for storing 15 decimal digits

char

1 byte

The Stores a single character/letter/number, or  the ASCII values

Basic Format Specifiers.

There are different format the specifiers for each data type. In this time you are some of them:

Format Specifier

Data Type

 

%d or %i

Int

 

%f

Float

 

%lf

double

 

%c

Char

 

%s

The Used for strings (text), which you will be learn more about in a later chapter

Set Decimal Precision.

You have probably already noticed that if you print to a floating point number, then the output will be show 6 digits after the decimal point:

Example

#include <stdio.h>

int main() {

  float myFloatNum = 3.5;

  double myDoubleNum = 19.99;

  printf("%f\n", myFloatNum);

  printf("%lf", myDoubleNum);

  return 0;

}

OUTPUT:


Here If you want to remove the extra zeros (set decimal precision), Then you can use a dot (.) followed by a number that the specifies how many digits that should be shown after the decimal point:

Example

#include <stdio.h>

int main() {

  float myFloatNum = 3.5;

  printf("%f\n", myFloatNum); // The Default will show 6 digits after the decimal point

  printf("%.1f\n", myFloatNum); // The Only show 1 digit

  printf("%.2f\n", myFloatNum); // The Only show 2 digits

  printf("%.4f", myFloatNum);   // The Only show 4 digits

  return 0;

}

OUTPUT:

Post a Comment

Post a Comment (0)

Previous Post Next Post