C++ Basics
First example
Every C++ program must have a function called main
, which is a starting point of the program execution. The keyword int
to the left of main
indicates that the function returns an integer value. The return statement return 0
indicates that the program has terminated successfully. If a program reaches the end of the main
function without encountering a return
statement, it is assumed that the program has terminated successfully.
Curly braces {}
are used to enclose the function's body. Strings are enclosed with double quotes ""
. Every statement in C++ must end with a semicolon. Preprocessing directive begins with a hash sign #
and does not end with a semicolon. You print a string to the console by using the object cout
from C++ standard library. <<
is the stream insertion operator which inserts the right operand into its left operand.
#include <iostream>
int main() {
// This is a single-line comment
/* This is
a multi-line
comment */
std::cout << "Hello World!\n";
return 0;
}
Variables
Variables must be declared with a name and data type before they can be used in a program. Several variables of the same type may be declared in one declaration. The braced initialization int sum{0}
is a new way of initializing variables. Avoid identifiers that begin with an underscore and a capital letter or two underscores, because C++ compilers may use names like that for internal purposes.
The standard input stream cin
from C++ standard library allows you to obtain user input from the console. >>
is the stream insertion operator which inserts the left operand into its right operand.
Braced initializers prevent narrowing conversions that could result in data loss.
#include <iostream>
int main() {
int number1{0}, number2{0};
int sum = 0;
std::cout << "Enter first integer: ";
std::cin >> number1;
std::cout << "Enter second integer: ";
std::cin >> number2;
sum = number1 + number2;
std::cout << "Sum is " << sum << "\n";
}
Operators
Integer division operator /
yields an integer quotient. Any fractional part in integer division is truncated. The modulus operator %
yields remainder after integer division. It can only be used with integer operands. The relational operators >
, >=
, <
, <=
have the same level of precedence and associate left to right. The equality operators ==
and !=
have the same level of precedence which is lower than that of the relational operators, and associate left to right.
The using
declarations simplify the coding because you don't need to repeat the std::
prefix every time. using namespace std;
directive allows using all the names in C++ standard library without std::
prefix in your code.
#include <iostream>
using std::cout;
using std::cin;
int main() {
int number1{ 0 };
int number2{ 0 };
cout << "Enter two integers to compare: ";
cin >> number1 >> number2;
if (number1 == number2) {
cout << number1 << " == " << number2 << "\n";
}
if (number1 != number2) {
cout << number1 << " != " << number2 << "\n";
}
if (number1 < number2) {
cout << number1 << " < " << number2 << "\n";
}
if (number1 > number2) {
cout << number1 << " > " << number2 << "\n";
}
if (number1 <= number2) {
cout << number1 << " <= " << number2 << "\n";
}
if (number1 >= number2) {
cout << number1 << " >= " << number2 << "\n";
}
}
C++ provides the conditional operator ?:
which can be used in place of an if/else
statement.
cout << (studentGrade >= 60 ? "Passed" : "Failed");
Strings
To work with string objects, you must include the <string>
header, which defines the String
class. String
is a part of the C++ standard library, therefore it belongs to the namespace std
. When you output a boolean value, C++ displays 1 for true and 0 for false. However, the stream manipulator boolalpha
from <iostream>
header tells the output stream to display boolean values as words true
and false
.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1{ "happy" };
string s2{ " birthday" };
string s3; // Initialize an empty string
// Display the strings and show their lengths
cout << "s1: \"" << s1 << "\"; length: " << s1.length()
<< "\ns2: \"" << s2 << "\"; length: " << s2.length()
<< "\ns3: \"" << s3 << "\"; length: " << s3.length();
// Compare strings with == and !=
cout << "\n\nThe results of comparing s2 and s1:" << boolalpha
<< "\ns2 == s1 " << (s2 == s1)
<< "\ns2 != s1 " << (s2 != s1);
// Test string member function empty
cout << "\n\nTesting s3.empty():\n";
if (s3.empty()) {
cout << "s3 is empty; assigning to s3;\n";
s3 = s1 + s2;
cout << "s3: \"" << s3 << "\"";
}
// Testing new C++20 string member functions
cout << "\n\ns1 starts with \"ha\": " << s1.starts_with("ha") << "\n";
cout << "s2 starts with \"ha\": " << s2.starts_with("ha") << "\n";
cout << "s1 ends with \"ay\": " << s1.ends_with("ay") << "\n";
cout << "s2 ends with \"ay\": " << s2.ends_with("ay") << "\n";
}
Statements
The if/else
statement performs one action when the condition is true and another action when the condition is false.
if (studentGrade >= 60) {
cout << "Passed";
} else {
cout << "Failed";
}
The while
iteration statement repeats an action while some condition is remains true.
A local variable is a variable declared in a block and can be used from the line of its declaration to the closing brace of the block.
C++ provides type float
, double
, and long double
to store floating-point numbers.
The for
loop is a counter-controlled iteration loop.
The switch/case statement The selection statement with initializers.