#include <iostream>
using namespace std;
int main() {
cout << "How many lines? ";
int n;
cin >> n;
// printing staircase
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
cout << "*";
}
cout << "\n";
}
}
The program reads the number of rows from the user into
variable n
and then prints a staircase with n layers.
The program execution may look like this:
How many lines? 5 * ** *** **** *****
main,
where the execution of the program begins.
In the first chapters of this course, our overall program framework is as follows:
#include <iostream>
using namespace std;
int main() {
...
}
In ... is the code you want to execute,
and the lines around it are always the same.
Later in the course, we will learn the meaning of the lines around it.
cin object.
For example, the following code reads the user input
to variable x:
int x; cin >> x;Similarly, we can print text to the screen via the
cout object.
Whenever we want a line break in the text,
we do this by using the \n tag (newline).
The following code is an illustration:
cout << "first "; cout << "line\n"; cout << "second line\n";The output of this code is as follows:
first line second line
//
and continues to the end of the line.
A multi-line comment begins with /*
and ends with */.
The following code shows an example of each of these commenting methods:
// this comment is on one line
/* this comment is on
two lines */
; indicates the end of a statement.
An expression is part of the code that has a value.
For example, x and a + 2 * b are expressions.
A block consists of one or more statements,
which are written between { and }.
A block is used to indicate, for example,
which statements are inside a function, if structure, or loop.
For example, the following code snippets work in exactly the same way:
for (int j = 1; j <= i; j++) {
cout << "*";
}
for
(int j = 1;
j <= i;
j++) { cout << "*"; }
However, the latter code is difficult to read because
it differs from the usual practice.