0% found this document useful (0 votes)
3 views40 pages

C++ Intro

C++ is a versatile programming language that combines high-level and low-level features, developed by Bjarne Stroustrup in 1979. It supports various programming paradigms, including procedural and object-oriented programming, and has a rich set of built-in data types and operators. The document also covers C++ program structure, comments, data types, variable definitions, and operators, providing examples and explanations for each concept.

Uploaded by

noopursakpal1309
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views40 pages

C++ Intro

C++ is a versatile programming language that combines high-level and low-level features, developed by Bjarne Stroustrup in 1979. It supports various programming paradigms, including procedural and object-oriented programming, and has a rich set of built-in data types and operators. The document also covers C++ program structure, comments, data types, variable definitions, and operators, providing examples and explanations for each concept.

Uploaded by

noopursakpal1309
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming language

that supports procedural, object-oriented, and generic programming.


C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-
level language features.
C++ was developed by Bjarne Stroustrup starting in 1979 at AT & T Bell Labs in Murray Hill,
New Jersey, as an enhancement to the C language and originally named C with Classes but later it
was renamed C++ in 1983.
C++ is a superset of C, and that virtually any legal C program is a legal C++ program.

C++ Program Structure


Let us look at a simple code that would print the words Hello World.

#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.

Semicolons & Blocks in C++


• In C++, the semicolon is a statement terminator. That is, each individual statement
must be ended with a semicolon. It indicates the end of one logical entity.
• A block is a set of logically connected statements that are surrounded by opening
and closing braces. For example:
{
cout << "Hello World"; // prints Hello World
return 0;
}
C++ Identifiers
• A C++ identifier is a name used to identify
a variable, function, class, module, or any other user-defined item.
• An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores, and digits (0 to 9).
• C++ does not allow punctuation characters such as @, $, and % within identifiers.
• C++ is a case-sensitive programming language. Thus, Hello and hello are two
different identifiers in C++.
Here are some examples of acceptable identifiers:
Ram shyam abc movie_name a_123
Myname50 _temp j a23b9 retVal

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
}

C-Style/Block Comments/Multiple line comments


The sequence /* is used to declare the start of the comment block and the sequence */ is used to
declare the end of comment. All text between the start and end sequences is interpreted as a comment,
even if the text is otherwise valid C++ syntax. These are sometimes called "C-style" comments, as
this comment syntax is inherited from C++'s predecessor language, C:
int main()
{
/*
This is a block comment.
*/
int a;
}
In any block comment, you can write anything you want. When the compiler encounters the symbol
*/, it
terminates the block comment:
int main()
{
/* A block comment with the symbol /*
Note that the compiler is not affected by the second /*
however, once the end-block-comment symbol is reached,
the comment ends.
*/
int a;
}
The above example is valid C++ (and C) code. However, having additional /* inside a block comment
might result in a warning on some compilers.

Importance of Comments
As with all programming languages, comments provide several benefits:

• Explicit documentation of code to make it easier to read/maintain


• Explanation of the purpose and functionality of code
• Details on the history or reasoning behind the code
• Placement of copyright/licenses, project notes, special thanks, contributor credits, etc. directly in
the source code.

However, comments also have their downsides:


• They must be
• Excessive comments tend to make the code less readable
The need for comments can be reduced by writing clear, self-documenting code. A simple example is
the use of explanatory names for variables, functions, and types. Factoring out logically related tasks
into discrete functions goes hand-in-hand with this.

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 –

1. Logical AND (&&)


o Returns true if both operands are true.
o Example: (a > 5 && b < 15)
2. Logical OR (||)
o Returns true if at least one operand is true.
o Example: (a > 5 || b < 15)
3. Logical NOT (!)
o Reverses the truth value of the operand.
o Example: !(a > 5)

#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;

// Add and Assign


a += b; // a = a + b
cout << "a += b: " << a << endl;

// Subtract and Assign


a -= b; // a = a - b
cout << "a -= b: " << a << endl;

// Multiply and Assign


a *= b; // a = a * b
cout << "a *= b: " << a << endl;

// Divide and Assign


a /= b; // a = a / b
cout << "a /= b: " << a << endl;

// Modulus and Assign


a %= b; // a = a % b
cout << "a %= b: " << 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++

1. Implicit Type Conversion Also known as ‘automatic type conversion’ .


Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid lose of data.
All the data types of the variables are upgraded to the data type of the variable with largest
data type.
bool -> char -> short int -> int ->

unsigned int -> long -> unsigned ->

long long -> float -> double -> long double

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

// y implicitly converted to int. ASCII


// value of 'a' is 97
x = x + y;

// x is implicitly converted to float


float z = x + 1.0;

cout << "x = " << x << endl


<< "y = " << y << endl
<< "z = " << z << endl;

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:

// C++ program to demonstrate


// explicit type casting

#include <iostream>
using namespace std;

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;
}
Output:
Sum = 2

• Conversion using Cast operator:


A Cast operator is an unary operator which forces one data type to be converted into another
data type.
C++ supports four types of casting:
• Const Cast
• Dynamic Cast
• Reinterpret Cast
• Static Cast

• const_cast<type> (expr) − The const_cast operator is used to explicitly override const


and/or volatile in a cast. The target type must be the same as the source type except for
the alteration of its const or volatile attributes. This type of casting manipulates the
const attribute of the passed object, either to be set or removed.
• dynamic_cast<type> (expr) − The dynamic_cast performs a runtime cast that verifies
the validity of the cast. If the cast cannot be made, the cast fails and the expression
evaluates to null. A dynamic_cast performs casts on polymorphic types and can cast a
A* pointer into a B* pointer only if the object being pointed to actually is a B object.
• reinterpret_cast<type> (expr) − The reinterpret_cast operator changes a pointer to
any other type of pointer. It also allows casting from pointer to an integer type and vice
versa.
• static_cast<type> (expr) − The static_cast operator performs a nonpolymorphic cast.
For example, it can be used to cast a base class pointer into a derived class pointer.
Example:
#include <iostream>
using namespace std;
int main()
{
float f = 3.5;

// using cast operator


int b = static_cast<int>(f);

cout << b;
}

Decision Making & Loops in C++


• Loops in C++
There may be a situation, when you need to execute a block of code several number of times.
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.

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.

Sr.No Loop Type & Description

1 while loop

Repeats a statement or group of statements while a given condition is true. It tests


the condition before executing the loop body.

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;

// while loop execution


while( a < 20 ) {
cout << "value of a: " << a << endl;
a++;
}

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 −

for ( init; condition; increment ) {


statement(s);
}
Here is the flow of control in a for loop −

• 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 –

C++ programming language provides following types of decision making statements.

Sr.No Statement & Description

1 if statement

An ‘if’ statement consists of a boolean expression followed by one or more


statements.

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).

5 nested switch statements


You can use one ‘switch’ statement inside another ‘switch’ 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;

// check the boolean condition


if( a < 20 ) {
// if condition is true then print the following
cout << "a is less than 20;" << endl;
}
cout << "value of a is : " << a << endl;

return 0;
}
When the above code is compiled and executed, it produces the following result −

a is less than 20;


value of a is : 10

• 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;

// check the boolean condition


if( a < 20 ) {
// if condition is true then print the following
cout << "a is less than 20;" << endl;
} else {
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;

return 0;
}
When the above code is compiled and executed, it produces the following result −

a is not less than 20;


value of a is : 100
• if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is very usefull
to test various conditions using single if...else if statement.

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;

// check the boolean condition


if( a == 10 ) {
// if condition is true then print the following
cout << "Value of a is 10" << endl;
} else if( a == 20 ) {
// if else if condition is true
cout << "Value of a is 20" << endl;
} else if( a == 30 ) {
// if else if condition is true
cout << "Value of a is 30" << endl;
} else {
// if none of the conditions is true
cout << "Value of a is not matching" << endl;
}
cout << "Exact value of a is : " << a << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −

Value of a is not matching


Exact value of a is : 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.


default : //Optional
statement(s);
}
The following rules apply to a switch statement −
• The expression used in a switch statement must have an integral or enumerated type,
or be of a class type in which the class has a single conversion function to an integral
or enumerated type.

• 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

• nested if-else statements


It is always legal to nest if-else statements, which means you can use one if or else if
statement inside another if or else if statement(s).

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;

// check the boolean condition


if( a == 100 ) {
// if condition is true then check the following
if( b == 200 ) {
// if condition is true then print the following
cout << "Value of a is 100 and b is 200" << endl;
}
}
cout << "Exact value of a is : " << a << endl;
cout << "Exact value of b is : " << b << endl;

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 −

double balance [] = {1000.0, 2.0, 3.4, 17.0, 50.0};


You will create exactly the same array as you did in the previous example.

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 () {

int n[ 10 ]; // n is an array of 10 integers

// initialize elements of array n to 0


for ( int i = 0; i < 10; i++ ) {
n[ i ] = i + 100; // set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;

// output each array element's value


for ( int j = 0; j < 10; j++ ) {
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}

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 −

Sr.No Concept & Description

1 Multi-dimensional arrays

C++ supports multidimensional arrays. The simplest form of the multidimensional


array is the two-dimensional array.

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.

3 Passing arrays to functions

You can pass to the function a pointer to an array by specifying the array's name
without an index.

4 Return array from functions

C++ allows a function to return an array.


Basics of Object Oriented Programming(OOP)
The major purpose of C++ programming is to introduce the concept of object orientation to
the C programming language. The programming paradigm where everything is represented as
an object is known as truly object-oriented programming language.
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming
is a methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
• Object

You might also like