Principle of Programming Language: Biyani's Think Tank
Principle of Programming Language: Biyani's Think Tank
Principle of Programming
Language
(BCA-I Year)
Sandhya Saju
Dhanesh Gupta
Deptt. of Information Technology
Biyani Girls College, Jaipur
2
Published by :
Think Tanks
Biyani Group of Colleges
Edition : 2011
Price :
While every effort is taken to avoid errors or omissions in this Publication, any
mistake or omission that may have crept in is not intentional. It may be taken note of
that neither the publisher nor the author will be responsible for any damage or loss of
any kind arising to anyone in any manner on account of such errors and omissions.
Preface
I am glad to present this book, especially designed to serve the needs of the
students. The book has been written keeping in mind the general weakness in
understanding the fundamental concepts of the topics. The book is self-explanatory
and adopts the “Teach Yourself” style. It is based on question-answer pattern. The
language of book is quite easy and understandable based on scientific approach.
Any further improvement in the contents of the book by making corrections,
omission and inclusion is keen to be achieved based on suggestions from the
readers for which the author shall be obliged.
I acknowledge special thanks to Mr. Rajeev Biyani, Chairman & Dr. Sanjay
Biyani, Director (Acad.) Biyani Group of Colleges, who are the backbones and main
concept provider and also have been constant source of motivation throughout this
Endeavour. They played an active role in coordinating the various stages of this
Endeavour and spearheaded the publishing work.
I look forward to receiving valuable suggestions from professors of various
educational institutions, other faculty members and students for improvement of the
quality of the book. The reader may feel free to send in their comments and
suggestions to the under mentioned address.
Author
4
Syllabus
Basic concepts of programming languages: Programming do mains, language evaluation
criterion and language categories, evolution of the major programming languages
(FORTRAN, ALGOL 60 COBOL, BASIC, PL/I, ALGOL 68, ADA, C, C++, JAVA)
Describing Syntax and Semantics, formal methods of describing syntax, recursive descent
parsing, attribute grammars, dynamic semantics.
Names, Variables, Binding, Type cheecking, Scope and lifetime data types, array types,
record types, union types, set types and pointer types, arithmetic expressions, type
conversions, relational and Boolean expressions, assignment statements, mixed mode
assignment.
Statement level control structures, compound statements, selection statement, iterative
statements, unconditional branching, guarded commands.
Subprogram, fundamentals of subprogram, design issues, parameter passing methods,
overloaded subprograms, generic subprograms, separate and independent compilation, design
issues for functions, accessing nonlocal environment, user defined overloaded operators,m
coroutines, implementing subprograms, blocks, implementing dynamic scooping.
Programming in C and C++: Character set, variables and constants, keywords, Instructions,
assignment statements, arithmetic expression, comment statements, simple input and output,
Boolean expressions, Relational operators, logical operators, control structures, decision
control structure, loop control structure, case control structure, functions, subroutines, scope
and liftime of identifiers, parameter passing mechanism, arrays and strings, structures, array
of structures, Console Input and Output functions, Disk I/O functions, Interaction with
hardware, Interrupts and Interrupt Vectir table, Unions of structures, operations on bits, usage
of enumerated data types. Bitfields, Pointers to Function, Function returning Pointers,
Graphics in C.
Content
S.No. Name of Topic
3. Functions
4. Array
5. Structure, Arrays and Union
6. Pointers
7. File Handling
8. C++ programming
9. Oops Concepts
10. Keywords
Chapter 1
Introduction to Programming tit-bits
Q 1. How do we define a character set?
Ans Any alphabet ,digit or symbols to represent information is called Character .
The characters are grouped into following categories:
1 Letters
2 Digits
3 Special characters
4 White spaces
The following are the valid alphabets, numbers and special symbols
permitted in C.
Digits: From 0 to 9
Letters: From a to z, A to Z.
Special characters : , . ? „ “ / \
White space: Blank Spaces , Tab , New Line.
Q3 Define Variables.
Ans A variable is a name given to the memory location for holding data. The name
of the memory location i.e. the variable name, remain fixed during execution
of the program but the data stored in that location may change from time to
time.
Eg. Marks1 , Marks2, abc , a , ab_1 ,
Rules for writing variable names
1. The first character of variable name must be an alphabetic.
2. Blank spaces are not allowed in a variable name.
3. Special characters such as arithmetic operators, #,^ can not be used in a
variable.
4. Reserved words(Keywords) cannot be used as variable names.
Principles of Programming languages 7
5. The maximum length of a variable name depends upon the compiler (8).
6. A variable name declared for one data type cannot be used to declare another
data type.
Q7 Explain Instructions.
Ans C instruction are of basically three types :
1 Type declaration instruction
2 Arithmetic Instruction
3 Control Instruction
Type Declaration Instructions
This instruction is used to declare the type of variables being used in the
program. Any variable used in the program must be declared before using it
in any statement. The type declaration statements is written at the beginning
of the main() function.
The main purpose of type declaration instruction is to declare the type of
variable C program.
For Example :
int num;
char c; // Type Declaration
float f;
main()
{
Some Statements
}
For Example :
int i, j, l, m;
i=i+1;
m=i* j +l;
(b) Real Mode Arithmetic Statement : These are arithmetic statement in
which all operands are either real constant or real variable.
For Example :
float si, roi, p, q ;
Principles of Programming languages 9
si = roi*p*q/100.0;
c) Mixed mode arithmetic statements : this is an arithmetic statement in
which some of the operands are integer and some of the operands are
real.
For Example :
int a, b, c, num ;
avg = ( a + b+ c + num)/4;
Control instruction:
To control the sequence of execution of various statements in a C program.
3 Logical Operators
A logical operator is used to compare or evaluate logical and relational
expressions. There are three logical operators available in the C language.
&& Logical AND
|| Logical OR
! Logical NOT
4 Assignment operator
An assignment operator (=) is used to assign a constant or a value of one
variable to another.
Example:
a = 5;
b = a;
rate = 10.5
net = (a/b) * 100;
* There is always difference between the equality operator (==) and the
assignment operator (=).
6 Bitwise Operators:
These are used to perfom bitwise operations such as testing the bits , shifting
the bits to left or right , one‟s compliment of bits. This operator can be apply
on only int and char data type.
& AND
| Inclusive OR
^ Exclusive OR
<< Shift Left
>> Shift Right
~ One's compliment
~A = 1100 0011
Input :
In any programming language input means to feed some data into program.
This can be given in the form of file or from command line. C programming
language provides a set of built-in functions to read given input and feed it to
the program as per requirement.
printf() function
This is one of the most frequently used functions in C for output
Output :
In any programming language output means to display some data on screen,
printer or in any file. C programming language provides a set of built-in
functions to output required data.
scanf() function
This is the function which can be used to to read an input from the command
line.
Objective
1. The statement char ch = z' would store in ch:
(a) the character z
(b) ASCII value of z
(c) z character along with single inverted commas
(d) Both (a) and (b) ( )
(b) prints 6
(c) prints 8
(d) is syntactically warning ( )
Chapter 2
The Decision , Loop , Case Control
Structure
if (expression)
statement;
or
Syntex:- if with else statement
if (expression)
{
Block of statements;
}
else
16
{
Block of statements;
}
Or
main()
{
int cows = 6;
if (cows > 1)
printf("We have cows\n");
if (cows == 5 )
{
printf("We have 5 cows\n");
}
else if( (cows == 6 )
Principles of Programming languages 17
{
printf("We have 6 cows\n");
}
}
Output
We have cows
Executing else part...!
We have 6 cows
? : Operator
The ? : operator is just like an if ... else statement except that because it is an
operator you can use it within expressions.
? : is a ternary operator in that it takes three values, this is the only ternary
operator C has.
? : takes the following form:
if condition is true ? then X return value : otherwise Y value;
switch statement:
The switch statement is much like a nested if .. else statement. Its mostly a
matter of preference which you use, switch statement can be slightly more
efficient and easier to read.
switch( expression )
{
case expression1:
statements1;
case expression2:
statements2;
case c-expression3:
statements3;
default : statements4;
}
Use of break
Use If a condition is met in switch case then execution continues on into
the next case clause also if it is not explicitly specified that the execution
should exit the switch statement. This is achieved by using break keyword.
Looping
Loops provide a way to repeat commands and control how many times they
are repeated. C provides a number of looping way.
18
while loop
The most basic loop in C is the while loop. Like an If statement, if the
test condition is true, the statements get executed. The difference is that after
the statements have been executed, the test condition is checked again. If it is
still true the statements get executed again.This cycle repeats until the test
condition evaluates to false.
syntax
while ( expression )
{
Single statement
or
Block of statements;
}
for loop
for loop is similar to while, it's just written differently. for statements
are often used to proccess lists such a range of numbers:
syntax:
for( expression1; expression2; expression3)
{
Single statement
or
Block of statements;
}
In the above syntax:
expression1 - Initialisese variables.
expression2 - Condtional expression, as long as this condition is true, loop will
keep executing.
expression3 - expression3 is the modifier which may be simple increment of a
variable.
do...while loop
do ... while is just like a while loop except that the test condition is
checked at the end of the loop rather than the start. This has the effect that the
content of the loop are always executed at least once.
syntax
do
{
Single statement
or
Block of statements;
Principles of Programming languages 19
}while(expression);
break and continue statements
C provides two commands to control the loop:
break -- exit form loop or switch.
continue -- skip 1 iteration of loop.
#include
main()
{
int i;
int j = 10;
for( i = 0; i <= j; i ++ )
{
if( i == 5 )
{
continue;
}
printf("Hello %d\n", i );
}
}
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 6
Hello 7
Hello 8
Hello 9
Hello 10
The goto statement (unconditional branching)
goto allows to make an absolute jump to another point in the program.
We should use this feature with caution since its execution causes an
unconditional jump ignoring any type of nesting limitations.
The destination point is identified by a label, which is then used as an
argument for the goto statement. A label is made of a valid identifier followed
by a colon (:).
goto loop example
20
#include <stdio.h>
int main ()
{
int n=10;
loop:
printf(“%d”, n);
n--;
if (n>0)
goto loop;
printf( "FIRE”);
}
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
exit function
exit is a function defined in the cstdlib library.
The purpose of exit is to terminate the current program with a specific exit
code. Its prototype is:
exit()
OBJECTIVE
1. Switch statement is used for
(a) Multiple selection
(b) one way selection
(c) two way selection
(d) None of the above
2. "Break" statement is used to exit from;
(a) If statement (b) For loop
(c) Switch (d) Both A and B ( )
5. How many times will take printf statement in the following code will be executed ?
for (i =1'< 1; i=I +1)
print ("hellow");
(a) 0 (b) 10
(c) 6 (d) 11 ( )
Chapter 3
Functions
Q1 What is a Function?
Ans The function is a self contained block of statements which performs a task of a
same kind. C program does not execute the functions directly. It is required to
invoke or call that functions. When a function is called in a program then
program control goes to the function body. Then, it executes the statements.
We call function whenever we want to process that functions statements i.e.
more than 1 times. Any c program contains at least one function. Function is
used to avoids rewriting the same code over and over.
The following is its format:
type name ( parameter1, parameter2, ...) { statements }
where:
• type is the data type specifier of the data returned by the function.
• name is the identifier by which it will be possible to call the function.
• parameters (as many as needed): Each parameter consists of a data type
specifier followed by an identifier.
• statements is the function's body. It is a block of statements surrounded by
braces { }.
Eg.
void add()
{
int a, b, c;
clrscr();
printf("\n Enter Any 2 Numbers : ");
scanf("%d %d",&a,&b);
c = a + b;
printf("\n Addition is : %d",c);
}
void main()
{
void add();
add();
Principles of Programming languages 23
getch();
}
1. Built in Functions :
These functions are also called as 'library functions'. These functions are
provided by system. These functions are stored in library files. e.g.
scanf()
printf()
strcpy
2 User Defined Functions :
The functions which are created by user for program are known as 'User
defined functions'.
include <stdio.h>
#include <conio.h>
void add()
{
int a, b, c;
clrscr();
printf("\n Enter Any 2 Numbers : ");
scanf("%d %d",&a,&b);
c = a + b;
24
t = p2;
p2 = p1;
p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", p1, p2 );
}
int main()
{
int a = 10;
int b = 20;
t = *p2;
*p2 = *p1;
*p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", *p1, *p2 );
}
before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b(p2) = 10
After: Value of a = 20 and value of b = 10
defined
Register CPU registers Garbage Local to the Till the control
block in remains
which within the
variable is block in which
defined the variable is
defined
Static Memory Zero Local to the Value of
block in variable
which persists
variable is between
defined different
function calls.
External Memory Zero Global As long as
program
execution
doesn‟t come
to end.
OBJECTIVE
1. Use of functions:
(a) Helps to avoid repeating a set instructions many times
(b) enhance the logical clarity of the program
(c) helps to avoid repeating programming across program
(d) All of the above ( )
2. Choose the storage class type which access the variable fastly:
(a) Automatic storage class
(b) Static storage class
(c) Register storage class
(d) External strogae class ( )
Chapter 4
Array
Q1. Define arrays.
Ans. A collection of variables which are all of the same type. It is a data structure,
which provides the facility to store a collection of data of same type under
single variable name. Just like the ordinary variable, the array should also be
declared properly. The declaration of array includes the type of array that is
the type of value we are going to store in it, the array name and maximum
number of elements.
Examples:
short val[ 200 ]; //declaration
val[ 12 ] = 5; //assignment
Q3. Write a program for one dimensional array and two dimensional array.
Ans The declaration form of one-dimensional array is
Data_type array_name [size];
The following declares an array called „numbers‟ to hold 5 integers
and sets the first and last elements. C arrays are always indexed from 0. So the
first integer in „numbers‟ array is numbers[0] and the last is numbers[4].
int numbers [5];
numbers [0] = 1; // set first element
numbers [4] = 5; // set last element
This array contains 5 elements. Any one of these elements may be
referred to by giving the name of the array followed by the position number of
the particular element in square brackets ([]). The first element in every array
is the zeroth element. Thus, the first element of array „numbers‟ is referred to
as numbers[ 0 ], the second element of array „numbers‟ is referred to as
numbers[ 1 ], the fifth element of array „numbers‟ is referred to as numbers[ 4
Principles of Programming languages 29
Example:
#include<stidio.h>
#include<conio.h>
int main()
{
int matrix[3][3],I,j,r,c;
clrscr();
printf(“Enter the order of matrix\n”);
scanf(“%d%d”,&r,&c);
printf(“Enter the elements of 3x3 matrix\n”,r,c);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf(“%d”,&matrix[i][j]);
printf(“Given matrix:\n”);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
printf(“%d\t”,matrix[i][j]);
printf(“\n”);
}
getch();
return 0;
}
Output
123
234
567
OBJECTIVE
Principles of Programming languages 31
4. A pointer is:
(a) Address of a variable
(b) Indication of a variable to be accessed next
(c) A variable for storing address
(d) None of the above ( )
8. Consider the declaration int a [5] = {0,1}; the value of the element a [2] :
(a) 0 (b) 2
(c) 1 (d) can not predict ( )
9. Consider the declaration int a [ ] = {0,1,2,3,4} what will be the value of a (0) a p5[ ?
(a) 0
32
(b) 4
(c) error message
(d) unpredictable ( )
Principles of Programming languages 33
Chapter 5
For Example:
To store the names, roll number and total mark of a student
you can declare 3 variables. To store this data for more than one student 3
separate arrays may be declared. Another choice is to make a structure. No
memory is allocated when a structure is declared. It just defines the “form” of
the structure. When a variable is made then memory is allocated. This is
34
equivalent to saying that there's no memory for “int” , but when we declare
an integer that is. int var; only then memory is allocated. The structure for the
above-mentioned case will look like
struct student
{
int rollno;
char name[25];
float totalmark;
};
Thus, the stud1 and stud2 are structure variables of type student. The above
structure can hold information of 2 students.
struct structure_name
{
type element 1;
type element 2;
……………..
type element n;
}var1,var2,…,varn;
The different variable types stored in a structure are called its members. The
structure member can be accessed by using a dot (.) operator, so the dot
operator is known as structure member operator.
Example:
In the above example stud1 is a structure variable of type
student. To access the member name, we would write
stud1.name
Similarly, stud1‟s rollno and stud1‟s totalmark can be accessed by writing
stud1.rollno And
stud1.totalmark
Ans Structure members can be initialized at declaration. This much the same
manner as the element of an array; the initial value must appear in the order
in which they will be assigned to their corresponding structure members,
enclosed in braces and separated by commas .The general form is
Example:
#include <stdio.h>
#include<conio.h>
int main()
{
struct student
{
char *name;
int rollno;
float totalmark;
};
struct student stud1={"Ashraf",1,98};
struct student stud3= {"Rahul",3,97};
struct student stud2={"Vineeth",2,99};
clrscr();
printf("STUDENTS DETAILS:\nRoll
36
number:%d\n\nName:%s\n\nTotal mark:%.2f\n”,
stud1.rollno,stud1.name,stud1.totalmark);
printf("\nRoll number:%d\n\nName:%s\n\nTotel
mark:%.2f\n",stud2.rollno,stud2.name,stud2.totalmark);
printf("\nRoll number:%d\n\nName:%s\n\nTotel
mark:%.2f\n",stud3.rollno,stud3.name,stud3.totalmark);
getch();
return 0;
}
Output
Roll Number 1
Name Ashraf
Total Marks 98
Roll Number 3
Name Rahul,
Total Marks 97
Roll Number 2
Name Vineet
Total Marks 9
Ans It is possible to store a structure has an array element. i.e., an array in which
each element is a structure. Just as arrays of any basic type of variable are
allowed, so are arrays of a given type of structure. Although a structure
Principles of Programming languages 37
contains many different types, the compiler never gets to know this
information because it is hidden away inside a sealed structure capsule, so it
can believe that all the elements in the array have the same type, even though
that type is itself made up of lots of different types.
Example:
struct student
{
int rollno;
char name[25];
float totalmark;
} stud[100];
Program:
#include <stdio.h>
#include <conio.h>
int main()
{
struct student
{
int rollno;
char name[25];
int totalmark;
}stud[100];
38
int n,i;
clrscr();
printf("Enter total number of students\n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter details of %d-th student\n",i+1);
printf("Name:\n");
scanf("%s",&stud[i].name);
printf("Roll number:\n");
scanf("%d",&stud[i].rollno);
printf("Total mark:\n");
scanf("%d",&stud[i].totalmark);
}
printf("STUDENTS DETAILS:\n");
for(i=0;i<n;i++)
{
printf("\nRoll number:%d\n",stud[i].rollno);
printf("Name:%s\n",stud[i].name);
printf("Totel mark:%d\n",stud[i].totalmark);
}
getch();
return 0;
}
Output will be the dynamic data entered by the user of all the students.
Ans Union is a data type with two or more member similar to structure but in
this case all the members share a common memory location. The size of
the union corresponds to the length of the largest member. Since the
member share a common location they have the same starting address.
memory is freed will always be reusable by another instance of the same type
of union. This is a natural strategy in system programming where many
instances of different kinds of variables with a related purpose and stored
dynamically.
{
int rollno;
float totalmark;
}x,y,z;
#include <stdio.h>
#include <conio.h>
int main()
struct testing
int a;
char b;
float c;
}var;
clrscr();
printf(“Size of var=%d\n”,sizeof(var));
printf(“Size of a=%d\n”,sizeof(var.a));
Principles of Programming languages 41
printf(“Size of b=%d\n”,sizeof(var.b));
printf(“Size of c=%d\n”,sizeof(var.c));
var.a=10;
var.b=”w”;
var.c=3.1422;
printf(“value of a=%d\n”,var.a);
printf(“value of b=%c\n”,var.b);
printf(“value of c=%f\n”,var.c);
getch();
return 0;
Union:
#include <stdio.h>
#include <conio.h>
int main()
union testing
int a;
char b;
42
float c;
}var;
clrscr();
printf(“Size of var=%d\n”,sizeof(var));
printf(“Size of a=%d\n”,sizeof(var.a));
printf(“Size of b=%d\n”,sizeof(var.b));
printf(“Size of c=%d\n”,sizeof(var.c));
var.a=10;
var.b=”w”;
var.c=3.1422;
printf(“value of a=%d\n”,var.a);
printf(“value of b=%c\n”,var.b);
printf(“value of c=%f\n”,var.c);
getch();
return 0;
Output of both these programs will be same. The difference lies in the storage.
OBJECTIVE
1. A sturucture member be default is:
(a) Public
(b) Provate
(c) Protected
Principles of Programming languages 43
Chapter 6
Pointers
Q 1. Explain Pointer.
Ans . A pointer refers to a memory location that contains an address.
Pointer Declaration
A pointer must be declared and the variable type it points to must be
specified:
short *aptr; //pointer declaration
double *bptr;
2. A pointer is:
(a) Address of a variable
(b) An indication of a variable to be accessed next
(c) A variable for storing address
(d) None of the above ( )
Chapter 7
File Handling
Writing: fprintf( )
fprintf( ) Syntax:
fprintf( arg1, arg2...)
where arg1 is the file stream pointer and arg2… are identical to arguments of
the
printf() function
Example:
fprintf(fptr,“%d\n”,x);
Reading: fscanf( )
fscanf( ) Syntax:
fscanf( arg1, arg2...)
where arg1 is the file stream pointer and arg2… are identical to arguments of
the
scanf() function
Example:
fscanf(fptr,“%d”,&x);
Output
[file example.txt]
This is a line.
This is another line.
50
Output:
This is a line.
This is another line.
2. File *fp:
(a) Disk data file to be opened (b) Structure file
(c) Both a and b (d) None of the above ( )
4. f close ( ) is a function:
(a) The values of its entire member
(b) only values of one member can be stored
(c) Only according to the size of its member
(d) None of the above ( )
52
Chapter 8
C++ programming
1. malloc()
2. calloc()
3. realloc()
4. free()
#include <iostream.h>
int main(int argc, char **argv) {
int n;
cout << sizeof(n) << ‟ ‟ << sizeof(double) << ‟\n‟;
}
Q 8. Does the pointer gives the information about the size of the array it points
to.
Ans . No Pointers do not give information about pointed array sizes
Q12. Given a sorted array of integers.write a program to find the rank of a given
value in that array.
Ans. #include <iostream.h>
// Returns the rank of x in a and -1 if not found
int rank2(int x, int *a, int n) {
// Let‟s optimize a bit
if(a[0] > x) return -1;
if(a[n-1] < x) return -1;
int i, j;
i = 0; j = n-1;
while(i+1 < j) {
Principles of Programming languages 55
int k = (i+j)/2;
if(a[k] <= x) i = k; else j = k;
}
if(a[i] == x) return i; else if(a[j] == x) return j;
else return -1;
}
int main() {
int a[] = {1, 5, 6, 7, 9, 12, 14, 23, 24, 24, 123};
cout << rank2(14, a, sizeof(a)/sizeof(int)) << ‟\n‟;
}
Q13. What is the difference between the = operator and the copy constructor.
Ans . The copy constructor is called either when we initialize a variable (with the =
operator!), or when we pass parameters by value. The = is called for all other
= assignments.
Ans . The default constructor, destructor, copy constructor, and copy assignment
operator are special member functions. These functions create, destroy, convert,
initialize, and copy class objects.
source code file, which does not contain the directives. The preprocessed
source code, an intermediate file, must be a valid C or C++ program, because
it becomes the input to the compiler
There are two kinds of templates: function templates and class templates.
Function templates
A function template behaves like a function except that the template can have
arguments of many different types In other words, a function template
represents a family of functions. For example, the C++ Standard Library
contains the function template max(x, y) which returns either x or y, whichever
is larger. max() could be defined like this, using the following template:
#include <iostream.h>
A function template does not occupy space in memory. The actual definition
of a function template is generated when the function is called with a specific
data type. The function template does not save memory.
Class templates
Ans By default, C++ matches a function call with the correct function definition at
compile time. This is called static binding. We can specify that the compiler
match a function call with the correct function definition at run time; this is
called dynamic binding. We declare a function with the keyword virtual if we
want the compiler to use dynamic binding for that specific function.
struct B: A {
void f() { cout << "Class B" << endl; }
58
};
int main() {
B x;
g(x);
}
The following is the output of the above example:
Class A
When function g() is called, function A::f() is called, although the argument
refers to an object of type B. At compile time, the compiler knows only that
the argument of function g() will be a reference to an object derived from A; it
cannot determine whether the argument will be a reference to an object of
type A or type B. However, this can be determined at run time. The following
example is the same as the previous example, except that A::f() is declared
with the virtual keyword:
The following is the output of the above example:
#include <iostream.h>
struct A {
virtual void f() { cout << "Class A" << endl; }
};
struct B: A {
void f() { cout << "Class B" << endl; }
};
int main() {
B x;
g(x);
}
Class B
The virtual keyword indicates to the compiler that it should choose the
appropriate definition of f() not by the type of reference, but by the type of
object that the reference refers to.
Therefore, a virtual function is a member function we may redefine for other
derived classes, and can ensure that the compiler will call the redefined
virtual function for an object of the corresponding derived class, even if we
call that function with a pointer or reference to a base class of the object.
A class that declares or inherits a virtual function is called a polymorphic class.
Ans . The inline function takes the format as a normal function but when it is
compiled it is compiled as inline code. The function is placed separately as
inline function, thus adding readability to the source program. When the
program is compiled, the code present in function body is replaced in the
place of function call.
The keyword inline specified in the above example, designates the function as
inline function. For example, if a programmer wishes to have a function
named inlinexmple that rturn value as integer and with no arguments as
inline it is written as follows:
Example:
60
#include <iostream.h>
int inlinexmple (int);
void main( )
{
int x;
cout << “\n Enter the Input Value: ”;
cin>>x;
cout<<”\n The Output is: “ << inlinexmple (x);
}
The output would be the same even when the inline function is written solely
as a function. The concept, however, is different. When the program is
compiled, the code present in the inline function inlinexmple ( ) is replaced in
the place of function call in the calling program. The concept of inline function
is used in this example because the function is a small line of code.
The above example, when compiled, would have the structure as follows:
#include <iostream.h>
int inlinexmple (int);
void main( )
{
int x;
cout << “\n Enter the Input Value: ”;
cin>>x;
Principles of Programming languages 61
When the above program is written as normal function the compiled code
would look like below:
#include <iostream.h>
int inlinexmple (int);
void main( )
{
int x;
cout << “\n Enter the Input Value: ”;
cin>>x;
//Call is made to the function inlinexmple
OBJECTIVE
1. Extensive of a header file, by default, is:
(a) 'h' (b) 'c'
(c) 'cpp' (d) 'exe' ( )
4. Value of (! !) is :
(a) 0 (b) 1
(c) 1 (d) none of the above ( )
62
7 The function declaration double ABC (int, float); denotes that the function ABC:
(a) Returns int value (b) returns float value
(c) Returns double value (d) declaration is incorrect ( )
9 To specify the number of colums to be used to print a number, one should use in print
f– statement?
(a) conversion specified
(b) field width specifier
(c) flag
(d) Precision ( )
10. A C + + Class can hold?
(a) only data
(b) only function
(c) both data and function
(d) none of the above ( )
14. For a function to access the private data of a class, it should be made:
(a) member function
(b) a friend function
(c) both a and b
(d) none of the above ( )
15. A C++ class can hold:
(a) Only data
(b) only function
(c) both same name as class
(d) None of the above ( )
64
Chapter 8
Oops Concepts
2. Less bugs : the data are accessed through the methods and we can use
them only the way to object‟s creator wants us to.
Q 2. Define class.
Ans . A class is a user defined data type that consists of data variables and functions
binded together. These variables and functions are called member functions
and member variables of the class. The member functions are also called
methods. The data members are called properties of the class. An object is the
instance of the class. An object is like a compound variable of the user defined
type. It links both code and data.. The declaration of a class is syntactically
same as structure. The class is declared using keyword class. The general form
of the declaration of the class is:-
class class_name
{
access_specifier:
Principles of Programming languages 65
data functions
access_specifier:
data functions
} object_list;
The object_list is optional. The object_list is used to declare objects of the class.
The class_name is the name of the class. The access_specifier can either
public, private or protected. The members of the class by default are private to
the class. If the access_specifier is private then members of the class are not
accessible outside the class. If the access_specifier is public then members of
the class can be accessed from outside the class. The protected access_specifier
is needed at the time of inheritance. The members can be accessed using an
object‟s name, a dot operator and name of the member.
int main()
{
double volume1=0;
cube c1,c2;
cout << "Enter the lenght of the cube" << endl;
cin >> c1.side;
cout << "The volume of the cube is : " << c1.volume() << endl;
66
c2.side=c1.side +2;
cout << "The volume of the second cube is : " << c2.volume() << endl;
return(0);
}
The result of the program is:-
The program consists of a class cube which has data member side of type
double and member function which calculates the volume of the cube.
Q 4. What is encapsulation?
Ans . Encapsulation is the process of combining data and functions into a single
unit called class. Using the method of encapsulation, the programmer cannot
directly access the data. Data is only accessible through the functions present
inside the class. Data encapsulation led to the important concept of data
hiding. Data hiding is the implementation details of a class that are hidden
from the user. The concept of restricted access led programmers to write
specialized functions or methods for performing the operations on hidden
members of the class.
int main()
{
cube c1(2.34);
cube c2;
cout << "The side of the cube is: " << c1.side << endl;
68
cout << "The volume of the first cube is : " << c1.volume() << endl;
cout << "Enter the length of the second cube : " ;
cin >> c2.side;
cout << "The volume of second cube is : " << c2.volume() << endl;
return(0);
}
There are two types of polymorphism one is compile time polymorphism and
the other is run time polymorphism. Compile time polymorphism is functions
and operators overloading. Runtime time polymorphism is done using
inheritance and virtual functions. Here are some ways how we implement
polymorphism in Object Oriented programming languages.
Compile time polymorphism -> Operator Overloading Function Overloading
Run time polymorphism -> Interface and abstract methods Virtual member
functions.
Example:
Principles of Programming languages 69
#include <iostream.h>
class figure {
protected:
double x, y;
public:
void set_dim(double i, double j=0) {
x = i;
y = j;
}
virtual void show_area() {
cout << "No area computation defined ";
cout << "for this class.\n";
}
};
int main()
{
figure *p; // create a pointer to base type
p = &t;
p->set_dim(10.0, 5.0);
p->show_area();
p = &s;
p->set_dim(10.0, 5.0);
p->show_area();
p = &c;
p->set_dim(9.0);
p->show_area();
Principles of Programming languages 71
return 0;
}
#include <iostream.h>
class A {
int data;
public:
void f(int arg) { data = arg; }
int g() { return data; }
};
class B {
public:
A x;
};
int main() {
B obj;
obj.x.f(20);
cout << obj.x.g() << endl;
// cout << obj.g() << endl;
}
72
In the main function, object obj accesses function A::f() through its data
member B::x with the statement obj.x.f(20). Object obj accesses A::g() in a
similar manner with the statement obj.x.g(). The compiler would not allow the
statement obj.g() because g() is a member function of class A, not class B.
The inheritance mechanism lets us use a statement like obj.g() in the above
example. In order for that statement to be legal, g() must be a member
function of class B.
Inheritance lets us include the names and definitions of another class's
members as part of a new class. The class whose members we want to include
in our new class is called a base class. Our new class is derived from the base
class. The new class contains a subobject of the type of the base class. The
following example is the same as the previous example except it uses the
inheritance mechanism to give class B access to the members of class A:
#include <iostream.h>
class A {
int data;
public:
void f(int arg) { data = arg; }
int g() { return data; }
};
class B : public A { };
int main() {
B obj;
obj.f(20);
cout << obj.g() << endl;
}
Class A is a base class of class B. The names and definitions of the members of
class A are included in the definition of class B; class B inherits the members
of class A. Class B is derived from class A. Class B contains a subobject of type
A.
We can also add new data members and member functions to the derived
class. We can modify the implementation of existing member functions or
Principles of Programming languages 73
data by overriding base class member functions or data in the newly derived
class.
We may derive classes from other derived classes, thereby creating another
level of inheritance. The following example demonstrates this:
struct A { };
struct B : A { };
struct C : B { };
Class B is a derived class of A, but is also a base class of C. The number of
levels of inheritance is only limited by resources.
public:
int y;
};
class C : public B { };
Class B is a direct base class of C. Class A is a direct base class of B. Class A is
an indirect base class of C. (Class C has x and y as its data members.)
We can Overload a function name f by declaring more than one function with
the name f in the same scope. The declarations of f must differ from each
other by the types and/or the number of arguments in the argument list.
When we call an overloaded function named f, the correct function is selected
by comparing the argument list of the function call with the parameter list of
each of the overloaded candidate functions with the name f. A candidate
function is a function that can be called based on the context of the call of the
overloaded function name.
void print(char* c) {
cout << " Here is char* " << c << endl;
Principles of Programming languages 75
int main() {
print(10);
print(10.10);
print("ten");
}
The following is the output of the above example:
Here is int 10
Here is float 10.1
Here is char* ten
Operator Overloading
An overloaded operator is called an operator function. We declare an operator
function with the keyword operator preceding the operator. Overloaded
operators are distinct from overloaded functions, but like overloaded
functions, they are distinguished by the number and types of operands used
with the operator.
Consider the standard + (plus) operator. When this operator is used with
operands of different standard types, the operators have slightly different
meanings. For example, the addition of two integers is not implemented in
the same way as the addition of two floating-point numbers. C++ allows you
to define we own meanings for the standard C++ operators when they are
applied to class types. In the following example, a class called complx is
defined to model complex numbers, and the + (plus) operator is redefined in
this class to add two complex numbers.
// This example illustrates overloading the plus (+) operator.
#include <iostream.h>
class complx
{
double real,
imag;
76
public:
complx( double real = 0., double imag = 0.); // constructor
complx operator+(const complx&) const; // operator+()
};
// define constructor
complx::complx( double r, double i )
{
real = r; imag = i;
}
int main()
{
complx x(4,4);
complx y(6,6);
complx z = x + y; // calls complx::operator+()
}
OBJECTIVE
1. The operator over loading function can be :
(a) member function only
(b) non member function only
(c) both b or b
(d) none of the above ( )
Principles of Programming languages 77
2. The number of copies created for a static data member of a class, when 10 class object
are created would be:
(a) 0 (b) 1
(c) 2 (d) 4 ( )
3. The number of copies created for a static data member of class, when 10 class objects
are created, would be:
(a) 0 (b) 1
(c) 9+ (d) 10 ( )
4 A destructor :
(a) has a return type
(b) may take parameters
(c) has same name of class
(d) both b and a ( )
5. A constructor:
(a) has a return type (b) may take parameter
(c) has same name as class (d) both a and b ( )
8. A new class can be derived from an existing class. This concept is called as:
(a) inheritance (b) Polymorphism
(c) overlaoding (d) dynamic binding ( )
(a) + (b) X
(c) / (d) % ( )
Chapter 9
CASE STUDY
k++;
}
Str2[k]=' ';
k++;
p=i+1;
}
}
for(i=0;i<p;i++)
cout<<str2[i];
break;
case 2:
cout<<"Enter the String"<<endl;
gets(str1);
l=strlen(str1);
p=l-1;
for(i=l-1;i>=-1;i--)
{
if((str1[i]==' ')||(i == -1))
{
for(j=i+1;j<=p;j++)
{
Str2[k]=str1[j];
k++;
}
Str2[k]=' ';
k++;
p=i-1;
}
}
for(i=0;i<=l;i++)
cout<<str2[i];
82
break;
default:
cout<<"Wrong Choice"<<endl;
break;
}
getch();
}
void main()
{
clrscr();
int x,y,sum;
float average;
cout << "Enter 2 integers : " << endl;
cin>>x>>y;
sum=x+y;
average=sum/2;
cout << "The sum of " << x << " and " << y << " is " << sum << "." << endl;
cout << "The average of " << x << " and " << y << " is " << average << "." <<
endl;
getch();
}
Principles of Programming languages 83
3. //This program takes in the velocity, acceleration and the time as a screen
input from the user.
//The final velocity is calculated using the formula v = u + a * t, and then
outputted using the //'cout' command.
#include <iostream.h>
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
int x,y,sum;
float average;
cout << "Enter 2 integers : " << endl;
cin>>x>>y;
sum=x+y;
average=sum/2;
cout << "The sum of " << x << " and " << y << " is " << sum << "." << endl;
cout << "The average of " << x << " and " << y << " is " << average << "." <<
endl;
getch();
4. //This program takes in an integer num as a screen input from the user.
//It then calculates the total value of the integer based on the formula x -
1/3!x^3 + 1/5!x^5 - //1/7!x^7 + 1/9!x^9.
//It then outputs the final answer using the 'cout' command.
#include <iostream.h>
84
#include <conio.h>
#include <math.h>
int main()
{
clrscr();
float factorial=1;
float num,tot,term,total;
int i,n=20,index,j=1;
cout << "Enter a single-digit integer : \n";
cin>>num;
tot=num;
total=num;
for(i=2,index=3;i<=n;i++,index+=2)
{
for(j=1,factorial=1;j<=index;j++)
factorial*=j;
tot=tot*pow((double)(-1),(double)(2*i-1))*num*num;
term=tot/factorial;
total+=term;
}
cout << "Total = " << total << endl;
getch();
return 0;
}
5. //This program does not take in any screen inputs from the user.
//It just prints out the first ten lines of the pascal's triangle using the 'cout'
command.
#include <iostream.h>
Principles of Programming languages 85
#include <conio.h>
#include <iomanip.h>
long triangle(int x,int y);
int main()
{
clrscr();
const lines=10;
for (int i=0;i<lines;i++)
for (int j=1;j<lines-i;j++)
cout << setw(2) << " ";
for (int j=0;j<=i;j++)
cout << setw(4) << triangle(i,j);
cout << endl;
getch();
}
long triangle(int x,int y)
{
if(x<0||y<0||y>x)
return 0;
long c=1;
for (int i=1;i<=y;i++,x--)
c=c*x/i;
return c;
}
#include <iostream.h>
#include <conio.h>
86
void main()
{
clrscr();
int x;
int A[4][4],sum=0; //Reading the matrix.
cout << "Enter the elements of the matrix : " << endl;
for(int y=0;y<4;y++)
for (int x=0;x<4;x++)
{
cout << "Element " << x+1 << ", " << y+1 << " : ";
cin>>A[x][y];
}
//Sum of either of the diagonal elements.
for(x=0;x<4;x++)
for(y=0;y<4;y++)
if(x==y)
sum+=A[x][y];
else if(y==4-(1+1));
sum+=A[x][y];
cout << "Sum of either of the diagonal elements is : " << sum;
getch();
}
Principles of Programming languages 87
Keywords
control_statement =statements that permit a processor to select the next of several possible
computations according to various conditions.
data_type =A collection of values together with the operations that use them and produce
them.
declaration =A piece of source code that adds a name to the program's environment and
binds it to a class of meanings, and may also define the name.
default =An item provided in place of an omitted item.
dynamic_binding =A binding that can be made at any time as a program runs and may
encapsulation =The ability to hide unwanted details inside an interface so that the result
works like a black box or vending machine - providing useful services to many
clients(programs or people).
enumerated data_type=data defined by listing its possible values.
equation =A formula stating the equality of two or more formula which may be true if the
correct values of the variables are found.
exception =a mechanism for handling abnormal situations.
expression =A shorthand description of a calculation
formal_parameter =The symbol used inside a subprogram in place of the actual_parameter
provided when the subprogram is called.
function =A subprogram that returns a value but can not change its parameters or have side
effects.
garbage =A piece of storage that has been allocated but can no longer be accessed by a
program.
goto = usable in all practical languages to indicate an unconditional jump.
header_file =A collection of function headers, class interfaces, constants and definitions that
is read by a compiler and changes the interpretation of the rest of the program by defining
operation for handling strings.
identifier := a name used in a programming language to identify something else - a variable,
function, procedure, etc.`.
Principles of Programming languages 89
syntax =A description of the rules that determine the validity and parsing of sentences or
statements in a language.
ternary = Ternary operators have two operands. Ternary numbers have base 3 and use 3
symbols.
tree =A collection of connected objects called nodes with all nodes connected indirectly by
precisely one path. An ordered tree has a root and the connections lead from this root to all
other nodes. Nodes at the end of the paths are caled leaves. The connections are called
branches. All computer science tress are drawn upside-down with the root at the top and the
leaves at the bottom.
unary = unary operators have one operand, unary numbers use base 1 and one symbol.
92
OBJECTIVE PART- I
Year - 2011
Time allowed : One Hour Maximum Marks : 20
The question paper contains 40 multiple choice questions with four choices and student will
have to pick the correct one (each carrying ½ mark).
3. BCPL is:
(a) Beginner Computer Programming Language
(b) Basic Computer Programs Language
(c) Basic Combined Programming Language
(d) None of the above ( )
8. ………………are data values that never change their values during program
execution.
(a)
(b)
(c)
(d) None of the above ( )
(a) C (b) C+
(c) COBOL (d) FORTRAN ( )
20. The……….function is used to return a single character from a standard input device :
(a) putch ( ) (b) putchar ( )
(c) getchar ( ) (d) none of the above ( )
22. The cin and cout objects required the header file:
Principles of Programming languages 95
(a) stdio.h
(b) iostream.h
(c) iomainp.h
(d) none of the above ( )
26. The binding of data and function together into a single class type variable is known to
as……………..
(a) Encapsulation
(b) Inheritance
(c) Polymorphism
(d) None of the above ( )
28. A…………………..is a special member function whose task is to initialize the object
of its class :
(a) Constructor
(b) Destructor
(c) Polymorphism
(d) None of the above ( )
96
30. Choose the storage class type which access the variable fastly:
(a) Automatic storage class
(b) Static storage class
(c) Register storage class
(d) External storage class ( )
31. A destructor :
(a) has a return type
(b) can have parameters
(c) has same name as class
(d) All of the above ( )
(d) Polymorphism ( )
36. We can give several meaning to an operator. This process is known as…………..
(a) Polymorphism
(b) Inheritance
(c) Operator overloading
(d) Function overloading ( )
40. Among the following which one is the scope resolution operator?
(a) *` (b)
(c) :: (d) ! ( )
Answer Key
1. ( b ) 2. ( a ) 3. ( c ) 4. (d ) 5. ( d ) 6. ( d 7. ( b ) 8. ( b ) 9. (d ) 10. ( b)
)
11. ( c) 12. (d ) 13. ( a) 14. (c) 15. (c ) 16. (a) 17. (a ) 18. (c ) 19. (d) 20.(c )
21. (d ) 22. (b) 23. ( d) 24. (c) 25. (a ) 26. (a) 27. (b ) 28. (a ) 29. (b ) 30. ( c)
31. (c ) 32. (c ) 33. (c ) 34. (b) 35. (d ) 36. ( c) 37. ( d) 38. (d) 39. (c ) 40. (c )
98
Year- 2011
int count ;
extern void write_extern();
main()
{
write_extern();
}
Second File: write.c
#include <stdio.h>
void write_extern(void)
{
count = 5;
printf("count is %d\n", count);
}
Here extern keyword is being used to declare count in the second file where as it has
its definition in the first file. Now compile these two files as follows:
$gcc main.c write.c
100
This will produce a.out executable program, when this program is executed, it
produces following result: 5
Summary
n--;
if (n>0)
goto loop;
printf( "FIRE”);
}
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
Q1.c Discuss the various parameter passing methods.
A There are two ways to pass parameters to a function:
Pass by Value:
This mechanism is used when we don't want to change the value of passed paramters.
When parameters are passed by value then functions in C create copies of the passed
in variables and do required processing on these copied variables.
int main()
{
int a = 10;
int b = 20;
t = p2;
p2 = p1;
p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", p1, p2 );
}
Pass by Reference :
This mechanism is used when you want a function to do the changes in passed
parameters and reflect those changes back to the calling function. In this case only
addresses of the variables are passed to a function so that function can work directly
over the addresses.
102
int main()
{
int a = 10;
int b = 20;
t = *p2;
*p2 = *p1;
*p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", *p1, *p2 );
}
before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b(p2) = 10
After: Value of a = 20 and value of b = 10
/ Division a/b
* Multiplication a*b
% Modulo or remainder a%b
2 Relational Operators
Relational operators compare between two operands and return in terms of true or
false i.e. 1 or 0. In C and many other languages a true value is denoted by the integer 1
and a false value is denoted by the integer 0. Relational operators are used in
conjunction with logical operators and conditional & looping statements.
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
!= Not equal to
== Equal to
3 Logical Operators
A logical operator is used to compare or evaluate logical and relational expressions.
There are three logical operators available in the C language.
&& Logical AND
|| Logical OR
! Logical NOT
4 Assignment operator
An assignment operator (=) is used to assign a constant or a value of one variable to
another.
Example:
a = 5;
b = a;
rate = 10.5
net = (a/b) * 100;
* There is always difference between the equality operator (==) and the assignment
operator (=).
6 Bitwise Operators:
These are used to perfom bitwise operations such as testing the bits , shifting the bits
to left or right , one‟s compliment of bits. This operator can be apply on only int and
char data type.
& AND
| Inclusive OR
^ Exclusive OR
<< Shift Left
>> Shift Right
~ One's compliment
~A = 1100 0011
{
int a;
char b;
float c;
}var;
clrscr();
printf(“Size of var=%d\n”,sizeof(var));
printf(“Size of a=%d\n”,sizeof(var.a));
printf(“Size of b=%d\n”,sizeof(var.b));
printf(“Size of c=%d\n”,sizeof(var.c));
var.a=10;
var.b=”w”;
var.c=3.1422;
printf(“value of a=%d\n”,var.a);
printf(“value of b=%c\n”,var.b);
printf(“value of c=%f\n”,var.c);
getch();
return 0;
}
Union:
#include <stdio.h>
#include <conio.h>
int main()
{
union testing
{
int a;
char b;
float c;
}var;
clrscr();
printf(“Size of var=%d\n”,sizeof(var));
printf(“Size of a=%d\n”,sizeof(var.a));
printf(“Size of b=%d\n”,sizeof(var.b));
printf(“Size of c=%d\n”,sizeof(var.c));
var.a=10;
var.b=”w”;
var.c=3.1422;
printf(“value of a=%d\n”,var.a);
printf(“value of b=%c\n”,var.b);
printf(“value of c=%f\n”,var.c);
106
getch();
return 0;
} Output of both these programs will be same. The difference lies in the storage.
Q3.a Write a program to input any number and print them in reverse order using
‘WHILE statement’ in C.
Ans #include<stdio.h>
void main()
{
long int number,reverse,n;
clrscr();
printf("Enter the number");
scanf("%ld",&number);
reverse=0;
while(number!=0)
{
n=number%10;
reverse=reverse*10+n;
number=number/10;
}
printf("The reverse number=%ld\n",reverse);
getch();
}
double side;
double volume()
{
return(side*side*side);
}
cube(double side1)
{
cout << "A constructor is called" << endl;
side=side1;
}
cube()
{
cout << "A default constructor is called " << endl;
}
~cube()
{
cout << "Destructing " << side << endl;
}
};
int main()
{
cube c1(2.34);
cube c2;
cout << "The side of the cube is: " << c1.side << endl;
cout << "The volume of the first cube is : " << c1.volume() << endl;
cout << "Enter the length of the second cube : " ;
cin >> c2.side;
cout << "The volume of second cube is : " << c2.volume() << endl;
return(0);
}
An exception is thrown by using the throw keyword from inside the try block.
Exception handlers are declared with the keyword catch, which must be placed
immediately after the try block:
// exceptions
#include <iostream>
using namespace std;
int main () {
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << endl;
}
return 0;
}
The code under exception handling is enclosed in a try block. In this example this code
simply throws an exception:
throw 20;
A throw expression accepts one parameter (in this case the integer value 20), which is
passed as an argument to the exception handler.
The exception handler is declared with the catch keyword. As you can see, it follows
immediately the closing brace of the try block. The catch format is similar to a regular
function that always has at least one parameter. The type of this parameter is very
important, since the type of the argument passed by the throw expression is checked
against it, and only in the case they match, the exception is caught.
We can chain multiple handlers (catch expressions), each one with a different
parameter type. Only the handler that matches its type with the argument specified in
the throw statement is executed.
top. push adds an item to the top of the stack, pop removes the item from the top. A
helpful analogy is to think of a stack of books; you can remove only the top book, also
you can add a new book on the top. stack is a recursive data structure.
Queues
A queue is a container of objects (a linear collection) that are inserted and removed
according to the first-in first-out (FIFO) principle. An excellent example of a queue is
a line of students in the food court of the UC. New additions to a line made to the back
of the queue, while removal (or serving) happens in the front. In the queue only two
operations are allowed enqueue and dequeue. Enqueue means to insert an item into the
back of the queue, dequeue means removing the front item. The picture demonstrates
the FIFO access
The difference between stacks and queues is in removing. In a stack we remove the
item the most recently added; in a queue, we remove the item the least recently added.
But before that it is important to know some new terminologies used in Object
Oriented programming namely
Objects
Classes
Objects:
In other words object is an instance of a class.
Classes:
These contain data and functions bundled together under a unit. In other words class is
a collection of similar objects. When we define a class it just creates template or
Skelton. So no memory is created when class is created. Memory is occupied only by
object.
Example:
Classclassname
{
Data
Functions
};
main ( )
{
classname objectname1,objectname2,..;
}
In other words classes acts as data types for objects.
Member functions:
The functions defined inside the class as above are called member functions.
Data Hiding:
This concept is the main heart of an Object oriented programming. The data is hidden
inside the class by declaring it as private inside the class. When data or functions are
defined as private it can be accessed only by the class in which it is defined. When
data or functions are defined as public then it can be accessed anywhere outside the
class. Object Oriented programming gives importance to protecting data which in any
system. This is done by declaring data as private and making it accessible only to the
class in which it is defined. This concept is called data hiding. But one can keep
member functions as public.
So above class structure becomes
Example:
Class classname
{
private:
datatype data;
Principles of Programming languages 111
public:
Member functions
};
main ( )
{
classname objectname1,objectname2,..;
}
Encapsulation:
The technical term for combining data and functions together as a bundle is
encapsulation.
Inheritance:
Inheritance as the name suggests is the concept of inheriting or deriving properties of
an exiting class to get new class or classes. In other words we may have common
features or characteristics that may be needed by number of classes. So those features
can be placed in a common tree class called base class and the other classes which
have these charaterisics can take the tree class and define only the new things that they
have on their own in their classes. These classes are called derived class. The main
advantage of using this concept of inheritance in Object oriented programming is it
helps in reducing the code size since the common characteristic is placed separately
called as base class and it is just referred in the derived class. This provide the users
the important usage of terminology called as reusability
Reusability:
This usage is achieved by the above explained terminology called as inheritance.
Reusability is nothing but re- usage of structure without changing the existing one but
adding new features or characteristics to it. It is very much needed for any
programmers in different situations. Reusability gives the following advantages to
users
It helps in reducing the code size since classes can be just derived from existing one
and one need to add only the new features and it helps users to save their time.
For instance if there is a class defined to draw different graphical figures say there is a
user who want to draw graphical figure and also add the features of adding color to the
graphical figure. In this scenario instead of defining a class to draw a graphical figure
and coloring it what the user can do is make use of the existing class for drawing
graphical figure by deriving the class and add new feature to the derived class namely
add the feature of adding colors to the graphical figure.
Polymorphism and Overloading:
Poly refers many. So Polymorphism as the name suggests is a certain item appearing
in different forms or ways. That is making a function or operator to act in different
forms depending on the place they are present is called Polymorphism. Overloading is
a kind of polymorphism. In other words say for instance we know that +, - operate on
112
integer data type and is used to perform arithmetic additions and subtractions. But
operator overloading is one in which we define new operations to these operators and
make them operate on different data types in other words overloading the existing
functionality with new one. This is a very important feature of object oriented
programming methodology which extended the handling of data type and operations.
main()
{
int n, i = 3, count, c;
if ( n >= 1 )
{
printf("First %d prime numbers are :\n",n);
printf("\n");
}
return 0;
}
Principles of Programming languages 113
A #include<stdio.h>
main()
{
int count = 40,i;
clrscr();
for(i=1;i<=u;i++)
{
printf(“\n\n\n”;
for(int j=1;j<=count;j++)
{
printf(“ “);
}
for(int k=1;k<=i;k++)
{
printf(“%8d”,i);
}
count=count-4;
}
getch();
}
point to the first node of the list; in that case the list is said to be circular or circularly
linked; otherwise it is said to be open or linear.
A singly linked list whose nodes contain two fields: an integer value and a link to the
next node
In a doubly linked list, each node contains, besides the next-node link, a second link
field pointing to the previous node in the sequence. The two links may be called
forward(s) and backwards, or next and prev(ious).
A doubly linked list whose nodes contain three fields: an integer value, the link
forward to the next node, and the link backward to the previous node
A technique known as XOR-linking allows a doubly linked list to be implemented
using a single link field in each node. However, this technique requires the ability to
do bit operations on addresses, and therefore may not be available in some high-level
languages.
In a multiply linked list, each node contains two or more link fields, each field
being used to connect the same set of data records in a different order (e.g., by name,
by department, by date of birth, etc.). (While doubly linked lists can be seen as
special cases of multiply linked list, the fact that the two orders are opposite to each
other leads to simpler and more efficient algorithms, so they are usually treated as a
separate case.)
In the case of a circular doubly linked list, the only change that occurs is that end, or
"tail", of the said list is linked back to the front, or "head", of the list and vice versa.
Virtual Function
A virtual function is a member function that is declared within a base class and
redefined by a derived class. To create virtual function, precede the function‟s
declaration in the base class with the keyword virtual. When a class containing
virtual function is inherited, the derived class redefines the virtual function to suit its
own needs.
Principles of Programming languages 115
Base class pointer can point to derived class object. In this case, using base class
pointer if we call some function which is in both classes, then base class function is
invoked. But if we want to invoke derived class function using base class pointer, it
can be achieved by defining the function as virtual in base class, this is how virtual
functions support runtime polymorphism.
Consider following program code:
Class A
{
int a;
public:
A()
{
a = 1;
}
virtual void show()
{
cout <<a;
}
};
Class B: public A
{
int b;
public:
B()
{
b = 2;
}
virtual void show()
{
cout <<b;
}
};
int main()
{
A *pA;
B oB;
pA = &oB;
pA->show();
return 0;
}
Output is 2 since pA points to object of B and show() is virtual in base class A.
116
OBJECTIVE PART- I
Year - 2010
Time allowed : One Hour Maximum Marks : 20
The question paper contains 40 multiple choice questions with four choices and student will
have to pick the correct one (each carrying ½ mark).
4. Which one of the following language is not implemented using pure interpretation?
(a) Syntex
(b) Semantic of programming languages
(c) Both a and b
(d) None of the above ( )
9. Ambiguity means:
(a) Two distinct left parse tree for a sentence
(b) Two distinct right parse tree for sentence
(c) More than one parse tree for a sentence
(d) None of the above ( )
10. Which of the following statement is true after execution of the program:
Int a [10], I, *p;
A [0] = I;
A p1[ =2;
P=a;
(*p)++;
(a) a [0] =2 (b) a [1] = 3
(c) a [1] =2 (d) a [0] =1 ( )
12. Choose the storage class type which access the variable fastly:
(a) Automatic storage class
(b) Static storage class
(c) Register storage class
(d) External strogae class ( )
22. In n has the value 3, output of the statemtn printf (%d",n++, ++n); is:
(a) 3,4 (b) 4,5
(c) 4,4 (d) Implementation dependent ( )
25. The cin and cout object required the header file:
(a) stdio.h (b) Iostream.h
(c) iomainp.h (d) None of the above ( )
26. A destructor :
(a) has a return type (b) can have parameter
(c) has same name as class (d) All of the above ( )
29. Among the following which one is the scope resoluation operator?
(a) * (b)
(c) :: (d) ! ( )
31. Cout is :
(a) a key word (b) an object
120
Answer Key
1. ( b ) 2. (b ) 3. (c ) 4. (a) 5. ( c ) 6. ( b ) 7. (c ) 8. ( a ) 9. ( c ) 10. ( a)
11. (b ) 12. (c ) 13. ( a) 14. (c) 15. ( a) 16. ( a) 17. (a ) 18. (b ) 19. ( d) 20.(d )
21. (b ) 22. (c ) 23. ( b) 24. (a) 25. ( b) 26. (c ) 27. (d ) 28. ( c) 29. (c ) 30. (b )
31. (b ) 32. (a ) 33. (a ) 34. (c) 35. (c ) 36. (a 37. (b) 38. ( c) 39. (c ) 40. ( b)
_____________
122
DESCRIPTIVE PART-II
Year- 2010
Q.3 (a) What are contract structure in language? Explain with syntax.
(b) Write a program in C to accept 10 elements of an array and find highest element
and average of elements of the array.
Q.4 (a) What is an operator? Describe several different types of operators that are included
in C.
(b) Write a program to calculate factorial of a given integer number n.
Q.5 (a) What is pointer? How is it declared and initialized? Explain the difference between
"Call by value"
(b) Write short notes on the following
(i) Data encapsulation
(ii) Operator overloading
OBJECTIVE PART- I
Year - 2009
Time allowed : One Hour Maximum Marks : 20
The question paper contains 40 multiple choice questions with four choices and student will
have to pick the correct one (each carrying ½ mark).
1. A destructor :
(a) Has a return type (b) Have parameters
(c) has same name as class (d) None of the above ( )
7. Prolog means:
(a) programming logic (b) Program logic
(c) Programming logic method (d) program function ( )
124
11. A new class can be derived from an existing class, that is done by:
(a) Inheritance
(b) overloading
(c) polymorphism
(d) overriding ( )
20. The number of copies created for a static data member of a class, when 10 class object
created would be:
(a) 0 (b) 1
(c) 9 (d) 10 ( )
32. Which of the following operator does not require any arguments while overloading the
operator ?
(a) ++
(b) +
(c) [ }
(d) ≪ ( )
36. Choose the strorage class type which accesses the variable fast:
(a) Automatic storage (b) Static storage class
(c) Register storage class (d) External storage class ( )
Answer Key
1. ( c ) 2. (a ) 3. (a ) 4. (c) 5. ( c ) 6. ( a ) 7. (a ) 8. ( c) 9. ( b ) 10. ( d)
11. (a ) 12. (c ) 13. ( b) 14. (b) 15. ( b) 16. ( a) 17. (b ) 18. (c) 19. ( a) 20.(b )
21. (d ) 22. (c ) 23. ( a) 24. (c) 25. ( c) 26. (c ) 27. (c ) 28. ( a) 29. (a ) 30. (c )
31. (b ) 32. (d ) 33. b ) 34. (c) 35. (a ) 36. (a) 37. (a) 38. ( c) 39. (b ) 40. ( c)
Principles of Programming languages 129
DESCRIPTIVE PART-II
Year- 2009
Q.1 (a) Define syntax and semantics. Distinguish between static and dynamic semantics.
(b) What are the advantages and disadvantages of implicit declarations?
Q.2 (a) What are the different of data types available in language? Explain in detail with an
example.
(b) Write a program in C language to check the implicit and explicit type conversin.
Q.3 (a) Write a program in C language to calculate the sum of the given number (34567 =
3+4+5+6+7 =25)
(b) What do you mean by nested loop? Explain break statement with the suitable
example.
Q.5 (a) Explain the concept of pointer. What is smart pointer? Discuss virtual function?
(b) What is structure? Explain the array of structure with an example?
Q.6 (a) What constructor? Explain constructor overloading and copy constructor.
(b) What is inheritance? Explain different levels of inheritance.
130
OBJECTIVE PART- I
Year - 2008
Time allowed : One Hour Maximum Marks : 20
The question paper contains 40 multiple choice questions with four choices and student will
have to pick the correct one (each carrying ½ mark).
4. You are not allowed to call a ……….. member functions from anywhere other than
member unction of the same class:
(a) Global (b) Public
(c) Local (d) Provate ( )
10. When the code a member function is defined inside a class declaration, it is called:
(a) Purchases book (b) Sales book
(c) Purchases returns book (d) Journal proper ( )
11. You can redefine the way………..work when used with objects:
(a) Standard operators
(b) Preprocessor directives
(c) Whilespace characters
(d) Undefined variables ( )
12. Each and every operator of C + + can be overloaded. This statement is……..
(a) True
(b) False
(c) Conditional
(d) None ( )
13. The principles of …………allows as to create new classes based on existing classes:
(a) Inheritance
(b) Function over loading
(c) Copy construction
(d) Polymorphism ( )
14. When you desire a class privately a protected base class member becomes;
(a) Public (b) Private
(c) Explicit (d) Inherited ( )
23. To read a single character from a file, we use the member function…………
(a) input (b) get
(c) put (d) read ( )
24. The …………..member function retunes the true value when the end of file has been
found:
(a) input (b) get
(c) put (d) read ( )
32. A function that does not return anything can be declared by:
(a) float (b) int
(c) void (d) char ( )
36. C is a:
(a) Middle level language (b) High level language
(c) Low level language (d) None ( )
Answer Key
1. ( b ) 2. (d ) 3. (a ) 4. (d) 5. ( a ) 6. ( a ) 7. (b ) 8. ( d ) 9. ( c ) 10. ( b)
11. (b ) 12. (b ) 13. ( b) 14. (b) 15. ( a) 16. ( c) 17. (d ) 18. (a ) 19. ( b) 20.(c )
21. (b ) 22. (a ) 23. ( b) 24. (c) 25. ( b) 26. (c ) 27. (a) 28. ( c) 29. (c ) 30. (d )
31. (d ) 32. (b ) 33. (c ) 34. (d) 35. (d ) 36. (a ) 37. (b) 38. ( d) 39. (a ) 40. ( a)
Principles of Programming languages 135
DESCRIPTIVE PART-II
Year- 2008
Q.1 (a) Explain the features of good programming language. Write a note on generations
of computer languages.
(b) What are different types of function available in C language? Write a note on
subroutines.
Q.2 (a) Write a program in c language to count the number of characters in a string.
(b) What are control structures in C language? What is method overaloading?
Q.3 (a) What are the construction and destructors? Write a note on classes and objects.
(b) Write a program in C language to calculate the real roots of the quadratic equation:
ax2 + bx + c = 0
Using the quadratic formula :
x=
Q.4 (a) What is an array? How it is defined in a C program? Write a program in C shoring
the use of an array?
(b) What are loop control structures? Write a note on interrupts.
Q.5 (a) What are the feature of object oriented programming languages? How a class is
defined inside a class?
(b) What are different types of data structures in C++? What is dynamic allocation?
Q.6 (a) Write an algorithm for inserting an element in a link list. What are class
constructors?
(b) Write a program in C ++ to calculate the income tax based in yearly pay of an
employee.
136
OBJECTIVE PART- I
Year - 2007
Time allowed : One Hour Maximum Marks : 20
The question paper contains 40 multiple choice questions with four choices and student will
have to pick the correct one (each carrying ½ mark).
4. int x,y = 2, z, a;
X = (y * =2) + (z =a=y)
printf ("d",x);
(a) prints 7
(b) prints 6
(c) prints 8
(d) is syntactically warning ( )
6. Printf ("%C",100):
(a) Prints 100
(b) Prints the ASCII equivalent of 100
(c) prints garbage
(d) none of the above ( )
9. C is a :
(a) high level language
(b) low level language
(c) high level language with some low level languages
(d) machine language ( )
11. A destructor :
(a) has a return type
(b) can have para meter
(c) has same name as class
(d) none of the above ( )
13. The cin and cout functions require the header file:
138
17. If max is a function that returns the large of the two integers given as arguments, then
which of the following statements finds the largest of three given numbers?
(a) max (max (a,b), max (a,c) ) (b) max(msx(a,b), max (b,c))
(c) max (b, max(a,b)) (d) all of the above ( )
19. main ( )
{
Int a = 5, b =2;
Printf ("d,a +++b);
}
(a) results in syntax (b) prints 7
(c) prints 8 (d) none of the above ( )
24. A constructor :
(a) has a return type (b) may take parameters
(c) both data and function (d) both b and a ( )
25. A new class can be derived from an existing class. This concept is called as:
(a) inheritance (b) Polymorphism
(c) overlaoding (d) dynamic binding ( )
26. Among the following, which one is the scope resolution operator?
(a) * (b)
(c) :: (d) ! ( )
Answer Key
1. ( b ) 2. (c ) 3. (a ) 4. (d) 5. ( c ) 6. ( d ) 7. (b) 8. ( a) 9. ( c) 10. ( a)
11. (c ) 12. (d ) 13. ( b) 14. (a) 15. ( d) 16. ( a) 17. (d ) 18. (a ) 19. ( b) 20.(b )
21. (c ) 22. (a ) 23. ( c) 24. (d) 25. ( a) 26. (c ) 27. (a ) 28. ( c) 29. (a ) 30. (b)
31. (b ) 32. (c ) 33. (d ) 34. (c) 35. (b) 36. (a ) 37. (c) 38. ( a) 39. (d ) 40. ( b)
_________
142
DESCRIPTIVE PART-II
Year- 2007
Q.1 (a) What is an operator? Describe several different types of operators that are included
in C.
(b) Define the following
(i) Syntax
(ii) Semanties
(iii) Grammar.
Q.2 (a) Write a C program calculate the real roots of the quadratic equation ax2 + bx +c = 0
Using a quadratic formula :
(b) Point out the error, if nay, in the following program:
(i) main ( )
{
ini i=1;
if (i > 10)
break;
}
}
(ii) main ( )
{
int i = 1
while ( ; ; )
{
printf("%d",i++);
If (i>10)
Break;
}
}
}
(iv) will the following function work ? <Yes/No.>
F1 (int a, int b)
{
return (f2(20));
}
F2 (int a
{ return (a * a);
}
Q.3 (a) What is an array in C? Explain, with example, how an array is declared and
initialized.
(b) Write a complete c program to print integer array of 10 elements and find
initialized.
Q.6 (a) What is pointer? How is it declared and initialized? Explain the difference between
"Call by value and call by reference?
(b) What is function? Describe the various category of function with examples.
144
OBJECTIVE PART- I
Year - 2006
Time allowed : One Hour Maximum Marks : 20
The question paper contains 40 multiple choice questions with four choices and student will
have to pick the correct one (each carrying ½ mark).
4. Value of (! !) is :
(a) 0 (b) 1
(c) 1 (d) none of the above ( )
12. The function declaration double ABC (int, float); denotes that the function ABC:
(a) Returns int value (b) returns float value
(c) Returns double value (d) declaration is incorrect ( )
14. Consider the declaration int a [5] = {0,1}; the value of the element a [2] :
(a) 0 (b) 2
(c) 1 (d) can not predict ( )
15. How many times will take printf statement in the following code will be executed ?
for (i =1'< 1; i=I +1)
print ("hellow");
(a) 0 (b) 10
(c) 6 (d) 11 ( )
16. The function prototype for a function smallest that takes 3 integers x,y,z and returns an
integer would be:
(a) void smallest (int); (b) void smallest (int x, int y, int z)
(c) int smallest (x,y,z) (d) int smallest (int, int, int); ( )
146
18. What is the value of sum when the following code is executed?
int a [5] = {0,1,2,3,4};
int sum = 1 = i=0
while (i< 4)
{
sum + = a [i];
i++;
}
(a) 10
(b) 7
(c) 6
(d) 5 ( )
19. Consider the declaration int a [ ] = {0,1,2,3,4} what will be the value of a (0) a p5[ ?
(a) 0
(b) 4
(c) error message
(d) unpredictable ( )
20. To specify the number of colums to be used to print a number, one should use in print
f– statement?
(a) conversion specified
(b) field width specifier
(c) flag
(d) Precision ( )
25. For a function to access the private data of a class, it should be made:
(a) member function
(b) a friend function
(c) both a and b
(d) none of the above ( )
27. A new class can be derived from an existing class. This concept is called us:
(a) inheritance
(b) polymorphism
(c) overloading
(d) dynamic binding ( )
28. The cin and cout functions require the header file:
(a) stdio.h
(b) iostream.h
(c) iomanip.h
(d) none of the above ( )
34. The word which makes the name of tan operator overloading function is:
(a) the operator symbol
(b) the key word operator
(c) the keyboard operator followed by the operator symbol
(d) user defined ( )
36. The number of copies created for a static data member of a class, when 10 class object
are created would be:
(a) 0 (b) 1
(c) 2 (d) 4 ( )
37. The number of copies created for a static data member of class, when 10 class objects
are created, would be:
(a) 0 (b) 1
(c) 9+ (d) 10 ( )
Principles of Programming languages 149
38. A destructor :
(a) has a return type
(b) may take parameters
(c) has same name of class
(d) both b and a ( )
39. A constructor:
(a) has a return type (b) may take parameter
(c) has same name as class (d) both a and b ( )
Answer Key
1. ( a) 2. (c ) 3. (b ) 4. (a) 5. ( d ) 6. ( b ) 7. (b ) 8. ( b ) 9. ( d) 10. ( d)
11. (b ) 12. (c ) 13. (d) 14. (a) 15. ( b) 16. ( c) 17. (c ) 18. (b ) 19. ( d) 20.(c )
21. (c ) 22. (b ) 23. ( d 24. (b) 25. ( c) 26. (a ) 27. (a ) 28. ( b) 29. (c ) 30. (b )
31. (d ) 32. (d ) 33. (c ) 34. (c) 35. (c ) 36. (b) 37. (b) 38. ( c) 39. (d ) 40. ( a)
150
DESCRIPTIVE PART - II
Year – 2006
Time allowed : 2 Hours Maximum Marks : 30
Attempt any four questions out of the six. All questions carry 7½ marks each.
Q.2 (a) What is an array? Explain with examples, how an array is declared and initialized.
(b) Identify and correct the error in each of the following:
(i) Print ("The value is & d/n". number);
(ii) if (C<7);
printf("C is less than 7/n");
Q.3 (a) Write a C program that calculate and print sum and average of 5 integer number.
Principles of Programming languages 151
Q.5 (a) Define a class to represent a complex number. The class has features of setting and
printing the values. Write a program to test the class.
**************
152
Bibliography
Books Referred-
Websites Referred-
Wikipedia,
www.cprogramming.com
www.eskimo.com
www.cprogrammingexpert.com,
www.compgeom.com
www.physicsforums.com
Principles of Programming languages 153
Notes
154
Notes