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

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

  • Brian

    I wrote this but in the x+y I get a random number such as 10117864 and with x-y I get -211786.

    I got my x values and my y values to accept input and to show the correct values but when it does the addition or subtraction, I get very strange numbers.

  • Logan

    I made mine like this. I know I should have used comments. just wanted other opinions on it

    • nascardriver

      Hey Logan,

      if you program prints anything, the last thing it prints should be a line feed (\n) to prevent output of programs getting mixed.
      Explicitly initializing `x` and `y` to `0` can be confusing, as the reader might think you're using the value for something. Empty curly braces are fine here.

  • 行走在技术的深坑里

    虽然语言障碍让我阅读很吃力,但是不得不承认这是一个非常棒的网站已经非常可爱的作者以及维护者!非常感谢辛勤的付出,我的C++之旅我想是从这里起航!(谷歌翻译还是很不错的!!)

  • Hector

    This is my solution.

    Thanks for share your knowledge with us! :)

  • Wanderlust814

    I feel my code is lacking the experimentation of more...advanced...beginners? I tried to get as close to lesson as possible. Still works great though.

    • Initialize your variables with brace initializers. Brace initialization doesn't use `=`.

      Looks good otherwise.

    • danik123

      Just to add up to nascardrivers answerd. The '=' can be there and is not mistake, for compiler it should be the same. If it helps you to have more intuitive grasp on the initialization, you can use it.

  • Shubham Maske

    Here is My answer :

    • - Don't use `using namespace`.
      - Declare one variable per line.
      - Inconsistent formatting. Use your editor's auto-formatting feature.
      - If your program prints anything, the last thing it prints should be a line feed ('\n').

      • Jake

        Hi nascardriver.

        You admonished Shubham to not use "using namespace".  I just came off a different beginner's "course" (Bucky's 9-hour YouTube video) and it uses CodeBlocks.  CodeBlocks inserts the "using namespace" directive (pragma? I don't know what I'm talking about yet :-)  One rationale for not "using" is that we don't know what in &!@%3$ a namespace is.  On the other hand, taking it as an arbitrary artifact of the language, I see it as a minor typing saver: I don't have to use the std:: prefix for cout and cin.  So please explain to us, we who have just enough knowledge to be dangerous, why I should not use a shortcut I already happen to know.  (Will anyone confess to remembering PL/1 and PROC OPTIONS(MAIN) ? ;-)

        • It can cause name conflicts, eg. you want to use a function but it resolves to a different function or multiple functions. This causes undesired behavior and a compilation error.
          There's a lesson about this that goes into more detail. You'll see it along your journey.

  • 4STR4L_3N3MY

    I did it like this!
    i know, i need to add comments.

    #include <iostream>

    int main()
    {
        int inP1;
        int inP2;

        std::cout << "Enter your first #: ";
        std::cin >> inP1;
        
        std::cout << "\n" << "Enter your second #: ";
        std::cin >> inP2;

        std::cout << "\n" << inP1 << " + " << inP2 << " = " << (inP1 + inP2);
        std::cout << "\n" << inP1 << " - " << inP2 << " = " << (inP1 - inP2);
        std::cout << "\n" << inP1 << " * " << inP2 << " = " << (inP1 * inP2);
        std::cout << "\n" << inP1 << " / " << inP2 << " = " << (inP1 / inP2);
    }

    When dividing, how do i program the higher # to be divided by the lower # - i dunno how to do that yet

    • Please use code tags when posting code (Yellow message below to comment box).

      - Print the line feed at the end of lines. Printing them at the beginning is likely to mess up output.
      - Use single quotation marks for characters ('\n' instead of "\n").

      You can use `std::swap` to swap the values of 2 variables.

      This will only work if the division is the last thing you do, as the variables stay swapped for all further operations.

  • Nico

    I have done like this:

    #include <iostream>

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

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

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

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

        std::cout << numOne << " + " << numTwo << " is: " << numOne + numTwo << '\n';
        std::cout << numOne << " - " << numTwo << " is: " << numOne - numTwo << '\n';

        return 0;
    }

  • senko

    what is the purpose of writing:

    if you can write:

    Am I missing something important? I didn't even know you could write it like that.

  • Jim

    This code is very different from what you posted and it gives the right answer. Is it still good?

    • Hi Jim!

      It's very similar to Alex' solution. You used multiplication instead of subtraction, that's fine, experimenting speeds up the learning process.

      - Inconsistent formatting. Use your editor's auto-formatting feature.
      - If you program prints anything, the last character it prints should be a line feed ('\n').

  • prasanth guntupalli

    #include<iostream>
    using namespace std;
    int main()
    {
    cout<<"declare any number"<<endl;
    cin>>a;
    cout<<"declare another number"<<endl;
    cin>>b;
    cout<<"result after addition is"<<endl;
    cout<<a+b<<endl;
    return 0;
    }

  • zim

    Hi, here is my code is it ok to initializing variable first or do you need to do this before you use them ? I just find it much neater to have them all above the main program first. thanks

    #include <iostream>

    int main()
    {
    int addA{};
    int addB{};

       std::cout << "enter a number 1 : ";
       std::cin >> addA;
       std::cout << "enter a number 2 : ";
       std::cin >> addB;
       std::cout << addA << " + " << addB << " = " <<  addA + addB << '\n';
       std::cout << addA << " - " << addB << " = " << addA - addB  << '\n';
       return 0;
    }

    • You should declare variables as close to their first use as possible. It won't make a difference yet, but once you get to classes, this will improve memory usage.

    • Chayim

      Your code should be like this:

      #include <iostream>
      using namespace std;

      int main()

      {
      int addA{};
      int addB{};

         std::cout << "enter 2 numbers: ";
         std::cin >> addA;
         std::cin >> addB;
         std::cout << addA << " + " << addB << " = " <<  addA + addB << '\n';
         std::cout << addA << " - " << addB << " = " << addA - addB  << '\n';
        
         return 0;
      }

    • Chayim

      Better like this:

      #include <iostream>
      using namespace std;

      int main()

      {
      int addA{};
      int addB{};

         std::cout << "enter 2 numbers: \n";
         std::cin >> addA;
         std::cin >> addB;
         std::cout << addA << " + " << addB << " = " <<  addA + addB << '\n';
         std::cout << addA << " - " << addB << " = " << addA - addB  << '\n';
        
         return 0;
      }

  • Logan

    Just one point, I did the question above and rather than declare the variable under two lines, I used one for num1 and num2; Is this okay? And if so, is there also a more concise way of doing ,"cin" in one line?

    The result below:
    Enter a number:
    4
    Enter a second number:
    8
    The result of 4 + 8 = 12
    The result of 4 - 8 = -4
    Press any key to continue . . .

    • > I used one for num1 and num2; Is this okay?
      No, this makes your code harder to read and can lead to mistakes. @num1 is uninitialized. The curly braces only apply to @num2.

      > is there also a more concise way of doing ,"cin" in one line?
      You'll learn about functions later. They can be used to wrap a call to @std::cin.operator>> so you can do this

      • Logan

        Thank you, yeah, I ran it separate and got the uninitialized message. Slight moment of madness. I think my crazy thinking was it would default both to zero. I tested it by then adding its own curly braces with amount inside, least that then worked, but as you say it looks messy.

        As for the cin, I am curious to what you mentioned up there, as opposed to using a Loop. To see if data can be placed into multiple variables without using a Loop. Just something I was wondering about. Thanks again!

  • Prateek

    I am trying to find area of a circle.

    #include <iostream>
    int main()
    {
    std::cout<<"Enter the radius of the circle : ";

    int radius{};                    // I just want user to enter an integral value of radius.

    std::cin>>radius;
    std::cout<<"Area of circle is "<< "π"<< "*"<< radius<<" *"<<radius<< "="<< π*radius*radius<<'\n';
    return 0;
    }

    I am getting a compilation error.
    What exactly is wrong in my program?

    • Nice

      Probably the fact that your compiler thinks π is an undefined identifier and not a number that can be multiplied.

    • no Name

      try this bro

      #include <iostream>
      #include <math.h>
      int main()
      {
      std::cout<<"Enter the radius of the circle : ";
      double radius{};
      double pi {16 * atan2(1.0, 5.0) - 4 * atan2(1.0, 239.0)};
      std::cin>>radius;
      std::cout<<"Area of circle with radius " << radius<< ' ' << "is " << pi*pow(radius,2)<<'\n';
      return 0;
      }

    • no Name

      wtf is this
      std::cout<<"Area of circle is "<< "π"<< "*"<< radius<<" *"<<radius<< "="<< π*radius*radius<<'\n';

      try to make like this
      #include <iostream>
      int main()
      {
      std::cout<<"Enter the radius of the circle : ";

      int radius{};                    // I just want user to enter an integral value of radius.
      double pi {3.1415926535897}; //pi value
      std::cin>>radius;
      std::cout<<"Area of circle with radius "<< radius << ' ' <<  "is: " << pi*radius*radius<<'\n';
      return 0;
      }

      • Prateek

        My problem was indeed silly,as I am just a beginner, and was trying to figure out a random simple question that came to my mind.
        I appreciate your efforts.
        Thank you

    • Alex

      This program has several things wrong with it. Namely, π hasn't been defined. Generally, you shouldn't use non-ASCII characters for variable names. So you should rename this to pi, and then define pi with a value. Or replace it with the literal value 3.14159.

    • Bruhdeel

      #include <iostream>

      int main()
      {
          std::cout << "Enter the radius of the circle : ";

          int radius{};

          std::cin >> radius;
          std::cout << "Area of the circle is " << "pi " << " * " << radius << " * " << radius << " = " << 3.1415926535897 * radius * radius << '\n';
          return 0;
      }
      I changed it up a bit and this compiled with no errors. Don't use non-ascii characters.

  • Austin

    Hi thank you so much for the time and effort you put into these lessons! I've really enjoyed following along.

    I have a question about defining a variable and assigning a variable. I noticed at question 3 you defined the variable, used std::cout, then assigned the variable through user input.

    I was under the impression that it's better to assign a value to a variable maybe right after declaring it. Maybe this is inconsequential, but I was wondering what was considered "best practice". I think I remember it being said in the lessons that this structure is debated but that you recommended a certain way of doing it.

    I'd be happy to clarify myself if necessary. Thank you!

    Here is how I wrote it:

  • ptitBarbu

    Great course Alex, very well explained !
    Thank you for that.

Leave a Comment

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