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

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

  • qwerty

    what do we mean by console?
    is it another name for command prompt?

    • sam p

      yes, they're the same thing - a window where the program prints stuff it wants us to read, and where we can type input.

      • qwerty

        so any window where a program displays its output is a console?

        • sam p

          well, not really;
          'console' implies that there is some interactivity, or two-way communication; the program can write messages to the user, and the user can enter input asked for by the program;
          if the program simply opens a window and prints output (and maybe the user clicks on an 'OK' or 'CLOSE' button to close the window, I don't think anyone would call that window a 'console')
          Hope that makes sense.

  • Rai

    For indentation would you prefer the curly brackets next to or in the next line after the function

    My professor prefers the below one but I see this site use the top one

    • I personally prefer to do it like the top one because I think it looks better and that the bottom one is harder to read, but it all comes down to what you prefer. The results will be the same anyway, so just do what you like.

  • QuantMad

    Greetings from Ukraine!

    Output:
    Write first digit: 95
    Write second digit: 15
    95+15=110
    95-15=80

  • Zach Roberts

    Here is what I came up with. Is there an easier way to write this.

  • CthulusFinanceMan

    When I was doing the exercise, I was getting some really large numbers even when I put in something like 4 & 5 (I'd get this output "4 + 5 adds to 9117864 - 5 subtracts to -111786" all in one line). My code at the time looked like this:

    I know what was causing this now, at the ends of the lines the '.\n' should have been ".\n", I wasn't being consistent. But why did this happen? And what is it actually doing to get there? (I don't have any programming experience to speak of, so please be gentle).

    • Riham

      Multicharacter literal, e.g. 'AB', has type int and implementation-defined value.
      Many implementations of multicharacter literals use the values of each char in the literal to initialize successive bytes of the resulting integer, in big-endian order.

      basically the compliter calculates the values by calculating the first number, which is the equivalent of '.' in the ascii table (http://www.asciitable.com/) which is 46, shifts it by 8, and adds '/n' (10) to it, the result is 11786.

      << num1 + num2 << '.\n' prints the actual sum (9) followed by 11786, you can verify it here:

  • NitoCore

    so i know some c++ and took this test just to see if i qualify to go past chapter 1, which i do, p simple stuff. trying to look for the chapter i should start with. but i noticed you use int x{}; instead of just int x; ? does it actually change anything? I can see where int{ enter number here } kinda makes sense since it is the same ammount of typing as int x = 1; but is there any reason to do it this way? is it just the way you learn, or does it actually do something different?

    • Alexandr

      Hey there!
      You definitely need to go through chapter 1 articles and read Best Practice and Warning notes in green and red areas.

      { number } means we initialize a variable with given value.

      int x is just a declaration, which means you tell the compiler to reserve memory for variable named x with type int, and all it does is memory allocation (without assigning any value), so whatever was in that memory before allocation continue to reside there. That is bad, because it leads to undefined behavior if you do not assign the variable before using it.

      Assignment operator (=) copies the specified value to the allocated memory. You can assign a value to the variable after you have declared it. The assignment allows you to write simething like

      and this value will be truncated to 4 as int can hold only the whole numbers. The {} operator disallow such things making your code more straightforward and clear.

  • MX

    i found this the easiest way to do it :D

  • A.J

    Why can't you nest comments as in using regions like
    [/#pragma region whatever]?
    Especially using that with comments.

  • Tony

    Chapter 1 finished on 18th 07 2020! Here's my code (with functions since I already know them). Let me know your feedback on what could be done better! Thanks :-)

  • 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]