Data Types
C++ provides several fundamental data types that are used to represent different types of values, including integers, floating-point numbers, characters, and boolean values. Here are the commonly used fundamental data types:
- int: Used to store integer values, both positive and negative.
- float: Used to store single-precision floating-point numbers. It occupies 4 bytes (32 bits) of memory. The float type can store numbers with a precision of about 6 decimal places.
- double: Used to store double-precision floating-point numbers. It occupies 8 bytes (64 bits) of memory. The double type provides higher precision compared to float and can store numbers with a precision of about 15 decimal places.
- char: Used to store individual characters.
- bool: Used to store Boolean values (true or false).
#include <iostream>
using namespace std;
int main() {
int score = 95;
float gpa = 3.8;
double pi = 3.14159;
char grade = 'A';
bool isPass = true;
cout << "Score: " << score << endl;
cout << "GPA: " << gpa << endl;
cout << "Pi: " << pi << endl;
cout << "Grade: " << grade << endl;
cout << "Passed? " << isPass << endl;
return 0;
}
String Data Type
A string is a sequence of characters represented as an object of the string class, which is part of the C++ Standard Library. This class provides a powerful and flexible way to work with text and character data.
Here's how you can declare and use a string variable:
#include <iostream>
#include <string>
using namespace std;
int main() {
string myString = "Hello, World!";
cout << myString << endl;
return 0;
}
Understanding data types is fundamental for effective and efficient programming in C++. By correctly choosing and using appropriate data types, you can ensure proper storage, manipulation, and representation of different values in your programs. Experiment with the examples provided to solidify your understanding of data types and advance your C++ skills.
Basic Topics
- Introduction to C++
- Basic Syntax and Structure
- Variables
- Data Types
- Operators
- Output and Input
- Conditional Statements
- Loops
- Break and Continue Statements