---
# System prepended metadata

title: 'Activity Class: Basic Programming'

---

# Activity Class: Basic Programming

## :memo: Where do I start?
### 1. The basic structure
```cpp=1
#include<iostream>
using namespace std;
int main(){
    return 0;
}
```
**Line 1**: *iostream* is a header file library (Use it to work with input and output)
**Line 2**: *using namespace std* means that we can use names for objects and variables from the standard library.
**Line 3**: *int main()* is the main function. It is where your program will strat to execute. 
**Line 4**: *return 0* ends the main function.


### 2. Input and Output
==cout== is used to output (print) values. 
==cin== is to get user input(enter values). However, when the user enters a value, there must be a **variable** to store the value. 
```cpp=1
#include<iostream>
using namespace std;
int main(){
    cout<<"Hello world!";
    int x;
    cin>>x;
    return 0;
}
```
To enter a new line: ==\n== and ==endl== are used.
```cpp=1
#include<iostream>
using namespace std;
int main(){
    cout<<"Hello world!"<<endl;
    cout<<"Welcome to the basic programming activity.\nThis is Casey."
    return 0;
}
```
```
Hello world!
Welcome to the basic programming activity.
This is Casey.
```
To let the user enter multiple data into different variables, ==>>== can be use to concatenate.
```cpp=1
#include<iostream>
using namespace std;
int main(){
    int a, b, c;
    cin>>a>>b>>c;     //The user enters numbers for a, b, and c
    cout<<a<<b<<c;    //Prints the value of a, b, and c
    return 0;
}
```
```
Hello world!
Welcome to the basic programming activity.
This is Casey.
```

### 3. Variables
Variables are containers for storing data values. 
A data type is a data storage format that can contain a specific type or range of values.


| Data type | Description |
| -------- | -------- |
| bool     | Boolean value. It can take one of two values: true or false     |
| int     | Integer    |
| double     | Double precision floating point number (~15 digits)     |
| char     | A character type may contain a single letter, digit, punctuation mark, symbol, formatting code, control code, or some other specialized code. Character values are surrounded by single quotes, such as 'a' or 'A' | 
| string     | String stores text. String values are surrounded by double quotes, such as "Hello world!"    | 

:::info
:notebook_with_decorative_cover:  **syntax:**
dataType variableName;
dataType variableName = value;
:::

### 4. Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions.

| Operator | Description | Example |
| -------- | -------- | -------- |
| +    | Addition     | a+b     |
| -    | Subtraction     | a-b     |
| *    | Multiplication     | a*b     |
| /    | Division    | a/b     |
| %    | Modulus(Returns the division remainder)     | a%b     |
| ++    | Increases the value of a variable by 1     | a++     |
| --    | Decreases the value of a variable by 1     | a--     |
| <    | Less than     | a<b     |
| >    | Greater than     | a>b     |
| <=    | Less than or equal to     | a<=b     |
| >=    | Greater or equal to     | a>=b     |
| ==    | equal to     | a==b     |
| !=    | NOT equal to     | a!=b     |
| &&    | AND     | a&&b     |
| \|\|    | OR     | a\|\|b     |
|=|Assignment |a=3


:rocket: Practice: 1. [Big Chocolate](https://drive.google.com/file/d/1ZXoCTBCqhtlnxPjf4kWF3vgHyw-OVtcO/view?usp=sharing)
:rocket: Practice: 2. [Pencils](https://docs.google.com/document/d/1xs3JhTTLX8Y_teav3gzpF9DiscDw0TA_K5OMY_J5Iag/edit?usp=sharing)
:rocket: Practice: 3. [triangle fun](https://drive.google.com/file/d/1ymnSZLhdmXvsn975CMiAJcI9btN16PLB/view?usp=sharing)

## :memo: Conditional Structures
The conditional sturctures are the logical conditions (true/false). It can perform different actions for different decisions.
### 1. if
Use ==if== to specify statements to be executed, if a specified condition is *true*.

:::info
:notebook_with_decorative_cover:  **syntax:**
if(*condition*){
> //statements

}
:::

```cpp=1
#include<iostream>
using namespace std;
int main(){
    int a = 2050, b = 2033;
    if(a>b){
        cout<<"a is greater than b.";
    }
    return 0;
}
```
```
a is greater than b.
```

### 2. if...else
Use ==else== to specify statements to be executed, if a specified condition is *false*. (*true* will go to the if statements)

:::info
:notebook_with_decorative_cover:  **syntax:**
if(*condition*){
> //statements (if condition is true)

}
else{
> //statements (if condition is false)

}
:::

```cpp=1
#include<iostream>
using namespace std;
int main(){
    int a, b;
    cin>>a>>b;
    if(a>b){
        cout<<"a is greater than b.";
    }
    else{
        cout<<"a is NOT greater than b.";
    }
    return 0;
}
```

```
(if enter a=2021, b=2000)
a is greater than b.
(if enter a=2000, b=2023)
a is NOT greater than b.
```

### 3. if...else if...(else)
Use ==else if== to specify **NEW** statements to be executed, if the first condition is *false*. (Neither the first condition is false nor the second one is false, then the else statement will be executed.)

:::info
:notebook_with_decorative_cover:  **syntax:**
if(*condition 1*){
> //statements (if condition 1 is true)

}
else if(*condition 2*){
> //statements (if condition 2 is true)

}
else{
> //statements (Neither condition 1 nor condition 2 are false)

}
:::

```cpp=1
#include<iostream>
using namespace std;
int main(){
    int a, b;
    cin>>a>>b;
    if(a>b){
        cout<<"a is greater than b.";
    }
    else if(a<b){
        cout<<"a is less than b.";
    }
    else{
        cout<<"a is equal to b."
    }
    return 0;
}
```

```
(if enter a=2021, b=2000)
a is greater than b.
(if enter a=2050, b=2023)
a is less than b.
(if enter a=2050, b=2025)
a is equal to b.
```

:rocket: Practice: 1. [Hashmat the Brave Warrior](https://drive.google.com/file/d/1Y3PXjMI-Sd4WhtnWN7RbpMI4Dj2_9Egd/view?usp=sharing)
:rocket: Practice: 2. [Relational Operator](https://drive.google.com/file/d/1liaiEfn4OxV96HPlnWKYlazDC5Fec9sA/view?usp=sharing)
:rocket: Practice: 3. [Searching for Nessy](https://drive.google.com/file/d/1ArgSiipsVwLJLMvdk3lKo4gxkjRu-6I2/view?usp=sharing)

Self practice problems:
:rocket: Practice: 4. [Watermelon](https://codeforces.com/problemset/problem/4/A)
:rocket: Practice: 5. [Bangla Numbers](https://drive.google.com/file/d/1bEVzxPOIsdJHYsTBdzFBxYEKic1vKmRN/view?usp=sharing)
:rocket: Practice: 6. [Queen](https://drive.google.com/file/d/1_ZU1QL8gacWX7paXknZ1NZLIiS9sy7Wf/view?usp=sharing)
:rocket: Practice: 7. [Combination Lock](https://drive.google.com/file/d/1aK4E-OyiSIGwnp-TiuMegva9rzCMj3S6/view?usp=sharing)

### 4. switch
Use ==switch== to specify select one of the statements to be executed. The expression will only be checked once and the value of the expression will be compared with the case value. If there is a match, the associated statement will be executed.

The ==default== keyword is optional and it specifies code to run if there is no case match. 

:::info
:notebook_with_decorative_cover:  **syntax:**
**switch**(*expression*){
> **case** x:
    > >//statement 1
    > >**break;**
    > >
> **case** y:
     > >//statement 2
     > >**break;**

> **case** ...:
    > >//statement 3
    > >**break;**
    > >
> **default**: 
    > >//statement 4
    > >
}
:::

```cpp=1
#include<iostream>
using namespace std;
int main(){
    int month;
    cin>>month;
    switch(month/3){
    	case 0:
    		cout<<"spring"<<endl;
    		break;
    	case 1:
    		cout<<"summer"<<endl;
    		break;
    	case 2:
    		cout<<"fall"<<endl;
    		break;
    	case 3:
    		cout<<"winter"<<endl;
    		break;
    	default:
    		cout<<"invalid month!"<<endl;
	}
    return 0;
}
```
```
(if enter month = 4)
summer
(if enter month = 11)
winter
(if enter month = 122)
invalid month!
```
The ==break== keyword is optional and it will stop the switch block. However, if the break is ignored, the rest of test will be executed. See the example below:
```cpp=1
#include<iostream>
using namespace std;
int main(){
    int month;
    cin>>month;
    switch(month/3){
    	case 0:
    		cout<<"spring"<<endl;
    	case 1:
    		cout<<"summer"<<endl;
    	case 2:
    		cout<<"fall"<<endl;
    	case 3:
    		cout<<"winter"<<endl;
    	default:
    		cout<<"invalid month!"<<endl;
	}
    return 0;
}
```
```
(if enter month = 4)
summer
fall
winter
invalid month!
(if enter month = 11)
winter
invalid month!
(if enter month = 122)
invalid month!
```
:rocket: Practice: [basic switch...case practice](https://docs.google.com/document/d/1aS1EY5s3_SESjS15dxfyR9mgNKevA-gSmV-v_F5Pl9c/edit?usp=sharing)

## :memo: Iteration Statements
while, do/while, for loop are provided to execute statements(code block) zero ormany times. They are executed in the order provided by the programmer. 

Each of the iterates until its termination expression evaluates to false(not satified), or until loop termination is forced with a **break** statement. 

### 1. while loop
The ==while== executes the code block as long as the specified condition is *true*.

:::info
:notebook_with_decorative_cover:  **syntax:**
while(*condition*){
> // code block to be executed

}
:::

```cpp=1
#include<iostream>
using namespace std;
int main(){
    int i = 0;
    while(i<10){
        cout<<i<<" ";
        i++;
    }
    return 0;
}
```
```
0 1 2 3 4 5 6 7 8 9 
```
**Line 7**: Don't forget to change the value of i! Otherwise, it might cause an infinite loop. 

### 2. do-while loop
The ==do/while== executes the code block once at the begining. After executing the code block, it will check the condition, if it is *true*, the code block will be repeated until the condition is *not true*.

:::info
:notebook_with_decorative_cover:  **syntax:**
do{
> // code block to be executed

}while(*condition*);
:::

```cpp=1
#include<iostream>
using namespace std;
int main(){
    int i = 0;
    do{
        cout<<i<<" ";
        i++;
    }while(i<10);
    return 0;
}
```
```
0 1 2 3 4 5 6 7 8 9 
```
:rocket: Practice: 1. [Can You Pass](https://docs.google.com/document/d/1Unsc96hZYb688BCWnD5DXCjmeMrs6ncYk0CCcy4mcaU/edit?usp=sharing)
:rocket: Practice: 2. [Ecological Premium](https://drive.google.com/file/d/15dtTiV_F0QPZePbCYHvWGsj1lHRTsGf0/view?usp=sharing)
:rocket: Practice: 3. [GCD](https://docs.google.com/document/d/1OYR73CcKKwU6TojWfI5wgduIePf-4YcpGLOg3vF8PUI/edit?usp=sharing)

### 3. for loop
The for-loop executes exactly how many times you want to loop through a block of code.By using the initial value, conditional statement, and the increment/decrement to control the times.

:::info
:notebook_with_decorative_cover:  **syntax:**
for(*initial value*; *condition*; *increment/decrement*){
> // code block to be executed

}
:::

**initial value**: This statement will only be execueted once before code block.
**condition**: Define when is acceptable to run the code block. When the condition is *true*, the code block can be executed. 
**increment/decrement**: This statement will be executed every time after the code block has been executed. It is used to make the variable move towards the termination.

```cpp=1
#include<iostream>
using namespace std;
int main(){
    for(int i=0; i<10; i++){
        cout<<i<<" ";
    }
    return 0;
}
```
```
0 1 2 3 4 5 6 7 8 9 
```
:::success
:question: How to use for loop to get the sum from 1 to 10? (1+2+3...+9+10)
:::
```cpp=1
#include<iostream>
using namespace std;
int main(){
    int sum = 0;
    for(int i=1; i<=10; i++){
        sum = sum + i;
    }
    cout<<"The sum of 1+2+3..+9+10 is "<<sum;
    return 0;
}
```
```
The sum of 1+2+3..+9+10 is 55 
```
**Line 4**: A variable to store the sum is needed and it needs to be initialized to 0.
**Line 6**: sum+i will be assigned to sum, i.e., the sum value will be updated. This statement can be performed by sum+=i;

:::success
:question: How to use while loop to re-write the question above?
(Get the sum from 1 to 10? (1+2+3...+9+10))
:::
```cpp=1
#include<iostream>
using namespace std;
int main(){
    int sum = 0, i = 1;
    while(________){
        sum = sum + i;
        ________;    //update i value by 1
    }
    return 0;
}
```

:rocket: Practice: 1. [Eva’s math assignment](https://docs.google.com/document/d/1D9Kh2V8DXOv34FU94HgWdELnTxuSSWjHwlMguVarHzw/edit?usp=sharing)
:rocket: Practice: 2. [Computer Lab](https://docs.google.com/document/d/10c-Gg4IcsPGz3ChZjI4XjdRaAQKtKY_DRoAV5XRv5fg/edit?usp=sharing)
:rocket: Practice: 3. [Behold my quadrangle](https://drive.google.com/file/d/1z9e0bx34WRsD9zoB64R3jJeJsZ3uoOzG/view?usp=sharing)

### 4. nested for loop
A loop can be nested inside of another loop.

:::info
:notebook_with_decorative_cover:  **syntax:**
for(*initial value*; *condition*; *increment/decrement*){
>  for(*initial value*; *condition*; *increment/decrement*){
>> // code block to be executed
>  }
>  
}
:::
Other than for-loop, you may also use while loop, do-while loop to construct a nested loop.

:rocket: Practice: 1.[Display patterns](https://docs.google.com/document/d/1BDxBAe3_lcYFcyfykXS6Majj3qz300z5QyiotSsJCR4/edit?usp=sharing)
:rocket: Practice: 2.[Triangle Wave](https://drive.google.com/file/d/1sosL-qhlbfF6Kcn7egTZ_gCZsWxqj0Fp/view?usp=sharing)

## :memo: Strings
Strings are used for storing text and characters. A string variable is surrounded by double quotes.

To use strings, you must include an additional header file in the source code, the ==\<string\>== library:
:::info
:notebook_with_decorative_cover:  **syntax:**
// Include the string library at the begining of the program.
**#include \<string\>**
:::
:::info
:notebook_with_decorative_cover:  **syntax:**
string string_name = "content of the string";
:::

```cpp=1
#include<string>
#include<iostream>
using namespace std;
int main(){
    string test = "Hello world!";
    cout<<test<<endl;
    //Hello world! will be printed
    return 0;
}
```
```
Hello world!
```
A string is a combination of characters so it can also be accessed like a array. The index will start from 0 and the size will use **length()** to access. 

```cpp=1
#include<string>
#include<iostream>
using namespace std;
int main(){
    string test = "Hello";
    for(int i=0; i<test.length(); i++){
		cout<<test[i]<<endl;
	}
    return 0;
}
```
```
H
e
l
l
o
```
### 1. Read a string includes spaces 
If you are going to read a string that includes spaces, ==getline== function will be needed. (See example below.)
```cpp=1
#include<string>
#include<iostream>
using namespace std;
int main(){
    string str;
    getline(cin,str);    //read a string that contains a space
    cout<<str;
    return 0;
}
```
### 2. Convert Character To Integer (char to int) 
Cast a character into an integer, the ASCII code will need to be considered. 
```cpp=1
//Without considering the ASCII code version
#include<string>
#include<iostream>
using namespace std;
int main(){
    char a = '5';
    cout<<(int)a;
    return 0;
}
```
```
53
```
```cpp=1
//Considering the ASCII code version
#include<string>
#include<iostream>
using namespace std;
int main(){
    char a = '5';
    cout<<(int)a-'0';
    return 0;
}
```
```
5
```
:::info
:notebook_with_decorative_cover:  **ASCII code:**
ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as 'a' or '@' or an action of some sort. 
:::
![](https://i.imgur.com/Tt4uPup.png)
:::success
:question: How to print the ASCII code of a sequence of characters?
:::
```cpp=1
#include<iostream>
using namespace std;
int main(){
    string str;
    cin>>str;
    for(int i=0; i< ____________ ; i++){
        cout<< ___________ <<" ";
    }
}
```
```
(If the user enters "abcde")
97 98 99 100 101
```

:rocket: Practice: 1.[幼稚園的算數遊戲](https://docs.google.com/document/d/1gAG8GvgQe4aP-hJaRgbSRY5rdT69Clurag59Ap7f2JQ/edit?usp=sharing)
:rocket: Practice: 2.[迴文](https://docs.google.com/document/d/16BhvGhvGr8axHO1Aa8VIIQcpmcLf4f1GNR8d7U-xesM/edit?usp=sharing)
:rocket: Practice: 3.[You can say 11](https://drive.google.com/file/d/19U4rVdpM2M1hbnmNyZk8rbJsqjvKN8ks/view?usp=sharing)


## :memo: Arrays
An array is a series of elements of the **same type** placed in contiguous memory locations that can be individually referenced by adding an **index** to a unique identifier.





## :memo: More basic practices
:rocket: Practice: 1.[Clock Hands](https://drive.google.com/file/d/1fnJ8BonN56epK6h_jID-szGKScTqEzc7/view?usp=sharing)
:rocket: Practice: 2.[Beat the Spread](https://drive.google.com/file/d/1oZn1kWbwzipisXVQq7zFZzmCwHqTmb9T/view?usp=sharing)
:rocket: Practice: 3.[The Cat in the Hat](https://drive.google.com/file/d/1hqraD-YsH1VGNGiv5DM4fJlGz8enkVhI/view?usp=sharing)
:rocket: Practice: 4.[Square Numbers](https://drive.google.com/file/d/1lFwC78LQCbT5eYQtrg2hSzmvSil3vf2T/view?usp=sharing)

## :memo: Other skills
### 1. Set decimal precision
Sets the decimal precision to be used to format floating-point values on output operations.
The ==setprecision()== function will be used and it is declared in ==\<iomanip\>== header.

When calling setprecision(n) means there will be n digits to be shown. (Round the n+1 digit. See example 1)
If you only want to set up the number of digits after the decimal point, ==fixed== will need to be added.(See example 2.)

```cpp=1
//Example 1
#include<iostream>
using namespace std;
int main(){
    double a = 12.311111;
    cout<<setprecision(4)<<a<<endl;
    //12.31 will be printed
    double b = 12.315111;
    cout<<setprecision(4)<<b<<endl;
    //12.32 will be printed
    return 0;
}
```
```
12.31
12.32
```
```cpp=1
//Example 2
#include<iostream>
using namespace std;
int main(){
    double a = 12.311111;
    cout<<fixed<<setprecision(4)<<a<<endl;
    //12.3111 will be printed
    double b = 12.311151;
    cout<<fixed<<setprecision(4)<<b<<endl;
    //12.3112 will be printed
    return 0;
}
```
```
12.3111
12.3112
```


