Basic Topics
Getting Started
What is C++?
- C++ is a general-purpose computer programming language that has the following primary characteristics:
- object-oriented
- dynamic memory allocation
- generic
- functional
C++ Compiler
we are going to use dev c++ compiler as it has the best and lightweight interface , unlike turboc++ we don't need to use clrscr() and getch()
A C++ compiler is itself a computer program which’s only job is to convert the C++ program from our form to a form the computer can read and execute. The original C++ program is called the “source code”, and the resulting compiled code produced by the compiler is usually called an “object file”.
Before compilation the preprocessor performs preliminary operations on C++ source files. Preprocessed form of the source code is sent to compiler.
After compilation stage object files are combined with predefined libraries by a linker, sometimes called a binder, to produce the final complete file that can be executed by the computer. A library is a collection of pre-compiled “object code” that provides operations that are done repeatedly by many computer programs.
First Program in C++
Below is an example of a simple C++ program:
// This is my first program in C++
/* This program will illustrate different components
of a simple program in C++ */
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!";
return 0;
}
When the above program is compiled, linked, and executed, the following output is displayed on the screen:
Hello World!
Explanation of the Program
- Comments:
Comments are ignored by the compiler and make the program more readable.
Single-line comments use
//
, and multi-line comments are enclosed in/* */
. - #include <iostream>: This is a directive to include the iostream file, which is required for input/output operations.
- using namespace std:
This makes elements of the standard C++ library accessible without specifying the
std
namespace explicitly. - int main() { } The entry point of the program. Code inside the curly braces is executed.
- cout << "Hello World!";
Outputs the string
Hello World!
to the screen. - return 0; Indicates successful execution of the program.
Printing Multiple Lines with a Single Statement
The following program demonstrates how to print multiple lines of text using a single statement:
/* This program illustrates how to print multiple lines of text
with a single statement */
#include <iostream>
using namespace std;
int main()
{
cout << "Welcome\nto\nC++";
return 0;
}
Output:
Welcome to C++
Explanation of Escape Sequences
The \
(backslash) character introduces escape sequences, which represent special characters:
Escape Sequence | Description |
---|---|
\n |
Newline |
\t |
Horizontal tab |
\a |
Bell (beep) |
\\ |
Backslash |
\' |
Single quote |
\" |
Double quote |
Variable: Memory Concept
Variables, one of the most important concepts in the C++ programming language, will be introduced and investigated in this article. So, without further ado, here is a list of topics that are all related to the "variables" discussed in this article.
- Introduction to variables
- Declaration of a Variable
- Initialization of a variable
- Dynamic initialization of a variable
- Variable scope
- Storage classes
Introduction to C++ variables
Variables are storage locations with names that can be changed while the program is running. For example, to store a student's name and grades during a program run, we need two storage locations with different names so that they can be easily distinguished.
Variables, called "symbolic variables," serve the purpose. The variables are called symbolic variables because these are named locations. For instance, the following statement declares a variable i of the data type int:
int i;
A separate (next) article describes data types. To summarize, when declaring a variable in a program, you must specify its data type to tell the compiler what type of data the variable can store. For example, since the above variable "i" was defined using "int,", then that variable can only store integer values.
Values associated with a symbolic variable in C++
There are the following two values associated with a symbolic variable:
- Its data value is stored at some location in memory. This is sometimes referred to as a variable's rvalue (pronounced "are-value").
- Its location value, that is, the address in memory at which its data value is stored, This is sometimes referred to as a variable's lvalue (pronounced "el-value").
Declaration of a Variable in C++
Here is the general form to declare a variable in C++:
type variableName;
Here, type is any valid C++ data type, and variableName is the variable's name. An identifier is a variable name. As a result, when declaring the name of a variable, all of the rules of identifier naming apply. The following declaration declares an int variable age:
int age;
Consider the following program as an example.
#include<iostream> using namespace std; int main() { int age; cout<<"How old are you? "; cin>>age; cout<<"\nYou're "<<age<<" years old."; cout<<endl; return 0; }
Identifiers
Symbolic names used for data items in a program are called identifiers. For example, x
, y
, and z
in the previous program are identifiers.
Rules for Identifiers
- An identifier can consist of alphabets, digits, and/or underscores.
- It must not start with a digit.
- C++ is case-sensitive, so uppercase and lowercase letters are treated differently.
- It should not be a reserved keyword.
Keywords
Reserved words in C++ with predefined meanings are called keywords. These cannot be used as identifiers. Some commonly used keywords are:
Keywords |
---|
asm |
auto |
bool |
break |
case |
catch |
char |
class |
const |
const_cast |
continue |
default |
delete |
do |
double |
dynamic_cast |
else |
enum |
explicit |
export |
extern |
false |
float |
for |
friend |
goto |
if |
inline |
int |
long |
mutable |
namespace |
new |
operator |
private |
protected |
public |
register |
reinterpret_cast |
return |
short |
signed |
sizeof |
static |
static_cast |
struct |
switch |
template |
this |
throw |
true |
try |
typedef |
typeid |
typename |
union |
unsigned |
using |
virtual |
void |
volatile |
wchar_t |
while |
Introduction
A programming language is a set of rules, symbols, and special words used to construct programs. Certain elements are common to all programming languages. Below, we discuss these elements in detail.
C++ Character Set
The character set is a set of valid characters that a language can recognize:
- Letters: A-Z, a-z
- Digits: 0-9
- Special Characters: Space, +, -, *, /, ^, \\, (), [], {}, =, !=, <>, ‘, “, $, ,, ;, :, %, !, &, ?, _, #, <=, >=, @
- Formatting Characters: Backspace, horizontal tab, vertical tab, form feed, and carriage return
Tokens
A token is a group of characters that logically belong together. Tokens in C++ include:
- Keywords
- Identifiers
- Literals
- Punctuators
- Operators
1. Keywords
These are reserved words in C++ with predefined meanings for the compiler. Refer to the previous section for details.
2. Identifiers
Symbolic names used for various data items in a program are called identifiers. Rules for forming identifiers:
- Can consist of alphabets, digits, and/or underscores
- Cannot start with a digit
- Are case-sensitive (uppercase and lowercase are distinct)
- Must not be a reserved word
3. Literals
Literals, often called constants, are data items that do not change during program execution. Types of literals:
- Integer Constants
- Character Constants
- Floating Constants
- String Literals
Integer Constants
Whole numbers without fractional parts. Types:
- Decimal: Sequence of digits, not starting with 0. Example: 124, -179, +108
- Octal: Sequence of digits starting with 0. Example: 014, 012
- Hexadecimal: Sequence preceded by
0x
or0X
. Example: 0x1A
Character Constants
Must contain one or more characters enclosed in single quotes. Example: 'A'
, '9'
. Escape sequences represent nongraphic characters (e.g., \n
for a new line).
Floating Constants
Numbers with fractional parts, written in fractional or exponent form. Example: 3.0, -17.0, -0.627
String Literals
A sequence of characters enclosed in double quotes. Automatically appended with \0
to denote the end. Example: "COMPUTER" is stored as "COMPUTER\0".
4. Punctuators
The following characters are used as punctuators in C++:
Punctuator | Purpose |
---|---|
[ ] | Indicate array subscript |
( ) | Indicate function calls, parameters, or grouping expressions |
{ } | Indicate start and end of compound statements |
, | Separator in function arguments |
; | Statement terminator |
: | Indicate labeled statements or conditional operator |
* | Pointer declaration or multiplication operator |
= | Assignment operator |
# | Preprocessor directive |
5. Operators
Special symbols for specific operations. Types of operators in C++:
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Unary Operators
- Assignment Operators
- Conditional Operators
- Comma Operators
Introduction
Operators are special symbols used for specific purposes. C++ provides many operators for manipulating data. There are six main types of operators:
- Arithmetical Operators
- Relational Operators
- Logical Operators
- Assignment Operators
- Conditional Operators
- Comma Operators
Arithmetical Operators
These operators are used to perform arithmetic operations:
Operator | Meaning |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulus |
The operators +, -, *, and / work with both integers and floating-point data types. The % operator is used only with integers.
Binary and Unary Operators
Binary Operators: Require two operands. Example: x + y
.
Unary Operators: Operate on a single variable. Example:
a = -50; a = +50;
Relational Operators
Relational operators test the relationship between two values. They return 0
if false and a non-zero value if true.
Relational Operators | Meaning |
---|---|
< | Less than |
<= | Less than or equal to |
== | Equal to |
> | Greater than |
>= | Greater than or equal to |
!= | Not equal to |
Logical Operators
Logical operators combine or negate relational expressions:
Operator | Meaning |
---|---|
|| | OR |
&& | AND |
! | NOT |
Assignment Operators
The =
operator assigns values. Compound assignment operators combine operations with assignment:
Operator | Example | Equivalent To |
---|---|---|
+= | A += 2 | A = A + 2 |
-= | A -= 2 | A = A - 2 |
*= | A *= 2 | A = A * 2 |
/= | A /= 2 | A = A / 2 |
%= | A %= 2 | A = A % 2 |
Increment and Decrement Operators
C++ provides ++
and --
to increment or decrement a value by 1:
- Pre-increment:
++variable
- Post-increment:
variable++
- Pre-decrement:
--variable
- Post-decrement:
variable--
Conditional Operator
The conditional operator (?:
) evaluates a condition:
big = (a > b) ? a : b;
If a > b
is true, big
gets a
. Otherwise, it gets b
.
Comma Operator
The comma operator evaluates expressions left to right. Only the last expression's value is considered.
sizeof Operator
The sizeof
operator determines the memory size of an object:
sizeof(char)
returns 1sizeof(float)
returns 4
Order of Precedence
The order of precedence determines the evaluation order of operators in an expression:
Order | Operators |
---|---|
First | () |
Second | *, /, % |
Third | +, - |
Basic Data Types
C++ supports a variety of data types, including:
Type | Description |
---|---|
int | Small integer number |
long int | Large integer number |
float | Small real number |
double | Double precision real number |
long double | Long double precision real number |
char | A single character |
The exact sizes and ranges of these types are system-dependent and can be found in the headers <climits>
and <cfloat>
.
C++ String Class
The string
class in C++ is used to handle sequences of characters. To use it, include the <string>
header file.
// Example program demonstrating the string class #include <iostream> #include <string> using namespace std; int main() { string mystring = "This is a string"; cout << mystring; return 0; }
Variable Initialization
A variable is a named location in memory that can store data. Variables must be declared before use.
float total; // Declaration int x, y; // Multiple variables in one declaration int a = 20; // Initialization with a value int b(30); // Constructor initialization
Constants
Constants are variables whose values cannot change during program execution. They are declared using the const
keyword.
const float PI = 3.1415; // Constant of type float const int RATE = 50; // Constant of type int const char CH = 'A'; // Constant of type char
Type Conversion
Type conversion is the process of converting one data type to another. There are two types:
1. Implicit Conversion
In implicit conversion, C++ automatically converts a lower data type to a higher data type in mixed expressions:
double a; int b = 5; float c = 8.5; a = b * c; // 'b' is converted to float, result converted to double
The order of data types is as follows (highest to lowest):
- long double
- double
- float
- long
- int
- char
2. Explicit Conversion
Explicit conversion (type casting) temporarily changes a variable's type:
totalPay = static_cast<double>(salary) + bonus; // 'salary' is cast to double before the addition
Introduction
The standard C++ library includes the header file <iostream>
, which facilitates input and output operations. These operations use the following stream objects:
cout
: Console outputcin
: Console input
Using cout
The cout
object is used to display output on the screen. It is combined with the insertion operator <<
.
cout << "Hello World"; // prints Hello World cout << 250; // prints 250 cout << sum; // prints the value of the variable 'sum'
Example of combining constants and variables in a single statement:
cout << "Area of rectangle is " << area << " square meter";
If area
is 24, the output will be:
Area of rectangle is 24 square meter
Using cin
The cin
object is used to take input from the user via the keyboard. It works with the extraction operator >>
to store the user input in variables.
int marks; cin >> marks; // Reads an integer value into 'marks'
Example program:
// Input/output example #include <iostream> using namespace std; int main() { int length, breadth, area; cout << "Please enter length of rectangle: "; cin >> length; cout << "Please enter breadth of rectangle: "; cin >> breadth; area = length * breadth; cout << "Area of rectangle is " << area; return 0; }
Output:
Please enter length of rectangle: 6 Please enter breadth of rectangle: 4 Area of rectangle is 24
Multiple inputs can be taken in a single statement:
cin >> length >> breadth; // Equivalent to: cin >> length; cin >> breadth;
Using cin
with Strings
The cin
object can be used to input strings. However, it stops reading at a space. For full-line input, use getline()
instead:
// cin and strings #include <iostream> #include <string> using namespace std; int main() { string name; cout << "Enter your name: "; getline(cin, name); cout << "Hello " << name << "!"; return 0; }
Output:
Enter your name: Mohsin Khan Hello Mohsin Khan!