What Is C++
What Is C++
The main difference between C and C++ is that C++ supports classes and
objects, while C does not.
C++ Syntax
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Line 1: #include <iostream> is a header file library that lets us work with
input and output objects, such as cout.
Line 2: using namespace std means that we can use names for objects and
variables from the standard library.
Line 3: A blank line. C++ ignores white space. But we use it to make the
code more readable.
Line 4: Another thing that always appear in a C++ program is int main().
This is called a function. Any code inside its curly brackets {} will be
executed.
Example
#include <iostream>
using namespace std;
int main() {
cout << 3;
return 0;
}
Example
cout << 3 + 3;
Example
cout << 2 * 5;
New Lines
To insert a new line in your output, you can use the \n character:
You can also use another << operator and place the \n character after the
text, like this:
Tip: Two \n characters after each other will create a blank line:
C++ Variables
Variables are containers for storing data values.
Syntax
type variableName = value;
Example
Create a variable called myNum of type int and assign it the value 15:
Example
int myNum = 5; // Integer (whole number without
decimals)
double myFloatNum = 5.99; // Floating point number (with
decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)
Example
int x, y, z;
x = y = z = 50;
cout << x + y + z;
Example
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value