Search

1.x — Chapter 1 summary and quiz

Quick Summary

A statement is a type of instruction that causes the program to perform some action. Statements are often terminated by a semicolon.

A function is a collection of statements that execute sequentially. Every C++ program must include a special function named main. When you run your program, execution starts at the top of the main function.

The rules that govern how elements of the C++ language are constructed is called a syntax. A syntax error occurs when you violate the grammatical rules of the language.

Comments allow the programmer to leave notes in the code. C++ supports two types of comments. Line comments start with a // and run to the end of the line. Block comments start with a /* and go to the paired */ symbol. Don’t nest comments.

You can use comments to temporarily disable lines or sections of code. This is called commenting out your code.

Data is any sequence of symbols that can be interpreted to mean something. A single piece of data, stored somewhere in memory is called a value.

A variable is a named piece of memory that we can use to store values. A variable’s name is called an identifier. In order to create a variable, we use a statement called a definition statement. When the program is run, each defined variable is instantiated, which means it is assigned a memory address.

A data type tells the compiler how to interpret a piece of data into a meaningful value. An integer is a number that can be written without a fractional component, such as 4, 27, 0, -2, or -12.

Copy assignment (via operator=) can be used to assign an already created variable a value.

Initialization can be used to give a variable a value at the point of creation. C++ supports 3 types of initialization: copy initialization, direct initialization, and uniform initialization.

You should prefer uniform initialization over the other initialization forms, and prefer initialization over assignment.

Although you can define multiple variables in a single statement, it’s better to define and initialize each variable on its own line, in a separate statement.

std::cout and operator<< allow us to output an expression to the console as text. std::endl outputs a new line character, forcing the console cursor to move to the next line. std::cin and operator>> allow us to get a value from the keyboard.

A variable that has not been given a value is called an uninitialized variable. Trying to get the value of an uninitialized variable will result in undefined behavior, which can manifest in any number of ways.

C++ reserves a set of names called keywords. These have special meaning within the language and may not be used as variable names.

A literal constant is a fixed value inserted directly into the source code. Examples are 5 and “Hello world!”.

An operation is a mathematical calculation involving zero or more input values, called operands. The specific operation to be performed is denoted by the provided operator. The result of an operation produces an output value.

Unary operators take one operand. Binary operators take two operands, often called left and right. Ternary operators take three operands.

An expression is a combination of literals, variables, operators, and function calls that are evaluated to produce a single output value. The calculation of this output value is called evaluation. The value produced is the result of the expression.

An expression statement is an expression that has been turned into a statement by placing a semicolon at the end of the expression.

Programming is hard, and your programs will rarely come out perfect (or close to it) the first time. Get your programs working first, then refine them into something great.

Quiz time

Question #1


What is the difference between initialization and assignment?

Show Solution

Question #2


When does undefined behavior occur? What are the consequences of undefined behavior?

Show Solution

Question #3


Write a program that asks the user to enter a number, and then enter a second number. The program should tell the user what the result of adding and subtracting the two numbers are.

The output of the program should match the following (assuming inputs of 6 and 4):

Enter an integer: 6
Enter another integer: 4
6 + 4 is 10.
6 - 4 is 2.

Show Solution


2.1 -- Introduction to functions
Index
1.11 -- Developing your first program

688 comments to 1.x — Chapter 1 summary and quiz

  • yash pal singh

    When I used '\n' instead of "\n" at line 13 and 14 I got some random numbers after 10 and 2

    • It is because of the "."
      In the lesson there is ".\n" because we want to see a "." at the end of the sentence. But if you put it like '.\n' it wont work. You either leave the point out like this: '\n' or leave it in like this: ".\n" because the point is the part of the sentence but the \n is not.

  • Rex

    is this a good way to do it or no? i do realize the output is not word by word but im just looking for any mistakes or feedback.

    • Dan

      Rex,

      There is nothing wrong with how you did it. I think the main point I'd make here is that there would be no way for the user to determine if the program read in the input correctly. On a simple problem like this, it doesn't matter much. as part of a larger program, it's good to output the inputs in a readable way to both assist the user and programmer with knowing what the inputs were.

  • Chris

    Here's my solution. I was wondering, when should you initialize variables before the main function (like I did), and when should you do it right before the statement it's actually used in (like in the solution)? Does it even matter?

  • Mauricio

    #include <iostream>

    int main ()
    {
        std::cout << "Please enter a whole number: ";
        int num1{0};
        std::cin >> num1;

        std::cout << "Please enter another whole number: ";
        int num2{0};
        std::cin >> num2;

        std::cout << num1 << "+" << num2 << " is " << num1 + num2 << std::endl;
        std::cout << num1 << "-" << num2 << " is " << num1 - num2 << std::endl;

        return 0;
    }

  • Vivian

    The solution for the program w=shown was so simple. Mine was like:
    #include <iostream>

    [int main()
    {
        std::cout << "Enter an integer: ";

        int num1{ 0 };
        std::cin >> num1;

        std::cout << "Enter another integer: ";

        int num2{ 0 };
        std::cin >> num2;

        std::cout << num1 << " + " << num2 << " is " << num1 + num2 << '\n';
        std::cout << num1 << " - " << num2 << " is " << num1 - num2 << '\n';

        return 0;
    }]
    Like complicated as but it works completely fine

  • Nuke

    #include <iostream>

    int main()
    {
        int x{};
        std::cout << "Enter an integer: ";
        std::cin >> x;

        int y{};
        std::cout << "Enter another integer: ";
        std::cin >> y;

        std::cout << x << " + " << y << " is " << x + y << ".\n";
        std::cout << x << " - " << y << " is " << x - y << ".\n";

        return 0;
    }

    Enter a number: 100
    Enter a second number: 50
    150121425012142
    C:\Users\CSP\source\repos\CSP\Debug\CSP.exe (process 8976) exited with code 0.
    Press any key to close this window . . .

    Why do I get a random number ??

  • insane

    #include <iostream>

    int main()
    {
        std::cout << "Enter an integer: ";

        int num = 0;
        std::cin >> num;

        std::cout << "Enter another integer: ";

        int second_num = 0;
        std::cin >> second_num;

        std::cout << num << " + " << second_num << " is " << num + second_num << "\n";
        std::cout << num << " - " << second_num << " is " << num - second_num;

        return 0;
    }

  • im new to coding. but i think i am following so far...
    but
    there seems to be a clear difference between how i interpreted Question #3 and what the task actually was.

    am i thinking about it to literally?
    //(that seems to be the case)
    instead of logically...

    and even tho it worked just as i expected it to, i can not really think of a practical application. any thoughts?

    i would really enjoy some feed back about this.
    sorry for the lack of color separation..

    [
    #include <iostream>

    int main()

    {
         std::cout << "Enter an integer:"; '\n';

         int num{ };                                    
         std::cin >; num;                            
         std::cout << "Enter another integer:"; '\n';
        
         std::cin; num;                            

         int x(6);                                    
         num = { num + 6 };                            
         std::cout << " 6 + 4 is " << num << '\n';    

         num = { num - 8 };                            
         std::cout << " 6 - 4 is " << num << '\n';

        return 0;
    ]

  • Andrei

    Hi,

    Can you also advise me on a problem I am facing?

    My code is :

    Whenever i am adding the numbers (6, -7) the second line says: 6 - -7= 13

    How can I make so my code displays a corect substraction if the second number is negative.

  • Vishal

  • BSkirt

    So I did this, and it worked, and it felt really good on first try. But is this for any reason inefficient? Am I braking any recommendations? Either way thank you for all who are providing the site!

    • nascardriver

      Only initialize variables with an explicit value if you're going to use that value. You're never using the 0 you're initializing `num` and `num2` with, so they should be initialized with empty curly braces to avoid confusing the reader

  • Anon

    #include <iostream>

    int main()
    {
        std::cout << "Enter an integer:";
        int num{};
        std::cin >> num;

        std::cout << "Enter another integer:";
        int num2{};
        std::cin >> num2;

        std::cout << num << "+" << num2 << "=" << (num + num2) << '\n';
        std::cout << num << "-" << num2 << "=" << (num - num2);

        return 0;
    }

    -Also why do we need the curly brackets when initializing the variable?
    -What does return 0; actually do? It doesn't seem to make a difference whether it's there or not. Why do we even write it?

  • I really love this website!!!!

  • Carlos Fernandes

    why not like this? why not the '/n'??
    Please someone help me:

    (#include <iostream>

    int main()
    {
        int num1{ 0 };
        std::cout << "Enter a number:";
        std::cin >> num1;

        int num2{ 0 };
        std::cout << " Enter a second number:";
        std::cin >> num2;

        std::cout << num1 << "+" << num2 << "is:" << num1 + num2 << '/n';

        std::cout << num1 << "-" << num2 << "is:" << num1 - num2 << '/n';

        return 0;
    })

  • Berrie

    Hey there,

    I have some tinkering experience with arduinos but I've finally decided to learn to code properly so I'm beginning this tutorial from scratch. Even though these first chapters are basic I've still learned a lot about how to structure and comment on code.

    My code looks as follows:

    I've decided to go with x and y as variable names because for a program this simple it doesn't need to be descriptive. I've also initialized them before the main function. Since my experience is limited to microcontrollers I do not know if this is good or bad practise.

    For microcontroller code there are always two functions that your program needs,

    and

    I believe the reason that these are initialized before these functions is because only then they can be used in both setup and loop.

    Is this a bad habit that I need to get rid of when I'm going to write programs for computers?

    • nascardriver

      Hi!

      Global variables are bad, because they could change to any value at any time, breaking seemingly unrelated code. Declare variables as close to their first use as possible.

      If you use `setup()` and `loop()` and they both need to access the same variable, the variable has to be global or at least in file-scope. Arduino probably has some reason to use `setup()` and `loop()`, but you can do without them even on Arduinos.

      • Berrie

        Hey nascardriver, thanks for the quick response.

        I've been trying some things out and I've learned something about how arduino structures code.

        Apparently the arduino IDE uses a hidden main function. When the loop() or setup() functions are ommited from the code the compiler responds with a message like this:

        In function `main':
        <some path>/main.cpp:43: undefined reference to `setup'

        After a quick search I've found the following main function:

        I don't know what init() does exactly but it is not in the empty sketch and the compiler doesn't seem to care if I add it or not. I pressume that the init() function contains board information like pin configurations/functionality. When I write my own init() function in the sketch it seems to ignore everything that is in it. (I have not validated this for myself)

        I get what you mean when you say about global variables being bad. I've tried to initialize variables in different places. I seems to work everywhere. Before, inside and after setup() but also inside loop() which I did not expect to work because these variables are initialized every time loop() executes. I have to do a deeper dive into what the code actually compiles to, to see if it actually makes a difference compared to initializing the variable in setup and just assigning a value inside loop.

        For now I'll try to stick with your advice and initialize variables close to where I use them. If this impacts performance I might rethink that approach.  

        In the case of arduinos performance really matters but while I'm following this tutorial to learn how to write better code I'm also moving to more advanced microcontrollers like the ESP8266/ESP32 where I have more than enough performance for my current projects. For the ESP microcontrollers it is probably better to write good code than to get the maximum performance out of the microcontroller because resources (clockcycles and memory) are abundant. And when I eventually encounter a project where I don't have enough resources I don't think it is going to make a big difference where I initialized variables (if there is a difference at all).

Leave a Comment

Put all code inside code tags: [code]your code here[/code]