C++ Intro
C++ Intro
#include <iostream.h>
#include<conio.h>
using namespace std;
// main() is where program execution begins.
int main()
{
clrscr();
cout << "Hello World"; // prints Hello World
return 0;
getch();
}
1. The C++ language defines several headers, which contain information that is either
necessary or useful to your program. For this program, the header <iostream> is
needed.
#include <iostream> is a preprocessor directive that includes the content of the
standard C++ header file iostream. iostream is a standard library header file that
contains definitions of the standard input and output streams. These definitions are
included in the std namespace, explained below.
The standard input/output (I/O) streams provide ways for programs to get input from
and output to an external system -- usually the terminal.
2. The line using namespace std; tells the compiler to use the std namespace.
3. The next line ‘// main() is where program execution begins.’ is a single-line
comment available in C++. Single-line comments begin with // and stop at the end of
the line.
4. The line int main() is the main function where program execution begins.
5. int main() { ... } defines a new function named main. By convention, the main
function is called upon execution of the program. There must be only one main
function in a C++ program, and it must always return a number of the int type.
Here, the int is what is called the function's return type. The value returned by the
main function is an exit code.
By convention, a program exit code of 0 or EXIT_SUCCESS is interpreted as success
by a system that executes the program. Any other return code is associated with an
error.
If no return statement is present, the main function (and thus, the program itself)
returns 0 by default. In this example, we don't need to explicitly write return 0;.
All other functions, except those that return the void type, must explicitly return a
value according to their return type, or else must not return at all.
6. The next line cout << "Hello World"; causes the message " Hello World " to be
displayed on the screen.
7. The next line return 0; terminates main() function and causes it to return the value 0
to the calling process.
C++ Keywords
The following list shows the reserved words in C++. These reserved words may not
be used as constant or variable or any other identifier names.
Comments in C++
A comment is a way to put arbitrary text inside source code without having the C++ compiler
interpret it with any
functional meaning. Comments are used to give insight into the design or method of a program.
There are two types of comments in C++:
Single-Line Comments
The double forward-slash sequence // will mark all text until a newline as a comment:
int main()
{
// This is a single-line comment.
int a; // this also is a single-line comment
int i; // this is another single-line comment
}
Importance of Comments
As with all programming languages, comments provide several benefits:
Whitespace in C++
A line containing only whitespace, possibly with a comment, is known as a blank line, and C++
compiler totally ignores it.
Whitespace is the term used in C++ to describe blanks, tabs, newline characters and comments.
Whitespace separates one part of a statement from another and enables the compiler to identify where
one element in a statement, such as int, ends and the next element begins.
For ex:
int age;
In the above statement there must be at least one whitespace character (usually a space) between int
and age for the compiler to be able to distinguish them.
Data types
While writing program in any language, you need to use various variables to store various
information. Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory.
You may like to store information of various data types like character, wide character,
integer, floating point, double floating point, boolean etc. Based on the data type of a
variable, the operating system allocates memory and decides what can be stored in the
reserved memory.
Primitive Built-in Types
C++ offers the programmer a rich assortment of built-in as well as user defined data types.
Following table lists down seven basic C++ data types:
Several of the basic types can be modified using one or more of these type modifiers:
• signed
• unsigned
• short
• long
The following table shows the variable type, how much memory it takes to store the value in
memory, and what is maximum and minimum value which can be stored in such type of
variables.
Variable Definition in C++
A variable definition tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type, and contains a list of one or more
variables of that type as follows:
type variable_list;
Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or
any user-defined object, etc., and variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here:
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which instructs the
compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows:
type variable_name = value;
int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
Operators in C++
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provide the following types of operators:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other
operators one by one.
• Arithmetic Operators
There are following arithmetic operators supported by C++ language:
Assume variable A holds 10 and variable B holds 20, then:
#include <iostream.h>
using namespace std;
void main()
{
int a = 21;
int b = 10;
int c ;
c = a + b;
cout << "Line 1 - Value of c is :" << c << endl ;
c = a - b;
cout << "Line 2 - Value of c is :" << c << endl ;
c = a * b;
cout << "Line 3 - Value of c is :" << c << endl ;
c = a / b;
cout << "Line 4 - Value of c is :" << c << endl ;
c = a % b;
cout << "Line 5 - Value of c is :" << c << endl ;
c = a++;
cout << "Line 6 - Value of c is :" << c << endl ;
c = a--;
cout << "Line 7 - Value of c is :" << c << endl ;
getch();
}
• Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then:
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20;
// Relational Operators
cout << "a == b: " << (a == b) << endl;
cout << "a != b: " << (a != b) << endl;
cout << "a > b: " << (a > b) << endl;
cout << "a < b: " << (a < b) << endl;
cout << "a >= b: " << (a >= b) << endl;
cout << "a <= b: " << (a <= b) << endl;
return 0;
}
Output
a == b: 0
a != b: 1
a > b: 0
a < b: 1
a >= b: 0
a <= b: 1
Explanation:
• Output Values: Relational operators return 1 (true) or 0 (false).
• For example:
o a == b: 10 == 20 is false, so output is 0.
o a < b: 10 < 20 is true, so output is 1.
• Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then –
#include <iostream>
int main() {
int a = 10, b = 20;
// Logical AND
cout << "(a > 5 && b < 15): " << (a > 5 && b < 15) << endl;
// Logical OR
cout << "(a > 5 || b < 15): " << (a > 5 || b < 15) << endl;
// Logical NOT
cout << "!(a > 5): " << !(a > 5) << endl;
return 0;
}
Output
(a > 5 && b < 15): 0
(a > 5 || b < 15): 1
!(a > 5): 0
Explanation:
1. Logical AND (&&):
o Evaluates true only if both conditions are true.
o (a > 5 && b < 15) evaluates to false because b < 15 is false.
2. Logical OR (||):
o Evaluates true if at least one condition is true.
o (a > 5 || b < 15) evaluates to true because a > 5 is true.
3. Logical NOT (!):
o Reverses the truth value.
o !(a > 5) is false because a > 5 is true, and NOT negates it.
• Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and
^ are as follows −
Bitwise Operators
1. Bitwise AND (&)
o Performs a bit-by-bit AND operation.
o Operates on each bit; result is 1 only if both bits are 1.
o Example: a & b
2. Bitwise OR (|)
o Performs a bit-by-bit OR operation.
o Operates on each bit; result is 1 if at least one bit is 1.
o Example: a | b
3. Bitwise XOR (^)
o Performs a bit-by-bit exclusive OR operation.
o Operates on each bit; result is 1 if bits are different.
o Example: a ^ b
4. Bitwise NOT (~)
o Inverts all bits of the operand.
o Flips all bits (2's complement used for negative representation).
o Example: ~a
5. Left Shift (<<)
o Shifts bits of the number to the left by the specified number of positions.
o Shifts bits left, filling with 0 on the right. Equivalent to multiplying by 2^n.
o Example: a << 1
6. Right Shift (>>)
o Shifts bits of the number to the right by the specified number of positions.
o Shifts bits right, discarding rightmost bits. Equivalent to dividing by 2^n.
o Example: a >> 1
The Bitwise operators supported by C++ language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then –
#include <iostream>
using namespace std;
int main() {
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
// Bitwise AND
cout << "a & b: " << (a & b) << endl; // 0101 & 0011 = 0001 (1)
// Bitwise OR
cout << "a | b: " << (a | b) << endl; // 0101 | 0011 = 0111 (7)
// Bitwise XOR
cout << "a ^ b: " << (a ^ b) << endl; // 0101 ^ 0011 = 0110 (6)
// Bitwise NOT
cout << "~a: " << (~a) << endl; // ~0101 = 1010 (in 2's complement: -6)
// Left Shift
cout << "a << 1: " << (a << 1) << endl; // 0101 << 1 = 1010 (10)
// Right Shift
cout << "a >> 1: " << (a >> 1) << endl; // 0101 >> 1 = 0010 (2)
return 0;
}
Output
a & b: 1
a | b: 7
a ^ b: 6
~a: -6
a << 1: 10
a >> 1: 2
• Assignment Operators
There are following assignment operators supported by C++ language –
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 5;
// Basic Assignment
cout << "Initial a: " << a << endl;
return 0;
}
Output
Initial a: 10
a += b: 15
a -= b: 10
a *= b: 50
a /= b: 10
a %= b: 0
Explanation:
1. Each compound operator performs the arithmetic or bitwise operation and updates the
variable.
2. These operators simplify code and improve readability.
4o
• Misc Operators
The following table lists some other operators that C++ supports.
Operators Precedence in C++
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Type Conversion/Casting in C++
It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).
Example of Type Implicit Conversion:
#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
return 0;
}
Output:
x = 107
y=a
z = 108
2. Explicit Type Conversion:
This process is also called type casting and it is user-defined. Here the user can typecast
the result to make it of a particular data type.In C++, it can be done by two ways:
i. Converting by assignment
ii. Conversion using Cast operator
• Converting by assignment:
This is done by explicitly defining the required type in front of the expression in
parenthesis. This can be also considered as forceful casting.
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
Example:
#include <iostream>
using namespace std;
int main()
{
double x = 1.2;
return 0;
}
Output:
Sum = 2
cout << b;
}
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general from of a loop statement in most of the programming languages –
C++ programming language provides the following type of loops to handle looping
requirements.
1 while loop
2 for loop
Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
3 do...while loop
Like a ‘while’ statement, except that it tests the condition at the end of the loop
body.
4 nested loops
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.
• while loop
A while loop statement repeatedly executes a target statement as long as a given condition is
true.
Syntax
The syntax of a while loop in C++ is −
while(condition) {
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following
the loop.
Flow Diagram
Here, key point of the while loop is that the loop might not ever run. When the condition is
tested and the result is false, the loop body will be skipped and the first statement after the
while loop will be executed.
Example
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
• do...while loop
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while
loop checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax
The syntax of a do...while loop in C++ is −
do {
statement(s);
}
while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in
the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the
loop execute again. This process repeats until the given condition becomes false.
Flow Diagram
Example
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution
do {
cout << "value of a: " << a << endl;
a = a + 1;
} while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
• for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax
The syntax of a for loop in C++ is −
• The init step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as
long as a semicolon appears.
• Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next
statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment
statement. This statement can be left blank, as long as a semicolon appears after the
condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again condition). After the condition
becomes false, the for loop terminates.
Flow Diagram
Example
#include <iostream>
using namespace std;
int main () {
// for loop execution
for( int a = 10; a < 20; a = a + 1 ) {
cout << "value of a: " << a << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
• Decision Making
Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages –
1 if statement
2 if...else statement
An ‘if’ statement can be followed by an optional ‘else’ statement, which executes
when the boolean expression is false.
3 switch statement
A ‘switch’ statement allows a variable to be tested for equality against a list of
values.
4 nested if statements
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’
statement(s).
• if statement
An if statement consists of a boolean expression followed by one or more statements.
Syntax
The syntax of an if statement in C++ is −
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true
}
If the boolean expression evaluates to true, then the block of code inside the if statement will
be executed. If boolean expression evaluates to false, then the first set of code after the end of
the if statement (after the closing curly brace) will be executed.
Flow Diagram
Example
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 10;
return 0;
}
When the above code is compiled and executed, it produces the following result −
• if ….else statement
An if statement can be followed by an optional else statement, which executes when the
boolean expression is false.
Syntax
The syntax of an if...else statement in C++ is −
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true
} else {
// statement(s) will execute if the boolean expression is false
}
If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Flow Diagram
Example
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
return 0;
}
When the above code is compiled and executed, it produces the following result −
When using if , else if , else statements there are few points to keep in mind.
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of he remaining else if's or else's will be tested.
Syntax
The syntax of an if...else if...else statement in C++ is −
if(boolean_expression 1) {
// Executes when the boolean expression 1 is true
} else if( boolean_expression 2) {
// Executes when the boolean expression 2 is true
} else if( boolean_expression 3) {
// Executes when the boolean expression 3 is true
} else {
// executes when the none of the above condition is true.
}
Example
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
• Switch statement
A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each case.
Syntax
The syntax for a switch statement in C++ is as follows −
switch(expression) {
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional
• You can have any number of case statements within a switch. Each case is followed
by the value to be compared to and a colon.
• The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will
fall through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases
is true. No break is needed in the default case.
Flow Diagram
Example
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
char grade = 'D';
switch(grade) {
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
cout<<”Very Well done”<<endl;
break;
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
}
This would produce the following result −
You passed
Your grade is D
Syntax
The syntax for a nested if statement is as follows −
if( boolean_expression 1) {
// Executes when the boolean expression 1 is true
if(boolean_expression 2) {
// Executes when the boolean expression 2 is true
}
}
You can nest else if...else in the similar way as you have nested if statement.
Example
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
int b = 200;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
Arrays in C++
C++ provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but it is
often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by
an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.
• Declaring Arrays
To declare an array in C++, the programmer specifies the type of the elements and the
number of elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimension array. The arraySize must be an integer constant greater
than zero and type can be any valid C++ data type.
For example, to declare a 10-element array called balance of type double, use this statement −
double balance[10];
• Initializing Arrays
You can initialize C++ array elements either one by one or using a single statement as
follows −
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements that
we declare for the array between square brackets [ ].
Following is an example to assign a single element of the array −
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write −
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th
index will be 5th, i.e., last element because all arrays have 0 as the index of their first element
which is also called base index. Following is the pictorial representation of the same array we
discussed above –
• Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the
element within square brackets after the name of the array. For example −
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to salary
variable. Following is an example, which will use all the above-mentioned three concepts viz.
declaration, assignment and accessing arrays −
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main () {
return 0;
}
This program makes use of setw() function to format the output. When the above code is
compiled and executed, it produces the following result −
Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
Arrays are important to C++ and should need lots of more detail. There are following few
important concepts, which should be clear to a C++ programmer −
1 Multi-dimensional arrays
2 Pointer to an array
You can generate a pointer to the first element of an array by simply specifying the
array name, without any index.
You can pass to the function a pointer to an array by specifying the array's name
without an index.