C++ was conceived in the late 1970s to overcome the limitations of C. It is an extension of the C programming language and at present is one of the most popular programming languages. With its powerful syntax, OOP framework and efficient nature it is one of the most useful programming languages of all.
Before we dive into the basics it’s imperative to know the similarities and differences between C and C++.
Similarities:
• Similar basic syntax.
• Similar code structure.
• Similar compilation process.
Differences
Now that we know how to distinguish between C and C++, let’s dive into the basics of the C++ language.
1. BASIC SYNTAX
#include <iostream> using namespace std; // main() is where program execution begins. int main() { // This is where you write your code return 0; }
This is the basic structure of a typical C++ program.
In line 1, #include<iostream> calls the header file. This header file contains a set of predefined functions which will be required later in the program.
In line 2, using namespace std is a standard namespace enabling you to use the object and variable names from the standard library.
Line 3, int main() marks the beginning of execution of the program.
2. OUTPUT
cout << "Hello World";
cout prints anything which you write between “”
In this case, Hello World will be the output.
3. INPUT
int x; cin>> x;
cin is the input function, taking the input from the user and storing it in the variable x.
4. COMMENTS
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
Anything after // is a comment and is ignored by compiler. Multiple line comments in a program can be written by using /*….*/
Comments are used for increasing the readability of the program and for a better understanding.
5. CONDITIONAL STATEMENTS
As their name suggests, these statements are deployed when you need to execute a certain operation only when a specific condition is
satisfied. Let’s take a look at the various types of conditional statements used.
if statement
if (condition) {
// This block of code will get executed if the condition is True
}
It will check whether the condition holds true or not and then the code written between the {} will execute only if the condition is true. If the condition is false, the compiler won’t bother about the code inside the {} as it need not be executed.
if else statement
if(2>3){ cout<< "2 is greater than 3"; } else{ cout<< "3 is greater than 2"; }
If the condition of if() is true, it executes the code in the if block. If the condition in if() is false, it executes the code in the else block.
else if
if(2>3){ cout<< "2 is greater than 3"; } else if(2==3){ cout<< "2 is equal to 3"; } else{ cout<< "3 is greater than 2"; }
When you need additional conditions to check you can use an else if statement.
switch case
It allows us to test an expression against a variety of numerous results.
switch (grade) { case 9: cout << "Freshman\n"; break; case 10: cout << "Sophomore\n"; break; case 11: cout << "Junior\n"; break; case 12: cout << "Senior\n"; break; default: cout << "Invalid\n"; break; }
If a match is found with a case, the code within the particular case begins to execute. When no match is found, the code within default will be executed. A case is ended by the break keyword.
6. Data Types
➢ integer
It stores integers. Memory allocated = 4 bytes. Ex:
int x = 4;
➢ float
It stores single precision floating point numerals. Memory allocated= 4 bytes. Ex:
float pi = 3.14;
➢ double
It stores double precision floating point numbers. For numbers with a large number of digits after the decimal use double as the data type. Memory allocated= 8 bytes. Ex:
double root_five = 2.236067;
➢ char
It stores single characters kept between ‘’ . Memory allocated= 1 byte. Ex:
char variable_name = ‘a’;
➢ string
It stores a collection of characters enclosed within “” . You must include
#include<cstring>; at the top of code because string is not a built in data type. Ex:
string str = “HOLA”;
7. OPERATORS
Operators in C++ can be classified into 6 types:
➢ Arithmetic Operators
Apart from these, there are increment and decrement operators ++ and -- respectively.
➢ Assignment Operators
➢ Relational Operators
➢ Logical Operators
➢ Bitwise Operators
➢ Other Operators
8. ARRAYS
An array is a variable that can store multiple values of the same data type. An array stores the values in one contagious block of memory, so it’s imperative that we specify the number of values it is going to hold beforehand.
We declare an array by specifying the variable type, the array name enclosed in square brackets, and the number of elements it should store. Here’s an example:
int main() { string str[4] = {"Volvo", "BMW", "Volkswagen", "Ford"}; for(int i=0;i<4;i++){ cout << str[i]+ " "; } return 0; }
9. REFERENCES AND POINTERS
When a variable is declared as a reference, it actually becomes an alternative name for an existing variable. A variable can be declared as a reference by putting ‘&’ in the declaration statement.
string variable1 = "Value1"; // a variable string &variable2 = variable1; // reference to variable1
A pointer is a variable storing the memory address of another variable.
int var = 2, *p;
p = &var;// The variable p holds the address of the variable var
11. FUNCTIONS
A function typically has:
Return value – The value that the function returns at its end is the return value. This value must have the same data type as the one in function declaration.
Parameters – These are the placeholders of the values passed on to them.
Declaration – It specifies the name of the function, its return type, parameter list.
When a function is called, a collection of statements are executed simultaneously.
int sum (int a, int b){ // Declaration return a+b; } int main(){ int first_number= 10; int second_number = 20; cout<< sum(first_number, second_number); // Calling a function }
12. ITERATIVE STATEMENTS
Iterative statements come into play when you need to execute a particular operation multiple number of times.
➢ while loop
The while loop loops through a specific block of code as long as the specified condition is true. The tasks won’t be performed unless the test condition is checked and satisfied.
int i=1; while(i <=100){ cout << "Write it hundred times \n"; i++; }
➢ do while loop
Unlike the while loop, the do while loop first executes the block of code and then checks the condition. Hence the tasks are performed at least once in this loop.
int i=1; do{ cout << "Write it hundred times \n"; i++; } while(i<=100);
➢ for loop
When you know exactly how many times the loop needs to run, you should prefer a for loop over while loop.
for (int i = 0; i < 10; i++) { cout << i << "\n"; }
A for loop has three parts
Initialization of the counter;
Test condition;
Counter increment/decrement.
13. MATH FUNCTIONS
c++ has many functions that allow us to perform mathematical tasks. Here are some of the most used c++ math functions~
➢ cout << max(1,2);
It returns the maximum value.
➢ cout << min(1,2);
It returns the minimum value.
➢ cout << sqrt(169);
It returns the square root value.
➢ cout << pow(a,b);
It returns the value of a raised to power b.
14. STRING FUNCTIONS
Some commonly used string functions in C++ are as follows:
➢ strlen() – It calculates the length of the given string. ➢ strcpy(s1, s2);
Copies string s2 into string s1.
➢ strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
➢ strcmp(s1, s2);
Compares string s1 and s2 lexicographically on the basis of their ASCII values.
15. FILE HANDLING
For achieving file handling, follow the steps listed down :-
➢ Naming a file
➢ Opening the file
➢ Writing data into the file
➢ Reading data from the file
➢ Closing the file
Here’s an example:
int main() { // Create and open a text file ofstream MyFile("filename.txt"); // Write to the file MyFile << "File Handling in C++"; // Close the file MyFile.close(); }
16. OOP
C++ is an object oriented programming language which implies that a class is the fundamental block in it.
A class is an user defined data type having data members and member functions.
class City { // Attribute string name; int population; public: // Method void increase_population() { population++; } };
While, an object is an instance of class.
An object can be declared by using the syntax: ClassName ObjectName;
C++'s object-oriented programming foundation is extremely useful because it incorporates real-world entities such as encapsulation, inheritance, polymorphism, and so on.
CONCLUSION
This was an attempt to provide an overview of the C++ programming language. For a beginner, this can serve as a basic layout, while for a veteran, it can serve as a review before an interview or exam to refresh the lessons learned. However, as with any language, in-person practise is required to learn and use the language effectively.
I wish you the best of luck on your coding journey!
WHAT IS WEB3?Web3 is the catch-all term for the vision of an upgraded version of the internet aimed at giving power back to the users. It is truly the......
Operating Systems is one of the core subjects for a computer science student. As such a lot of important questions are asked on this subject in interv......
Getting started with cloud computing ?The words "cloud" and "web" will be interchangeable. What kind of business operates today without the internet? ...
SOFTWARE MAINTENANCE:Software Maintenance can be defined as the process of modifying a software product after its delivery. The main purpose of softwa...
A quick summary upto what we did this far from this series:Software EngineeringSoftware engineering is a discipline of engineering concerned wit...
Introduction:Understanding time complexity of a function is imperative for every programmer to execute a program in the most efficient manner. Time co...
Software MethodologyA software methodology (which is also known as software process) is a set of related development Phases that leads to the pr...
Software Engineering is a subject that requires when you are a software developer as well as when you are in your college preparing for a semester or ...
Are you getting ready for your SQL developer job interview?You've come to the correct place.This tutorial will assist you in brushing up on your SQL s...
Introduction: What is SQL?To understand SQL, we must first understand databases and database management systems (DBMS).Data is essentially a collectio...
Networking: Importance in real life!Using a computer for work, as well as for personal use, ha...
FORMULA LIST:ALGEBRA :1.Sum of first n natural numbers = n(n+1)/22.Sum of the squares of first n nat...
ER-DiagramWhat are ER Models ?An Entity Relationship Diagram (ERD) is a visual representation of dif...
What is actually DBMS?A Database Management System (DBMS) is system software used to manage the orga...
C CHEATSHEETINTRODUCTION:C programming language was developed by Dennis Ritchie of Bell Labs in 1972...
C is a general purpose high-level language most popular amongst coders, it is the most compatible, e...
C++ programming language has templates which basically allows functions and classes to work with gen...
Interview Questions are a great source to test your knowledge about any specific field. But remember...
The most popular high-level, multipurpose programming language right now is Python.Python supports p...
IntroductionPython is a high-level programming language with dynamic binding and high-level inherent...
Interview Questions are a great source to test your knowledge about any specific field. But remember...
Object-Oriented Programming or better known as OOPs is one of the major pillars of Java that has lev...
Java is a high-level programming language known for its robustness, object-oriented nature, enhanced...