C++ C Learning Guide For Fast Learning C++ Examples Exercises Solved
C++ / C Learn C++ Fast Complete Guide With Example Programs and Solved Exercises
- Introduction to C++
- Setting up a Development Environment
- Basic Syntax and Data Types
- Variables and Operators
- Control Flow and Loops
- Functions
- Arrays and Strings
- Pointers and Memory Management
- Object-Oriented Programming in C++
- Exception Handling
- Standard Template Library (STL)
- File Input and Output
- Advanced Topics (e.g. templates, lambda expressions, etc.)
- Conclusion and Further Resources
Chapter 1: Introduction to C++
C++ is a powerful, high-performance programming language that is widely used in the software industry. It is an extension of the C programming language, but with additional features such as classes and templates. C++ is particularly well-suited for developing large, complex systems, such as operating systems, video games, and simulations.
One of the strengths of C++ is its ability to support multiple programming paradigms, including object-oriented, procedural, and generic programming. This allows for a wide range of programming styles and makes C++ a versatile language for many different types of projects.
C++ also has a large and active community, with many open-source libraries and frameworks available. This makes it easy to find resources and support for C++ development.
In this book, we will cover the basics of C++ programming and explore some of its advanced features. We will start by setting up a development environment and learning the basic syntax of the language. From there, we will delve into topics such as variables, operators, control flow, and functions. We will also cover object-oriented programming in C++, as well as the Standard Template Library (STL).
By the end of this book, you will have a solid understanding of C++ and be able to start building your own projects with this powerful language.
Chapter 2: Setting up a Development Environment
Before we can start writing C++ programs, we need to set up a development environment. This includes installing a compiler and an editor or integrated development environment (IDE). In this chapter, we will go through the process of setting up a development environment on both Windows and Mac operating systems.
Installing a Compiler
A compiler is a program that converts the source code of a program into machine code that can be executed by a computer. In order to write and run C++ programs, we need to install a C++ compiler. Some popular C++ compilers include:
GCC (GNU Compiler Collection): This is an open-source compiler that is available for Windows, Mac, and Linux operating systems. It is a popular choice among C++ developers and is often included with Linux distributions by default.
Visual Studio: This is a development environment for Windows that includes a C++ compiler. It also includes a code editor, debugging tools, and other features that make it a great choice for C++ development on Windows.
Xcode: This is a development environment for Mac that includes a C++ compiler. It also includes a code editor, debugging tools, and other features that make it a great choice for C++ development on Mac.
Once you have chosen and installed a compiler, you should be able to run C++ programs from the command line.
Installing an Editor or IDE
An editor or IDE is a program that you can use to write and edit source code. While you can use any text editor to write C++ code, an IDE often includes additional features such as code highlighting, debugging tools, and project management. Some popular editors and IDEs for C++ development include:
Visual Studio Code: This is a lightweight code editor that is available for Windows, Mac, and Linux. It has a large selection of plugins and extensions that can be added to enhance its functionality.
Sublime Text: This is a popular code editor that is available for Windows, Mac, and Linux. It has a simple, clean interface and is known for its fast performance.
Eclipse: This is an open-source IDE that is available for Windows, Mac, and Linux. It has a wide range of features, including debugging tools and project management.
Code::Blocks: This is an open-source IDE that is available for Windows, Mac, and Linux. It is designed specifically for C++ development and includes a variety of features such as code completion and debugging tools.
Once you have set up a development environment, you are ready to start writing C++ programs. Here is a simple example of a C++ program that prints "Hello, World!" to the console:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
This program uses the iostream library to output the string "Hello, World!" to the console. The #include directive tells the compiler to include the iostream library in the program. The std::cout object is used to output the string to the console, and the std::endl is used to insert a newline character. The return 0; statement at the end of the main function tells the program to exit with a status of 0, indicating that the program ran successfully.
With the setup of development environment, you can start writing more complex and useful programs.
Chapter 3: Basic Syntax and Data Types
In this chapter, we will cover the basic syntax and data types of C++. Understanding these concepts is essential for writing C++ programs.
Syntax
C++ syntax is similar to the syntax of other programming languages, such as Java and C#. It uses curly braces {} to define the scope of a block of code, and semicolons ; to separate statements.
Comments are used to add notes or explanations to the code. Single-line comments start with // and multi-line comments start with /* and end with */.
Copy code
// This is a single-line comment
/* This
is
a
multi-line
comment */
Data Types
C++ supports a variety of data types, including:
Integer types: int, short, long, long long
Floating-point types: float, double
Character type: char
Boolean type: bool
Wide character type: wchar_t
Wide string types : wstring
For example, the following code declares an integer variable x and assigns it the value of 10:
Copy code
int x = 10;
The following code declares a floating-point variable y and assigns it the value of 3.14:
Copy code
double y = 3.14;
The following code declares a character variable c and assigns it the value of 'a':
Copy code
char c = 'a';
It's important to note that C++ is a strongly typed language, meaning that a variable can only hold values of its declared data type. Attempting to assign a value of a different type to a variable will result in a compile-time error.
Variable Declarations
To declare a variable in C++, you need to specify its data type followed by its name. You can also initialize the variable with a value when it is declared.
Copy code
int x; // Declare an integer variable x
int x = 10; // Declare and initialize an integer variable x with the value of 10
Constants
A constant is a variable whose value cannot be changed after it is initialized. You can declare a constant by using the keyword const.
Copy code
const double pi = 3.14;
In this chapter, we covered the basic syntax and data types of C++. With this understanding, you can start writing more complex programs that use variables and data types.
Exercise 1:
- Declare a variable of type
int
calledage
and initialize it with your current age. - Declare a variable of type
double
calledgpa
and initialize it with your current grade point average. - Declare a variable of type
char
calledgrade
and initialize it with your current final grade in a course. - Print out the values of all the variables you declared.
Exercise 2:
- Declare a variable of type
int
calleda
and initialize it with the value of 10. - Declare a variable of type
int
calledb
and initialize it with the value of 20. - Declare a variable of type
int
calledc
and initialize it with the value of a + b. - Print out the value of variable
c
.
Exercise 3:
- Declare a variable of type
double
calledfahrenheit
and initialize it with the value of 72. - Declare a variable of type
double
calledcelsius
and convert fahrenheit to celsius using this formula (F - 32) * 5/9 and assign the result to celsius. - Print out the value of variable
celsius
.
Exercise 4:
- Declare a constant of type
double
calledpi
and initialize it with the value of 3.14. - Declare a variable of type
double
calledradius
and initialize it with the value of 5. - Declare a variable of type
double
calledarea
and calculate the area of a circle using the formula pi * radius * radius and assign the result to area. - Print out the value of variable
area
.
Exercise 5:
- Declare a variable of type
string
calledname
and initialize it with your name. - Declare a variable of type
string
calledaddress
and initialize it with your address. - Print out the values of both variables.
Chapter 4: Variables and Operators in C++
In this chapter, we will cover the use of variables and operators in C++. Understanding how to use variables and operators is essential for writing C++ programs.
Variables
In C++, a variable is a named location in memory that can store a value. We have already covered the basics of variable declarations in the previous chapter. In this chapter, we will focus on the use of variables in expressions and assignments.
Expressions
An expression is a combination of variables, constants, and operators that evaluates to a value. For example, the expression a + b is an expression that evaluates to the sum of the values of variables a and b.
Here are some examples of expressions:
Copy code
int x = 5;
int y = 10;
int z = x + y; // z will contain the value 15
Assignments
An assignment is an expression that assigns a value to a variable. The assignment operator = is used to assign a value to a variable.
Here are some examples of assignments:
Copy code
int x = 5; // assigns the value 5 to x
x = 10; // assigns the value 10 to x
x = x + 1; // assigns x + 1 to x (x becomes 11)
Operators
C++ has a wide range of operators that can be used to perform various operations on variables. These operators include arithmetic, comparison, logical, and bitwise operators.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication, and division.
Here are some examples of arithmetic operators:
Copy code
int x = 5;
int y = 10;
int z = x + y; // z will contain the value 15
z = x - y; // z will contain the value -5
z = x * y; // z will contain the value 50
z = x / y; // z will contain the value 0
Comparison Operators
Comparison operators are used to compare the values of two variables. They return a boolean value of either true or false.
Here are some examples of comparison operators:
Copy code
int x = 5;
int y = 10;
bool b = x == y; // b will contain the value false
b = x != y; // b will contain the value true
b = x < y; // b will contain the value true
b = x > y; // b will contain the value false
Logical Operators
Logical operators are used to perform logical operations such as and, or and not.
Here are some examples of logical operators:
bool a = true;
bool b = false;
bool c = a && b; // c will contain the value false
c = a || b; // c will contain the value true
c = !a; // c will contain the value false
Exercise 1:
Declare two variables of type int called a and b and initialize them with any values.
Use the arithmetic operators to perform the following operations and assign the result to a new variable of type int:
Addition
Subtraction
Multiplication
Division
Print out the result of each operation
Solution:
Copy code
#include <iostream>
int main() {
int a = 5;
int b = 10;
int c = a + b;
std::cout << "Addition: " << c << std::endl;
c = a - b;
std::cout << "Subtraction: " << c << std::endl;
c = a * b;
std::cout << "Multiplication: " << c << std::endl;
c = a / b;
std::cout << "Division: " << c << std::endl;
return 0;
}
Exercise 2:
Declare two variables of type int called x and y and initialize them with any values.
Use the comparison operators to perform the following operations and assign the result to a new variable of type bool:
Equality
Inequality
Less than
Greater than
Print out the result of each operation
Solution:
Copy code
#include <iostream>
int main() {
int x = 5;
int y = 10;
bool b = x == y;
std::cout << "Equality: " << b << std::endl;
b = x != y;
std::cout << "Inequality: " << b << std::endl;
b = x < y;
std::cout << "Less than: " << b << std::endl;
b = x > y;
std::cout << "Greater than: " << b << std::endl;
return 0;
}
Exercise 3:
Declare two variables of type bool called a and b and initialize them with any values.
Use the logical operators to perform the following operations and assign the result to a new variable of type bool:
Logical And
Logical Or
Logical Not
Print out the result of each operation
Solution:
Copy code
#include <iostream>
int main() {
bool a = true;
bool b = false;
bool c = a && b;
std::cout << "Logical And: " << c << std::endl;
c = a || b;
std::cout << "Logical Or: " << c << std::endl;
c = !a;
std::cout << "Logical Not: " << c << std::endl;
return 0;
}
Chapter 5: C++ Control Flow
In this chapter, we will cover the use of control flow statements in C++. Control flow statements are used to control the flow of execution of a program based on certain conditions. Understanding how to use control flow statements is essential for writing C++ programs.
If-Else Statements
The if-else statement is used to execute a block of code if a certain condition is true, and another block of code if the condition is false. The syntax of the if-else statement is as follows:
Copy code
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
Here is an example of using an if-else statement to check if a number is positive or negative:
Copy code
int number = 5;
if (number >= 0) {
std::cout << number << " is a positive number" << std::endl;
} else {
std::cout << number << " is a negative number" << std::endl;
}
This code will output "5 is a positive number" because the condition number >= 0 is true.
Switch-Case Statements
The switch-case statement is used to execute a block of code based on the value of an expression. The syntax of the switch-case statement is as follows:
Copy code
switch (expression) {
case value1:
// code to execute if expression is equal to value1
break;
case value2:
// code to execute if expression is equal to value2
break;
...
default:
// code to execute if expression does not match any of the case values
}
Here is an example of using a switch-case statement to print out a message based on the value of a variable:
Copy code
int day = 2;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
default:
std::
The switch-case statement is used to execute a block of code based on the value of an expression. The syntax of the switch-case statement is as follows:
Copy code
switch (expression) {
case value1:
// code to execute if expression is equal to value1
break;
case value2:
// code to execute if expression is equal to value2
break;
...
default:
// code to execute if expression does not match any of the case values
}
Here is an example of using a switch-case statement to print out a message based on the value of a variable:
Copy code
int day = 2;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
default:
std::cout << "Invalid day" << std::endl;
}
This code will output "Tuesday" because the value of the variable day is 2, which matches the case 2.
While Loops
A while loop is used to execute a block of code multiple times as long as a certain condition is true. The syntax of the while loop is as follows:
Copy code
while (condition) {
// code to execute
}
Here is an example of using a while loop to print the numbers from 1 to 10:
Copy code
int i = 1;
while (i <= 10) {
std::cout << i << std::endl;
i++;
}
This code will output the numbers from 1 to 10, because the while loop will continue to execute as long as the condition i <= 10 is true.
For Loops
A for loop is used to execute a block of code multiple times for a specified number of iterations. The syntax of the for loop is as follows:
Copy code
for (initialization; condition; increment) {
// code to execute
}
Here is an example of using a for loop to print the numbers from 1 to 10:
Copy code
for (int i = 1; i <= 10; i++) {
std::cout << i << std::endl;
}
This code will output the numbers from 1 to 10, because the for loop will continue to execute as long as the condition i <= 10 is true.
Exercise 1:
Write a program that takes an integer input from the user and checks if it is even or odd using an if-else statement.
Solution:
Copy code
#include <iostream>
int main() {
int num;
std::cout << "Enter an integer: ";
std::cin >> num;
if (num % 2 == 0) {
std::cout << num << " is an even number." << std::endl;
} else {
std::cout << num << " is an odd number." << std::endl;
}
return 0;
}
Exercise 2:
Write a program that takes an integer input from the user and checks if it is a prime number using a for loop.
Solution:
Copy code
#include <iostream>
int main() {
int num;
std::cout << "Enter an integer: ";
std::cin >> num;
bool isPrime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
std::cout << num << " is a prime number." << std::endl;
} else {
std::cout << num << " is not a prime number." << std::endl;
}
return 0;
}
Exercise 3:
Write a program that takes an integer input from the user and uses a switch-case statement to print the name of the corresponding month of the year.
Solution:
Copy code
#include <iostream>
int main() {
int month;
std::cout << "Enter a month number (1-12): ";
std::cin >> month;
switch (month) {
case 1:
std::cout << "January" << std::endl;
break;
case 2:
std::cout << "February" << std::endl;
break;
case 3:
std::cout << "March" << std::endl;
break;
// Add the remaining case statements for the other months
default:
std::cout << "Invalid month number" << std::endl;
}
return 0;
}
Chapter 6: Functions in C++
In this chapter, we will cover the use of functions in C++. Functions are used to organize and reuse code, making it more readable and maintainable. Understanding how to use functions is essential for writing C++ programs.
Function Declaration
A function is a block of code that performs a specific task and can be called multiple times from different parts of a program. The syntax of a function declaration is as follows:
Copy code
return_type function_name(parameter_list) {
// function body
}
Here is an example of a function that takes in two integers and returns their sum:
Copy code
int add(int x, int y) {
return x + y;
}
Function Call
A function is called by using its name followed by its parameter list.
Copy code
int result = add(5, 10);
Here is an example of a complete program that uses the function add():
Copy code
#include <iostream>
int add(int x, int y) {
return x + y;
}
int main() {
int a = 5;
int b = 10;
int c = add(a, b);
std::cout << "The sum of " << a << " and " << b << " is " << c << std::endl;
return 0;
}
This program will output "The sum of 5 and 10 is 15"
Functions can also take no parameters and return no value, in which case the keyword "void" is used in the function declaration and call.
Copy code
void printHello() {
std::cout << "Hello!" << std::endl;
}
and call it like this
Copy code
printHello();
Chapter 7: Arrays and Strings C++
In this chapter, we will cover the use of arrays and strings in C++. An array is a collection of variables of the same data type, stored in contiguous memory locations. A string is a sequence of characters. Understanding how to use arrays and strings is essential for working with data in C++.
Arrays
Declaring Arrays
An array is declared by specifying its data type, name, and size. The syntax of declaring an array is as follows:
Copy code
data_type array_name[size];
Here is an example of declaring an array of integers called "numbers" with a size of 5:
Copy code
int numbers[5];
Initializing Arrays
An array can be initialized at the time of declaration by providing a list of values, separated by commas. The syntax of initializing an array is as follows:
Copy code
data_type array_name[] = {value1, value2, ...};
Here is an example of declaring and initializing an array of integers called "squares" with the first 5 square numbers:
Copy code
int squares[] = {1, 4, 9, 16, 25};
Accessing Array Elements
Individual elements of an array can be accessed using their index, which is an integer value that starts at 0. The syntax of accessing an array element is as follows:
Copy code
array_name[index];
Here is an example of accessing the third element of the array "squares":
Copy code
std::cout << squares[2] << std::endl;
This code will output "9", because the third element of the array "squares" is 9.
Strings
In C++, strings are represented using the standard library class std::string. The class provides a variety of methods for manipulating and working with strings. Here is an example of declaring and initializing a string:
Copy code
std::string name = "John Doe";
You can also use the + operator to concatenate strings:
Copy code
std::string firstName = "John";
std::string lastName = "Doe";
std::string fullName = firstName + " " + lastName;
You can also get the length of a string using the length() method:
Copy code
std::string name = "John Doe";
int length = name.length();
Exercise 1:
Write a program that declares an array of 10 integers, initializes the elements with values from 1 to 10, and prints out the elements using a for loop.
Solution:
Copy code
#include <iostream>
int main() {
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i = 0; i < 10; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
Chapter 8: Pointers and Memory Management
In this chapter, we will cover the use of pointers and memory management in C++. Pointers are variables that store memory addresses and are used to manipulate memory directly. Memory management is the process of allocating and deallocating memory dynamically during the execution of a program. Understanding how to use pointers and manage memory is essential for writing efficient and performant C++ programs.
Dynamic Memory Allocation
In C++, memory can be allocated dynamically during runtime using the new operator. The new operator returns a pointer to the memory address of the newly allocated memory. The syntax for allocating memory dynamically is as follows:
Copy code
pointer_name = new data_type;
Here is an example of allocating memory for an integer and storing the memory address in the pointer "ptr":
Copy code
int *ptr = new int;
Dynamic Memory Deallocation
Once dynamically allocated memory is no longer needed, it should be deallocated using the delete operator. The syntax for deallocating memory is as follows:
Copy code
delete pointer_name;
Here is an example of deallocating the memory allocated for the integer pointer "ptr":
Copy code
delete ptr;
Dynamic Arrays
Dynamic arrays can be created by allocating memory for an array using the new operator. The syntax for allocating memory for a dynamic array is as follows:
Copy code
pointer_name = new data_type[size];
Here is an example of allocating memory for a dynamic array of 10 integers and storing the memory address in the pointer "ptr":
Copy code
int *ptr = new int[10];
Memory Leaks
Memory leaks occur when dynamically allocated memory is not properly deallocated. This can lead to a depletion of system resources and cause a program to crash. It is important to always deallocate memory when it is no longer needed to prevent memory leaks.
Exercise 1:
Write a program that dynamically allocates memory for an array of 10 integers, assigns values to the elements, and then deallocates the memory.
Solution:
Copy code
#include <iostream>
int main() {
int *arr = new int[10];
for (int i = 0; i < 10; i++) {
arr[i] = i + 1;
}
for (int i = 0; i < 10; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
delete[] arr;
return 0;
}
In this chapter, we will cover the use of classes and objects in C++. A class is a blueprint for creating objects, which are instances of a class. Classes provide a way to organize and encapsulate data and behavior, making it more readable and maintainable. Understanding how to use classes and objects is essential for writing efficient and maintainable C++ programs.
Defining Classes
A class is defined by specifying its name and the data members and member functions it contains. The syntax for defining a class is as follows:
Copy code
class ClassName {
// data members
// member functions
};
Here is an example of defining a class called "Person" that contains data members for a person's name and age, and a member function for printing the person's information:
Copy code
class Person {
std::string name;
int age;
public:
void setName(std::string n) { name = n; }
void setAge(int a) { age = a; }
void printInfo() {
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
}
};
Creating Objects
An object is created by specifying the class name, followed by the object name, and enclosing them in parentheses. The syntax for creating an object is as follows:
Copy code
ClassName object_name;
Here is an example of creating an object of the "Person" class called "John":
Copy code
Person John;
Accessing Class Members
Class data members and member functions can be accessed by using the dot operator (.) on an object. The syntax for accessing a data member is as follows:
Copy code
object_name.data_member;
The syntax for accessing a member function is as follows:
Copy code
object_name.member_function();
Here is an example of setting the name and age of the "John" object and calling the "printInfo" member function:
Copy code
John.setName("John Doe");
John.setAge(30);
John.printInfo();
Constructors
A constructor is a special member function that is called when an object is created. It is used to initialize the object's data members. The syntax for defining a constructor is as follows:
Copy code
ClassName::ClassName(parameters) {
// constructor body
}
Here is an example of adding a constructor to the "Person" class that accepts a name and age as parameters:
Copy code
class Person {
std::string name;
int age;
public:
Person(std::string n, int a) {
name = n;
age = a;
}
void printInfo() {
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
}
};