Skip to content

Learning CPP by Example

Learn CPP By Example

1. cpp starter template.

int main() { 

    return 0;

}

2. Declaring an int

int score;

3. Declaring a char

char player_name;

4. Declaring a float

float price;

5. Declaring a boolean.

bool paid;

6. Declaring a int with value initialized.

int score = 0;

7. Declaring a char with an initial value.

char firstLetter = 'w';

8. Declaring a float value with a initial value.

float price = 10.25f;

9. Declaring bool with an initial value.

bool paid = true;

10. Declaring a constant.

const int MAX_COUNT = 100;

11. Creating a type of a user defined type.

Background bg;

12. Add a value to an int variable

amount = amount + 100;

13. Writing an if condition

if (condition) { 

    // execute condition here.

}

14. Writing an if - else condition

if (condition)
{ 
    // execute if condition logic here.
}

else { 
    // execute else condition logic here.
}

15. Declaring a string.

std::string name;

16. while loops.

while (condition) { 

    // logic here.

    break; // used to break out of the loop.


}

17. for loops

for (int idx = 0; idx < 50; idx++)
{
    // logic 
}

18. Declaring an array.

int price_list[10];

19. Initializing elements in an array.

price_list[0] = 32;

20. Switch case

switch (expression) 
{
    case a:
        // logic here.
        break;

    case b:
        // logic here.
        break;

    default:
        // do something here if nothing matches.
        break

}

21. Enums

enum class Levels { 
    EASY,
    MEDIUM,
    HARD
}

22. Declare a function.

void f();

23. Declare a function accepting 2 integers.

void f(int x, int y);