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.

Preprocessor directives tell the compiler to perform a special task. In this chapter, we use them to #include <iostream>, which allows us to access the input/output routines in the standard library.

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.10 -- Developing your first program

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

  • Syneyes

    I'd like to know if creating a variable before or after printing out "Enter x" has any effects on the functionality of the code itself? I'd guess that creating the variable before printing the text asking you to enter a value for it is better just for the person reading the source code since it kinda signals that it is referring specifically do enter a value for that variable that was just created above it, but it doesn't have any effect on the actual functionality of it if it was created either after or before the std::cout statement? (I also assume that for the std::cin things are different since creating the variable it is trying to use after the statement would result on the std::cin statement trying to input a value to a variable that doesn't even exist before it)

    Example:

    This:

    Or this:

    • nascardriver

      There is no functional difference between the two. On a low level or if you'd create complex objects, there are differences which you'll figure out later. For `int`, it doesn't matter. I like the first version, because it separates functional code (The creation of the variable) from IO. That way the IO part can more easily be replaced with something (maybe GUI) later.

  • Laylay

    Hi!

    Why doesn't std::cin work on my xcode?
    When I used that predefined variable, everything after the first std::cin didn't show on the console; however, after I deleted all the std::cin, things went all good.

    Why is this happening?

    • nascardriver

      Please post your code, expected output, and actual output

      • Laylay

        This is the code I copied from 1.10:

        My output--
        Enter an integer:

        Expected output--
        Enter an integer: 12
        Double that number is: 24

        (After deleted all the std::cin, I got my expected output)

        • nascardriver

          `std::cin` waits until you enter something. Pressing enter without entering anything doesn't get you out of `std::cin`. If you enter an integer, it will override `num`. If you enter a non-integer, extraction will fail and `num` is set to 0.

  • evolve

    I wish there were more challenges in this lesson, only 1 is not enough in my opinion.

  • Luxary

    Hi, thanks a lot for all of these resources, so far I found everything very clear and easy to pick up.

    There's one thing that is bugging me, and I'm sure it'll be addressed later in the course, but I noticed that using whitespaces when multiple std::cin statements are involved, leads to some unexpected behaviour.
    As in, using a whitespace will somehow "skip" to the second std::cin statement, thus breaking our (basic) formatting:

    Enter an integer: 2 3
    Enter another integer: 2 + 3 is 5.
    2 - 3 is -1.

    But it still seems to work pretty much. I'm guessing there are some precautions to take while parsing data, to clean it up and avoid this kind of unexpected behaviour, right? I just wanted to make a note in case someone is especially curious and eager to experiment. Thanks, once again :)

    • nascardriver

      All whitespace is the same to `std::cin >>`. It doesn't matter if it's a line feed or a space. There are ways to clean up the input in case you don't want to allow what you've shown. We cover that later.

  • Gyromite

    I was wondering if this code was good?
    #include <iostream>

    int main()
    {
        int num;

        std::cout << "Enter a integer ";
        std::cin >> num;
        std::cout << "Enter another integer ";
        std::cin >> num;
    }

    • JD

      can only have one value, so when you try to get the second integer it's going to overwrite the first one.

    • Mazhar Khan

      A better alternative would be:

      #include <iostream>
      int main()
      {
        int num_1{};
        int num_2{};
        
        std::cout<<"Enter an integer.\n";
        std::cin>>num_1;
        std::cout<<"Enter another integer.\n";
        sid::cin>>num_2;
      }

      then yyou can perform whatever operation you would like to perform on those number.

  • Tyler B.

    Hi Alex/community,
    In the solution to Question #3, lines 13 & 14, the statement ends with '.\n' instead of '\n'.
    When I edited my code to match my program still ran. However, it did not work as expected.

    This peaked my curiosity as to what '.\n' does. Does anyone have the answer to this?

  • Zatch

    #include <iostream>

    int main()

    {
        std::cout << "Binary addition and subtraction " << '\n';
        int X{};
        std::cout << "First number: " << X;
        std::cin >> X;
        int Y{};
        std::cout << "Second number: " << Y;
        std::cin >> Y;

        std::cout << "ADDITION: " << X + Y << '\n';
        std::cout << "SUBTRACTION: " << X - Y ;
        return 0;
        }

  • headhunteru23

    Here's mine with comments to painfully justify why my code is a bit longer than the recommended solution. I feel like I did the right thing in case I need to change the code at the cost of some extra resource usage. I also try to use the right terminology in my comments but I hope I haven't mixed terminology (ex: using expression statement when it's not and so on).

  • WALL-E

    Is this any good?

  • Kaan

    This one is from me :)

    • nascardriver

      hi!

      You pointed this out in another solution, so I have to do it to yours too. You're initializing `num1` and `num2` to specific values, but you don't use this value. If you want to initialize variables for the sake of them being initialized, but you don't want to use the value, use empty curly braces.

      This also initializes `num1` to 0, but a reader won't be confused as to why you initialized it to 0.

    • WALL-E

      Why not initialize 'num1' and 'num2' before everything else instead of after the 'cout' statements? Sure, the function won't change at all, but it'll make the code look a bit neater.

      • nascardriver

        By creating the variables at the beginning, you're causing them to be created and take up memory before you need them. For `int`s, that's not a huge deal. For more complex types, this can have negative effects when your function ends before they variable gets used.

Leave a Comment

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