C++ basics
C++ basics
Reference: https://www.w3schools.com/cpp/
❮ Previous
Next ❯
What is C++?
C++ is a cross-platform language that can be used to create high-performance
applications.
C++ was developed by Bjarne Stroustrup, as an extension to the C language.
C++ gives programmers a high level of control over system resources and memory.
The language was updated 3 major times in 2011, 2014, and 2017 to C++11, C++14,
and C++17.
Main
C C++
Dennis Ritchie and Kernighan Bjarne Stroustrup
At AT & T Bell Lab, California, USA At AT & T Bell Lab, California,
in 1960’s USA in 1970’s
Pop-Procedure oriented Oop- object oriented
programming programming
Top-down approach-sequential Bottom-up approach
structure Objects can be created
anywhere.
Functions and procedures or Functions are used
subroutines-small pieces of code
Functions can be reused Functions can be reused
Reusability Objects
Modularity Classes
Encapsulation
Data abstraction
Data hiding
Inheritance
Polymorphism
Reusability
Modularity
Student-object
Features and functions to student-class-student class
Ug /pg Student
Id
Name
Age
Marks
Get_attendance()
Get_Marks()
Poly(many) + morphism(forms)
C++ Quickstart
Let's create our first C++ file.
Open Codeblocks and go to File > New > Empty File.
Write the following C++ code and save the file as
myfirstprogram.cpp (File > Save File as):
myfirstprogram.cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Don't worry if you don't understand the code above - we will discuss it
in detail in later chapters. For now, focus on how to run the code.
In Codeblocks, it should look like this:
Then, go to Build > Build and Run to run (execute) the program.
Result:
Hello World!
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
Example explained
Line 1: #include <iostream> is a header file library that lets us work
with input and output objects, such as cout (used in line 5). Header files
add functionality to C++ programs.
Line 2: using namespace std means that we can use names for objects
and variables from the standard library.
Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }
Line 7: Do not forget to add the closing curly bracket } to actually end
the main function.
Omitting Namespace
You might see some C++ programs that runs without the standard
namespace library. The using namespace std line can be omitted and
replaced with the std keyword, followed by the :: operator for some
objects:
Example
#include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
}
int main() {
cout << "Hello World!";
return 0;
}
You can add as many cout objects as you want. However, note that it
does not insert a new line at the end of the output:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}
New Lines
To insert a new line, you can use the \n character:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
Tip: Two \n characters after each other will create a blank line:
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n\n";
cout << "I am learning C++";
return 0;
}
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}
Both \n and endl are used to break lines. However, \n is used more often
and is the preferred way.
#include<iostream.h>pre-processor directive
#include<conio.h>
void main( )
{
int a, b,c;
clrscr();
cout<<”enter the values of a and b”;
cin>>a; 10
cin>>b; 20
c= a-b;
cout<<”the sum of a and b is =”<<c; 30
getch();
}
add.cpp
compile
compiled successfully
run
output screen visible
output
enter the values of a and b
10
20
the sum of a and b is =30
C++ Comments
Comments can be used to explain C++ code, and to make it more
readable. It can also be used to prevent execution when testing
alternative code. Comments can be singled-lined or multi-lined.
Any text between // and the end of the line is ignored by the compiler
(will not be executed).
Example
cout << "Hello World!"; // This is a comment
Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
C++ Variables
Variables are containers for storing data values.
Syntax
type variable = value;
Where type is one of C++ types (such as int), and variable is the name
of the variable (such as x or myName). The equal sign is used to assign
values to the variable.
Example
Create a variable called myNum of type int and assign it the value 15:
You can also declare a variable without assigning the value, and assign
the value later:
Example
int myNum;
myNum = 15;
cout << myNum;
Note that if you assign a new value to an existing variable, it will overwrite
the previous value:
Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10
Display Variables
The cout object is used together with the << operator to display variables.
To combine both text and a variable, separate them with the << operator:
Example
int myAge = 35;
cout << "I am " << myAge << " years old.";
Example
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
Example
int x = 5, y = 6, z = 50;
cout << x + y + z;
C++ Identifiers
All C++ variables must be identified with unique names.
Example
// Good
int minutesPerHour = 60;
The general rules for constructing names for variables (unique identifiers)
are:
C++ Constants
Constants
When you do not want others (or yourself) to override existing variable
values, use the constkeyword (this will declare the variable as "constant",
which means unchangeable and read-only):
Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable
'myNum'
you should always declare the variable as constant when you have values
that are unlikely to change:
Example
const int minutesPerHour = 60;
const float PI = 3.14;
cin is a predefined variable that reads data from the keyboard with the
extraction operator (>>).
In the following example, the user can input a number, which is stored in
the variable x. Then we print the value of x:
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
Good To Know
cout is pronounced "see-out". Used for output, and uses the insertion
operator (<<)
cin is pronounced "see-in". Used for input, and uses the extraction
operator (>>)
Example
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String
float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for
storing 7 decimal digits
double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for
storing 15 decimal digits
boolean 1 byte Stores true or false values
The data type specifies the size and type of information the variable will
store:
Numeric Types
Use int when you need to store a whole number without decimals, like 35
or 1000, and floator double when you need a floating point number
(with decimals), like 9.99 or 3.14515.
int
int myNum = 1000;
cout << myNum;
float
float myNum = 5.75;
cout << myNum;
double
double myNum = 19.99;
cout << myNum;
float vs. double
The precision of a floating point value indicates how many digits the
value can have after the decimal point. The precision of float is only six
or seven decimal digits, while double variables have a precision of about
15 digits. Therefore it is safer to use double for most calculations.
Scientific Numbers
A floating point number can also be a scientific number with an "e" to
indicate the power of 10:
Example
float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;
Boolean Types
A boolean data type is declared with the bool keyword and can only take
the values true or false. When the value is
returned, true = 1 and false = 0.
Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
Boolean values are mostly used for conditional testing, which you will
learn more about in a later chapter.
Character Types
The char data type is used to store a single character. The character
must be surrounded by single quotes, like 'A' or 'c':
Example
char myGrade = 'B';
cout << myGrade;
Example
char a = 65, b = 66, c = 67;
cout << a;
cout << b;
cout << c;
Tip: A list of all ASCII values can be found in our ASCII Table Reference.
String Types
The string type is used to store a sequence of characters (text). This is
not a built-in type, but it behaves like one in its most basic usage. String
values must be surrounded by double quotes:
Example
string greeting = "Hello";
cout << greeting;
To use strings, you must include an additional header file in the source
code, the <string>library:
Example
// Include the string library
#include <string>
C++ Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
int x = 100 + 50;
Although the + operator is often used to add together two values, like in
the example above, it can also be used to add together a variable and a
value, or a variable and another variable:
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
e. Comparison/relational Operators
Comparison operators are used to compare two values.
In the following example, we use the greater than operator (>) to find
out if 5 is greater than 3:
Example
int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than
3
== Equal to x == y
!= Not equal x != y
Logical Operators
Logical operators are used to determine the logic between variables or
values:
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result !(x < 5 && x < 10)
is true
cnditi