0% found this document useful (0 votes)
137 views

OOP - C++ Programming Basics-1

This document provides an overview of key concepts in C++ programming including: 1) It discusses the structure of a basic C++ program including headers, namespaces, main functions and input/output streams. 2) It covers basic C++ constructs like variables, functions, parameters, return types, and comments. 3) It explains important concepts like the input and output operators, escape sequences, and character sets used in C++.

Uploaded by

Sourin Sarkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views

OOP - C++ Programming Basics-1

This document provides an overview of key concepts in C++ programming including: 1) It discusses the structure of a basic C++ program including headers, namespaces, main functions and input/output streams. 2) It covers basic C++ constructs like variables, functions, parameters, return types, and comments. 3) It explains important concepts like the input and output operators, escape sequences, and character sets used in C++.

Uploaded by

Sourin Sarkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

OOP (IT-2001)

KALINGA INSTITUTE OF INDUSTRIAL


TECHNOLOGY

School of Computer Engineering

Strictly for internal circulation (within KIIT) and reference only. Not for outside circulation without permission

Lecture Note
3 Credit Mr. Rajat Behera - Associate Professor
Course Contents
2

Sr # Major and Detailed Coverage Area Hrs


2 C++ Programming basics 6
• Review of fundamental constructs of C used in C++ : Character
set, Keyword, Constant, Variable, Data types, operator & expression,
control structure (branching & looping), typecasting, array & strings
• C++ Programming basics: Streams based I/O (Input with cin,
Output using cout), Type bool, The setw manipulator, Type conversions,
strict type checking, name space, scope resolution operator (::)
• Variables: Scope & lifetime of variables, variable declaration at the
point of use, Ordinary Variable Vs. Pointer Variable Vs. Reference
Variable (variable aliases)
• Function: Parameter passing by value Vs. by address Vs. by
reference, inline function, function overloading, default arguments.

School of Computer Engineering


C++ Program Structure
3

Let us look at a simple code that would print the words Hello World.
The C++ language defines
#include <iostream> several headers, which contain
information that is either
using namespace std;
necessary or useful to the
program. For this program, the
// main() is where program header <iostream> is needed.
//execution begins.
The line using namespace std tells
int main() {
the compiler to use the std
// prints Hello World namespace. Namespaces are a
cout << "Hello World"; relatively recent addition to C++
return 0; The line int main() is the main
} function where program execution
cout << " Hello World " causes
begins.
Terminates the the message " Hello World " to be
program displayed on the screen.

School of Computer Engineering


Structure of the C++ Program
4

Preprocessor directive section

Global Declaration section

Class definition and method definition section

main method

Method definition section

School of Computer Engineering


C++ Program Compilation and Execution
5

Compilation Run
g++ filename.cpp ./a.out
E.g. g++ hello.cpp
Compilation and Execution Process

Source Object
Compiler
Files Files

Library
Files
Executable
Linker
Files

School of Computer Engineering


Files used in C++ Program
6

Files in C++ Program

Source Files Header Files Object Files Executable Files

 Source Files – Contains source code of the program whose extension is .cpp
and contains main and other functions.
 Header Files – Make the subroutines and store them in header file.
 Object Files – Generated by compiler after processing the source code file. It
contain a compact binary code of the function definition. The linker uses
this object file to produce an executable file by combining the object files
together. Generally, it have .obj extension
 Binary Executable Files – Generated by Linker. The linker links the various
object files to produce a binary file that can be directly executed.

School of Computer Engineering


Input/Output Operator
7

In C++, input and output (I/O) operators are used to take input and
display output. The operator used for taking the input is known as
the extraction or get from operator (>>), while the operator used
for displaying the output is known as the insertion or put to
operator (<<).
Input Operator - The input operator, commonly known as the
extraction operator (>>), is used with the standard input stream,
cin. cin treats data as a stream of characters. These characters flow
from cin to the program through the input operator. The input
operator works on two operands, namely, the c in stream on its left
and a variable on its right. Thus, the input operator takes
(extracts) the value through cin and stores it in the variable.

School of Computer Engineering


Input Operator Example
8

To understand the concept of an input operator, consider this example.

#include<iostream>
using namespace std;

int main ()
{
int a;
cin>>a;
a = a+1;
return 0;
}

In this example, the statement cin>> a takes an input from the user and stores it
in the variable a.

School of Computer Engineering


Output Operator
9

The output operator, commonly known as the insertion operator (<<), is used.
The standard output stream cout Like cin, also treats data as a stream of
characters. These characters flow from the program to cout through the output
operator. The output operator works on two operands, namely, the cout stream
on its left and the expression to be displayed on its right. The output operator
directs (inserts) the value to cout. A program to demonstrate the working of an
output operator.
#include<iostream>
using namespace std;
int main ()
{
int a;
cin>>a;
a=a+1;
cout<<a;
return 0;
} School of Computer Engineering
Cascading of Input/Output Operators
10

The cascading of the input and output operators refers to the consecutive
occurrence of input or output operators in a single statement. A program with
cascading of the input/output operator is as follows

#include<iostream>
using namespace std;

int main ()
{
int a, b;
cin>>a>>b;
cout<<"The value of b is : "<<b;
cout<<“\nThe value of a is : "<<a;
return 0;
}

School of Computer Engineering


Comments
11

Comments are portions of the code ignored by the compiler which allow the user
to make simple notes in the relevant areas of the source code. Comments come
either in block form or as single lines. C++ supports two types of commenting –
 Single-line comments (informally, C++ style), start with // and continue until
the end of the line. If the last character in a comment line is a \ the comment
will continue in the next line.
 Multi-line comments (informally, C style), start with /* and end with */.
Example:
/* This is a single line comment */

/*
This is a multiple line comment
*/

School of Computer Engineering


Escape Sequence
12

An escape sequence is a combination of characters that is translated into another


character or sequence of characters that may be difficult or impossible to
represent directly. Similar to new line character, other escape sequences
supported by C++ is presented below.
Escape Sequence Purpose Escape Sequence Purpose
\r carriage return \' single quote
\b backspace \\ backslash
\a audible bell \f form feed - new page
\t horizontal tab \O Octal constant
\v vertical tab \x Hexadecimal constant
\n line feed - new line
\? question mark
\" double quote

School of Computer Engineering


C++ Character Set
13

Character set is a set of valid characters that a language can recognize. A


character represents any letter, digits, or any other sign. C++ has the following
character set :
 Letters : A-Z, a-z
 Digits : 0-9
 Special Symbols : Space + - ∗ ⁄ ^ \ ( ) [ ] { } = != < > . ′ ″ $ , ; : % ! & _ # <= >= @
 White Spaces : Blank space, Horizontal tab (→), Carriage return (↵), Newline, Form
feed
 Other Characters: C++ can process any of the 256 ASCII characters as data or as
literals.
Class Work
1. WAP to add two numbers. 5. WAP to calculate the area of the triangle
2. WAP to check even or odd using Heron’s formula.
3. WAP to find factorial of number
4. WAP to swap two numbers
School of Computer Engineering
C++ Keyword
14

Keywords are the words that convey a special meaning to the language compiler.
These are the reserved words for special purpose and must not be used as
normal identifier names.

Identifiers containing a double underscore (_ _) are reserved for use by C++


implementations and standard libraries and should be avoided by users.

School of Computer Engineering


C++ Constant
15

Constants are the data items that never change their value during a program run.
Following is an example program of C++ constants :

/* C++ Constants or Literals Example */

#include<iostream>
using namespace std;

int main()
{
const int num=10;
cout<<"The constant integer value is "<<num;
return 0;
}

School of Computer Engineering


C++ Variable
16

A variable provides us with named storage that our programs can manipulate.
Each variable in C++ has a specific type, which determines the size and layout of
the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and
lowercase letters are distinct because C++ is case-sensitive
Sr# Type Description
1 bool Stores either value true or false.
2 char Typically a single octet (one byte).
3 int The most natural size of integer for the machine.
4 float A single-precision floating point value.
5 double A double-precision floating point value.
6 void Represents the absence of type.

School of Computer Engineering


Variable Declaration
17

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

School of Computer Engineering


C++ Data Types
18

While writing program in any language, various variables to be used to store


various information. Variables are nothing but reserved memory locations to
store values. This means that when a variable is created, reserve some space in
memory to be reserved.
Primitive Built-in Types Type Modifiers

Sr# Type Keyword Several of the basic types can be


1 Boolean bool modified using one or more of these
2 Character char type modifiers −
3 Integer int
 signed
4 Floating point float
 unsigned
5 Double floating point double
 short
6 Valueless void
 long
7 Wide character wchar_t

School of Computer Engineering


C++ Operator and Expression
19

C++ Operator - 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
C++ Expression - An expression is a sequence of operators and their operands,
that specifies a computation.

School of Computer Engineering


Control Structure (branching)
20

Decision making structures (branching) 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 −
Sr# Statement Description

1 if An ‘if’ statement consists of a boolean expression followed by


one or more statements.
2 If … else An ‘if’ statement can be followed by an optional ‘else’ statement,
which executes when the boolean expression is false.
3 switch A ‘switch’ statement allows a variable to be tested for equality
against a list of values.
4 nested if use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’
statement(s).
5 ? : Operator Exp1 ? Exp2 : Exp3; 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.

School of Computer Engineering


Control Structure (looping)
21

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 −
Sr# Loop Type Description

1 while Repeats a statement or group of statements while a given


condition is true. It tests the condition before executing the loop
body.
2 for Execute a sequence of statements multiple times and abbreviates
the code that manages the loop variable.
3 switch A ‘switch’ statement allows a variable to be tested for equality
against a list of values.
4 do … while Like a ‘while’ statement, except that it tests the condition at the
end of the loop body.
5 nested use one or more loop inside any another ‘while’, ‘for’ or
‘do..while’ loop.

School of Computer Engineering


Looping Control Statements
22

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. C++ supports the following control statements.

Sr# Control Statement Description


1 break Terminates the loop or switch statement and
transfers execution to the statement immediately
following the loop or switch.
2 continue Causes the loop to skip the remainder of its body
and immediately retest its condition prior to
reiterating.
3 goto Transfers control to the labeled statement. Though
it is not advised to use goto statement in your
program.

School of Computer Engineering


Typecasting
23

Converting an expression of a given type into another type is known as type-


casting.
Implicit conversion Explicit conversion

Implicit conversions do not require any C++ is a strong-typed language. Many


operator. They are automatically conversions, specially those that imply
performed when a value is copied to a a different interpretation of the value,
compatible type. require an explicit conversion.
For example: For example:
short a=2000; short a=2000;
int b; int b;
b=a; b = (int) a; // c-like cast notation
b = int (a);

School of Computer Engineering


Arrays
24

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, declare one array variable can be declared 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.

School of Computer Engineering


1-D Array Declaration, Initialization & Access
25

Array Declaration Accessing Array Element


When declaring arrays, specify -
 Name
 Type of array
 Number of elements An element is accessed by indexing the array
i.e. arrayType arrayName[ numberOfElements ]; name. This is done by placing the index of the
Examples - int c[ 10 ] or float myArray[ 3284 ]; element within square brackets after the name
of the array. For example −
 Declaring multiple arrays of same type -
int c[10], x [27]; double salary = balance[3];

Array Initialization
Compile Time: Run Time:

int num[6] = { 2, 4, 12, 5, 45, 5 } ; float sum[100] ; float sum[100] ;


int n[ ] = { 2, 4, 12, 5, 45, 5 } ; for (i=0; i<100;++i) for (i=0; i<100;++i)
float press[ ] = { 12.3, 34.2, -23.4, -11.3 } ; { {
sum[i] = 0.0; cout<<sum[i];
} }

School of Computer Engineering


Simple Program Using Array
26

Program to find average marks obtained by a class of 30 students in a test.


int main( )
{
int avg, sum = 0 ;
int i ;
int marks[30] ; /* array declaration */
for ( i = 0 ; i <= 29 ; i++ )
{
cout<<“\nEnter marks of student ” << i+1 <<“:” ) ;
cin>>marks[i]; /* store data in array */
}
for ( i = 0 ; i <= 29 ; i++ )
{
sum = sum + marks[i] ; /* read data from an array*/
}
avg = sum / 30 ;
cout<<"\nAverage marks = “<< avg ;
return 0;
}

School of Computer Engineering


Two Dimensional Array
27

So far we have explored arrays with only one dimension. It is also possible for arrays to
have two or more dimensions. The two dimensional array is also called a matrix.
Array Declaration Array Representation & Memory Map
When declaring 2-D arrays, specify - int a[4][3];
 Name Column 0 Column 1 Column 2
 Type of array Row 0 a[0][0] a[0][1] a[0][2]
 Number of elements Row 1 a[1][0] a[1][1] a[1][2]
Examples - int c[10][10]; Row 2 a[2][0] a[2][1] a[2][2]
Row 3 a[3][0] a[3][1] a[3][2]
float myArray[3284][100];
a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] a[3][0] a[3][1] a[3][2]
NOTE - number of elements are declared twice. First one for row
and other for column 1000 1002 1004 1006 1008 1010 1012 1014 1016 1018 1020 1022

Accessing Array Element


An element is accessed by indexing the array name. This is done by placing two index of
the element within square brackets after the name of the array. For example a 2D array
declaration is double a[3][3], then the element can be accessed -
double b = a[1][1];

School of Computer Engineering


Initializing Two Dimensional Array
28

Compile Time: Run Time:


int stud[4][2] = {
{ 1234, 56 }, int stud[4][2]; int stud[4][2];
{ 1212, 33 }, for (i=0; i<4;++i) for (i=0; i<4;++i)
{ {
{ 1434, 80 },
for (j=0; j<2;j++) for (j=0; j<2;j++)
{ 1312, 78 } cin>>stud[i][j];
stud[i][j] = 0;
}; }
}
or even this would work...
int stud[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;

It is important to remember that while initializing a 2-D array it is necessary to


mention the second (column) dimension, whereas the first dimension (row) is
optional. Thus the declarations shown on left are perfectly acceptable, but not the right.

 int arr[2][3] = { 12, 34, 23, 45, 56, 45 } ;  int arr[2][ ] = { 12, 34, 23, 45, 56, 45 } ;
 int arr[ ][3] = { 12, 34, 23, 45, 56, 45 } ;

School of Computer Engineering


2-D Array Example
29

Below is a sample program that stores roll number and marks obtained by a student.
int main( )
{
int stud[4][2] ;
int i, j ;
for ( i = 0 ; i <= 3 ; i++ )
{
cout<<"\n Enter roll no. and marks of student “<< i+1 << “:” ) ;
cin>>stud[i][0]>>[i][1] ;
}
for ( i = 0 ; i <= 3 ; i++ )
{
cout<<“\nRoll No:”<< stud[i][0]<<“, Mark:“ << stud[i][1] ;
}
return 0;
}

School of Computer Engineering


Three Dimensional Array
30

We aren’t going to show a programming example that uses a three dimensional array.
This is because, in practice, one rarely uses this array. However, an example of
initializing a three-dimensional array will consolidate your understanding of subscripts:

int arr[2][4][2] = { A three-dimensional array can be thought of


{ as an array of arrays of arrays. The outer
{ 2, 4 }, array has two elements, each of which is a
{ 7, 8 }, two-dimensional array of four one-
{ 3, 4 }, dimensional arrays, each of which contains
{ 5, 6 } two integers. In other words, a one-
dimensional array of two elements is
},
constructed first. Then four such one
{ dimensional arrays are placed one below the
{ 7, 6 }, other to give a two dimensional array
{ 3, 4 }, containing four rows. Then, two such two
{ 5, 3 }, dimensional arrays are placed one behind
{ 2, 3 } the other to yield a three dimensional array
}, containing three 2-dimensional arrays.
};
School of Computer Engineering
3-D Array Visual Representation
31

int arr[3][3][3] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 31,
32, 33, 34, 35, 36, 37, 38, 39};

Conceptual View

Memory Map

School of Computer Engineering


String
32

C++ provides following two types of string representations –


 The C-style character string.
 The string class type introduced with Standard C++
C-style character string String class type

The C-style character string originated The standard C++ library provides a
within the C language and continues to string class type that supports all the
be supported within C++. This string is operations mentioned above,
actually a one-dimensional array of additionally much more functionality.
characters which is terminated by a #include <string> is the header to
null character '\0'. Thus a null- include in the program.
terminated string contains the Example –
characters that comprise the string string str1 = "Hello";
followed by a null. string str2 = "World";
Example – string str3 = str1 + str2;
char greeting[] = "Hello";
School of Computer Engineering
String - Commonly Used Function – C Style
33

Sr# Function Purpose


1 strcpy(s1, s2) Copies string s2 into string s1.
2 strcat(s1, s2) Concatenates string s2 onto the end of string s1.
3 strlen(s1) Returns the length of string s1.
4 strcmp(s1, s2) Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;
greater than 0 if s1>s2.
5 strchr(s1, ch) Returns a pointer to the first occurrence of character ch in
string s1.
6 strstr(s1, s2) Returns a pointer to the first occurrence of string s2 in string
s1.

School of Computer Engineering


String - Commonly Used Function – string class type
34

Sr# Function Purpose


1 length() Find the length of a string

2 empty() Returns whether a string is empty or not. It returns 1 if the string length
is 0 and 0 if not.
3 resize() Resizes our string to a specified length.
4 clear() Clears the content of strings.
5 at() Returns the character at some specified position in a string
6 compare() Compares the value of a string str1 with another string str2.
It returns 0 if both the strings are equal.
It returns a positive value if either str1 > str2
It returns a negative value if either str1 < str2
7 find() finds the position of the first occurrence of a character or string in a
string.
8 substr() returns a substring from a string by specifying its position.

School of Computer Engineering


String Examples
35

Reading/Writing string length(), empty(), resize(),clear () illustration


#include <iostream> #include <iostream>
#include <string> #include <string>
using namespace std; using namespace std;

int main() int main()


{ {
string str; string str = “I have baggage of candies”;

cout << "Enter a string: “; cout << str.length()<endl;


cin >> str; cout << str.empty()<endl;
cout << "You entered: " << str << endl; str.resize(str.length() +2, ‘+’);

cout << "\n Enter another string: " <<flush; str = “I love C++”;
cin >> str; str.clear();
cout << "You entered: "<<str<<endl; cout << str<<endl;

return 0; return 0;
} }

School of Computer Engineering


string Examples cont…
36

string copy, concatenation and at() compare(), find(), substr() and multiword input
#include <iostream> #include <iostream>
#include <string> #include <string>
using namespace std; using namespace std;
int main() int main()
{ {
string str1 = "Hello"; string str1 = “have apple";
string str2 = "World"; string str2 = “have orange";
string str3;
int len ; cout << str1.compare(str2)<< endl;
cout << str1.find(‘a’)<< endl;
// copy str1 into str3 cout << str2.find(“have”)<< endl;
str3 = str1; cout << str1.substr(3)<< endl;
cout << "str3 : " << str3 << endl; cout << str2.substr(3, 5)<< endl;
// concatenates str1 and str2 string name;
str3 = str1 + str2; getline(cin, name);
cout << "str1 + str2 : " << str3 << endl; cout << name << endl;
cout << str3.at(5)<< endl; return 0;
return 0; }
}

School of Computer Engineering


Class Work
37

1. WAP to find the frequency of char in string


2. WAP to remove all characters in a string except alphabets.
3. WAP to swap two string
4. Sort the collection of string in alphabetical order
string erasing string replacing
#include <iostream> #include <iostream>
#include <string> #include <string>
using namespace std; using namespace std;

int main() int main()


{ {
string text = "This is a test"; string text = "This is a test";
text.erase (5,5); // the string contains "This test" text.replace (5,2,"was");
return 0; // the string contains "This was a test"
} return 0;
}

School of Computer Engineering


Streams based I/O
38
In every program, there is some data which is taken as input and generate the processed data as
output following the input > process > output cycle. In C++, I/O is performed by using streams. A
stream is a “stream of data” in which character sequences are “flow into” or “flow out off.” The
header file iostream must be included to make use of the input/output (cin/cout) operators. The
source stream which provides data to the program is called the input stream and the destination
stream which receives output from the program is called the output stream.
Standard Output (cout) Standard input (cin)
By default, the standard output of a program With the cin and >> operators it is possible to read input
points at the screen. So with the cout operator from the keyboard.
and the “insertion” operator (<<) you can print a
Example –
message onto the screen. The << operator can be
used multiple times in a single statement. char MY_CHAR;
cout << "Press a character and press return: ";
Example – cin >> MY_CHAR;
cout << "Hello World!“ <<endl; cout << MY_CHAR;
char Yes = ‘y';
cout << Yes; The cin operator is also chainable. For example:
cin >> a >> b;
cout << "Hello, " << "this is a test " << "string.";
In this case the user must give two input values, that are
Note - use the endl manipulator instead of the separated by any valid blank separator (tab, space or
new-line character i.e. “\n” new-line).

School of Computer Engineering


The setw manipulator
39
The setw(int) function is used to set the field width of the output data. For using setw()
we have to use iomanip header file.
Parameter - int - Number of characters to be used as field width.
Example –
#include <iostream> // std::cout, std::endl
#include <iomanip> // std::setw

int main () {
std::cout << std::setw(10);
std::cout << 77 << std::endl;
std:: cout << "Hello" << setw(7) << "World" ;
return 0;
}
Output:

Hello<space><space>World

School of Computer Engineering


Type Conversion
40

Type Conversion is that which converts from one data type into another. For example
converting a int into float or converting a float into double. The Type Conversion is that
which automatically converts one data type into another. We can store a large data type
into the other. For example we can't store a float into int because a float is greater than int.
Different situations of data conversion between incompatible types:-
 Conversion from basic type to class type.
 Conversion from class type to basic type.
 Conversion from one class type to another class type

Difference between Type Conversion and Type Casting:


When a user can convert the one data type into then it is called as the type casting
Remember the type Conversion is performed by the compiler but a casting is done by the
user.
When we use the Type Conversion then it is called the promotion. When we use the type
casting, it means converting a large data type into another and is called as the demotion.
When we use the type casting, we can loss some data.

School of Computer Engineering


Strict type checking
41

C++ uses very strict type checking. A prototype must be known for each function
which is called, and the call must match the prototype. The program

int main()
{
printf("Hello World\n");
return (0);
}

does often compile under C, though with a warning that printf() is not a known
function.

Many C++ compilers will fail to produce code in such a situation. The error is of
course the missing #include<stdio.h> directive.

School of Computer Engineering


Namespace
42

Consider a situation, when we have two persons with the same name, Zara, in
the same group. Whenever we need to differentiate them definitely we would
have to use some additional information along with their name, like either
the area, if they live in different area or their mother’s or father’s name, etc.
Same situation can arise in C++ applications. For example, you might be
writing some code that has a function called xyz() and there is another
library available which is also having same function xyz(). Now the compiler
has no way of knowing which version of xyz() function you are referring to
within your code.
A namespace is designed to overcome this difficulty and is used as additional
information to differentiate similar functions, classes, variables etc. with the
same name available in different libraries. Using namespace, you can define
the context in which names are defined. In essence, a namespace defines a
scope.

School of Computer Engineering


Namespace cont…
43

Defining a Namespace

A namespace definition begins with the keyword namespace followed by the


namespace name as follows −

namespace namespace_name {
// code declarations
}

To call the namespace-enabled version of either function or variable, prepend (::)


the namespace name as follows −

name::code; // code could be variable or function.

School of Computer Engineering


Namespace cont…
44

#include <iostream>
using namespace std; int main () {
// Calls function from first name space.
// first name space first_space::func();
namespace first_space {
void func() { // Calls function from second name space.
cout << "Inside first_space" << endl; second_space::func();
}
} return 0;
}
// second name space One can also avoid prepending of namespaces with
namespace second_space { the using namespace directive. This directive tells
void func() { the compiler that the subsequent code is making
cout << "Inside second_space" << endl; use of names in the specified namespace.
} using namespace first_space;
} int main () {.
func(); // calls function from first name space
return 0;
}

School of Computer Engineering


Nested Namespace
45

Namespaces can be nested where you can define one namespace inside another name
space as follows −

namespace namespace_name1 {
// code declarations
namespace namespace_name2 {
// code declarations
}
}
Members of nested namespace can be accessed by using resolution operators as follows

// to access members of namespace_name2


using namespace namespace_name1::namespace_name2;

// to access members of namespace:name1


using namespace namespace_name1;

School of Computer Engineering


Nested Namespace Example
46

#include <iostream>
using namespace std; using namespace first_space::second_space;
int main () {
// first name space // This calls function from second name space.
namespace first_space { func();
void func() {
cout << "Inside first_space" << endl; return 0;
} }

// second name space


namespace second_space {
void func() {
cout << "Inside second_space" << endl;
}
}
}

School of Computer Engineering


Scope Resolution operator (::)
47

In C++, scope resolution operator is :: and it is used for following purposes.


1. To access a global variable when there is a local variable with same name
#include<iostream>
using namespace std;

int x; // Global x

int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}

School of Computer Engineering


Scope Resolution operator cont…
48

2. To define a function outside a class.


#include<iostream>
using namespace std; // Definition outside class using ::
void A::fun()
class A {
{ cout << "fun() called";
public: }

// Only declaration int main()


void fun(); {
}; A a;
a.fun();
return 0;
}

School of Computer Engineering


Scope Resolution operator cont…
49

3. To access a class’s static variables


class Test
{
// In C++, static members must be explicitly defined
static int x;
// like below
public:
int Test::x = 1;
static int y;
int Test::y = 2;
// Local parameter 'a' hides class member
int main()
// 'a', but we can access it using ::
{
void func(int x)
Test obj;
{
int x = 3 ;
// We can access class's static variable
obj.func(x);
// even if there is a local variable
cout << "Value of static x is " << Test::x;
cout << "\nTest::y = " << Test::y;
cout << "\nValue of local x is " << x;
}
return 0;
};
}

School of Computer Engineering


Scope & Lifetime of variables
50

Life Time – Life time of any variable is the time for which the particular variable
outlives in memory during running of the program.
Scope – The scope of any variable is actually a subset of life time. A variable may
be in the memory but may not be accessible though. So, the area of our program
where we can actually access our entity (variable in this case) is the scope of that
variable. The scope of any variable can be broadly categorized into three
categories :
1. Global scope : When variable is defined outside all functions. It is then
available to all the functions of the program and all the blocks program
contains.
2. Local scope : When variable is defined inside a function or a block, then it is
locally accessible within the block and hence it is a local variable.
3. Function scope : When variable is passed as formal arguments, it is said to
have function scope.

School of Computer Engineering


Variable declaration at the point of use
51

Because

Declaring local variables without using them immediately may


unnecessarily increase their scope. This decreases legibility, and
increases the likelihood of error.

School of Computer Engineering


Ordinary, Pointer and Reference Variable
52

 Ordinary variable is a variable which can hold a value as like eg. int, float or
char. It may be signed or unsigned and take different memory space as per
as their data type.
 The pointer variable is a variable which hold the address of a another
variable and it is obviously unsigned.
 When a variable is declared as reference, it becomes an alternative name
for an existing variable. A variable can be declared as reference by putting
‘&’ in the declaration.
int n=10, *p;
p=&n;
int& ref = n;
Here p is a pointer variable and n is a ordinary variable. p stores the
address of n where as n stores an integer value. ref is the reference variable
and is reference to n.
School of Computer Engineering
Function
53

 A function is a group of statements that together perform a task.


Every C++ program has at least one function, which is main(), and
all the most trivial programs can define additional functions.
 You can divide up your code into separate functions. How you divide
up your code among different functions is up to you, but logically
the division usually is so each function performs a specific task.
 A function declaration tells the compiler about a function's name,
return type, and parameters. A function definition provides the
actual body of the function.
 A function is knows as with various names like a method or a sub-
routine or a procedure etc.

School of Computer Engineering


Function Advantages
54

Creating functions in a program is beneficial. They


 Avoid repetition of codes.
 Increase program readability.
 Divide a complex problem into many simpler
problems.
 Reduce chances of error.
 Makes modifying a program becomes easier.
 Makes unit testing possible.

School of Computer Engineering


Function Types
55

Two types of functions. They are –


 Library functions - Library functions are built in function
that are defined in the C++ library. Function prototype is
present in header files so we need to include specific header
files to use library functions. These functions can be used by
simply calling the function. Some library functions are pow(),
sqrt(), strcpy(), toupper(), isdigit(), etc.
 User-defined functions - These functions are defined by user
as per the requirement, hence called user-defined functions.
Function definition is written by user and is present in the
program. main() is an example of user-defined function.

School of Computer Engineering


Defining a Function
56

The general form of a C++ function definition is as follows:


return_type function_name( parameter list )
{
body of the function
}
Here are all the parts of a function:
 Return Type: A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.
 Function Name: This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
School of Computer Engineering
Defining a Function cont…
57

 Parameters: A parameter is like a placeholder. When a function is


invoked, you pass a value to the parameter. This value is referred to as
actual parameter or argument. The parameter list refers to the type, order,
and number of the parameters of a function. Parameters are optional; that
is, a function may contain no parameters.
 Function Body: The function body contains a collection of statements that
define what the function does.
Example
1. Pre-defined arguments 6. Recursion
2. Variable arguments 7. Function Overloading
3. Default values for parameters
4. Call by value, Call by address and call by reference
5. Inline Function

School of Computer Engineering


Pre-defined Arguments
58

#include <iostream> int main ()


using namespace std; {
// local variable declaration
int sum(int a, int b) int a, b, result;
{
int result; cin>> a >> b;
result = a + b; cin.ignore();

return (result); // calling a function to add the values.


} result = sum(a, b);
cout << "Total value is :" << result << endl;
int subtract(int a, int b)
{ // calling a function as follows.
int result; result = subtract (a, b);
result = a - b; cout << “Difference is :" << result << endl;

return (result); return 0;


} }
School of Computer Engineering
Variable Arguments
59

Sometimes, you may come across a situation, when you want to have a function, which
can take variable number of arguments, i.e., parameters, instead of predefined number of
parameters. The C programming language provides a solution for this situation and you
are allowed to define a function which can accept variable number of parameters based
on your requirement. The following example shows the definition of such a function.

int func(int, ... )


{
.
.
.
}

int main()
{
func(1, 2, 3);
func(1, 2, 3, 4);
}
School of Computer Engineering
Variable Arguments cont…
60

It should be noted that the function func() has its last argument as ellipses, i.e. three
dotes (...) and the one just before the ellipses is always an int which will represent the
total number variable arguments passed. To use such functionality, you need to make use
of stdarg.h header file which provides the functions and macros to implement the
functionality of variable arguments and follow the given steps −

 Define a function with its last parameter as ellipses and the one just before the
ellipses is always an int which will represent the number of arguments.

 Create a va_list type variable in the function definition. This type is defined in
stdarg.h header file. va_list stores the list of arguments.

 Use int parameter and va_start macro to initialize the va_list variable to an argument
list. The macro va_start is defined in stdarg.h header file.

 Use va_arg macro and va_list variable to access each item in argument list.

 Use a macro va_end to clean up the memory assigned to va_list variable.


School of Computer Engineering
Variable Arguments Example
61
#include <iostream> //continuation of program
using namespace std; int main()
#include <stdarg.h> {
double average(int num,...) cout<<"Average of 2, 3, 4, 5 =“ <<average(2,3,4,5)<<endl;
{ cout<<"Average of 2, 3, 4, 5, 15 =“ <<average(2,3,4,5, 15)<<endl;
va_list valist; return 0;
double sum = 0.0; }
int i;
/* initialize valist for num number of arguments */
va_start(valist, num);
/* access all the arguments assigned to valist */
for (i = 0; i < num; i++)
{
sum += va_arg(valist, int);
}
/* clean memory reserved for valist */
va_end(valist);
return sum/num;
}
School of Computer Engineering
Default Values for Parameters
62
#include <iostream> Rules
using namespace std;
 Only the last argument must be given default
int sum(int a, int b = 20) value. You cannot have a default argument
{ followed by non-default argument.
return (a + b);
}
sum (int x, int y); // Correct
int main () sum (int x, int y=0); // Correct
{ sum (int x=0, int y); // Incorrect
int a = 100;
int b = 200;  If you default an argument, then you will have to
cout << “Value :" << sum(a, b)<< endl; default all the subsequent arguments after that.
cout << “Value is :" << sum(a)<< endl;
} sum (int x,int y=0,int z); // Incorrect
sum (int x,int y=10,int z=10); // Correct

 You can give any value a default value to


argument, compatible with its data type.

School of Computer Engineering


Passing Parameters to the Function
63

1. Call by Value – This method copies the actual value of an


argument into the formal parameter of the function. In this case,
changes made to the parameter inside the function have no effect
on the argument.
2. Call by Address - This method copies the address of an argument
into the formal parameter. Inside the function, the address is used
to access the actual argument used in the call. This means that
changes made to the parameter affect the argument.
3. Call by Reference - This method copies the reference of an
argument into the formal parameter. Inside the function, the
reference is used to access the actual argument used in the call.
This means that changes made to the parameter affect the
argument.
School of Computer Engineering
Passing Parameters to the Function cont…
64

Call by Value Call by Reference


void swapByValue ( int x, int y ) void swapByRef ( int &x, int &y )
{ {
int t ; int t ;
t=x; t=x; No Hazard : No Pointer
x=y; x=y;
y=t; y=t;
} }
Call by Address
void swapByAddress ( int *x, int *y )
{
int t ;
t = *x ;
Hazard : NULL Pointer
*x = *y ;
*y = t ;
}

School of Computer Engineering


Passing Parameters to the Function cont…
65

No # Call by Value Call by Reference


1 A copy of value is passed to the An address of value is passed to the function
function
2 Changes made inside the function Changes made inside the function is reflected
is not reflected on other functions outside the function also
3 Actual and formal arguments will Actual and formal arguments will be created
be created in different memory in same memory location
location
Diagrammatic Difference
Original Value

No Modified Yes

Call by Value Call by Reference


School of Computer Engineering
Inline Function
66

 Calling a function generally causes a certain overhead (stacking arguments,


jumps, etc...), and thus for very short functions, it may be more efficient to
simply insert the code of the function where it is called, instead of
performing the process of formally calling a function.
 Preceding a function declaration with the inline specifier informs the
compiler that inline expansion is preferred over the usual function call
mechanism for a specific function. This does not change at all the behavior of
a function, but is merely used to suggest the compiler that the code
generated by the function body shall be inserted at each point the function is
called, instead of being invoked with a regular function call.
Example: When to use?
inline int add (int a, int b)
 Use inline function when performance is needed.
{
 Use inline function over macros.
return a+b;
 Use inline function for short functions.
}
School of Computer Engineering
Recursive Function
67

Head Recursion Tail Recursion


A function with a recursive call at the A function with a recursive call at the end
beginning of the path is the head of a path is the tail recursion. It is the last
recursion. operation before returning to caller.

void myFunc( int counter) void myFunc( int counter)


{ {
if(counter == 0) Base Criteria if(counter == 0)
Base Criteria
return; return;
else else
{ {
myFunc(--counter); Progressive Criteria cout<<counter<<endl;
cout<<counter<<endl; myFunc(--counter); Progressive Criteria
} }
} }

School of Computer Engineering


Function Overloading
68

Multiple functions with same names but different parameters are said to be overloaded.
Function overloading allows to use the same name for different functions, to perform,
either same or different functions.
Function overloading is usually used to enhance the readability of the program. If you
have to perform one single operation but with different number or types of arguments,
then you can simply overload the function.
Ways to overload a function
1. By changing number of Arguments. 2. By having different types of argument.
1. Number of Arguments are different
In this type of function overloading we define functions with same names but different
number of parameters of the same type.
int sum (int x, int y) int sum (int x, int y, int z) int main()
{ { {
sum(10, 20);
cout << x+y; cout << x+y + z;
sum(10,20,30);
} } return 0;
}
School of Computer Engineering
Function Overloading cont…
69

2. Different Datatype of Arguments


In this type of overloading we define two or more functions with same name and same
number of parameters, but the type of parameter is different.

#include <iostream> //continuation of program


using namespace std; double sum(double x, double y)
{
// Function prototype cout << x+y;
int sum(int, int); }
int sum(double, double);
int sum(int x, int y)
int main() {
{ cout<< x+y;
sum (10,20); }
sum(10.5,20.5);
return 0;
}

School of Computer Engineering


Function Prototype
70

 Provides the compiler with the description of functions that will be used
later in the program

 Its define the function before it been used/called

 Function prototypes need to be written at the beginning of the program.

 The function prototype must have :


 A return type indicating the variable that the function will be return

 Function Prototype Examples:


 double squared(double);
 void print_report(int);
 int get_menu_choice(void);

School of Computer Engineering


Function Prototype Example
71

#include<iostream> void area()


{
// Prototype Declaration float area_circle;
void area(); float rad;

int main() cout<<"\nEnter the radius : ");


{ cin>>rad;
area(); area_circle = 3.14 * rad * rad ;
return 0; cout<<"Area of Circle = “<<area_circle;
} }

Class Work (Use Prototypes)


 Write a function to add 3 numbers
 Write a function to compute nk where n and k are supplied by user

School of Computer Engineering


main function return value
72

If the execution of main ends normally without encountering a


return statement the compiler assumes the function ends with an
implicit return statement i.e. return 0;

When main returns zero (either implicitly or explicitly), it is


interpreted by the environment as that the program ended
successfully. Other values may be returned by main, and some
environments give access to that value to the caller in some way,
although this behavior is not required and nor necessarily portable
between platforms.

Some authors consider a good practice to explicitly write the


returns zero statement.
School of Computer Engineering
73

School of Computer Engineering


Home Work (HW)
74

1. WAP (Write a program) to print out all Armstrong numbers between 1 and
500. If sum of cubes of each digit of the number is equal to the number itself,
then the number is called an Armstrong number. For example, 153 = ( 1 * 1 *
1)+(5*5*5)+(3*3*3)
2. WAP to find the norm of a matrix. The norm is defined as the square root of
the sum of squares of all elements in the matrix.
3. WAP to sort a set of names stored in an array in alphabetical order.
4. WAP to remove characters in string except alphabets
5. WAP to input a two dimensional array and print lower triangular matrix and
upper triangular matrix. Lower triangular matrix is a matrix which contains
elements below principle diagonal including principle diagonal elements
and rest of the elements are 0. Upper triangular matrix is a matrix which
contains elements above principle diagonal including principle diagonal
elements and rest of the elements are 0.
6. WAP to reverse a string using recursion.
7. WAP to concatenate three strings using recursion.
School of Computer Engineering
Home Work (HW)
75

8. WAP for a matchstick game being played between the computer and a user.
Your program should ensure that the computer always wins. Rules for the
game are as follows:
a. There are 21 matchsticks.
b. The computer asks the player to pick 1, 2, 3, or 4 matchsticks.
c. After the person picks, the computer does its picking.
d. Whoever is forced to pick up the last matchstick loses the game.
9. Write a menu driven program which has following options:
a. Factorial of a number.
b. Prime or not
c. Odd or even
d. Exit
10. WAP to input two matrices A and B. The task is to multiply matrix A and
matrix B recursively. If matrix A and matrix B are not multiplicative
compatible, then generate output “Not Possible”.

School of Computer Engineering


Home Work (HW)
76

11. WAP to compute F(m, n) where F(m, n) can be recursively defined as


F(m, n) = 1 if m=0 or m>= n >=1
F(m, n) = F(m, n-1) + F(m-1, n-1) otherwise
12. WAP to merge two integer arrays and display the merged array. The merge
array should be in arranged in descending order.
13. WAP to fill a square matrix with value 0 on the diagonal elements, 1 on the
upper diagonal elements and -1 on the lower diagonal elements.
14. WAP to transpose n X n X n matrix.
15. WAP to replace a pattern with another pattern in the text. E.g. If the input
text is “Hi, I am doing good at home” and the replace pattern is “Home” and
the another pattern is “hostel”, the new text would be “Hi, I am doing good at
hostel”
16. WAP to enter a text that has columns. Replace all the commas with semi
colons and then display the text.
17. WAP to insert a word before a given word in the text.

School of Computer Engineering


Home Work (HW)
77

18. WAP to input the string expression. Check whether the pairs and the orders of
“{“,”}”,”(“,”)”,”[“,”]” are correct in expression. For example, the program should print
true for exp = “[()]{}{[()()]()}” and false for exp = “[(])”
19. WAP to input a decimal number m. Convert it in binary string and apply n iterations,
in each iteration 0 becomes 01 and 1 becomes 10. Find kth character in the string
after nth iteration.
20. WAP to input an array of distinct integers and a sum value. Find count of any triplets
with sum smaller than given sum value.
21. WAP that calculates the day of the week for any particular date in the past or future.
22. WAP to input two strings. Modify 1st string such that all the common characters of
the 2nd strings have to be removed and the uncommon characters of the 2nd string
have to be concatenated with uncommon characters of the 1st string. If the modified
string is empty then print '-1'.
23. Given a string consisting of only 0, 1, A, B, C where
A = AND, B = OR, C = XOR
Calculate the value of the string assuming no order of precedence and evaluation is
done from left to right.

School of Computer Engineering


Home Work (HW)
78

24. WAP to print the following pattern wherein the input is the character.
A
AB
ABC
ABCD
ABCDE
ABCDEF

25. WAP to print the following pattern wherein the input is the number.
1
22
333
4444
55555

School of Computer Engineering

You might also like