c++ notes (very basic)

这篇博客介绍了C++的基础知识,包括 HelloWorld、变量、算术运算符、条件语句(如if、else、switch)、逻辑运算符、循环(while、for)、错误处理、向量操作、函数、类和对象以及引用和指针的概念。通过实例和练习,帮助读者掌握C++编程的基本技能。
摘要由CSDN通过智能技术生成


1.HELLO WORLD

std::cout << "Hello World!\\n";
std::cout is the “character output stream”. It is pronounced “see-out”.

<< is an operator that comes right after it.

"Hello World!\\n" is what’s being outputted here. You need double quotes around text. The \\n is a special character that indicates a new line.

; is a punctuation that tells the computer that you are at the end of a statement. It is similar to a period in a sentence.

Compile and Execute

Compile: A computer can only understand machine code. A compiler can translate the C++ programs that we write into machine code. You call on the compiler by using the terminal, which is the black panel to the right of the code editor that contains a dollar sign $. To compile a file, you need to type g++ followed by the file name in the terminal and press enter:

g++ hello.cpp

Execute: To execute the new machine code file, all you need to do is type ./ and the machine code file name in the terminal and press enter. In this case, our compiled file name is a.out. Putting it all together, we end up with the following::

./a.out

The executable file will then be loaded to computer memory and the computer’s CPU (Central Processing Unit) executes the program one instruction at a time.


2.Variables

2.1 Arithmetic Operators

Here are some arithmetic operators:

+ addition

- subtraction

* multiplication

/ division

% modulo (divides and gives the remainder)

user input

The name cin refers to the standard input stream (pronounced “see-in”, for character input). The second operand of the >> operator (“get from”) specifies where that input goes.

To see how it works, we have to try it with a program.

2.2 Challenge: Temperature (Part 1)

Recently, Kelvin began publishing his weather forecasts on his website, however, there’s a problem: All of his forecasts describe the temperature in Fahrenheit degrees.

Let’s convert a temperature from Fahrenheit (F) to Celsius ©.

The formula is the following:

C = (F - 32) / 1.8C=(F−32)/1.8

2.3Review

Here is a review of the lesson:

A variable represents a particular piece of your computer’s memory that has been set aside for you to use to store, retrieve, and manipulate data.

C++ basic data types include:

    int: integers

    double: floating-point numbers

    char: individual characters

    string: sequence of characters

    bool: true/false

Single equal sign = indicates assignment, not equality in the mathematical sense.

cin is how to receive input from the user.

3.CONDITIONALS & LOGIC

3.1 If Statement

if (condition) {

some code

}

3.2 Relational Operators

o have a condition, we need relational operators:

== equal to

!= not equal to

> greater than

< less than

>= greater than or equal to

<= less than or equal to

Relational operators compare the value on the left with the value on the right.

3.3Else Clause

if (condition) {

  do something

} else {

  do something else

}

3.4 Else If

if (condition) {

  some code

} else if (condition) {

  some code

} else {

  some code

}

if (grade == 9) {
 
  std::cout << "Freshman\\n";
 
} 
else if (grade == 10) {
 
  std::cout << "Sophomore\\n";
 
}
else if (grade == 11) {
 
  std::cout << "Junior\\n";
 
} 
else if (grade == 12) {
 
  std::cout << "Senior\\n";
 
}
else {
 
  std::cout << "Super Senior\\n";
 
}

3.5 Switch Statement

A switch statement provides an alternative syntax that is easier to read and write. However, you are going to find these less frequently than if, else if, else in the wild.

A switch statement looks like this:

switch (grade) {

  case 9:
    std::cout << "Freshman\\n";
    break;
  case 10:
    std::cout << "Sophomore\\n";
    break;
  case 11:
    std::cout << "Junior\\n";
    break;
  case 12:
    std::cout << "Senior\\n";
    break;
  default:
    std::cout << "Invalid\\n";
    break;

}

3.6 Review

Here are some of the major concepts:

An if statement checks a condition and will execute a task if that condition evaluates to true.

if / else statements make binary decisions and execute different code blocks based on a provided condition.

We can add more conditions using else if statements.

Relational operators, including <, >, <=, >=, ==, and != can compare two values.

A switch statement can be used to simplify the process of writing multiple else if statements. The break keyword stops the remaining cases from being checked and executed in a switch statement.

4. LOGICAL OPERATORS

Logical operators are used to combine two or more conditions. They allow programs to make more flexible decisions. The result of the operation of a logical operator is a bool value of either true or false.

There are three logical operators that we will cover:

&&: the and logical operator

||: the or logical operator

!: the not logical operator

We will also discuss the order of operations.


5. LOOPS

In this lesson, we will learn about two types of loops: while loops and forloops!

5.1 While Loop Demo

#include <iostream>

int main() {
  
  int pin = 0;
  int tries = 0;
  
  std::cout << "BANK OF CODECADEMY\\n";
  
  std::cout << "Enter your PIN: ";
  std::cin >> pin;

  tries++;

  while (pin != 1234 && tries < 3) {
    
    std::cout << "Enter your PIN: ";
    std::cin >> pin;
    tries++;
    
  }
  
  if (pin == 1234) {
    
    std::cout << "PIN accepted!\\n";
    std::cout << "You now have access.\\n"; 
    
  }
  
}

5.2 Guess Number

Here is what a while loop looks like:

while (condition) {

  statements

}

The while loop looks very similar to an if statement. And just like an if statement, it executes the code inside of it if the condition is true.

However, the difference is that the while loop will continue to execute the code inside of it, over and over again, as long as the condition is true.

In other words, instead of executing if something is true, it executes while that thing is true.

while (guess != 8) {
std::cout << "Wrong guess, try again: "; std::cin >> guess;
}

5.3 For Loop Demo

When we know exactly how many times we want to iterate (or when we are counting), we can use a for loop instead of a while loop:

for (int i = 0; i < 20; i++)
{

  std::cout << "I will not throw paper airplanes in class.\\n";

}

Let’s take a closer look at the first line:

for (int i = 0; i < 20; i++)

There are three separate parts to this separated by ;:

The initialization of a counter: int i = 0

The continue condition: i < 20

The change in the counter (in this case an increment): i++

6. ERRORS

In C++, there are many different ways of classifying errors, but they can be boiled down to four categories:

Compile-time errors: Errors found by the compiler.

Link-time errors: Errors found by the linker when it is trying to combine object files into an executable program.

Run-time errors: Errors found by checks in a running program.

Logic errors: Errors found by the programmer looking for the causes of erroneous results.

7. VECTORS

For example, our program might need:

A list of Twitter’s trending tags

A set of payment options for a car

A catalog of eBooks read over the last year
//creating a vector
std::vector<type> name;
std::vector<double> location;
//initializing a vector
std::vector<double> location = {42.651443, -73.749302};
//initial size to two using parentheses
std::vector<double> location(2);

7.1 Index

For example, suppose we have a char vector with all the vowels:

std::vector<char> vowels = {'a', 'e', 'i', 'o', 'u'};
/*
- The character at index `0` is `'a'`.
- The character at index `1` is `'e'`.
- The character at index `2` is `'i'`.
- The character at index `3` is `'o'`.
- The character at index `4` is `'u'`.
*/
//output
std::cout << vowels[0] << "\n";
std::cout << vowels[1] << "\n";
std::cout << vowels[2] << "\n";
std::cout << vowels[3] << "\n";
std::cout << vowels[4] << "\n";

a
e
i
o
u

7.2 Adding and Removing Elements

.push_back()

To add a new element to the “back”, or end of the vector, we can use the .push_back() function.
.pop_back()

You can also remove elements from the “back” of the vector using .pop_back().

For example, suppose we have a vector called dna with three letter codes of nucleotides:

std::vector<std::string> dna = {"ATG", "ACG"};
//We can add elements using `.push_back()`:
dna.push_back("GTG");
dna.push_back("CTG");
//pop_back() last one:
dna.pop_back();

7.3 .size()

std::vector<std::string> grocery = {"Hot Pepper Jam", "Dragon Fruit", "Brussel Sprouts"};
std::cout << grocery.size() << "\n";
//output 
3

7.4 Operations

For example, suppose we have an int vector that looks like this:

10 20 30

0 1 2

You can write a for loop that iterates from 0 to vector.size(). And here’s the cool part: you can use the counter of the for loop as the index! Woah.

for (int i = 0; i < vector.size(); i++) {

  vector[i] = vector[i] + 10;

}

This will change the vector to:

20 30 40

0 1 2

Here, we incremented i from 0 to vector.size(), which is 3. During each iteration, we are adding 10 to the element at position i:

When i = 0, we added 10 to vector[0]

When i = 1, we added 10 to vector[1]

When i = 2, we added 10 to vector[2]

8. Function

8.1 Built-in Functions

To call a basic function, we just need the function name followed by a pair of parentheses like sqrt(9). For example:

std::cout << sqrt(9) << "\\n";

// This would output 3

8.2 Declare & Define

A C++ function is comprised of two distinct parts:

Declaration: this includes the function’s name, what the return type is, and any parameters (if the function will accept input values, known as arguments).

Definition: also known as the body of the function, this contains the instructions for what the function is supposed to do.

8.3 Void — The Point of No Return

Enter the void specifier, which is added in the function declaration before the function name. A void function, also known as a subroutine, has no return value, making it ideally suited for situations where you just want to print stuff to the terminal.

8.4 Average

#include <iostream>

// Define average() here:

double average(double num1,double num2){
double average;
average = (num1+num2)/2;
std::cout<<average<<"\n";
}

int main() {
  
average(42.0, 24.0);
average(1.0, 2.0) ;
  
}

8.5 First Three Multiples

#include <iostream>
#include <vector>

// Define first_three_multiples() here:
std::vector <int> first_three_multiples(int num){
  std::vector <int> multiples={num,num*2,num*3};
  return multiples;

}

int main() {
  for (int element :first_three_multiples(8) ){
  std::cout<<element<< "\n";
  }
  
}

8.6 Palindrome

#include <iostream>

// Define is_palindrome() here:

bool is_palindrome(std::string text){

 std::string reversed_text = "";

for (int i=text.size()-1;i>=0;i--){
  reversed_text += text[i];
}

 if (text==reversed_text){
  return 1;
 }
 else{
  return 0;
 }

}

int main() {
  
  std::cout << is_palindrome("madam") << "\n";
  std::cout << is_palindrome("ada") << "\n";
  std::cout << is_palindrome("lovelace") << "\n";
  
}

9. Classes and Objects

9.1 Creating classes

class City {

  // attribute
  int population;

// we'll explain 'public' later
public:
  // method
  void add_resident() {
    population++;
  }

};

9.2 Creating Objects

//music.cpp
#include <iostream>
#include "song.hpp"

int main() {

  Song electric_relaxation;
  electric_relaxation.add_title("Electric Relaxation");
  std::cout << electric_relaxation.get_title();
}
//song.hpp
#include <string>

// add the Song class here:
class Song {
  
  std::string title;

public:
  void add_title(std::string new_title);
  std::string get_title();
  

};
//song.cpp
#include "song.hpp"

// add Song method definitions here:
void Song::add_title(std::string new_title) {

  title = new_title;

}

std::string Song::get_title() {

  return title;

}

10.References and Pointers

10.1 References

int &sonny = songqiao;

Two things to note about references:

Anything we do to the reference also happens to the original.

Aliases cannot be changed to alias something else.

10.2 Pass-By-Reference

#include <iostream>

int triple(int i) {

  i = i * 3;
  
  return i;

}

int main() {
  
  int num = 1;
  
  std::cout << triple(num) << "\n";
  std::cout << triple(num) << "\n";

}
//output 3 3

#include <iostream>

int triple(int &i) {

  i = i * 3;
  
  return i;

}

int main() {
  
  int num = 1;
  
  std::cout << triple(num) << "\n";
  std::cout << triple(num) << "\n";

}
//output 3 9

10.3 Memory Address

int porcupine_count = 3;
std::cout << &porcupine_count << "\n";
//output
0x7ffd7caa5b54

10.4 Pointers

a pointer variable is mostly the same as other variables, which can store a piece of data. Unlike normal variables, which store a value (such as an int, double, char), a pointer stores a memory address

int* number;
double* decimal;
char* character;
//pointers.cpp
#include <iostream>
int main() {
  
  int power = 9000;
  
  // Create pointer
  int* ptr = & power;
  
  // Print ptr
  std::cout<<ptr <<"\n";
  
}

10.5 Null Pointer

int* ptr = nullptr;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值