Skip to content

Variable, Expression, I/O, Conditioning

Variable and Expression:

Variables can be described as boxes which store values in them.

1
2
3
4
5
6
7
#include <iostream>
using namespace std;
int main(){
    int a = 15;
    cout << a << endl;
    return 0;
}

In C++, we can write some simple expressions.

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;
int main(){
    int a = 15;
    int b = 20;
    int c = a + b;
    cout << c << endl;
    return 0;
}

Input and Output

In C++, we use cin and cout to read user's input and print output to the screen

cin for reading input, and cout for printing output

1
2
3
4
5
6
7
8
9
// Example 1
#include <iostream>
using namespace std;
int main(){
    int a;
    cin >> a;
    cout << a << endl;
    return 0;
}

Conditioning: if & else

In C++, we can useif and else to create logical conditioning.

For example, we want to output b when a equals 10, otherwise, we output -1

We can do it through the following codes

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <iostream>
using namespace std;
int main(){
    int a;
    int b = 1;
    cin >> a;
    if(a == 10) // we use '==' to represent equals in C++
        cout << b << endl;
    else
        cout << -1 << endl;
    return 0;
}

There are also other types of variables:

Also mind that char use single quote mark char c = 'x'; while string uses double quote mark string d = "cp";

endl means end of the line

In C++, we use endlto start a new line when we are printing output

1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;
int main(){
    double b = 1.5; // floating-point number
    char c = 'x';   // a single character
    string d = "cp";    // a string
    cout << b << endl << c << endl << d << endl;
}

Practice Problem:

link to complete problem set

(you need to register an account on vjudge.net before submitting your solution)