文章目录

  • 1.HELLO WORLD
    • Compile and Execute
  • 2.Variables
    • 2.1 Arithmetic Operators
    • 2.2 Challenge: Temperature (Part 1)
    • 2.3Review
  • 3.CONDITIONALS & LOGIC
    • 3.1 If Statement
    • 3.2 Relational Operators
    • 3.3Else Clause
    • 3.4 Else If
    • 3.5 Switch Statement
    • 3.6 Review
  • 4. LOGICAL OPERATORS
  • 5. LOOPS
    • 5.1 While Loop Demo
    • 5.2 Guess Number
    • 5.3 For Loop Demo
  • 6. ERRORS
  • 7. VECTORS
    • 7.1 Index
    • 7.2 Adding and Removing Elements
    • 7.3 .size()
    • 7.4 Operations
  • 8. Function
    • 8.1 Built-in Functions
    • 8.2 Declare & Define
    • 8.3 Void — The Point of No Return
    • 8.4 Average
    • 8.6 Palindrome
  • 9. Classes and Objects
    • 9.1 Creating classes
    • 9.2 Creating Objects
  • 10.References and Pointers
    • 10.1 References
    • 10.2 Pass-By-Reference
    • 10.3 Memory Address
    • 10.4 Pointers

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: integersdouble: floating-point numberschar: individual charactersstring: sequence of charactersbool: true/falseSingle 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 = 0The continue condition: i < 20The 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 tagsA set of payment options for a carA 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 {// attributeint population;// we'll explain 'public' later
public:// methodvoid 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 pointerint* ptr = & power;// Print ptrstd::cout<<ptr <<"\n";}

10.5 Null Pointer

int* ptr = nullptr;

c++ notes (very basic)相关推荐

  1. 鸟叔的linux私房菜:第0章 计算机概论学习笔记(Learning Notes for Basic Computer Theory)

    本博客是针对<鸟叔的Linux私房菜 基础学习篇 第四版>的第0章 计算机概论的学习笔记. 1 电脑辅助人脑的好工具 11 计算机硬件的五大单元 12 一切设计的起点CPU的架构 其它单元 ...

  2. Linux 设备树device tree 使用手册

    摘要:设备树使用手册Thispagewalksthroughhowtowriteadevicetreeforanewmachine.Itisintendedtoprovideanoverviewofd ...

  3. 一个博士应该干什么(转自水木清华)

    标  题: 到底美国PhD要干啥? Notes on the PhD Degree[zt] 发信站: BBS 水木清华站 (Fri Feb 18 02:54:21 2005), 站内 发信人: kis ...

  4. 数据库应用 --- Yelp Data Analysis Application

    数据库应用 --- Yelp Data Analysis Application Overview Basic Info Functionality 初始GUI Simple Business Sea ...

  5. 【 Notes 】COMPARISON OF BASIC METHODS AND POSITIONING SYSTEMS

    目录 COMPARISON OF BASIC METHODS AND POSITIONING SYSTEMS CONCLUSION, SUMMARY, AND FUTURE APPLICATIONS ...

  6. LeetCode基本记录【2】// BASIC NOTES AND CODES OF LEETCODE [ 2 ]

    LeetCode基本记录[2] 19. Remove Nth Node From End of List Given a linked list, remove the nth node from t ...

  7. LeetCode基本记录【5】// BASIC NOTES AND CODES OF LEETCODE [ 5 ]

    LeetCode基本记录[5] 78. Subsets Given a set of distinct integers, nums, return all possible subsets (the ...

  8. fastai 2019 lesson9 notes 笔记

    lesson9 How to train your model 本文markdown源文件:lesson9.md 2019年视频地址:https://course19.fast.ai/videos/? ...

  9. OpenDaylight系类教程(十二)-- Release Notes

    2019独角兽企业重金招聘Python工程师标准>>> Release Notes Target Environment For Execution The OpenDaylight ...

最新文章

  1. vc++向txt文件中写入数据,追加数据
  2. [导入]编写程序实现n阶(n为奇数)魔方(C)
  3. 实验报告书 c语言,c语言实验报告书.doc
  4. DataGridView中在新增行时怎样设置每个Cell单元格的字体样式
  5. DevExpress的TextEdit控件没法调整高度解决
  6. yum安装ruby_centos 6.5 ruby环境安装
  7. php中如何实现多进程
  8. Revit2018下载和安装教程
  9. ps怎么撤销参考线_ps打开辅助线的快捷键在哪,ps如何取消辅助线
  10. 关于密钥和密钥管理的常见问题及解答
  11. tmux简洁教程及config关键配置
  12. 解决“手机锂电池无输出电压,无法充电”
  13. Python检查图片损坏情况代码
  14. 使用java实现路由协议_如果使用OSPF作为路由协议,那么( )【选两项】
  15. 迪杰斯特拉算法及变式(最短距离,打印路径,最短经过节点数)
  16. Nachos内存管理实现
  17. 零基础雪橇python_python零基础到项目实战-带你装b带你飞,带你冲刺年薪50万
  18. 国家2020年区划数据爬取
  19. 基于Python3的科学运算与常用算法-第1,2章
  20. 数据库读写分离(一)

热门文章

  1. 【PS】ps基础绘画球体
  2. html 过滤引号,用js正则表达式过滤双引号的解决办法
  3. 【DFS练习】水洼数
  4. Markdown 内如何使用表情符号
  5. 考研英语 单词常见前后缀/词根
  6. saltstack python3_SaltStack事件驱动(3) – BEACONS
  7. python3里复数的算法_Python高级复数算法
  8. 小程序获取微信绑定的手机号
  9. pip 添加trusted host 一劳永逸
  10. 剑指offer面试题2:实现单例模式