Unit-2
C++ Language Basics
SUSHANT BHATTARAI
Prepared By: Sushant Bhattarai
About this chapter 2
This chapter deals with fundamental things that
you need to know before you start writing
programs.
Basic Program 3
Construction
#include <iostream>
using namespace std;
int main()
{
cout<< “Hello World\n”;
return 0;
}
Basic Program 4
Construction
Basic Program Construction- Functions 5
Functions are one of the fundamental building
blocks of C++.
The above program consists of a function called
main().
The brackets following the word main are the
distinguishing feature of a function.
Without the bracket the compiler would think that
main might be a variable.
Basic Program Construction- Functions 6
You must give braces ({ }) to signify body of a
function.
Always start with main().
If there is no function called main() in your
program, an error will be signaled.
Basic Program Construction- Program 7
Statements
cout<<“ Hello world\n”;
It tells the computer to display the quoted phrase.
A semicolon; signifies the end of statement.
The last statement is return 0;
This is because the type of main is int.
Basic Program Construction- whitespace 8
White space is ignored by C++ compiler.
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World\n";
return 0;
}
Basic Program Construction-String Constants 9
“Hello World” is an example of a string constant.
Basic Program Construction-Directives 10
The two lines that begin the program are
directives.
The first is a preprocessor directive, and
the second is a using directive.
#include tells the compiler to add the
source file IOSTREAM to the file before
compiling.
Second is called using directive which
specifies namespace.
Some Programs-1 11
#include <iostream>
using namespace std;
int main()
{
int a,b;
cout<<“Enter two numbers”<<endl;
cin>>a>>b;
cout<<“The sum is”<<a+b;
return 0;
}
Some Programs-2 12
#include <iostream>
using namespace std;
Int main()
{
char msg[20];
cout<<“Enter a some text:”;
cin>>msg;
cout<<“ Your message is :”<<msg;
return 0;
}
Some Programs-3 13
#include <iostream>
using namespace std;
int main()
{
int a,b,c;
cout<<“Enter two numbers”<<endl;
cin>>a>>b;
c=a+b;
cout<<“The sum of ”<<a<<“ and ”<<b<<“ is: ”<<c;
return 0;
}
2.1 Character set, tokens (keywords,
identifiers, operators)
SUSHANT BHATTARAI
Tokens 15
The basic elements recognized by
C++ compiler are called tokens.
A token does not break down into
component elements by the
compiler.
Keywords, constants, identifiers,
string, operators, special symbols.
Identifier 16
Every word used in C++ program to
identify name of variables, functions,
classes, arrays, pointers etc. are known as
identifiers.
The rules for naming identifiers are-
1. It must be combination of letters and
digits and must begin with a letter.
2. Underscore is permitted between two
words, but white space is not allowed.
3. Keywords cannot be used
4. Can be 31 characters.
Keywords 17
Keywords are predefined or
reserved words.
Example: long, char, do, goto, void
etc..
Operators 18
are those entities that perform an
operation on an operands.
Are of several types like
1. Arithmetic operators
2. relational
Arithmetic Operators 19
1. +
2. -
3. *
4. /
5. %
20
Arithmetic Assignment Operators
1. a += b is same as a = a + b
2. a *= b is same as a = a*b
3. a -= b is same as a = a – b
4. a /= b is same as a = a/b
5. a %= b is same as a = a % b
21
Increment Operators
Pre increment and post increment.
The use of ++i and i++ is same as i=i+1
22
Increment Operators
23
Increment Operators
Relational Operators 24
1. > greater than
2. < less than
3. == equal to
4. != not equal to
5. >= greater than or equal to
6. <= less than or equal to
Relational Operators 25
Relational Operators 26
Logical Operators 27
1. AND &&
2. OR ||
3. NOT !
Logical Operators 28
Logical Operators 29
Conditional Operator 30
Conditional Operator 31
2.2 Commenting
SUSHANT BHATTARAI
Comments 33
//This is single line comment.
/*this
Is a multi line
comment
*/
Comments 34
//Created by Sushant Bhattarai
/*m
u
l
t
i
*/
#include <iostream>
using namespace std;
int main()
{
cout<<"Hello World"<<endl;
return 0;
}
2.3 Variable Declaration
SUSHANT BHATTARAI
Variables Declaration 36
Any variable must be defined before using it in a
program.
Syntax: data-type var1,var2,…varN;
int n1;
int centi,temp;
float radius;
char gender;
Some rules for declaring a 37
variable
The variable name should start with only letters or
underscore. int a; int _a;
The variable name should not be keyword.
White spaces are not allowed before, between
characters of variables.
The variable name is case sensitive.
Example 38
#include <iostream>
using namespace std;
int main()
{
string a;
string b;
cout<<"Enter your first name"<<endl;
cin>>a;
cout<<"Enter your surname"<<endl;
cin>>b;
cout<<"How You Doin’? "<<a+b<<endl;
return 0;
}
Example 39
Constants 40
Constants refer to fixed values that do not
change during the execution of a program.
We can defined constants in two ways.
1. Defined Constant(using define keyword)
2. Declared Constant(using const keyword)
Defined Constant 41
We can define our own names for constants by
using #define.
#define const_name value
#define pi 3.14
#define g 9.8
Example 42
#include <iostream>
#define pi 3.14
using namespace std;
int main()
{
float r,a;
cout<<“ Enter Radius”<<endl;
cin>>r;
a=pi*r*r;
cout<<“ The area is ”<<a;
return 0;
}
Declared Constant 43
Use const prefix
const float PI = 3.14
This kind of constant is effective because you can
use it in a particular scope.
Example 44
#include <iostream>
using namespace std;
int main()
{
float r;
const float pi=3.14;
cout<< "ENTER A RADIUS "<<endl;
cin>>r;
cout<<"The area is "<<pi*r*r<<endl;
return 0;
}
3.4 Data Type
SUSHANT BHATTARAI
Data Type 46
There are various types of data.
While writing, we store variables in our computer’s
memory.
But computer has to know what kind of data we
want to store in them as it is not going to occupy
same amount of memory.
The different data types supported by C++ can
be summarized as below.
Data Type 47
Name Description Memory Size Range
char character 1 Byte -128 to 127
short short integer 2 Bytes signed:-32768 to
32767
unsigned: 0 to
65535
long long integer 4 Bytes -2147483648 to
2147483647
float floating point 4 Bytes +/- 3.4e+/-38
number
double double 8 Bytes +/-1.7e+/-308
precision
floating point
number
long double long double 10 Bytes 3.4e-4932 to
precision 1.1e+4932
Some Programs-4 48
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float a,b;
cout<<" ENTER NUMBER "<<endl;
cin>>a>>b;
cout<<"The sum is "<<a+b<<endl;
cout<<"The difference is "<<a-b<<endl;
cout<<"The product is "<<a*b<<endl;
cout<<"The quotient is "<<a/b<<endl;
return 0;
}
Some Programs-5 49
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float r;
cout<<" ENTER A RADIUS "<<endl;
cin>>r;
cout<<"The area is "<<(22/7)*r*r<<endl;
return 0;
}
3.5 Type Conversion and
promotion rules
SUSHANT BHATTARAI
Type Conversion 51
int, float, double, long, long double, char etc are
fundamental data types.
We can convert one basic data type into
another.
There are two types of conversion.
1. Implicit Type Conversion(Automatic Conversion)
2. Explicit Type Conversion(Typecasting)
Implicit Type Conversion 52
do not require any operator and it is performed
by compiler itself.
In an expression, if we try to evaluate two or more
data items of different type, then one type should
be converted into another(i.e lower into higher)
before result is calculated.
char, short, int, long, float , double ,
long double
Lower type Higher type
Implicit Type Conversion 53
#include <iostream>
numi=num;//type conversion
#include <cmath>
a=ai;
#include <windows.h> cout<<"Value as short type: "<<num<<endl;
using namespace std; cout<<"Value as int type: "<<numi<<endl;
int main() cout<<a<<endl;
{ cout<<ai<<endl;
return 0;
int a;
}
float ai=3.14;
short num=200;
int numi;
cout<<"Hello"<<endl;
system("cls");
Implicit Type Conversion 54
Explicit Type Conversion 55
Also called typecast.
Performed by programmer as per need
Either type_name(expression)
Or, (type_name)expression
Example: We are converting int to float.
Explicit Type Conversion 56
Explicit Type Conversion 57
3.6 Input/output basics
SUSHANT BHATTARAI
Output using cout 59
cout<<“ Hello World \n”;
cout is an object defined in standard
output stream.
The operator <<(insertion) directs the
content to the object on the left.
Input using cin 60
cin>>a;
cin is an object defined in standard input
stream.
Causes the program to wait for the user
to type in a number.
It will be saved in a and the object cin
will take the value from the stream object
and places it in the variable on the right.
3.7 Preprocessor directives
SUSHANT BHATTARAI
Preprocessor directives 62
A preprocessor directive is an instruction to the
compiler.
A part of the compiler called the preprocessor
deals with these directives before it begins the
real compilation process.
Are usually signified by #.
3.8 Control Structures
SUSHANT BHATTARAI
Loops 64
Loops cause a section of your program to be
repeated a certain number of times.
The repetition continues while a condition is true.
3 kinds of loop.
1. The for Loop
2. The while Loop
3. The do Loop
The for Loop 65
The for loop executes a section of code a
fixed number of times.
The syntax is
The for Loop 66
The for Loop 67
The while Loop 68
The while Loop is used when you don’t
know how many times something is to be
repeated before hand.
The while Loop 69
The while Loop 70
Debug the above example if any error is present
The do Loop 71
The do while Loop is used when you don’t know how
many times something is to be repeated before
hand but at least want to make sure the body runs
one time.
The do Loop 72
The do Loop 73
When to use which loop? 74
When to use for loop?
When to use while loop?
When to use do loop?
The if Statement 75
The if Statement 76
The if Statement 77
Prime or composite? 78
The if..else Statement 79
Even or Odd? 80
Count number of Words 81
Nested if..else statements 82
Nested if..else statements 83
The switch Statement 84
The switch Statement 85
The switch Statement 86
The Conditional Operator 87
3.9 Array, Pointer, String
SUSHANT BHATTARAI
Array 89
In real life we commonly group similar objects into
units.
In computer array hold the data items of the
same type.
An array is a collection of similar objects.
datatype array_name[size_of_array]
Array Example-1 90
A simple example
Array 91
Defining Array 92
Defining Array 93
Array Example-2 94
for(i=0;i<4;i++)
#include <iostream> {
cout<<"ENTER NAME: ";
#include <iomanip>
cin>>name[i];
using namespace std; cout<<"ENTER ADDRESS:";
cin>>address[i];
}
int main()
cout<<"NAME"<<setw(12)<<"ADDRESS"<<endl;
{
for(i=0;i<4;i++)
int i; {
const int size=4; cout<<name[i]<<setw(8)<<address[i]<<endl;
}
string return 0;
name[size],address[size]; }
Array Example-2 95
Initializing Array 96
Initializing Array 97
Multidimensional Array 98
datatype array_name[size1][size2]
Multidimensional Array 99
10
Multidimensional Array 0
10
String 1
String are the array of characters.
String are used by C++ to manipulate text such as
words and sentences.
A string is terminated by a null character that is \0
10
Initializing Strings 2
char name[ ] = {‘R’, ‘A’, ‘M’,’\0’};
char name[ ] = “RAM”;
10
Initializing Strings 3
10
Initializing Strings 4
10
String Handling Functions 5
Functions used to manipulate strings are:
strlen()
strcpy()
strcat()
strcmp()
strrev() etc
10
strlen() 6
Returns length of string.
Integer_variable = strlen(string)
10
strlen() 7
10
strlen() 8
10
strcpy() 9
Copies one string to another.
strcpy(destination_string, source_string)
11
strcpy() 0
11
strcpy() 1
11
strcat() 2
Appends one string at the end of the another.
strcat(string1,string2);
string1=string1+string2
11
strcat() 3
11
strcat() 4
11
strcmp() 5
Compares 2 string
Accepts two strings as a parameter and returns
1. Less than 0 if the first string is less than the second
2. 0 if the first string if both are same
3. More than 0 if the first string is more than the
second
11
strcmp() 6
11
strcmp() 7
11
strcmp() 8
11
strcmp() 9
12
strrev() 0
Is used to reverse a string
strrev(string);
12
strrev() 1
12
strrev() 2
12
Reading embedded blanks 3
We can read blanks using get() function of cin
object.
cin.get(string_name,size,character_end)
character_end is optional
character_end by default is ‘\n’
12
Reading embedded blanks 4
12
Reading embedded blanks 5
12
Reading embedded blanks 6
We can also use getline function of cin object.
12
Reading embedded blanks 7
12
Reading embedded blanks 8
12
get() Vs getline() 9
When get() encounters delimiter it doesn’t
removes it from the buffer.
getline() extracts(removes) the delimeter from the
buffer.
13
get() Vs getline() 0
13
get() Vs getline() 1
13
get() Vs getline() 2
13
get() Vs getline() 3
13
Pointers 4
A pointer is a variable that contains a
memory address of another variable.
Eg
int num;
int *p;
p=#
& is called reference operator used to
get address of a vaiable.
* is called dereference operator used
to get value pointed by the pointer
13
Pointers 5
13
Pointers 6
13
Reference Variable 7
A reference variable is an alias for a variable.
It is like a pointer with a few differences.
It is declared using & operator.
Syntax
data_type& ref_variable = var;
13
Reference Variable 8
13
Reference Variable 9
14
Pointer Vs. Reference 0
Variable
A pointer can be re-assigned any number of times
while a reference can’t be reassigned after
initialization.
References cannot be null whereas pointers can.
3.10 Dynamic memory
allocation
SUSHANT BHATTARAI
14
Dynamic memory 2
allocation
The process of allocating and freeing memory at
runtime is called DMA.
This is advantageous as memory is used efficiently.
Memory can be shrinked as well as expanded.
14
new operator 3
Used to request dynamic memory.
Syntax:
pointer_variable = new DataType;
Eg:-
int *p,*q
p = new int;
q = new int[10];
14
delete operator 4
Used to free the reserved memory.
Syntax:
delete pointer_variable;
delete []pointer_variable;
14
Example 5
#include <iostream>
#include <iomanip> for(i=0;i<n;i++)
using namespace std; {
cin>>*(p+i);
sum=sum+*(p+i);
int main() }
{ avg=sum/n;
int n,i; cout<<endl;
float *p,sum=0,avg; cout<<"THE AVERAGE MARKS
OF ";
cout<<"ENTER THE NUMBER OF
STUDENTS: "; for(i=0;i<n;i++)
cin>>n; cout<<setw(3)<<*(p+i);
cout<<" is: "<<avg<<endl;
p = new float[n];
delete []p;
cout<<"ENTER MARKS OF "<<n<<" return 0;
STUDENTS"<<endl;
}
14
Example 6
3.11 Functions
SUSHANT BHATTARAI
14
What is Function? 8
#include <iostream>
z=add(x,y);
using namespace std;
cout<<"THE SUM IS
int add(int a,int b); "<<z<<endl;
return 0;
int main() }
{ int add(int a,int b)
{
int x,y,z;
return a+b;
cout<<"ENTER TWO }
NUMBERS"<<endl;
cin>>x>>y;
14
What is function? 9
A function is defined as a self-
contained block of statements that
performs a particular task or job.
Advantages of function
1. Manageability.
2. Code Reusability.
3. Non –redundant Programming.
4. Logical Clarity.
5. Modularity.
15
Examples 0
15
Examples 1
15
Function Declaration 2
int add(int a, int b); is declaration.
a and b are parameters.
15
Calling the Function 3
z=add(x,y); is calling part.
Or, you can write cout<<“THE SUM
IS”<<add(x,y)<endl
15
Function Definition 4
15
Passing arguments 5
3 types.
1. Passing arguments as constants.
2. Passing arguments by value.
3. Passing arguments by address(Function Call by
reference)
15
Passing constants 6
15
Passing Values 7
15
8
Pass by address(call by
reference)
In this kind of function call, the address of variable
is passed to the function as argument instead of
actual value of variable.
The reference variable is used for call by
reference.
15
9
Pass by address(call by
reference)
16
0
Pass by address(call by
reference)
16
Without return 1
16
Returning by value 2
16
3
Function overloading
Overloading is like the joke about the famous
scientist who insisted that the thermos bottle was
the greatest invention of all time.
Why? “It’s a miracle device”, he said.
“It keeps hot things hot and cold things cold. How
does it know?”
16
4
Function overloading
An overloaded function appears to perform
different activities depending on the kind of data
sent to it.
We can have two function with the same name
but different in either number of arguments or
type of arguments. The correct version of function
is called based on nature of argument. This is
called Function overloading.
16
Types of function 5
overloading.
1. Different number of Arguments.
2. Different types of Arguments.
16
Different number of 6
Arguments
We can define more than one function with same
name but different number of arguments.
16
Different number of 7
Arguments
16
Different number of 8
Arguments
16
Different type of 9
arguments
We can define more than one function with same
name but different type of argument.
17
Different type of 0
arguments
17
Different type of 1
arguments
17
2
Inline function
Call and return take time.
So, to save execution time we put the code in the
function body directly inline with the code in the
calling program.
It is called inline function.
We use inline keyword in the function definition.
17
3
Inline function
17
4
Inline function
17
5
Default argument
Sometimes, a function can be called without
specifying all it’s argument.
The function definition must provide default values
for those arguments that are not specified.
17
6
Default argument
17
7
Default argument
17
Passing array to a function 8
For function call passing array as an argument.
function_name(array_name)
For declaring
datatype function_name(data_type array_name[]);
17
example 9
18
output 0
3.13 Structure and Unions
SUSHANT BHATTARAI
18
Structures 2
Simple variables are organized into more complex
structure.
entities using
A structure is a collection of
simple variables.
The variables in a structure
can be of different types.
The data items are called the members of the
structure.
18
Structures Example 3
18
Structures Example 4
18
Declaring Structures 5
struct part
{
int modelnumber;
float cost;
};
18
Defining a Structure 6
Variable
18
Accessing Structure 7
Members
part1.modelnumber;
part1.cost;
18
Initializing Structure 8
part part1={101,200000};
18
Another Example 9
19
Another Example 0
19
Another Example 1
19
Array of Structures 2
Arrays can contain structures as well as
simple types.
19
Array of Structures 3
19
Array of Structures 4
19
Array of Structures 5
19
Common Escape 6
Sequences
19
Enumerators 7
It refers to numbered list.
Can create our own data type.
Are declared using enum keyword.
19
Enumerators 8
19
Enumerators 9
20
Review Questions 0
1. What is function overloading? Explain with a
simple program.[5+5]