Back to Course

Introduction to C++

0% Complete
0/0 Steps
  1. C++: Basics
    5Topics
    |
    6 Quizzes
  2. C++: Compilation and Execution
    5Topics
    |
    6 Quizzes
  3. C++: Variables
    9Topics
    |
    10 Quizzes
  4. C++: Conditions Operators
    5Topics
    |
    6 Quizzes
  5. C++: Logical Operators
    3Topics
    |
    4 Quizzes
  6. C++: Loops and Errors
    8Topics
    |
    9 Quizzes
  7. C++: Vectors
    4Topics
    |
    3 Quizzes
Lesson 3, Topic 9
In Progress

C++: Basic Data Types

Yasin Cakal 7 Nov 2021
Lesson Progress
0% Complete

C++ is a strongly typed language. We have a few basic data/variable types that we have been introduced to in the previous topics. These include:

  • int used for integers like 23 and 45.
  • double is used for floating-point numbers like 2.23 and 4.45.
  • char is used for characters like $ and &.
  • string is used for a succession of characters like ‘My name is Yasin!’.
  • bool is used for true and false values.

Let’s declare and initialize all such variable types to understand better.

  • int year=2021;
  • double percentage=82.4;
  • char dollar=$;
  • std::string text="try again!";
  • bool is_it_too_late = false;

To modify these data types, we use datatype modifiers. They can change the data length a data type can save. Some datatype modifiers include:

  • long
  • short
  • unsigned
  • signed

To stop variables from changing while the program is executing, we use constant variables const. To fix the variable such so that it can not be modified, add const before declaring the variable like const int percentage=21;.

You can also convert one datatype into another. We can do this by typing the data type you want to convert to in brackets and then write the variable name like if you want to convert an int type variable percentage into double, you can try this code:

#include <iostream>
int main()
{
    double perc;
    int perc1;
    perc=242.2;
    perc1 = (int) perc;
    perc=perc1+5;
    std::cout<<"Percentage in integer is= "<<perc;
}

Output:

Percentage in integer is= 247

As we can see, the double value was converted to int and then used in calculation to give the correct answer.

Responses

Leave a Reply

%d bloggers like this: