<<<<<<< HEAD Unit 03: C++ Basics (CS 200) - R.W.'s Courses

Unit 03: C++ Basics

  1. Files in a C++ project
  2. Contents of a C++ source file
  3. C++ statements
  4. Displaying text to the screen
  5. Program comments
  6. Syntax errors, logic errors
  7. Minimizing bugs and debugging time
  8. Variables and data types
  9. Console input and output

  10. Example code and additional resources

This week's stuff:

Files in a C++ project

At minimum, a C++ program requires one file - a .cpp source file. Usually programs are bigger and contain multiple files, like .h header files as well as other .cpp source files. The file that contains the program starting point is usually named main.cpp, but it doesn't have to have this name.

A C++ source file is technically just a plaintext file, which can be opened in a text editor like notepad, though there are better code editors than notepad.

Contents of a C++ source file

Every C++ program requires a main() function as its starting point. The most basic C++ program must have the following:


int main()
{
    return 0;
}
        

For now you can take this code for granted but you will understand it more as the class continues. But, some basic info:

  • The int main() is the function that starts our program.
  • The contents of the program must be between the opening curly brace { and the closing curly brace }. This region is known as main()'s code block. We will see more code blocks (with { }) later in the class.
  • The return 0; is where the program ends. 0 is returned for 0 errors.
  • Code we add will go after the { and before the return 0;.

Additionally, C++ is case sensitive, so capitalization matters. Make sure you write main() in all lower case - Main() and MAIN() won't work!

C++ statements

  • C++ statements are single commands to be performed, and always end with a semicolon ;
  • There are some commands we'll cover later that aren't just single commands, so they don't end with a semicolon. We will cover those later.
  • Example basic commands:
    • Declaring a variable:
      int total_cats;
    • Assigning a value to a variable:
      total_cats = 10;
    • Doing arithmetic:
      int result = number1 * number2;
    • Displaying text to the screen:
      cout << "Hello!";

Displaying text to the screen

In order to display text to the screen with our program, we need to include a library.A library is a set of pre-written code that can be used across multiple programs. C++ contains a standard library of pre-written code we can use. To gain access to the cout (console-output) statement, we need to add this at the top of our C++ program file:

#include <iostream>

After that, we can use the cout command to display text like this:

std::cout << "Hello!";

The std:: prefix stands for "standard", as in the C++ standard library. This command will display "Hello!" to the screen when the program is built and run.
You can also add empty lines to the program using the endl (end-line) command:

std::cout << std::endl;

And these commands can be chained together:

std::cout << "Hello!" << std::endl << "World!" << std::endl;

The << sign is known as the output stream operator.

Program comments

We can leave comments in our code. Comments are meant for humans, and not the computer - the compiler just ignores these lines. But, they can be handy to help clarify what's going on in your program.

A single line comment begins with two forward slashes:

// Note: formula for area

Sometimes you need more text, so you can use a multi-line comment. These begin with /* and end with */ like this:


/*
MY PROGRAM
This program does abcxyz stuff.
*/
        

Syntax errors, logic errors

We're going to be making a lot of errors during this semester and throughout our programming career! As you keep practicing, you'll get better at the diagnosis and fixing process, but bugs will always occur. I know they can be frustrating, but it's a normal part of development. Here are some tips...

  • Syntax errors are errors in the language rules of your program code. This include things like typos, misspellings, or just writing something that isn't valid C++ code, such as forgetting a ; at the end of some instructions.

    Although they're annoying, syntax errors are probably the "best" type of error because the program won't build while they're present. Your program won't build if you have syntax errors.


  • Logic errors are errors in the programmer's logic. This could be something like a wrong math formula, a bad condition on an if statement, or other things where the programmer thinks thing A is going to happen, but thing B happens instead.

    These don't lead to build errors, so the program can still be run, but it may result in the program crashing, or invalid data being generated, or other problems.

Minimizing bugs and debugging time

We're going to be making a lot of errors during this semester and throughout our programming career! As you keep practicing, you'll get better at the diagnosis and fixing process, but bugs will always occur. I know they can be frustrating, but it's a normal part of development. Here are some tips...

  • Write a few lines of code and build after every few lines - this will help you detect syntax errors early.

  • DON'T write the "entire program" before ever doing a build or a test - chances are you've written in some syntax errors, and now you'll have a long list of errors to sift through!

  • If you aren't sure where an error is coming from, try commenting out large chunks of your program until it's building again. Then, you can un-comment-out small bits at a time to figure out where the problem is.

Variables

  • Variables are a place where we can store data under some "name".
  • These variables may be used to store numbers that we can do math with, or perhaps store records for a user, or many other things -- any software you use in your daily life has variables built in.
  • Data types include integers (whole numbers), floating point numbers (numbers with decimals), strings (text), booleans (true/false), characters (single letters/symbols), and we can even eventually make our own data types.
Data TypeExample values
int-5, 1, 45
float 98.5, 7.75
string "Username", "HI!"
char '$', 'x'
bool true, false

Variable names can contain letters, numbers, and underscores - but NO SPACES!

Variable declaration and assignment

Variable declaration: In our C++ programs, we need to tell our program about a variable before we start using it. This type of instruction is called a variable declaration. To do this, we specify the variable's DATA TYPE and give it a NAME.

string username;
int total_followers;

Programs flow from the top to the bottom (until we get to functions :) so before you use any variables, they must be declared above.


Variable assignment: You can assign values to variables in C++ using the assignment operator, =, like this:

username = "MooseInvader";
total_followers = 12345;

You can also assign a value to a variable during its declaration. This is known as initializing the variable:

string username = "Texpert";

Variable arithmetic

With numeric variables you may need to do arithmetic with them. The basic arithmetic operators are:

OperationOperatorExample code
Add+total_posts = video_post_count + text_post_count;
Subtract-total_followers = total_followers - 1;
Multiply*area = width * length;
Divide/price_per_pizza = 9.99 / 3;

When writing a command statement with a math expression, the LHS (left-hand-side) of the equal sign is WHERE TO STORE THE RESULT. The RHS (right-hand-side) of the equal sign is THE MATH EXPRESSION TO BE SOLVED.

Outputting text and variables

We can use the cout command (pronounced "C-Out" for Console Output) to display text to the screen. We can display string literals "like this" - which are hard-coded text we put in - or we can display variable values.

Note that to use output and input commands, we need to add #include <iostream> at the top of our code file. This is a library of pre-written code we can utilize.


#include <iostream>
using namespace std;

int main()
{
  // endl means "end line", starts the next text on a new line.
  cout << "Hello," << endl;
  cout << "world!" << endl;
  
  return 0;
}
        

If we want to display a variable's value, we put the variable's name in the cout command:

cout << total_cats << endl;

And when displaying variable values, it's best to add a string-literal label so that the user knows what the data they're looking at means.

cout << "Total cats I have: " << total_cats << endl;

Getting input from the keyboard

Often we want our programs to be interactive, so that the user can interface with it and our program can respond to the user's input. The first step to this is getting input from the keyboard and storing that input in a variable. We do this with the cin ("C-in", Console Input) command:


#include <iostream>
using namespace std;

int main()
{
  cout << "Enter your favorite number: " << endl;
  int favorite_number;
  cin >> favorite_number;     // Getting input and storing in favorite_number variable
  cout << "Your favorite number is " << favorite_number << endl;
  
  return 0;
}
        

String input and cin.ignore()

If we want to get string text, we can use cin >>, but that won't capture any spaces. If you want to get information like a name, address, etc., you will probably want to use the getline function instead:

#include <iostream>
using namespace std;

int main()
{
  cout << "Enter your username: ";
  string username;
  getline( cin, username );   // Get a full line of text
  
  return 0;
}
        

However, if you inter-mix cin >> ... and getline( cin, ... ), then we will run into some buffer issues. If your program is skipping an input, that means you need to add a cin.ignore(); to your program. This ONLY needs to happen when going FROM cin >> ... TO getline( cin, ... ):

int pin;
string username;

cout << "Enter your PIN: ";
cin >> pin;

cin.ignore();   // Flush the input buffer

cout << "Enter your username: ";
getline( cin, username );   // Get a full line of text
        

Example code and additional resources

In-class example code:

  1. Super basics v1
  2. Super basics v2
  3. Mad lib
  4. Item price, name, quantity

Archived videos and class lectures:

======= Unit 03: C++ Basics (CS 200) - R.W.'s Courses

Unit 03: C++ Basics

  1. Files in a C++ project
  2. Contents of a C++ source file
  3. C++ statements
  4. Displaying text to the screen
  5. Program comments
  6. Syntax errors, logic errors
  7. Minimizing bugs and debugging time
  8. Variables and data types
  9. Console input and output

  10. Example code and additional resources

This week's stuff:

Files in a C++ project

At minimum, a C++ program requires one file - a .cpp source file. Usually programs are bigger and contain multiple files, like .h header files as well as other .cpp source files. The file that contains the program starting point is usually named main.cpp, but it doesn't have to have this name.

A C++ source file is technically just a plaintext file, which can be opened in a text editor like notepad, though there are better code editors than notepad.

Contents of a C++ source file

Every C++ program requires a main() function as its starting point. The most basic C++ program must have the following:


int main()
{
    return 0;
}
        

For now you can take this code for granted but you will understand it more as the class continues. But, some basic info:

  • The int main() is the function that starts our program.
  • The contents of the program must be between the opening curly brace { and the closing curly brace }. This region is known as main()'s code block. We will see more code blocks (with { }) later in the class.
  • The return 0; is where the program ends. 0 is returned for 0 errors.
  • Code we add will go after the { and before the return 0;.

Additionally, C++ is case sensitive, so capitalization matters. Make sure you write main() in all lower case - Main() and MAIN() won't work!

C++ statements

  • C++ statements are single commands to be performed, and always end with a semicolon ;
  • There are some commands we'll cover later that aren't just single commands, so they don't end with a semicolon. We will cover those later.
  • Example basic commands:
    • Declaring a variable:
      int total_cats;
    • Assigning a value to a variable:
      total_cats = 10;
    • Doing arithmetic:
      int result = number1 * number2;
    • Displaying text to the screen:
      cout << "Hello!";

Displaying text to the screen

In order to display text to the screen with our program, we need to include a library.A library is a set of pre-written code that can be used across multiple programs. C++ contains a standard library of pre-written code we can use. To gain access to the cout (console-output) statement, we need to add this at the top of our C++ program file:

#include <iostream>

After that, we can use the cout command to display text like this:

std::cout << "Hello!";

The std:: prefix stands for "standard", as in the C++ standard library. This command will display "Hello!" to the screen when the program is built and run.
You can also add empty lines to the program using the endl (end-line) command:

std::cout << std::endl;

And these commands can be chained together:

std::cout << "Hello!" << std::endl << "World!" << std::endl;

The << sign is known as the output stream operator.

Program comments

We can leave comments in our code. Comments are meant for humans, and not the computer - the compiler just ignores these lines. But, they can be handy to help clarify what's going on in your program.

A single line comment begins with two forward slashes:

// Note: formula for area

Sometimes you need more text, so you can use a multi-line comment. These begin with /* and end with */ like this:


/*
MY PROGRAM
This program does abcxyz stuff.
*/
        

Syntax errors, logic errors

We're going to be making a lot of errors during this semester and throughout our programming career! As you keep practicing, you'll get better at the diagnosis and fixing process, but bugs will always occur. I know they can be frustrating, but it's a normal part of development. Here are some tips...

  • Syntax errors are errors in the language rules of your program code. This include things like typos, misspellings, or just writing something that isn't valid C++ code, such as forgetting a ; at the end of some instructions.

    Although they're annoying, syntax errors are probably the "best" type of error because the program won't build while they're present. Your program won't build if you have syntax errors.


  • Logic errors are errors in the programmer's logic. This could be something like a wrong math formula, a bad condition on an if statement, or other things where the programmer thinks thing A is going to happen, but thing B happens instead.

    These don't lead to build errors, so the program can still be run, but it may result in the program crashing, or invalid data being generated, or other problems.

Minimizing bugs and debugging time

We're going to be making a lot of errors during this semester and throughout our programming career! As you keep practicing, you'll get better at the diagnosis and fixing process, but bugs will always occur. I know they can be frustrating, but it's a normal part of development. Here are some tips...

  • Write a few lines of code and build after every few lines - this will help you detect syntax errors early.

  • DON'T write the "entire program" before ever doing a build or a test - chances are you've written in some syntax errors, and now you'll have a long list of errors to sift through!

  • If you aren't sure where an error is coming from, try commenting out large chunks of your program until it's building again. Then, you can un-comment-out small bits at a time to figure out where the problem is.

Variables

  • Variables are a place where we can store data under some "name".
  • These variables may be used to store numbers that we can do math with, or perhaps store records for a user, or many other things -- any software you use in your daily life has variables built in.
  • Data types include integers (whole numbers), floating point numbers (numbers with decimals), strings (text), booleans (true/false), characters (single letters/symbols), and we can even eventually make our own data types.
Data TypeExample values
int-5, 1, 45
float 98.5, 7.75
string "Username", "HI!"
char '$', 'x'
bool true, false

Variable names can contain letters, numbers, and underscores - but NO SPACES!

Variable declaration and assignment

Variable declaration: In our C++ programs, we need to tell our program about a variable before we start using it. This type of instruction is called a variable declaration. To do this, we specify the variable's DATA TYPE and give it a NAME.

string username;
int total_followers;

Programs flow from the top to the bottom (until we get to functions :) so before you use any variables, they must be declared above.


Variable assignment: You can assign values to variables in C++ using the assignment operator, =, like this:

username = "MooseInvader";
total_followers = 12345;

You can also assign a value to a variable during its declaration. This is known as initializing the variable:

string username = "Texpert";

Variable arithmetic

With numeric variables you may need to do arithmetic with them. The basic arithmetic operators are:

OperationOperatorExample code
Add+total_posts = video_post_count + text_post_count;
Subtract-total_followers = total_followers - 1;
Multiply*area = width * length;
Divide/price_per_pizza = 9.99 / 3;

When writing a command statement with a math expression, the LHS (left-hand-side) of the equal sign is WHERE TO STORE THE RESULT. The RHS (right-hand-side) of the equal sign is THE MATH EXPRESSION TO BE SOLVED.

Outputting text and variables

We can use the cout command (pronounced "C-Out" for Console Output) to display text to the screen. We can display string literals "like this" - which are hard-coded text we put in - or we can display variable values.

Note that to use output and input commands, we need to add #include <iostream> at the top of our code file. This is a library of pre-written code we can utilize.


#include <iostream>
using namespace std;

int main()
{
  // endl means "end line", starts the next text on a new line.
  cout << "Hello," << endl;
  cout << "world!" << endl;
  
  return 0;
}
        

If we want to display a variable's value, we put the variable's name in the cout command:

cout << total_cats << endl;

And when displaying variable values, it's best to add a string-literal label so that the user knows what the data they're looking at means.

cout << "Total cats I have: " << total_cats << endl;

Getting input from the keyboard

Often we want our programs to be interactive, so that the user can interface with it and our program can respond to the user's input. The first step to this is getting input from the keyboard and storing that input in a variable. We do this with the cin ("C-in", Console Input) command:


#include <iostream>
using namespace std;

int main()
{
  cout << "Enter your favorite number: " << endl;
  int favorite_number;
  cin >> favorite_number;     // Getting input and storing in favorite_number variable
  cout << "Your favorite number is " << favorite_number << endl;
  
  return 0;
}
        

String input and cin.ignore()

If we want to get string text, we can use cin >>, but that won't capture any spaces. If you want to get information like a name, address, etc., you will probably want to use the getline function instead:

#include <iostream>
using namespace std;

int main()
{
  cout << "Enter your username: ";
  string username;
  getline( cin, username );   // Get a full line of text
  
  return 0;
}
        

However, if you inter-mix cin >> ... and getline( cin, ... ), then we will run into some buffer issues. If your program is skipping an input, that means you need to add a cin.ignore(); to your program. This ONLY needs to happen when going FROM cin >> ... TO getline( cin, ... ):

int pin;
string username;

cout << "Enter your PIN: ";
cin >> pin;

cin.ignore();   // Flush the input buffer

cout << "Enter your username: ";
getline( cin, username );   // Get a full line of text
        

Example code and additional resources

In-class example code:

  1. Super basics v1
  2. Super basics v2
  3. Mad lib
  4. Item price, name, quantity

Archived videos and class lectures:

>>>>>>> 1b3da755f69f89a8787c7d747b10904acabef938