C++ Tutorial
C++ Tutorial
C++ Tutorial
PROGRAMMING LANGUAGE
C++ HISTORY
APPLICATIONS
• Games
• GUI applications
• Web Browsers
• Compilers
• Operating Systems
1. Source Code: The user written codes, the standard and external libraries
2. Preprocessing: Outputs Intermediate Code with all header file contents along with source codes
3. Compiler: Converts higher level language to lower level language. E.g(GCC- GNU Compiler Collection)
Outputs the assembly code. Also check for formatting errors.
4. Assembler: Assembly Code to Object Code or Machine Code that the computer can understand
5. Linker: Links a set of generated object files(one for each source code) and standard and external
libraries and generate the executable file(.exe).
6. Loader: Loads the executable file in the memory(RAM)
7. Execution: To actually perform the required calculations and produce the result.
$ vi filename.cpp
• Press <insert> or <i> to enter the editing mode and write your code
#include <iostream>
int main() {
std::cout << "Hello World";
return 0;
}
$ g++ filename.cpp
$ ./a.out
• Output
Hello World
A BASIC C++ CODE STRUCTURE
#include <iostream>
int main() {
std::cout << "Hello World";
return 0;
}
• 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.
• The line int main() is the main function where program execution begins.
• The next line std::cout << "Hello World"; causes the message "Hello World" to be displayed on the screen.
cout refers to console output and std is a namespace(A group of predefined functions).
• The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.
Namespaces can be explicitly defined to avoid multiple uses. For example cin and cout both are defined in the
std namespace. So to take an input and print on screen we can use the std namespace as follows
#include <iostream>
int main() {
int age;
cout << "Please enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
#include <iostream>
int main() {
int age;
std::cout << "Please enter your age: ";
std::cin >> age;
std::cout << "Your age is: " << age << std::endl;
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.
x = y;
y = y + 1;
add(x, y);
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++ does not recognize the end of the line as a terminator. For this reason, it does not matter where you put a
statement in a line. For example −
x = y;
y = y + 1;
add(x, y);
is the same as
x = y; y = y + 1; add(x, y);
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, Manpower and manpower are two different identifiers in C++.
Here are some examples of acceptable identifiers −
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.
C++ COMMENTS
Program comments are explanatory statements that you can include in the C++ code. These comments help
anyone reading the source code. All programming languages allow for some form of comments. C++ supports
single-line and multi-line comments. All characters available inside any comment are ignored by C++ compiler
DATATYPES
• 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.
Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating
double
point
Valueless void
Wide character wchar_t
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.
The size of variables might be different from those shown in the above table, depending on the compiler and
the computer you are using.
Following is the example, which will produce correct size of various data types on your computer.
#include <iostream>
using namespace std;
int main() {
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}
This example uses endl, which inserts a new-line character after every line and << operator is being used to pass
multiple values out to the screen. We are also using sizeof() operator to get size of various data types.
When the above code is compiled and executed, it produces the following result which can vary from machine
to machine −
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4
TYPEDEF DECLARATIONS
You can create a new name for an existing type using typedef. Following is the simple syntax to define a new
type using typedef −
For example, the following tells the compiler that feet is another name for int −
Now, the following declaration is perfectly legal and creates an integer variable called distance −
feet distance;
ENUMERATED TYPES
An enumerated type declares an optional type name and a set of zero or more identifiers that can be used as
values of the type. Each enumerator is a constant whose type is the enumeration.
Creating an enumeration requires the use of the keyword enum. The general form of an enumeration type is −
Here, the enum-name is the enumeration's type name. The list of names is comma separated.
For example, the following code defines an enumeration of colors called colors and the variable c of type color.
Finally, c is assigned the value "blue".
By default, the value of the first name is 0, the second name has the value 1, and the third has the value 2, and
so on. But you can give a name, a specific value by adding an initializer. For example, in the following
enumeration, green will have the value 5.
enum color { red, green = 5, blue };
Here, blue will have a value of 6 because each name will be one greater than the one that precedes it.
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
definitions 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 −
For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all
bytes have the value 0); the initial value of all other variables is undefined.
• A variable declaration provides assurance to the compiler that there is one variable existing with the
given type and name so that compiler proceed for further compilation without needing complete detail
about the variable.
• A variable declaration has its meaning at the time of compilation only, compiler needs actual variable
definition at the time of linking of the program.
• A variable declaration is useful when you are using multiple files and you define your variable in one of
the files which will be available at the time of linking of the program.
• You will use extern keyword to declare a variable at any place. Though you can declare a variable
multiple times in your C++ program, but it can be defined only once in a file, a function or a block of
code.
EXAMPLE
Try the following example where a variable has been declared at the top, but it has been defined inside the main
function −
#include <iostream>
using namespace std;
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
f = 70.0/3.0;
cout << f << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following result −
30
23.3333
• lvalue − Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear
as either the left-hand or right-hand side of an assignment.
• rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is
an expression that cannot have a value assigned to it which means an rvalue may appear on the right-
but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and
so may not be assigned and can not appear on the left-hand side. Following is a valid statement −
g = 20;
h = g*2;
But the following is not a valid statement and would generate compile-time error −
10 = 20;
SCOPE OF A VARIABLE
A scope is a region of the program and broadly speaking there are three places, where variables can be declared
−
We will learn what is a function and it's parameter in subsequent chapters. Here let us explain what are local
and global variables.
LOCAL VARIABLES
Variables that are declared inside a function or block are local variables. They can be used only by statements
that are inside that function or block of code. Local variables are not known to functions outside their own.
Following is the example using local variables –
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
GLOBAL VARIABLES
Global variables are defined outside of all the functions, usually on top of the program. The global variables will
hold their value throughout the life-time of your program. A global variable can be accessed by any function.
That is, a global variable is available for use throughout your entire program after its declaration. Following is
the example using global and local variables −
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
A program can have same name for local and global variables but value of local variable inside a function will
take preference. For example −
#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main () {
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
When the above code is compiled and executed, it produces the following result −
10
INITIALIZING LOCAL AND GLOBAL VARIABLES
When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables
are initialized automatically by the system when you define them as follows −
It is a good programming practice to initialize variables properly, otherwise sometimes program would produce
unexpected result.
INTEGER LITERALS
• An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix:
0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
• An integer literal can also have a suffix that is a combination of U and L, for unsigned and long,
respectively. The suffix can be uppercase or lowercase and can be in any order.
• Here are some examples of integer literals −
212 // Legal
215u // Legal
0xFeeL // Legal
078 // Illegal: 8 is not an octal digit
032UU // Illegal: cannot repeat a suffix
85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsigned int
30l // long
30ul // unsigned long
FLOATING-POINT LITERALS
• A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You
can represent floating point literals either in decimal form or exponential form.
• While representing using decimal form, you must include the decimal point, the exponent, or both and
while representing using exponential form, you must include the integer part, the fractional part, or
both. The signed exponent is introduced by e or E.
• Here are some examples of floating-point literals −
3.14159 // Legal
314159E-5L // Legal
510E // Illegal: incomplete exponent
210f // Illegal: no decimal or exponent
.e55 // Illegal: missing integer or fraction
BOOLEAN LITERALS
• There are two Boolean literals and they are part of standard C++ keywords −
• A value of true representing true.
• A value of false representing false.
• You should not consider the value of true equal to 1 and value of false equal to 0.
CHARACTER LITERALS
• Character literals are enclosed in single quotes. If the literal begins with L (uppercase only), it is a wide
character literal (e.g., L'x') and should be stored in wchar_t type of variable . Otherwise, it is a narrow
character literal (e.g., 'x') and can be stored in a simple variable of char type.
• A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal
character (e.g., '\u02C0').
• There are certain characters in C++ when they are preceded by a backslash they will have special
meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of
such escape sequence codes −
#include <iostream>
using namespace std;
int main() {
cout << "Hello\tWorld\n\n";
return 0;
}
When the above code is compiled and executed, it produces the following result −
Hello World
STRING LITERALS
• String literals are enclosed in double quotes. A string contains characters that are similar to character
literals: plain characters, escape sequences, and universal characters.
• You can break a long line into multiple lines using string literals and separate them using whitespaces.
• Here are some examples of string literals. All the three forms are identical strings.
➢ "hello, dear"
➢ "hello, \
dear"
➢ "hello, " "d" "ear"
DEFINING CONSTANTS
• There are two simple ways in C++ to define constants −
• Using #define preprocessor.
• Using const keyword.
#include <iostream>
using namespace std;
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
When the above code is compiled and executed, it produces the following result −
50
#include <iostream>
using namespace std;
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
When the above code is compiled and executed, it produces the following result −
50
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ Program.
These specifiers precede the type that they modify. There are following storage classes, which can be used in a
C++ Program
• auto
• register
• static
• extern
• mutable
{
int mount;
auto int month;
}
The example above defines two variables with the same storage class, auto can only be used within functions,
i.e., local variables.
{
register int miles;
}
The register should only be used for variables that require quick access such as counters. It should also be noted
that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be
stored in a register depending on hardware and implementation restrictions.
The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to
be restricted to the file in which it is declared.
In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all
objects of its class.
include <iostream>
// Function declaration
void func(void);
main() {
while(count--) {
func();
}
return 0;
}
// Function definition
void func( void ) {
static int i = 5; // local static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is " << count << std::endl;
}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
When you have multiple files and you define a global variable or function, which will be used in other files also,
then extern will be used in another file to give reference of defined variable or function. Just for understanding
extern is used to declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing the same global variables
or functions as explained below.
main() {
count = 5;
write_extern();
}
void write_extern(void) {
std::cout << "Count is " << count << std::endl;
}
Here, extern keyword is being used to declare count in another file. Now compile these two files as follows −
This will produce write executable program, try to execute write and check the result as follows −
$./write
5
THE MUTABLE STORAGE CLASS
The mutable specifier applies only to class objects, which are discussed later in this tutorial. It allows a member
of an object to override const member function. That is, a mutable member can be modified by a const member
function.
OPERATORS
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 −
RELATIONAL OPERATORS
There are following relational operators supported by C++ language
LOGICAL OPERATORS
There are following logical operators supported by C++ language.
BITWISE OPERATORS
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows
−
p q p & qp | qp ^ q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table. Assume variable A holds 60
and variable B holds 13, then −
MISC OPERATORS
The following table lists some other operators that C++ supports.
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.
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
LOOPS
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 −
WHILE LOOP
A while loop statement repeatedly executes a target statement as long as a given condition is true.
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.
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
return 0;
}
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.
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
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.
• 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.
#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
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.
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.
#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
NESTED LOOPS
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.
while(condition) {
while(condition) {
statement(s);
}
statement(s); // you can put more statements.
}
do {
statement(s); // you can put more statements.
do {
statement(s);
} while( condition );
} while( condition );
The following program uses a nested for loop to find the prime numbers from 2 to 100 −
#include <iostream>
using namespace std;
int main () {
int i, j;
return 0;
}
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
LOOP CONTROL STATEME NTS
Loop control statements change execution from its normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed.
BREAK
The break statement has the following two usages in C++ −
When the break statement is encountered inside a loop, the loop is immediately terminated and program
control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of
the innermost loop and start executing the next line of code after the block.
break;
#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;
if( a > 15) {
// terminate the loop
break;
}
} 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
CONTINUE STATEMENT
The continue statement works somewhat like the break statement. Instead of forcing termination, however,
continue forces the next iteration of the loop to take place, skipping any code in between.
For the for loop, continue causes the conditional test and increment portions of the loop to execute. For the
while and do...while loops, program control passes to the conditional tests.
continue;
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution
do {
if( a == 15) {
// skip the iteration.
a = a + 1;
continue;
}
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: 16
value of a: 17
value of a: 18
value of a: 19
GOTO STATEMENT
A goto statement provides an unconditional jump from the goto to a labeled statement in the same function.
NOTE − Use of goto statement is highly discouraged because it makes difficult to trace the control flow of a
program, making the program hard to understand and hard to modify. Any program that uses a goto can be
rewritten so that it doesn't need the goto.
goto label;
..
.
label: statement;
Where label is an identifier that identifies a labeled statement. A labeled statement is any statement that is
preceded by an identifier followed by a colon (:).
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a = 10;
// do loop execution
LOOP:do {
if( a == 15) {
// skip the iteration.
a = a + 1;
goto LOOP;
}
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: 16
value of a: 17
value of a: 18
value of a: 19
One good use of goto is to exit from a deeply nested routine. For example, consider the following code fragment
−
for(...) {
for(...) {
while(...) {
if(...) goto stop;
.
.
.
}
}
}
stop:
cout << "Error in program.\n";
Eliminating the goto would force a number of additional tests to be performed. A simple break statement would
not work here, because it would only cause the program to exit from the innermost loop.
#include <iostream>
using namespace std;
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment
expression, but C++ programmers more commonly use the ‘for (;;)’ construct to signify an infinite loop.
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
−
IF STATEMENT
#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
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
return 0;
}
OUTPUT:
return 0; return 0;
} }
OUTPUT: OUTPUT:
int main () {
// local variable declaration:
char grade = 'D';
switch(grade) {
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
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;
}
OUTPUT :
You passed
Your grade is D
THE ? : OPERATOR
We have covered conditional operator “? :” in previous chapter which can be used to replace if...else statements.
It has the following general form −
Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ‘?’ expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and
becomes the value of the entire ‘?’ expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the
value of the expression.