[email protected] +965-69300304
TRANSCRIPT
VKS_LEARNING-HUB/2016/CS -1 1
[email protected] +965-69300304
vinodsrivastava.wordpress.com
Fundamental (Built-in) Data Types of C++: void Cannot create variable of the type void except type less pointer void *p;
char Allocated 1 byte of memory to represent a single character from ASCII character set or some special
character constant called back slash constant (escape sequence) like:
\a is the bell character
\b is the back space character
\t is the tab character
\n is the new line character int Allocated 4 bytes of memory to represent an integer value float Allocated 4 bytes of memory to represent a floating point value double Allocated 8 bytes of memory to represent a floating point value
Type Modifier: Type modifiers are used to change default type of the built-in data types. Type modifiers
supported by C++ are long, short, signed and unsigned.
Data type void and float does not support any type modifiers
Data type int supports all the four type modifiers
short int, signed short int and unsigned short int is allocated 2 bytes of memory
long int, signed long int and unsigned long int is allocated 4 bytes of memory
Data type char supports signed and unsigned
signed char and unsigned char is allocated 1 byte of memory
Data type double supports only long (long double is allocated 10 bytes of memory)
If a variable is created using only type modifier then the default data type for the variable is int
Typecasting: converting data from one type to another type temporarily, inside the processor (CPU). There are
two ways of type casting. First method is parenthesis around the data. Second method is parenthesis around the
data type.
char alpha='C'
int co1=int(alpha); //parenthesis around data (alpha)
int co2=(int)alpha; //parenthesis around data type (int) cout<<co1<<" ,
"<<co2<<endl; // displays 67 , 67
Automatic Type Conversion: value on the right hand side of the assignment operator is automatically converted
to the data type of the variable on the left hand side of assignment operator.
char alpha='D';
int code=alpha; //Automatically 'D' is converted to 68
cout<<code<<endl; //displays 68
VKS_LEARNING-HUB/2016/CS -1 2
Token: Building block of a program is called a token. It is also called program element. Tokens of a C++
program can be classified as Keyword, Identifier, Constant, Operator, String and Comment.
a) Keyword: It is component of a program which has special meaning for the C++ compiler. C++ keyword
cannot be redefined. In Borland C++ editor keyword appear in bold face. C++ compiler contains list of all the
keywords.
b) Identifier: Identifier is a component of a program which is identified by a C++ compiler.
Built-in: It is name of built-in functions, constants, variables, classes and structure. To use built-in
identifier we need appropriate header file. Built-in identifier can be redefined.
User-defined: Name created by the programmer like variable names, user-defined function names, constant
names, class / structure names.
c) Constant: A constant is a program element whose value remains same through the program.
d) Operator: Operators are used in C++ to carry out various functions. Mostly operators are used in arithmetic
calculations and in logical expressions.
Unary operator: An operator that needs one operand
Binary operator: An operator that needs two operands
Ternary operator: An operator that needs three operands (Called condition operator). Ternary operator can
be used in place of if-else statement.
int a, b, hi;
cout<<"Input 2 integers? "; cin>>a>>b;
hi = a>b ? a : b; //Or, a>b ? hi=a : hi=b;
cout<<"Max="<<hi;
e) String constant: Anything enclosed within a pair of double quotes (") is called string constant
f) Comment (Remarks): Non executable statements of a C++ program are called Comments. A Comment is
completely ignored by a compiler. No code is generated for a Comment.
Single line Comment: single line comment starts with // // this is a single line comment
Multi-line comment: multi-line comment start with forward slash and star (/*) and end with star and
forward slash (*/) /* this first line of comment
this second line of comment */
Compiler directive: instruction given to the compiler. Compiler directive is also called Pre-processor. Every
Compiler Directive begins with hash (#).
#include to include header files
#define to create C++ macros
Increment / Decrement Operator: Increment operator (++) increments value stored in a variable by 1.
Decrement operator (--) decrements value stored in a variable by 1.
int m=10, n=20;
++m; --n;
cout<<m<<" , "<<n<<endl; //Displays 11 , 19
m++; n--;
cout<<m<<" , "<<n<<endl; //Displays 12 , 18
Difference between pre-increment (decrement) and post-increment (decrement). Assume int x=6;
Operator C++ Statement Output Explanation Remarks
++ cout<<++x<<endl; 7 Increments x and then displays x Pre-increment
++ cout<<x++<<endl 6 Displays x and then increments x Post-increment
-- cout<<--x<<endl; 6 Decrements x and then displays x Pre-decrement
-- cout<<x--<<endl; 7 Displays x and then decrements x Post-decrement
VKS_LEARNING-HUB/2016/CS -1 3
Syntax error: error committed when the rule (grammar / syntax) of the language is violated. Syntax errors are
detected by the compiler. Syntax errors are also known as Compile-Time errors because the errors are flagged by
the compiler during compilation time.
Examples: Omitted semicolons or coma, Using a variable without defining / declaring it
Run-time error: Syntactically correct statement performs illegal operation during execution of a program
because program encounters unexpected data.
Examples: Division by zero (0), Square root of a negative number
Logical error: Syntactically correct statement gives an unexpected output due an error in program design or
program implementation.
Examples: Counter or accumulator not initialized, Missing parenthesis / block when they are required
Switch-Case: The sequence of mutually exclusive alternatives can be delineated by if-else-if statement, can also
be coded using switch-case construct. Expression after switch is called Case Selector. A Case Selector is either
an integer (int) or a character (char) expression. The switch evaluates the Case Selector and looks for its value
among the Case Labels. If a match is found, then the statement(s) immediately after the matching case label is
(are) executed until break is encountered or end of switch-case is reached. If no match is found then default
label is executed. The break and default are optional keywords used with switch-case.
char house;
cout<<"House [F]aith [H]armony [P]eace [T]ruth? "; cin>>house;
switch (col)
{
case 'F': cout<<"You are in Faith House\n"; break;
case 'H': cout<<"You are in Harmony House\n"; break;
case 'P': cout<<"You are in Peace House\n"; break;
case 'T': cout<<"You are in Truth House\n"; break;
default: cout<<"Wrong Choice. Try again!\n";
}
Entry Controlled loop (while, for loop) Exit Controlled loop (do-while loop)
Condition is tested in the beginning and then the
loop is executed. If the condition is false in the
beginning, loop is never executed at all
Condition is tested in the end after the loop has
been executed once. If the condition is false in the
beginning, loop is executed once
Minimum number of iteration is zero Minimum number iteration is one
Function Header (Function Declarator): it contains the name of the function, return type of the function and
optional list of formal parameters.
Function Body (Function Block): it is the block after the function header. Function block contains statement that
carries out action inside the function including the optional return statement. If the return value of a function is
void, then return statement is not required. Function’s return statement terminates the function and Returns
a value to the calling function.
Function definition: Function header along with function block defines a complete function.
Function
Header
double factorial(int n)
{
double fact=1;
for (int k=1; k<=n; k++)
fact*=k;
return fact;
}
Function
Definition Function
Block
Function Declaration (Function Prototype): is a function header terminated by a semi-colon where a function
header consists of function name, return type of the function and optional list of formal parameters. Function
declaration is mandatory when calling function is defined before called function.
VKS_LEARNING-HUB/2016/CS -1 4
#include<iostream.h>
void add(int, int); //Function declaration
void main()
{
int a=100, b=250;
add(a, b);
}
//Function definition given below
void add(int x, int y) { cout<<"Sum="<<(x+y)<<endl; }
Parameter: is used to transfer data between a calling function and called function. Parameters are broadly of two
types: Actual Parameter and Formal Parameter. Formal Parameters are of two types: Value Parameter and
Reference Parameter.
Actual Parameter Formal Parameter
Parameter used during the function invocation
from the calling function
Parameter used in the header of function definition
of the called function
Actual parameter may either be a variable or an
expression or a constant
Formal parameter is either a variable or an alias
#include<iostream.h>
void add(int a, int b) //a, b are formal parameters
{
cout<<(a+b)<<endl;
}
void main()
{
int x=20, y=30;
add(x, y); //x and y are actual parameters
add(100, 200); //100 and 200 are actual parameters
add(x+10, y-15); //x+10 and y-15 are actual parameters
}
Value Parameter (Call by Value) Reference Parameter (Call by Reference)
Copy of actual parameter Alias of actual parameter
Change in value parameter does not update actual
parameter
Change in reference parameter, updates actual
parameter
#include<iostream.h>
void add(int a, int& b) //a value parameter, b reference parameter
{
a=300;
b=200;
cout<<a<<","<<b<<endl; //Displays 300,200
}
void main()
{
int x=20, y=30;
add(x, y);
cout<<x<<","<<y<<endl; // Displays 20,200
}
Global Variable Local Variable
Variable created before any block Variable created inside a block
Default value of a global variable is zero Default value of a local variable is garbage
Global variable is visible throughout the program Local variable is visible inside the block and
blocks nested blow
VKS_LEARNING-HUB/2016/CS -1 5
Scope Resolution operator (::): Inside a block, if there is a local variable and a global variable having same
name and to use both the global variable and the local variable scope resolution operator (::) is used with the
global variable name. Scope resolution operator (::) is used as unary operator.
#include<iostream.h>
int m=5;
void main()
{
double m=8.5;
cout<<::m<<" , "<<m<<endl; // Displays 5 , 8.5
{
char m='T';
cout<<::m<<" , "<<m<<endl; // Displays 5 , T
}
}
Function with Default Parameters: Formal parameters are assigned some constant values so that a function can
be invoked without any actual parameters. Default parameter starts from right. #include<iostream.h>
void print(char c='*', int n=10)
{
for(int x=0; x<n; x++)
cout<<c;
cout<<endl;
}
void main()
{
print();
print('@');
print('#', 20);
print(70);
}
Function Overloading: Two or more functions having same name but differentiated on the basis of formal
parameters is called function over loading.
void add(int a, int b) { cout<<"Sum="<<(a+b)<<endl; }
void add(double a, double b) { cout<<"Sum="<<(a+b)<<endl; }
void add(int a, double b) { cout<<"Sum="<<(a+b)<<endl; }
void add(double a, int b) { cout<<"Sum="<<(a+b)<<endl; }
Function Returning by Reference: Function name is an alias of one of the reference parameters. Since reference
parameters are alias of actual parameters, therefore function name indirectly is an alias of one on the actual
parameters. Advantage is that, we can have function on LHS of the assignment operator.
#include<iostream.h>
int& getmin(int& x, int& y) { return x<y ? x : y; }
void main()
{
int a=20, b=10;
getmin(a, b)=50;
cout<<a<<','<<b<<endl;
getmin(a, b)=100;
cout<<a<<','<<b<<endl;
}
User Defined Constant (Named Constant or Read-Only Identifier): An identifier created with keyword const.
Value is assigned to a user defined constant cannot be updated. const int MAX=20;
const double PI=3.14159;
VKS_LEARNING-HUB/2016/CS -1 6
Macro: Macro is an identifier which is created by using Compiler Directive #define. Macro identifier
represents replacement text. A replacement text represents either a symbolic constant or single line or multi-line
code.
#define MAX 20
#define PI 3.14159
Macro Identifier Constant Identifier
Macro identifier is created using #define
Macro Identifier has no data type
No memory is allocated to a Macro Identifier
Scope resolution operator cannot used with a
Macro Identifier
Constant identifier is created using const
Constant Identifier has a data type
Memory is allocated to a Constant Identifier
Scope resolution operator can be used with a
Macro Identifier
random(), randomize(): function random() is used to generate random integer. random(10) will
generate a random value between 0 and 9. Function randomize() is used with function random(), so that
function random() will generate different random number for every run.
random() randomize()
random() has return value int
random() needs an integer parameter
randomize() has return value void
randomize() does not need any parameter
Initializer with array: An initializer is used to assign values to the elements of an array, when the array is
getting created. After the creation of an array we cannot use an initializer to assigns values to the elements of an
array.
int a[5]={15, 35, 25, 65, 45};
double b[5]={11.1, 33.3, 77.7, 22.2, 55.5};
When values inside the initializer are less than the size of the array, then the remaining elements are assigned the
value zero to int / float / double type, nul character to char type and nul string (empty string) to string type. It is
syntax error when values inside the initializer exceed size of the array.
Initializer with structure: Values can be stored in structure variable by using an initializer. Initializer can only
be used at the point of creation of a structure variable. Once the variable has been created we cannot use an
initializer anymore.
struct student
{
int roll; char name[20]; double marks; char grade[3];
};
student s={12, "JUGAL KISHORE", 88.5, "A2"};
When values inside the initializer are less than the number of data members of the structure variable, then the
remaining data members will be assigned value zero (for int / float / double type), nul character (for chat type)
nul string (for string type). When values inside the initializer are more than the number of data members of the
structure variable or data type of list of values inside the initializer does not match with the data type of data
members of the structure variable, then the compiler will flag a syntax error.
Class, Object: Wrapping up of data members and associated member function as one single user defined entity is
called a class. An instance of a class is called an object. Also variable of the type class can also be called an
object.
Data Encapsulation: Wrapping up of data members and associated member functions in a single user defined
unit is known as data encapsulation. In a class, we pack the data and member functions together as a single unit
(capsule).
VKS_LEARNING-HUB/2016/CS -1 7
class student
{
char name[20]; double marks;
public:
student(char *n="", double m=0) { strcpy(name, n); marks=m; }
student(student& s) { strcpy(name, s.name); marks=s.marks; }
void input() { gets(name); cin>>marks; }
void display() { cout<<name<<","<<marks<<endl; }
};
Data Hiding: Keeping the data in private or protected area of a class to prevent it from accidental modification
(change) from outside the class is known as data hiding. Private or protected data members can only be accessed
by using public member functions of the same class.
class student
{
char name[20]; double marks;
public:
void input() { gets(name); cin>>marks; }
void display() { cout<<name<<","<<marks<<endl; }
char* retname() { return name; }
double retmarks() { return marks; }
void updatemarks(double m) { marks=m; }
void updatename(char *n) { strcpy(name, n); }
};
Inheritance: Inheritance is a process of creating a new class (derived / sub class) from an existing old class (base
/ super class). The derived class acquires some properties (public / protected members of old class become
members of new class) of base class and derived class also adds new features of its own.
Single Level Inheritance: A new class is created from one base class.
class AAA
{
// Members of AAA
};
class BBB: public AAA
{
// Members of BBB
};
Multi-level Inheritance: A new class is created from a derived class, that is, between top most base class and
bottom most derived there is at least one intermediate class.
class AAA
{
// Members of AAA
};
class BBB: public AAA
{
// Members of BBB
};
class CCC: public BBB
{
// Members of CCC
};
Class AAA
Class BBB
Class AAA
Class BBB
Class CCC
VKS_LEARNING-HUB/2016/CS -1 8
Multiple Inheritance: A new class is derived from more than two or more base classes.
class AAA
{
// Members of AAA
};
class BBB
{
// Members of BBB
};
class CCC: public AAA, public BBB
{
// Members of CCC
};
Hierarchical Inheritance: Two or more new classes are created from single base class.
class AAA
{
// Members of AAA
};
class BBB: public AAA
{
// Members of BBB
};
class CCC: public AAA
{
// Members of CCC
};
Abstract class and Concrete class: A class without an instance is called Abstract class where as a class with an
instance is called Concrete class.
class AAA //AAA is abstract class
{
int a, b;
public:
void input1() { cout<<"Input two values? "; cin>>a>>b; }
void display1() { cout<<a<<" , "<<b<<endl; }
};
class BBB: public AAA //BBB is concrete class
{
int x, y;
public:
void input2() { cout<<"Input two values? "; cin>>x>>y; }
void display2() { cout<<x<<" , "<<y<<endl; }
};
void main()
{
BBB obj; //BBB is concrete class
// C++ code
}
Constructor: is a special public member function of a class that creates an object. A Constructor functions have
the following characteristics:
Name of a constructor is same as that of a class name
A constructor function is defined / declared only in the public area of a class
A constructor function does not have any return type, not even void
A class can have many constructors
Except default constructor, all other constructor function have at least one parameter
Constructor functions are not inherited
Class AAA Class BBB
Class CCC
Class BBB Class CCC
Class AAA
VKS_LEARNING-HUB/2016/CS -1 9
Default constructor: is a constructor without any parameter. It is the constructor added by the compiler when
there are no constructor functions defined / declared in a class.
class student
{
char name[20]; double marks;
public:
student() { strcpy(name, ""); marks=0.0; }
void input() { gets(name); cin>>marks; }
void display() { cout<<name<<","<<marks<<endl; }
};
Parameterised constructor: is a constructor with parameter and it is always defined by a programmer
class student
{
char name[20]; double marks;
public:
student(char *n, double m) { strcpy(name, n); marks=m; }
void input() { gets(name); cin>>marks; }
void display() { cout<<name<<","<<marks<<endl; }
};
Constructor with default parameter: is a parameterized constructor with constant values assigned to the formal
parameters of the constructor function. Default parameters start from right.
class student
{
char name[20]; double marks;
public:
student(char *n="", double m=0) { strcpy(name, n); marks=m;}
void input() { gets(name); cin>>marks; }
void display() { cout<<name<<","<<marks<<endl; }
};
Copy constructor: is a constructor function in which an object of the same class is passed by reference to the
constructor function and it is used to duplicate an object when the object is getting created. A copy constructor is
added by the compiler when there is no copy constructor defined / declared in the class.
class student
{
char name[20]; double marks;
public:
student(student& s) { strcpy(name, s.name); marks=s.marks; }
void input() { gets(name); cin>>marks; }
void display() { cout<<name<<","<<marks<<endl; }
};
Constructor Overloading: a class having more than one constructor functions.
class student
{
char name[20]; double marks;
public:
student(char *n="", double m=0) { strcpy(name, n); marks=m; }
student(student& s) { strcpy(name, s.name); marks=s.marks; }
void input() { gets(name); cin>>marks; }
void display() { cout<<name<<","<<marks<<endl; }
};
VKS_LEARNING-HUB/2016/CS -1 10
Destructor is a special public member function of a class that destroys an object, when an object goes out of
scope. Destructor functions have the following characteristics:
Destructor function name begin with ~ (tilde character) and followed by class name
A destructor function is defined / declared only in the public area of a class
A destructor function does not have any return type, not even void
A destructor function does not have any parameter
A class can have only one destructor
A destructor functions are not inherited
Constructor Destructor
Constructor name and class name are same Destructor starts with ~ followed by class name
A constructor creates an object A destructor deletes an object from memory
A class can have many constructors A class can have only one destructor
A constructor function cannot be invoked as a
normal member function
A destructor function can be invoked like a
normal member function
Similarities between construction and destructor function of a class:
Constructor and destructor functions are public member functions of a class
Constructor and destructor functions have no return type, not even void
Constructor and destructor functions are not inherited
Polymorphism: The process of using an operator or a function in different ways for different set of inputs given
is known as polymorphism, that is, functions / operators have same name but perform different actions depending
on parameters.
void print(int i) { cout<<"Integer = "<<i<<endl; }
void print(double d) { cout<<"Double = "<<d<<endl; }
void print(char s[]){ cout<<"String = "<<s<<endl; }
Reusability: The concept is implemented through inheritance. Through heritance, member functions of base
class can be used through an instance of derived class. That code / function created in the base class can be used
with instance of derived also. This concept of using member function of base class in derived class also is known
as reusability of code.
class employee
{
int code; char name[20];
protected:
double bsal;
public:
void einput() { cin>>code; gets(name); cin>>bsal; }
void edisplay() { cout<<code<<","<<name<<","<<bsal<<endl; }
};
class pay : public employee
{
double hra, da, gsal;
public:
void sal() { hra=0.4*bsal; da=0.6*bsal; gsal=bsal+hra+da; }
void payslip() { cout<<hra<<","<<da<<","<<gsal<<endl; }
};
Data Abstraction: Data abstraction refers to, providing only essential information to the outside world and hiding
their background details, i.e., to represent the needed information in program without presenting the details. Data
abstraction is a program designing technique used in OOP that relies on the separation of interface (definitions
of member functions) and implementation (calling of the member functions).
For example: cout and << is used to display a data on the screen. But how it is done internally, is not known to us.
VKS_LEARNING-HUB/2016/CS -1 11
class student
{
char name[20]; double marks;
public:
student(char *n="", double m=0) { strcpy(name, n); marks=m; }
void input() { gets(name); cin>>marks; }
void display() { cout<<name<<","<<marks<<endl; }
char* retname() { return name; }
double retmarks() { return marks; }
void updatemarks(double m) { marks=m; }
};
Object Oriented Program Procedural Oriented Program
Equal emphasis is on data and functions Emphasis is on doing things (Functions)
Data Hiding prevents accidental change in the
data
Accidental change of data due to excessive use of
global variables
Supports Polymorphism, Inheritance and
Encapsulation
Does not support Polymorphism, Inheritance and
Encapsulation
Visibility Label Accessibility Inheritable
Public Can be used inside the class as well as outside the class Yes
Protected Can be used inside the class only Yes
Private Can be used inside the class only No
Base Class Access Specifier Derived Class Further Inheritable
Public Public
Public Yes
Protected Protected
Public Protected
Protected Yes
Protected Protected
Public Private
Private No
Protected Private
File, Buffer: Data stored in a backing storage is called File. In C++ a file can be either Binary File or Text File.
Buffer is a temporary storage in the main storage used during transfer of data between main storage and backing
storage since backing storage is under the control of OS.
ofstream A stream class used for opening a file in output / append mode (write mode); Data is
transferred from main storage to backing storage through a buffer
ifstream A stream class used for opening a file in input mode (read mode); Data is transferred from
backing storage to main storage through a buffer
fstream A stream class used for opening a file in output mode / input mode / both; Data is
transferred between main storage and backing
open() Member function of ofstream / ifstream / fstream to open a file for either writing
or reading
close() Member function of ofstream / ifstream / fstream to close a file after write / read
operation has been completed
>> Reads a character / a word at time ignoring white space characters from a text file
get() Reads a character at a time including white space characters from a text file
put() Write a character at time in a text file
getline() Reads a line of text at a time from a text file
write() Writing fixed amount of bytes of data into a binary file
read() Reads fixed amount of bytes of data from a binary file
seekp() Moves the file pointer (in bytes) in a file opened in output (put) mode
seekg() Moves the file pointer (in bytes) in a file opened in input (get) mode
tellp() Returns the position of the file pointer in a file opened in output (put) mode
tellg() Returns the position of the file pointer in a file opened in input (get) mode
sizeof An operator that returns the size of a variable / data type in terms of bytes
VKS_LEARNING-HUB/2016/CS -1 12
ios::binary Used to open a binary file
ios::out Used with fstream to open a file in output mode; If the file exists then the new data
overwrites the existing data in the file (previously stored data are lost)
ios::app Used with ofstream / fstream to open a file in append mode; If the file exists then the new
data is added at the end of the file; No loss of previously stored data
ios::in Used with fstream to open a file in input mode
Pointer: it is an address of a variable. Dereferencing (Indirection): indirectly accessing a memory location using
a pointer variable. * is used as a dereferencing operator with fundamental data type and struct / class type
whereas -> is used as a dereferencing operator with struct / class type. A pointer will display an address except
for a pointer to a char. Pointer to a char is treated as a string (array of char).
struct student { char name[20]; double marks; };
int a=20, *pa=&a;
char b='D', *pb=&b;
cout<<pa<<" , "<<*pa<<endl; //Displays 0x0018ff50 , 20
cout<<pb<<" , "<<*pb<<endl; //Displays DÇ ↑ , D
student s={"SANDEEP", 88.5;}, *ps=&s;
cout<<ps->name<<","<<ps->marks<<endl; //displays SANDEEP,88.5
cout<<(*ps).name<<","<<(*ps).marks<<endl; //displays SANDEEP,88.5
* as a dereferencing operator -> as a dereferencing operator
* is a unary operator -> is a binary operator
* can be used with any data type -> can be used with struct / class type
1 Marks questions
(1) Which C++ header file(s) will be essentially required to be included to run /execute the following
C++ code:
void main()
{
char Msg[ ]="Sunset Gardens";
for (int I=5;I<strlen(Msg);I++) //String.h
puts(Msg); // stdio.h
}
Ans : stdio.h, string.h
(2) Name the header files that shall be need for the following code:
void main()
{
char text[] =”Something”
cout<<”Remaining SMS chars: ”<<160-strlen(text)<<endl; //string.h
} Ans: iostream.h, string.h
2) Find the output of the following program: typedef char Str80[80];
void main()
{ char *Notes;
Str80 str= “ vR2GooD”;
int L=6;
Notes =Str;
while(L>=3)
{
Str[L]=(isupper(Str[L])? tolower(Str[L]) : toupper(Str[L]));
cout<<Notes<<endl;
L--;
Notes++; }
}
VKS_LEARNING-HUB/2016/CS -1 13
* consider all required header file are include
Note (index) L str Output
vR2GooD
0 6 vR2Good vR2Good
1 5 vR2GoOd R2GoOd
2 4 vR2GOOd 2GOOd
3 3 vR2gOOd gOOd
Ans : vR2Good
R2GoOd
2GOOd
gOOd
3) Observe the following program and find out, which output(s) out id (i) to (iv) will not be expected from
program? What will be the minimum and maximum value assigned to the variables Chance?
#include<iostream.h> CBSE 2012
#include<stdlib.h>
void main()
{
randomize();
int Arr[] = {9,6};, N;
int Chance = random(2)+10;
for(int c=0;c<2;c++)
{
N= random(2);
cout<<Arr[N];
}
}
i) 9#6#
ii) 19#17#
iii) 19#16#
iv) 20#16#
Ans: The output not expected from program are (i),(ii) and (iv)
Minimum value of Chance =10
Maximum value of Chance = 11
3 Marks questions:
4) Find the output of the following program: CBSE 2012 #include<iostream.h>
class METRO
{
int Mno, TripNo, PassengerCount;
public:
METRO ( int Tmno=1)
{ Mno =Tmno; PassengerCount=0;}
void Trip(int PC=20)
{ TripNo++, PassengerCount+=PC};
void StatusShow()
{ cout<<Mno<< “:”<<TripNo<< “ :”<<PassengerCount<<endl;}
};
void main()
{
M 5 0 0
5 1 20
METRO M(5),T;
M.Trip();
VKS_LEARNING-HUB/2016/CS -1 14
T 1 0 0
1 1 0
M.StatusShow();
T.StatusShow();
M.StatusShow();
}
Ans : 5: 1: 20
1: 1: 0
5: 1: 20
2& 3 marks practice questions:
5) Rewrite the following program after removing the syntactical error(s) if any. Underline each correction.
#include<iostream.h>
void main( )
{ F = 10, S = 20;
test(F;S);
test(S);
}
void test(int x, int y = 20)
{ x=x+y;
count<<x>>y;
}
6) Rewrite the following program after removing syntactical error(s) if any. Underline each correction.
#include “iostream.h”
Class MEMBER
{ int Mno;
float Fees;
PUBLIC:
void Register ( ) {cin>>Mno>>Fees;}
void Display( ) {cout<<Mno<<" : "<<Fees<<endl;}
};
void main()
{ MEMBER delete;
Register();
delete.Display();
}
7) Find the output for the following program: #include<iostream.h>
#include<ctype.h>
void Encript ( char T[ ])
{ for( int i=0 ; T[i] != „ \0‟ ; i += 2)
if( T[i] = = „A‟ || T[i] = = „E‟ )
T[i] = „#‟ ;
else if (islower (T[i] ))
T[i] = toupper(T[i]);
else
T[i] = „@‟;}
void main()
{ char text [ ] = “SaVE EArTh in 2012”;
encrypt(text);
cout<<text<<endl;
}
VKS_LEARNING-HUB/2016/CS -1 15
8) Find the output of the following program: #include<iostream.h>
void main( )
{ int U=10,V=20;
for(int I=1;I<=2;I++)
{ cout<<”[1]”<<U++<<”&”<<V 5 <<endl;
cout<<”[2]”<<++V<<”&”<<U + 2 <<endl; } }
9) Rewrite the following C++ program after removing the syntax error(s) if any. Underline each correction.
include<iostream.h>
class FLIGHT
{ Long FlightCode;
Char Description[25];
public
void addInfo()
{ cin>>FlightCode; gets(Description);}
void showInfo()
{ cout<<FlightCode<<”:”<<Description<<endl;}
};
void main( )
{ FLIGHT F; addInfo.F(); showInfo.F; }
10) In the following program, find the correct possible output(s)from the options: #include<stdlib.h>
#include<iostream.h>
void main( )
{ randomize( );
char City[ ][10]={“DEL”, “CHN”, “KOL”, “BOM”, “BNG”};
int Fly;
for(int I=0; I<3;I++)
{Fly=random(2) + 1;
cout<<City[Fly]<< “:”;
}}
Outputs: (i) DEL : CHN : KOL: (ii) CHN: KOL : CHN:
(iii) KOL : BOM : BNG: (iv) KOL : CHN : KOL:
11) In the following C++ program what is the expected value of Myscore from options (i) to (iv) given
below. Justify your answer. #include<stdlib.h>
#include<iostream.h>
void main( )
{ randomize( );
int Score[ ] = {25,20,34,56,72,63},Myscore;
cout<<Myscore<<endl;
}
i) 25 (ii) 34 (iii) 20 (iv) Garbage Value.
Function overloading in C++
A function name having several definitions that are differentiable by the number or types of their
arguments is known as function overloading.
Example : A same function print() is being used to print different data types:
#include <iostream.h>
class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
VKS_LEARNING-HUB/2016/CS -1 16
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(void)
{
printData pd; // Call print to print integer
pd.print(5); // Call print to print float
pd.print(500.263);//// Call print to print character
pd.print("Hello C++"); return 0; }
When the above code is compiled and executed, it produces following result:
Printing int: 5 Printing float: 500.263 Printing character: Hello C++
Differences between struct and classes in C++
Structure Class
Defined using struct keyword
Members are public by default
It cannot be inherited
Defined using class keyword
Members are private by default
It can be inherited
/*C++ PROGRAM TO PASS OBJECT AS AN ARGUMEMT. The program Adds the two heights given in
feet and inches. */ #include< iostream.h>
#include< conio.h>
class height
{
int feet,inches;
public:
void getht(int f,int i)
{
feet=f;
inches=i;
}
void putheight()
{
cout< < "\nHeight is:"< < feet< < "feet\t"< < inches< < "inches"< < endl;
}
void sum(height a,height b)
{
height n;
n.feet = a.feet + b.feet;
n.inches = a.inches + b.inches;
if(n.inches ==12)
{
n.feet++;
n.inches = n.inches -12;
}
cout< < endl< < "Height is "< < n.feet< < " feet and "< < n.inches< < endl;
}
};
VKS_LEARNING-HUB/2016/CS -1 17
void main()
{
height h,d,a;
clrscr();
h.getht(6,5);
a.getht(2,7);
h.putheight();
a.putheight();
d.sum(h,a);
getch();
}
/**********OUTPUT***********
Height is 6feet 5inches
Height is 2feet 7inches
Height is 9 feet and 0
4 Marks Solved Problems: Q 1) Define a class TAXPAYER in C++ with following description:
Private members :
Name of type string
PanNo of type string
Taxabincm (Taxable income) of type float
TotTax of type double
A function CompTax( ) to calculate tax according to the following slab:
Taxable Income Tax% Up to 160000 0
>160000 and <=300000 5
>300000 and <=500000 10
>500000 15
Public members : A parameterized constructor to initialize all the members
A function INTAX( ) to enter data for the tax payer and call function CompTax( ) to assign TotTax.
A function OUTAX( ) to allow user to view the content of all the data members.
Ans. class TAXPAYER
{
char Name[30],PanNo[30];
float Taxabincm;
double TotTax;
void CompTax()
{
if(Taxabincm >500000)
TotTax= Taxabincm*0.15;
else if(Taxabincm>300000)
TotTax= Taxabincm*0.1;
else if(Taxabincm>160000)
TotTax= Taxabincm*0.05;
else
TotTax=0.0;
}
public: TAXPAYER(char nm[], char pan[], float tax, double tax) //parameterized constructor
{
strcpy(Name,nm);
strcpy(PanNo,pan);
Taxabincm=tax;
TotTax=ttax;
VKS_LEARNING-HUB/2016/CS -1 18
}
void INTAX()
{
gets(Name);
cin>>PanNo>>Taxabincm;
CompTax();
}
void OUTAX()
{ cout<<Name<<‟\n‟<<PanNo<<‟\n‟<<Taxabincm<<‟\n‟<<TotTax<<endl; }
};
Q 2 : Define a class HOTEL in C++ with the following description:
Private Members Rno //Data Member to store Room No
Name //Data Member to store customer Name
Tariff //Data Member to store per day charge
NOD //Data Member to store Number of days
CALC //A function to calculate and return amount as NOD*Tariff and if the value of NOD*Tariff is
more than 10000 then as 1.05*NOD*Tariff
Public Members: o Checkin( ) //A function to enter the content RNo,Name, Tariff and NOD
o Checkout() //A function to display Rno, Name, Tariff, NOD and Amount (Amount to be displayed by
calling function CALC( )
Solution : #include<iostream.h>
class HOTEL
{
unsigned int Rno;
char Name[25];
unsigned int Tariff;
unsigned int NOD;
int CALC( )
{
int x;
x=NOD*Tariff;
if( x>10000)
return(1.05*NOD*Tariff);
else
return(NOD*Tariff);
}
public:
void Checkin()
{
cin>>Rno>>Name>>Tariff>>NOD;
}
void Checkout()
{
cout<<Rno<<Name<<Tariff<<NOD<<CALC();
}
};
VKS_LEARNING-HUB/2016/CS -1 19
1 & 2 Marks Solved Problems: Q1 :- Answer the questions after going through the following class.
class Exam
{
char Subject[20] ;
int Marks ;
public :
Exam() // Function 1
{
strcpy(Subject, “Computer” ) ; Marks = 0 ;}
Exam(char P[ ]) // Function 2
{
strcpy(Subject, P) ;
Marks=0 ;
}
Exam(int M) // Function 3
{
strcpy(Subject, “Computer”) ; Marks = M ;
}
Exam(char P[ ], int M) // Function 4
{
strcpy(Subject, P) ; Marks = M ;
}
};
(a) Which feature of the Object Oriented Programming is demonstrated using Function 1, Function2,
Function 3 and Function 4 in the above class Exam?
Ans:- Function Overloading (Constructor overloading)
(b) Write statements in C++ that would execute Function 3 and Function 4 of class Exam.
Ans:- Exam a(10); and Exam b(“Comp”, 10);
Q2 Consider the following declaration:
class welcome
{
public:
welcome (int x, char ch); // constructor with parameter
welcome(); // constructor without parameter
void compute();
private:
int x; char ch;
};
Which of the following are valid statements?
welcome obj (33, „a9‟);
welcome obj1(50, „9‟);
welcome obj3();
obj1= welcome (45, „T‟);
obj3= welcome;
Ans. Valid and invalid statements are
welcome obj (33, „a9‟); valid
welcome obj1(50, „9‟); valid
welcome obj3(); invalid
obj1= welcome (45, „T‟); valid
obj3= welcome; invalid
VKS_LEARNING-HUB/2016/CS -1 20
2 Marks Practice Problems Q1. What do you understand by constructor and destructor functions used in classes? How are these functions
different from other member functions? 2
Q2. What do you understand by default constructor and copy constructor functions used in classes? How are these
functions different from normal constructors? 2
Q3 Given the following C++ code, answer the questions (i) & (ii). 2
class TestMeOut
{
public :
~TestMeOut() // Function 1
{ cout << "Leaving the examination hall " << endl; }
TestMeOut() // Function 2
{ cout << "Appearing for examination " << endl; }
void MyWork() // Function 3
{ cout << "Attempting Questions " << endl; }
};
(i) In Object Oriented Programming, what is Function 1 referred as and when does it get invoked / called?
(ii) In Object Oriented Programming, what is Function 2 referred as and when does it get invoked / called?
More Programming Questions (Sorting/Searching/Merging)
struct student
{
int roll; char name[20];
};
void bubblesortroll(student arr[], int n)
{
for(int x=1; x<n; x++)
for(int k=0; k<n-x; k++)
if (arr[k].roll>arr[k+1].roll)
{
student t=arr[k];
arr[k]=arr[k+1];
arr[k+1]=t;
}
}
void bubblesortname(student arr[], int n)
{
for(int x=1; x<n; x++)
for(int k=0; k<n-x; k++)
if (strcmp(arr[k].name, arr[k+1].name)>0)
{
student t=arr[k];
arr[k]=arr[k+1];
arr[k+1]=t;
}
}
void selectionsortroll(student arr[], int n)
{
for(int x=0; x<n-1; x++)
{
student t=arr[x]; int p=x;
for(int k=x+1; k<n; k++)
if (arr[k].roll<t.roll)
{
t=arr[k];
p=k;
VKS_LEARNING-HUB/2016/CS -1 21
}
arr[p]=arr[x];
arr[x]=t;
}
}
void selectionsortname(student arr[], int n)
{
for(int x=0; x<n-1; x++)
{
student t=arr[x]; int p=x;
for(int k=x+1; k<n; k++)
if (strcmpi(arr[k].name, t.name)<0)
{
t=arr[k];
p=k;
}
arr[p]=arr[x];
arr[x]=t;
}
}
void insertionsortroll(student arr[], int n)
{
for(int k=1; k<n; k++)
{
student t=arr[k]; int x=k-1;
while(x>=0 && t.roll<arr[x].roll)
{
arr[x+1]=arr[x];
x--;
}
arr[x+1]=t;
}
}
void insertionsortname(student arr[], int n)
{
for(int k=1; k<n; k++)
{
student t=arr[k];
int x=k-1;
while(x>=0 && strcmpi(t.name, arr[x].name)<0)
{
arr[x+1]=arr[x];
x--;
}
arr[x+1]=t;
}
}
void binarysearchroll(student arr[], int n, int roll)
{
int lb=0, ub=n-1, mid, found=0;
while (lb<=ub && found==0)
{
mid=(lb+ub)/2;
if (roll<arr[mid].roll)
ub=mid-1;
VKS_LEARNING-HUB/2016/CS -1 22
else
if (roll>arr[mid].roll)
lb=mid+1;
else
found=1;
}
if (found==1)
cout<<roll<<" found in the array\n";
else
cout<<roll<<" not found in the array\n";
}
void binarysearchname(student arr[], int n, char *name)
{
int lb=0, ub=n-1, mid, found=0;
while (lb<=ub && found==0)
{
mid=(lb+ub)/2;
if (strcmpi(name, arr[mid].name)<0)
ub=mid-1;
else
if (strcmpi(name, arr[mid].name)>0)
lb=mid+1;
else
found=1;
}
if (found==1)
cout<<name<<" found in the array\n";
else
cout<<name<<" not found in the array\n";
}
void mergeroll(student a[],student b[],student c[],int n1,int n2)
{
int i=0, j=0, k=0;
while (i<n1 && j<n2)
if (a[i].roll<b[j].roll)
c[k++]=a[i++];
else
c[k++]=b[j++];
while (i<n1)
c[k++]=a[i++];
while (j<n2)
c[k++]=b[j++];
}
void mergename(student a[],student b[],student c[],int n1,int n2)
{
int i=0, j=0, k=0;
while (i<n1 && j<n2)
if (strcmpi(a[i].name, b[j].name)<0)
c[k++]=a[i++];
else
c[k++]=b[j++];
while (i<n1)
c[k++]=a[i++];
while (j<n2)
c[k++]=b[j++];
}
VKS_LEARNING-HUB/2016/CS -1 23
class student
{
int roll; char name[20]; double marks;
public:
void inputdata()
{
cout<<"Roll ? "; cin>>roll;
cout<<"Name ? "; gets(name);
cout<<"Marks? "; cin>>marks;
}
void showdata() { cout<<roll<<','<<name<<','<<marks<<endl; }
int retroll() { return roll; }
double retmarks() { return marks; }
char* retname() { return name; }
void inputmarks() { cout<<"New Marks? "; cin>>marks; }
}; 1. Binary file question are based on class student declared above.
a) //Append many records, int n parameter to the function
void appendmany(int n)
{
student s;
ofstream fout("STUDENT.DAT", ios::binary|ios::app);
for (int x=0; x<n; x++)
{
s.inputdata();
fout.write((char*)&s, sizeof(s));
}
fout.close();
}
//Append many records, int n local variable to the function
void appendmany()
{
student s; int n;
cout<<"How many Records? "; cin>>n;
ofstream fout("STUDENT.DAT", ios::binary|ios::app);
for (int x=0; x<n; x++)
{
s.inputdata();
fout.write((char*)&s, sizeof(s));
}
fout.close();
}
b) void display() {
student s;
ifstream fin("STUDENT.DAT", ios::binary);
while (fin.read((char*)&s, sizeof(s)))
s.showdata();
fin.close();
}
VKS_LEARNING-HUB/2016/CS -1 24
c) //Search for Roll – int roll local variable to the function void searchroll()
{
student s; int roll, found=0;
cout<<"Input roll number to search? "; cin>>roll;
ifstream fin("STUDENT.DAT", ios::binary);
while (fin.read((char*)&s, sizeof(s)))
if (s.retroll()==roll)
{
s.showdata(); found=1;
}
fin.close();
if (found==0)
cout<<"No Record Found With Roll="<<roll<<endl;
}
//Search for Name – char name[] parameter to the function
void searchname(char name[])
{
student s; int found=0;
ifstream fin("STUDENT.DAT", ios::binary);
while (fin.read((char*)&s, sizeof(s)))
if (strcmpi(s.retname(), name)==0)
{
s.showdata(); found=1;
}
fin.close();
if (found==0)
cout<<"No Record Found With Name="<<name<<endl;
}
//Search for Name – char name[] local variable to the function
void searchname()
{
student s; int found=0; char name[20];
cout<<"Input name to search? "; gets(name)
ifstream fin("STUDENT.DAT", ios::binary);
while (fin.read((char*)&s, sizeof(s)))
if (strcmpi(s.retname(), name)==0)
{
s.showdata(); found=1;
}
fin.close();
if (found==0)
cout<<"No Record Found With Name="<<name<<endl;
}
//Search using Roll and Name – both local variables
void searchrollname()
{
student s; int found=0; int roll; char name[20];
cout<<"Input roll to search? "; cin>>roll;
cout<<"Input name to search? "; gets(name)
ifstream fin("STUDENT.DAT", ios::binary);
while (fin.read((char*)&s, sizeof(s)))
if (s.retroll()==roll && strcmpi(s.retname(), name)==0)
{
s.showdata(); found=1;
}
fin.close();
VKS_LEARNING-HUB/2016/CS -1 25
if (found==0)
cout<<" No Record Found In The File\n";
}
//Search using Roll and Name – both parameters to the function
void searchrollname(int roll, char name[])
{
student s; int found=0;
ifstream fin("STUDENT.DAT", ios::binary);
while (fin.read((char*)&s, sizeof(s)))
if (s.retroll()==roll && strcmpi(s.retname(), name)==0)
{
s.showdata(); found=1;
}
fin.close();
if (found==0)
cout<<"No Record Found In The File\n";
}
//Display marks greater than equal to 80
void searchmarks80()
{
student s; int found=0;
ifstream fin("STUDENT.DAT", ios::binary);
while (fin.read((char*)&s, sizeof(s)))
if (s.retmarks()>=80)
{
s.showdata(); found=1;
}
fin.close();
if (found==0)
cout<<"No Record Found In The File\n";
}
//Display marks less than equal to 40
void searchmarks40()
{
student s; int found=0;
ifstream fin("STUDENT.DAT", ios::binary);
while (fin.read((char*)&s, sizeof(s)))
if (s.retmarks()<=40)
{
s.showdata(); found=1;
}
fin.close();
if (found==0)
cout<<"No Record Found In The File\n";
}
//Display marks between 60 and 75 (including 60 and 75)
void searchmarks60and75()
{
student s; int found=0;
ifstream fin("STUDENT.DAT", ios::binary);
while (fin.read((char*)&s, sizeof(s)))
if (s.retmarks()>=60 && s.retmarks()<=75)
{
s.showdata(); found=1;
}
VKS_LEARNING-HUB/2016/CS -1 26
fin.close();
if (found==0)
cout<<"No Record Found In The File\n";
}
d) //Copy records where marks greater than equal to 80
void copymarks80()
{
student s;
ifstream fin("STUDENT.DAT", ios::binary);
ofstream fout("Marks80.dat", ios::binary);
while (fin.read((char*)&s, sizeof(s)))
if (s.retmarks()>=80)
fout.write((char*)&s, sizeof(s))
fin.close(); fout.close();
}
//Copy records where marks less than equal to 40
void copymarks40()
{
student s;
ifstream fin("STUDENT.DAT", ios::binary);
ofstream fout("Marks40.dat", ios::binary);
while (fin.read((char*)&s, sizeof(s)))
if (s.retmarks()<=40)
fout.write((char*)&s, sizeof(s))
fin.close(); fout.close();
}
e) //Updating one record using roll – parameter to the function
void updaterec(int roll)
{
fstream f("STUDENT.DAT", ios::binary|ios::in|ios::out);
student s;
while (f.read((char*)&s, sizeof(s)))
if (roll=s.retroll())
{
s.inputmarks();
f.seekg(-sizeof(s), ios::cur);
//Or, f.seekp(-sizeof(s), ios::cur);
//Or, f.seekg(f.tellg()-sizeof(s));
//Or, f.seekp(f.tellg()-sizeof(s));
f.write((char*)&s, sizeof(s));
}
f.close();
}
In place of tellg() one can use tellp() as well. 2. Text file questions:
a) //Counting characters void countchar()
{
char ch; int count=0;
ifstream fin("NEWS.TXT");
while (fin.get(ch))
count++;
fin.close();
cout<<"Characters="<<count<<endl;
VKS_LEARNING-HUB/2016/CS -1 27
}
//Counting words
void countword()
{
char word[20]; int count=0;
ifstream fin("NEWS.TXT");
while (fin>>word)
count++;
fin.close();
cout<<"Words="<<count<<endl;
} //Counting line
void countline()
{
char line[80]; int count=0;
ifstream fin("NEWS.TXT");
while (fin.getline(line, 80))
count++;
fin.close();
cout<<"Lines="<<count<<endl;
} b) //Counting uppercase characters
void countupper()
{
char ch; int count=0;
ifstream fin("NEWS.TXT");
while (fin.get(ch))
if (ch>='A' && ch<='Z') //Or, if (isupper(ch))
count++;
fin.close();
cout<<"Uppercase="<<count<<endl;
}
//Counting digits
void countdigit()
{
char ch; int count=0;
ifstream fin("NEWS.TXT");
while (fin.get(ch))
if (ch>='0' && ch<='9') //Or, if (isdigit(ch))
count++;
fin.close();
cout<<"Digits="<<count<<endl;
}
//Counting letters / alphabets
void countletter()
{
char ch; int count=0;
ifstream fin("NEWS.TXT");
while (fin.get(ch))
if (ch>='A' && ch<='Z' || ch>='a' && ch<='z')
//Or, if (isalpha(ch))
count++;
fin.close();
cout<<"Letters="<<count<<endl;
VKS_LEARNING-HUB/2016/CS -1 28
}
//Counting uppercase and lowercase
void countupperlower()
{
char ch; int uc=0, lc=0;
ifstream fin("NEWS.TXT");
while (fin.get(ch))
if (ch>='A' && ch<='Z') //Or, if (isupper(ch))
uc++;
else
if (ch>='a' && ch<='z') //Or, if (islower(ch))
lc++;
fin.close();
cout<<"Uppercase="<<uc<<endl;
cout<<"Lowercase="<<lc<<endl;
} //Counting vowels
void countvowel()
{
char ch; int count=0;
ifstream fin("NEWS.TXT");
while (fin.get(ch))
{
ch=toupper(ch); //ch=tolower(ch);
if (ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U')
//if (ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')
count++;
}
fin.close();
cout<<"Vowels="<<count<<endl;
}
//Counting space characters
void countspace()
{
char ch; int count=0;
ifstream fin("NEWS.TXT");
while (fin.get(ch))
if (ch==' ' || ch=='\t' || ch=='\n')
count++;
fin.close();
cout<<"White Spaces characters"<<count<<endl;
}
//Counting spaces
void countspace()
{
char ch; int count=0;
ifstream fin("NEWS.TXT");
while (fin.get(ch))
if (ch==' ') //Or, if (ch==char(32))
count++;
fin.close();
cout<<"Spaces="<<count<<endl;
}
c) //Counting "IS" and "ARE" together
VKS_LEARNING-HUB/2016/CS -1 29
void countisare()
{
ifstream fin("NEWS.TXT");
char word[20]; int count=0;
while (fin>>word)
if (strcmpi(word, "IS")==0 || strcmpi(word, "ARE")==0)
count++;
fin.close();
cout<<"Number of IS/ARE="<<count<<endl;
} //Counting "IS" and "ARE" separately void countisare()
{
ifstream fin("NEWS.TXT");
char word[20]; int count1=0, count2=0;
while (fin>>word)
{
if (strcmpi(word, "IS")==0)
count1++;
if (strcmpi(word, "ARE")==0)
count2++;
}
fin.close();
cout<<"Number of IS="<<count1<<endl;
cout<<"Number of ARE="<<count2<<endl;
} //Counting words starting with E or I
void countwordei()
{
char word[20]; int count=0;
ifstream fin("NEWS.TXT");
while (fin>>word)
{
char ch=toupper(word[0]); //Or, char ch=tolower(word[0]);
if (ch=='E' || ch=='I') //Or, if (ch=='e' || ch=='i')
count++;
fin.close();
cout<<"Number of words starting with E/I="<<count<<endl;
}
d) //Counting line starting with A or T void countlineat()
{
char line[80]; int count=0;
ifstream fin("NEWS.TXT");
while (fin.getline(line, 80))
{
char ch=toupper(line[0]); //Or, char ch=tolower(line[0]);
if (ch=='A' || ch=='T') //Or, if (ch=='a' || ch=='t')
count++;
fin.close();
cout<<"Number of lines starting with A/T="<<count<<endl;
} Address calculation of double dimension array
VKS_LEARNING-HUB/2016/CS -1 30
a) A double dimension array DA[30][50] is stored in computer’s main storage. Every element of DA requires 8 bytes of memory. If the base address of DA is 2000 then calculate the address of DA[23][42] when the array is stored as: i) Row Major ii) Column Major ROW = 30, COL = 50, Base = 2000, W = 8, r = 23, c = 42 Row Major: Address of DA[r][c] = Base + W * (r * COL + c)
Address of DA[23][42] = 2000 + 8 * (23 * 50 + 42) = 11536 Col Major: Address of DA[r][c] = Base + W * (r + c * ROW)
Address of DA[23][42] = 2000 + 8 * (23 + 42 * 30) = 12264 b) A double dimension array DD[5..25][7..30] is stored in computer’s main storage. Every element of DD
requires 4 bytes of memory. If the base address of DD is 1000 then calculate the address of DD[17][25] when the array is stored as: i) Row Major ii) Column Major lbr = 5, ubr = 25, ROW = ubr - lbr + 1 = 25 - 5 + 1 = 21 lbc = 7, ubc = 30, COL = ubc - lbc + 1 = 30 - 7 + 1 = 24 Base = 1000, W = 4, r = 17, c = 25 Row Major: Address of DD[r][c] = Base + W * ((r - lbr) * COL + (c - lbc))
Address of DA[17][25] = 1000 + 4 * ((17 - 5) * 24 + (25 - 7)) = 2224 Col Major: Address of DD[r][c] = Base + W * ((r - lbr) + (c - lbc) * ROW)
Address of DA[17][25] = 1000 + 4 * ((17 - 5) + (25 - 7) * 21) = 2560 c) A double dimension array MAT[40][25] is stored in computer’s main storage as row wise. If the address
of MAT[24][8] is 3932 and address of MAT[33][21] is 4884, then find the base address, width (W) and also calculate the address of MAT[27][19]. ROW = 40, COL = 25 Base + W * (24 * 25 + 8) = 3932 Or, Base + 608 * W = 3932 …… (1) Base + W * (33 * 25 + 21) = 4884 Or, Base + 846 * W = 4884 …… (2) Subtracting (1) from (2) Base + 846 * W = 4884 Base + 608 * W = 3932 238 * W = 952 W = 952 / 238 = 4 Substituting the value of W in (1) Base + 4 * 608 = 3932 Base = 3932 - 2432 = 1500 Address of MAT[27][19] = 1500 + 4 * (27 * 25 + 19) = 4276
d) A double dimension array MAT[20][30] is stored in computer’s main storage as column major. If the address of address of MAT[15][23] is 4850 and address of MAT[12][18] is 4232, then find the base address, width (W) and also calculate the address of MAT[16][25]. ROW = 20, COL = 30 Base + W * (15 + 23 * 20) = 4850 Or, Base + 475 * W = 4850 …… (1) Base + W * (12 + 18 * 20) = 4232 Or, Base + 372 * W = 4232 …… (2) Subtracting (2) from (1) Base + 475 * W = 4850 Base + 372 * W = 4232 103 * W = 618 W = 618 / 103 = 6 Substituting the value of W in (1) Base + 6 * 475 = 4850 Base = 4850 - 2850 = 2000 Address of MAT[16][25] = 2000 + 6 * (16 + 25 * 20) = 5096