Sie sind auf Seite 1von 79

Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

1.Application Understanding
Objective
Introduction to Application Understanding
Different types of Applications
Examples of each type of applications
IT applications are all about managing information using a technology. To Create, Read, Update and Delete information are some of the main
operations in all IT applications. Login, Search, Validations etc are some common functionalities in all IT applications. For example
http://irctc.com/displayServlet is a web application and you can check all operations and functionalities in this website. Three Tier Architecture is the
common architecture used in modern IT applications. Presentation, Business Logic and Database will be in three different physical entities.

Different types of Applications

Desktop Application – is a computer software designed to help the user to perform specific tasks. Eg: VLC Media Player, Microsoft Office.

Web Application - is an application that is accessed over a network such as the Internet or an Intranet. Eg: www.Amazon.com, www.facebook.com.

Mobile Application - Mobile application software is developed for small low-power handheld devices such as personal digital assistants, enterprise
digital assistants or mobile phones. Eg: Weather Forcast, News Reader, Games, Whatsapp etc.

Related Videos

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/application-understanding-0 1 / 79
Campus Commune 8/5/2014

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/application-understanding-0 2 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

2.Problem Solving Orientation


Objective
Introduction to Problem Solving Approach
Identifying a problem
Step-by-step approach to solve a problem
Key elements required for problem solving and programming

2.1 Problem solving orientation

2.2 Key elements required for problem solving and programming

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/problem-solving-orientation-0 3 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

2.1. Problem solving orientation


A problem is a difficulty or a challenge, or situation that needs a solution.

Eg: Driving a car, Making Tea, Solving a crossword puzzle

Sample problem scenario

We can discuss a problem scenario faced by Railway department.

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/problem-solving-orientation-1 4 / 79
Campus Commune 8/5/2014

As part of service and development in nation lots of trains were added to the Railway department. As a result the passenger services also increased.
Railway stations increased. Lakhs of passengers and customers started availing various services like regular ticket bookings, reservation of tickets,
ticket cancellations, enquires etc. Services for passengers and customers at railway stations resulted in long queues. This created unhappy
passengers and customers. Railway employees were also overburdened with paper and manual work. Dissatisfied customers and overburdened
employees was the end result of development.

Railway wants to improve stake holder satisfaction. This was the problem scenario faced by Railway department. This problem can be solved in 2
ways – manually or automated.

Railway department hired new staff and increased the number of customer service counters. Passenger count and train services are steadily
increasing, so this solution is not going to work for a long term. Manual errors are also creeping up during calculations, leading to customer
dissatisfaction, and wastage of time to correct errors.

Management is now thinking why not automate the entire system.


Ticket booking and seat availability tracking
Passenger data management
Regular ticketing and so on…
They decided to come up with a computerized system that handles various day to day activities at their office.

Computer Programs

Computer is a machine. It needs to be instructed how to perform a task, how to handle data, where to store it and so on.

Programs – Set of instructions that is carried out by the computer

Software – Collection of computer programs and data that tells computer what to do

In a computer based solution, business requirement of a user, ultimately get translated to lines of code that instructs computer to work in such a
way as to meet the requirement

How to solve a problem

Whenever a problem occurs, people tend to concentrate too much on the solution and sometimes forget the essence of the problem. It is essential
for the individual to have a right approach to the problem itself in order to figure out the best solution.

People who are really good at solving problems go about it systematically. They have a way of placing the problem in context and do not jump to
conclusions. They evaluate all alternatives.

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/problem-solving-orientation-1 5 / 79
Campus Commune 8/5/2014

Steps in Problem Solving

Step 1 - Analyzing the problem


This involves understanding the input and output, various alternatives to reach the output, listing the assumptions
Step 2 - Designing an algorithm
Defining a step by step procedure to solve the problem
Step 3 - Testing the design for correctness
Checking for the correctness of algorithm by walking through the algorithm manually
Step 4 - Implementing the solution (Translating to code)
Once the correctness of algorithm is checked, it can be translated to any programming language
Step 5 - Testing the program
Once the program is developed it needs to be tested against various test cases which checks if the program is correct for all expected range of
inputs.
Step 6 – Deployment and Maintenance
In this module, the product or the output is given to the customer or end user for their purpose.

Related Videos

Ask a doubt (Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune)

Open Doubts Closed Doubts


SANJAY BEMAL
I could not find the 1st quiz questions of C++ modules. Please help me

about 4 days ago

SWATHI BATTINA
Wikipedia and MS outlook ...both are web based applications.but in quiz given only one of them is web based.

about 15 days ago

SHANKHO GHOSH
MS - Outlook is a desktop based application. It is a part of MS-Office. Gmail is a web based application

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/problem-solving-orientation-1 6 / 79
Campus Commune 8/5/2014

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/problem-solving-orientation-1 7 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

2.2. Key elements required for problem solving and programming


1. Good analytical skills
2. Declarative and imperative knowledge about the solution
3. Ability to apply abstraction
4. Knowledge in a programming language
5. Following good programming practices
1. Good analytical skills
Analytical skill is the ability to use good reasoning in analyzing a situation and also the ability to solve the problem. Analytical skill can also be said as
the ability to organise a mass of data and draw proper correlations, and then interpreting these trends in terms that are meaningful to others.
Suppose you have rain data for your town for the past thirty years, given to you at random, with no comments. You can organise the data
chronologically, then draw a graph to demonstrate the data and then , by extending the graph along its closest fitting curve, you can make
reasonable predictions about the extent of rain next year, assuming that all other factors remain STEADY.

2. Declarative and imperative knowledge about the solution


Declarative knowledge is the knowledge of what to do and imperative knowledge is the knowledge of how to do. If you have problem in hand and
when you know the solution of the problem then you have declarative knowledge. So “What is” type of knowledge is called declarative knowledge.
Imperative knowledge is a procedural knowledge which is the knowledge exercised in the performance of some task. “How to” type of knowledge is
called Imperative Knowledge.

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/key-elements-required-for-problem-solving-and-prog-0 8 / 79
Campus Commune 8/5/2014

Example:
Declarative Knowledge:

This What is type of knowledge is called Declarative knowledge

Imperative Knowledge:

This How to Knowledge is called Imperative Knowledge.

3. Ability to apply abstraction


Abstraction will modularize the logic for a specific functionality in a computer program. It will also hide complexity of implementation details of a
function behind a specific interface defined to invoke the function. It is recommended that programmers use abstractions whenever suitable in
order to avoid duplication.

4. Knowledge in a programming language


A programming language is a formal language designed to communicate instructions to a machine, particularly a computer. Programming
languages can be used to create programs that control the behaviour of a machine and/or to express algorithms precisely.
Elements of a programming language
1. Syntax: structural elements of the language. Programs must be syntactically correct.
2. Grammar: defines how syntactical elements need to be combined to form programs
3. Semantics: defines meaning of the code

5. Good programming practices


A good programming practice is related to writing efficient and readable code, a code which is easily maintainable.

Related Videos

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/key-elements-required-for-problem-solving-and-prog-0 9 / 79
Campus Commune 8/5/2014

Ask a doubt (Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune)

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/key-elements-required-for-problem-solving-and-prog-0 10 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

3.C++ - Introduction
Objective:

Introduction to C++

Understand data types

Understand variables as constants

Working with array

3.1 C++ Overview

3.2 Working with Data Items

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/c-introduction 11 / 79
Campus Commune 8/5/2014

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/c-introduction 12 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

3.1. C++ Overview


C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming language that supports procedural, object-oriented,
and generic programming.

C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features.

C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey, as an enhancement to the C language and
originally named C with Classes but later it was renamed C++ in 1983.

C++ is a superset of C, and that virtually any legal C program is a legal C++ program.

Note: A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time.

Writing first C++ Program


Let us have a look at a sample code in C++ that would print Hello World in the console:

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/c-overview 13 / 79
Campus Commune 8/5/2014

Let us look various parts of the above program:

The C++ language defines several headers, which contain information that is either necessary to your program. For this program, the header
<iostream> is needed.

using namespace std; tells the compiler to use the namespace std.

int main() is the main function where program execution begins.

cout << "Hello World."; Displays the message “Hello World” on screen.

// prints Hello World : Is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line

return 0; terminates main()function and return the value 0 to the calling process.

Compiling and Executing C++ Program


Open a text editor and add the code as above.

Save the file as: hello.cpp

Open a command prompt and go to the directory where you saved the file.

Type 'g++ hello.cpp ' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the
next line and would generate a.out executable file.

Now, type ' a.out' to run your program.

You will be able to see ' Hello World ' printed on the window.

Related Videos

Ask a doubt (Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune)

Open Doubts Closed Doubts


RAJANEEKANTA MISHRA
i faced the difficulty twice in both my attempt that the same qn i've faced is not taking the answer while submitting and the next
3-4 questions are skipped just by negating my marks.

about 2 months ago

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/c-overview 14 / 79
Campus Commune 8/5/2014

DEVIKAVYA REGATI
I too faced same problem

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/c-overview 15 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

3.2. Working with Data Items


C++ Data Types
While doing programming in any programming language, you need to use various variables to store various information. Variables are nothing but
reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

C++ supports a large number of data types. The built in or basic data types supported by C++ are integer, floating point, double floating point,
character and boolean. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the
reserved memory.These are summarized in table along with description and memory requirement.

Data Type Byte Description examples

char 1 Character value A,a,1,@

int 2 Integer value 1,123,-123

float 4 Floating point value 1.01,-1.23

double 8 Double floating point value 123456.123456

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/working-with-data-items 16 / 79
Campus Commune 8/5/2014

bool 1 Boolean values True(1),false(0)

Variable Declaration in C++


A variable provides us with named storage that programs can manipulate. Each variable in C++ has a specific type, which determines the size and
layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the
variable.

The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper
and lowercase letters are distinct because C++ is case-sensitive.

A variable declaration tells the compiler where and how much to create the storage for the variable. A variable declaration specifies a data type, and
contains a list of one or more variables of that type as follows:

Syntax: <datatype> variable_list;

Here, type must be a valid C++ data type including char, int, float, double, bool etc., and variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here:

You can declare more than one variable of same type in a single statement

Variable Initialization in C++


When we declare a variable it's default value is undetermined. We can declare a variable with some initial value.

Syntax: variable_name = value

Variables can also be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant
expression as follows:

Syntax: type variable_name = value;

The following example shows how variable can be declared an initialized inside the main function:

When the above code is compiled and executed, it produces the following result:

30

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/working-with-data-items 17 / 79
Campus Commune 8/5/2014

23.3333

Scope of Variable
A scope is a region of the program where variables can be declared:

Inside a function or a block which is called local variables,

Outside of all functions which is called global variables.

Local Variables:

Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block
of code. Local variables are not known to functions outside their own. Following is the example using local variables:

Global Variables:

Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-
time of your program.

A global variable can be accessed by any function. That is, a global variable is available for use throughout the entire program after its declaration.
Following is the example using global and local variables:

A program can have same name for local and global variables but value of local variable inside a function will take preference. For example:

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/working-with-data-items 18 / 79
Campus Commune 8/5/2014

When the above code is compiled and executed, it produces the following result:

10

Using Constants in C++


Constants refers to fixed values that program may not alter. They are also called literals.

Any attempt to change the value of a constant will result in an error message. Constants can be of any of the basic data types and can be divided into Int
eger constants, Floating-Point constants, Character constants, String constants and Boolean constants.

Constants are treated just like regular variables except that their values cannot be modified after their definition.

Constant
Description examples
Type
They are whole number without any fractional
Integer 212
part.
They are numbers having fractional parts. They
Floating-
may be written in fractional form or exponent 3.14
point
form.
They must contain one character and must be
enclosed in single quotation marks. There are
certain characters in C++ when they are preceded
Character 'A', '\n'
by a backslash they will have special meaning and
they are used to represent like newline (\n) or tab
(\t).
A sequence of character enclosed within double
quotes is called a string literal, by default added
"Computer","Hello
String with a special character ‘\0' which denotes the end
World"
of the string. More than one words can be
separated by whitespace.
Boolean Contains boolean values true,false

You can use const prefix to declare constants with a specific type as follows:

Syntax: <const type> variable = value;

Following example explains it in detail:

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/working-with-data-items 19 / 79
Campus Commune 8/5/2014

When the above code is compiled and executed, it produces the following result:

15

Arrays
C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a
collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as Age1, Age2, ..., and Age5, you declare one array variable such as Age and use Age[0], Age[1], and
..., Age[5] to represent individual variables. A specific element in an array is accessed by an index or subscript.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Declaring Arrays
To declare an array in C++, the specify the type of the elements and the number of elements as size required by an array :

Syntax: type arrayName [ arraySize ];

This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type.

The above code declare a 5-element array called balance of type double.

Initializing an Array
An array can be initialized along with declaration. For array initialization it is required to place the elements separated by commas enclosed within
braces.

You can initialize C++ array elements either one by one as follows:

You can initialize C++ array elements using a single statement as follows:

The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ].

The above figure represent array balance with specific values.

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write:

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/working-with-data-items 20 / 79
Campus Commune 8/5/2014

The above code will create exactly the same array as you did in the previous example.

Accessing Array Elements


In any point of a program in which an array is visible, we can access the value of any of its elements individually as if it was a normal variable, thus
being able to both read and modify its value. This is done by placing the index of the element within square brackets after the name of the array.
For example:

The above statement will take 5th element from the array and assign the value to salary variable.

Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays:

This program makes use of setw() function to format the output. When the above code is compiled and executed, it produces the following result:

Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109

Related Videos

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/working-with-data-items 21 / 79
Campus Commune 8/5/2014

Ask a doubt (Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune)

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/working-with-data-items 22 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

4.1. Operators
Type Of Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations on variables or values. C++ is rich in built-
in operators and provides the following types of operators:

Arithmetic Operators

Comparison or Relational Operators

Arithmetic Assignment Operators

Logical Operators

Unary, binary and Ternary Operators

Arithmetic Operators
Arithmetical operators are used to perform an arithmetic (numeric) operation on variables and values.

Assume variable A holds 10 and variable B holds 20, then:

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/operators-1 23 / 79
Campus Commune 8/5/2014

Operator Description Example


A + B will give
+ Adds two operands
30
- Subtracts second operand from the first A - B will give -1

A * B will give
* Multiplies both operands
200
/ Divides numerator by de-numerator B / A will give 2
Modulus Operator and remainder of after an integer
% B % A will give 0
division

Example:

Output:

Addition:30

Division:2

Multiplication:200

Modulo:0

Comparison Operators
The comparison or relational operators are used to test the relation between two values. All comparison operators are binary operators and
therefore require two operands. A relational expression returns zero when the relation is false and a non-zero when it is true.

Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example


(A == B)
Checks if the values of two operands are equal or not, if yes
== is not
then condition becomes true.
true.
Checks if the values of two operands are not equal or not, if (A != B)
!= is true.
not equal then condition becomes true.
Checks if the value of left operand is greater than the value (A > B) is
>
of right operand, if yes then condition becomes true. not true.
Checks if the value of left operand is less than the value of (A < B) is
<
right operand, if yes then condition becomes true. true.
Checks if the value of left operand is greater than or equal to (A >= B)
>= the value of right operand, if yes then condition becomes is not
true. true.
Checks if the value of left operand is less than or equal to the (A <= B)
<=
value of right operand, if yes then condition becomes true. is true.

Example:

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/operators-1 24 / 79
Campus Commune 8/5/2014

Output: Result is 1

Arithmetic Assignment Operators


Arithmetic Assignment operators are combination of both Arithmetic and Assignment Operators. It assigns value to variable after arithmetic
operation.

Operator Description Example


C = A + B will
Simple assignment operator, Assigns values from
= assign value of A
right side operands to left side operand
+ B into C
Add AND assignment operator, It adds right C += A is
+= operand to the left operand and assign the result to equivalent to C =
left operand C+A
Subtract AND assignment operator, It subtracts C -= A is
-= right operand from the left operand and assign the equivalent to C =
result to left operand C-A
C *= A is
Multiply AND assignment operator, It multiplies right
*= operand with the left operand and assign the result equivalent to C =
to left operand C*A

Divide AND assignment operator, It divides left C /= A is


/= operand with the right operand and assign the equivalent to C =
result to left operand C/A
Modulus AND assignment operator, It takes C %= A is
%= modulus using two operands and assign the result equivalent to C =
to left operand C%A

Example:

Output:

Value of a:11

Logical Operators
The logical operators are used to combine one or more relational expression.

Assume variable A holds 1 and variable B holds 0, then:

Operator Description Example


Called Logical AND operator. If both the operands are non- (A && B)
&&
zero, then condition becomes true. is false.
|| Called Logical OR Operator. If any of the two operands is non- (A || B)
zero, then condition becomes true. is true.
Called Logical NOT Operator. Use to reverses the logical state !(A &&
! of its operand. If a condition is true, then Logical NOT B) is
operator will make false. true.
Example:

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/operators-1 25 / 79
Campus Commune 8/5/2014

Output :

C is Largest Number: 1

Unary Operators
Operators that operates on single operand are named as unary operators.

C++ provides unary operators like ++ ( increment) and – (decrement) .

Increment(++) operator increments the value present in a variable by 1.

Decrement(- -) operator decrements the value present in a variable by 1.

Unary operators an operate from two different position

>> pre-fix – when operator placed before a variable. For example (++Count)

>> post-fix – when operator placed after a variable. For example(Count++)

The difference in result is explained in the following example.

Sometimes, binary operators can act as unary operator.

a=-50;
a=+50;
Here plus sign (+) and minus sign (-) are unary because they are not used between two variables.

Related Videos

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/operators-1 26 / 79
Campus Commune 8/5/2014

Ask a doubt (Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune)

Open Doubts Closed Doubts


MUTHUKRISHNAN GANESAN
In the example code given above for illustrating the concept of Pre increment and Post Increment, the variable 'b' must have
been declared before it's usage in the statement b=++a. Am I right? Plz clarify..

about 1 month ago

SANTHOSH DEVUNURI
Hi,
Assuming the variable "b" is already declared.
Thankq

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/operators-1 27 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

5.C++ -Conditional Constructs


Objective
If Statement

If .. Else Statement

If .. Elseif .. else statement

Nested if statement

Switch .. case statement

5.1 Conditional Constructs

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/c-basic-interations 28 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

5.1. Conditional Constructs


If Statement
If statement can be use to evaluate conditional statements. Based on the result of evaluation one of more statements can be executed

syntax of the if statement

if(condition)
{
statement(s) if condition evaluates to true;
}

Statements are executed if the condition is true. No output if the condition false.

if .. else statement
To perform some action in either of the situation based on the conditional evaluation if.. else construct can be used.

syntax of the if..else statement

if(condition)

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/conditional-constructs 29 / 79
Campus Commune 8/5/2014

statement(s) if condition evaluates to true;


}

else

statement(s) if condition evaluates to false;

If .. elseif ..else statement


Using if...elseif...else multiple condition can be evaluated.

syntax of the if statement

if(condition)
{

statement(s) if condition evaluates to true;


}

else if (condition2)

statement(s) if condition2 evaluates to true;

else

statement(s) if none of the above conditions are true;

Consider the following example:

Nested If statements
To evaluate multilevel conditional statements, If statements can be placed within another if/else block.

Consider the following example:

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/conditional-constructs 30 / 79
Campus Commune 8/5/2014

Switch-case statements
The other way conditional evaluation can be performed using switch statement which permits multiple branching:

The syntax of switch statement is:

switch (var / expression)


{
case constant1 :

statement 1;
break;
case constant2 :

statement 2;
break;

...
default:

statement n;
break;
}

The execution of switch statement begins with the evaluation of expression. If the value of expression matches with the constant then the
statements following this statement execute sequentially till it reaches the break statement. The break statement transfers control to the end of the
switch statement. If the value of expression does not match with any constant, the statement with default is executed.

Some important points about switch statement

The expression of switch statement must be of type integer or character type.

The default case need not to be used at last case. It can be placed at any place.

The case values need not to be in specific order.

Consider the following example:

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/conditional-constructs 31 / 79
Campus Commune 8/5/2014

Ask a doubt (Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune)

Open Doubts Closed Doubts


SWATHI BATTINA
Can we compare an unsigned and a signed variable..? we can apply the concept of implicit conversion and we can
compare...is this possible in c++? can some one plz elaborate on this topic?

about 14 days ago

RAJESH MALLAPUREDDY
Material provided in this chapter is not enough to take quiz exam.. And i failed for the first time.

about 1 month ago

MUTHUKRISHNAN GANESAN
In the code above explaining the nested-if concept, should there be a statement like cin>>Type; for getting input from the
user inside the else block???? kindly clarify.. If i am wrong, any1 plz correct me.. Thanks in advance..:)

about 1 month ago

BHARGAVI MURALI
Yes, there should be a statement to get the type input.

SHAIK NAZNEEN
Can anyone tell me how to reset the module?

about 1 month ago

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/conditional-constructs 32 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

6.C++ - Basic Iterations


Objective
Understanding iterative statements

while iterative statement

do.. while iterative statement

for iterative statement

Understand break and continue conditions

6.1 Basic Iterations

6.2 Practice Problems

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/c-basic-iterations 33 / 79
Campus Commune 8/5/2014

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/c-basic-iterations 34 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

6.1. Basic Iterations


Understanding iterative statements
A iterative construct is a structure which allows a block of statements to be executed repeatedly.

The iterative constructs provided in C++ are:

while iterative construct

do..while iterative construct

for iterative construct

While iterative Construct


The while iterative construct is called a entry-controlled (pre-testing) looping. It evaluates the logical expression for exit of the loop at the
beginning.

If the logical expression in the while loop evaluates to true, then the statements associated with the loop are executed. If the logical expression
evaluates to false, then the statements associated with the loop are not executed.

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/basic-iterations 35 / 79
Campus Commune 8/5/2014

Since the test for exit of the loop is performed before the first instruction in the loop, based on the condition it may not execute for a single time.

The variables appearing in the logical expression are initialized (assigned a value) prior to the beginning of the while loop. This is necessary since the
logical expression in the while loop is tested before the actual loop is executed.

The typical while loop syntax will be:

while (logical expression)

statement(s) if the expression returns true;

The counter-controlled while loop uses a loop control variable in the logical

expression. The loop control variable initialized before entering the while loop, and a statement in the body of the while loop should
increment/decrement the control variable.

The following example prints the serise of odd number upto 10:

Output : 1 3 5 7 9

Do..While iterative construct


The do ... while iterative construct is called a exit-controlled (post-testing) loop. It evaluates the logical expression for exit of the loop at the end.

First, the statements associated with the loop are executed, at the end of first execution the logical expression is evaluated if the expression
evaluates to true, then it re-executes, else the statements associated with the loop are not executed.

Since the test for exit of the loop is performed end of the loop body, whatever the condition is the loop body will executed at least once

The variables appearing in the logical expression are initialized (assigned a value) prior to the beginning of the while loop. This is necessary since the
logical expression in the while loop is tested before the actual loop is executed.

Consider the following example:

For Iterative Construct


For looping construct is known for its neat and clean syntax. Unlike other loop in for loop all three loop controlling statements (initialization, test
condition and increment/decrement) are clearly mentioned in the first line of it.

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/basic-iterations 36 / 79
Campus Commune 8/5/2014

The general syntax is:

for( initialization; test condition; increment/decrement)

// ststements to be executed in the body of the loop

The following example acepts a number and prints the table of that number

Output :

Enter a Number : 9

9*1=9

9 * 2 = 18

9 * 3 = 27

9 * 4 = 36

9 * 5 = 45

9 * 6 = 54

9 * 7 = 63

9 * 8 = 72

9 * 9 = 81

9 * 10 = 90

Break Keyword
In the program flow when break statement encountered it terminate a loop or an switch block, skipping the following statements in the block.

Continue Keyword
In the program flow when continue statement encountered it re-starts a loop, skipping the following statements in the block.

The following program prints even numbers upto 8

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/basic-iterations 37 / 79
Campus Commune 8/5/2014

Related Videos

Ask a doubt (Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune)

Open Doubts Closed Doubts


JERRY JACOB
The above provided material is not completely sufficient enough to attempt the quiz. and frequently the right answers are
declared wrong. I lost my miles.

about 1 day ago

ANJALI TOMAR
the matter given in the section is really insufficient to clear to quiz for non-software students..

about 6 days ago

VASANTHA SUMANTH
Almost 1/3 of the questions answers are given wrong. And for 2-3 questions they gave a program and dint asked what they
want but had given options. In this module it has crossed limits. Dont know what to do.

about 17 days ago

SHANEELA KANUMILLI
Can anyone tell me how to reset the module?

about 1 month ago

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/basic-iterations 38 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

6.2. Practice Problems


Topic: Decision Making

1. Find the biggest of given 3 numbers


2. Develop a program that accepts a deposit amount and period of deposit. Calculate the maturity amount after the period of deposit. The bank
pays 4% interest per year for any deposits made in the bank.
Period Interest rate
Upto 180 days 2%
180 days to 1 year 3%
1-2 years 4%
> 2 years 5%
3. Consider student marks for 5 subjects and check whether he passes or failed. If passed given the grade based on the average of 5 subjects.
Grade Condition Grade
>= 90% & < =100% A
>= 80% & < 90% B
>= 70% & < 80% C
>= 40% & < 70% D
4. Check whether given number is even or odd

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/practice-problems-13 39 / 79
Campus Commune 8/5/2014

Topic: Basic Iterations


5. Find all the even numbers within the limit of an input integer value.

6. Find sum of first n natural numbers using while loop

7. Find sum of squares of first n natural numbers using for loop

8. Find sum of the digits of given integer using do while loop

9. Find out first n prime numbers

10. Check whether the given number is prime or not

Topic: CASE
11. Display the day of the given number from 1-7.
Eg: 1 – Sunday, 2 – Monday,
12. Check whether the given character is Vowel or Consonant

Click here to download the solutions

Ask a doubt (Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune)

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/practice-problems-13 40 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

7.C++ - Functions
Objective
Understanding Functions

Function Prototyping

Function Definition

Function Calling

Function call by value and call by reference

Pre-Defined Functions

String Handling Functions

7.1 Functions

7.2 Practice Problems

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/c-functions 41 / 79
Campus Commune 8/5/2014

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/c-functions 42 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

7.1. Functions
Understanding Functions
A function is a block of reusable code identified by a name. it can be executed from as many different points as required.

The advantage of creating functions are

>> To make the program more understandable

>> To modularize the tasks of the program

>> Write a module once use several time

Function Prototyping
Functions should be declared before they are used. These type of declaration are also called function prototype. Function prototype gives compiler
information about function name, type of arguments to be passed and return type.

The typical syntax for function prototyping is:

return_type function_name(datatype1 [,datatype2...] );

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/functions 43 / 79
Campus Commune 8/5/2014

For example,

int add(int, int);

is a function prototype which provides following information to the compiler:

>> Name of the function is add()

>> return type of the function is int.

>> Two arguments of type int are passed to function.

Function prototype are not required if the definition of the function is written before main() function.

Function Definition
Function definition contains programming codes to perform specific task.

Syntax of function definition

return_type function_name(datatype1 argument1 [,datatype2 argument2)

//body of function

Function Calling
Function call is the statement which triggers the code in function body to execute.

The following code illustrates function Prototyping, definition and calling.

Call by Value and Call by Reference


By default, C++ uses call by value method to pass arguments to functions. In this method the value of arguments are copied into the formal
parameter of the called function.

If any changes made to the parameter inside the called function, the changes are not reflected in calling function argument.

Consider the following programs demonstrating call by value and call by references .

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/functions 44 / 79
Campus Commune 8/5/2014

Output :

Enter two Numbers: 20 30

After swap in swap 1st Num= 30; 2nd Num=20;

After swap in main 1st Num= 20; 2nd Num=30;

Output :

Enter two Numbers: 20 30

After swap in swap 1st Num= 30; 2nd Num=20;

After swap in main 1st Num= 30; 2nd Num=20;

Pre-Defined Functions
In C++ language there are many pre-defined functions available which are grouped in different libraries that can be included in the C++ program,
e.g.

>> Math functions are declared in <math.h>

>> Character-manipulation functions are declared in <ctype.h>

>> The string function are declared in <cstring.h>

Some of the math and character functions are listed below:

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/functions 45 / 79
Campus Commune 8/5/2014

String Handling Functions


C++ provides rich set of string handling functions

Function Name Explanation Example

strlen(“Amit”)
strlen(str) Returns the length of string str
returns 4

strcpy(str1,”Amit”)
strcpy(str1,
Copies string str2 into string str1.
str2); Copies the string Amit into str1

strcpy(str1,”Agr”)
strcat(str1, Concatenates string str2 at the end of
Concatenates the string Agr at end of existing
str2); string str1.
content of str1

Returns 0 if str1 and str2 are the same;


strcmp(“Amit”,”Agr”)
strcmp(str1, less than 0 if str1<str2;
str2); returns 1 as ASCII code of m is greater than g.
greater than 0 if str1>str2.

Related Videos

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/functions 46 / 79
Campus Commune 8/5/2014

Ask a doubt (Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune)

Open Doubts Closed Doubts


ERAVADA SUVARNA
can anyone tell me how to reset the module?

about 1 month ago

S VEERALAKSHMI
All the right answers get negative marks......can't get valid score.....

about 2 months ago

CHIDDARTHAN
Even for all right answers its reducing mark. For 90 percent of the correct answers the mark is getting reduced in the
chapter.How could we finish it then

about 2 months ago

KEDARNATH MISHRA
all the answers are right but still it says wrong how can I complete it .my 2 chances are lost . what I have to do?

MUTHUKRISHNAN GANESAN
yes the system is marking almost everything wrong eventhough it's correct..

PREETI
Almost all correct answers are marked wrong . Even I lost my 2 chances ..

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/functions 47 / 79
Campus Commune 8/5/2014

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/functions 48 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

7.2. Practice Problems


Topic: Pointers and References

Function Pointers and Reference Parameters:

1. Write a program that performs addition and subtraction of two floating point numbers by another function which takes the formal arguments of
the functions addFloats() , subFloats() and returns the result.

2. Read a number and make it double using a void function.

3. Write a user defined function "readNumbers()" that reads two numbers from the key board, and another function "printNumbers()" that prints
the numbers in ascending order.

4. Write a user defined function that takes the marks in three different subjects and returns total marks and average marks.

5.Create a class time with member variables, hours,minutes and seconds. Over load extraction and insertion operators to read a time object and to
display a time object.

6. Write a program, that prompts the user to choose whether the list of numbers should be sorted in ascending or descending order and performs
The task accordingly

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/practice-problems-14 49 / 79
Campus Commune 8/5/2014

Click here to download the solutions

Ask a doubt (Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune)

Open Doubts Closed Doubts


DIVYA TURLAPATI
Please explain the getResult() function of the first problem's solution.

about 22 days ago

SANTHOSH DEVUNURI
Hi
In the solution, with the help of "getResult()" function, we can call "addFloats()" and "subFloats()" functions. For
implementing this, the "getResult()" function is defined with three parameters as mentioned in the solution. The
first parameter represents function pointer and the remaining two are simple parameters of type float. Please
note that a function with parenthesis will invoke the function and a function without parenthesis will return the
address of the function located in the memory. For more information, refer the below code snippet.
Example:
void show();
int main()
{
show(); // Invoke the show() function
cout<<show; // prints the address of the "show" function located in the memory
}
void show()
{
cout<<"Hello";
}
Note: To pass a function as parameter to another function, the function should take function pointer as a
parameter. The type of function parameter will be based on the return type of actual function which is being
passed as parameter from the calling function.

Thanq

SIGMA DAS
According to the theory given in the section 7.1, Function Prototype is not required if the definition of the function is written
before main() function but as per the quiz, the answer is exactly the opposite. What is the correct answer?

about 2 months ago

SANTHOSH DEVUNURI
Hi,

Function Prototype is not required if the definition of the function is before main() function.

Thanq

KAMATCHI K
I answered correctly for all questions but i got negative marks....i got this problems for more than 10 to 11 questions...due
to this i am failed to clear this level and also i lost my miles too.......can you tell me the reason for this problem?

about 2 months ago

BHABNA ACHARYA

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/practice-problems-14 50 / 79
Campus Commune 8/5/2014

Can I reset my scores myself if they are not good??

about 2 months ago

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/practice-problems-14 51 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

8.C++ - Pointers
Objective
Concept of Pointers

Declaration of Pointer

Relation between pointer and array.

Pointer Arithmetic

Difference between pointer and reference

Using Pointer in function call

8.1 Pointers

8.2 Practice Problems

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/c-pointers 52 / 79
Campus Commune 8/5/2014

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/c-pointers 53 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

8.1. Pointers
Concept of Pointers
When we declare a variable such as

char Grade='A';

A memory location is allocated to the program which is reffered by a name Grade, and value stored in the memory location is the charecter A.

The value of the variable can be accessed by some other way, with the help of the address of the variable, using pointer.

A pointer is a special type of variable that can store other variable's address. An address of a variable can be extracted by ampersand (&) operator

Declaration of Pointers
char *Ptr; // A pointer declared that can store

// address of a char type variable

Ptr = &Grade; // Pointer Ptr is now

//pointing (storing the address of ) variable Grade

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/pointers 54 / 79
Campus Commune 8/5/2014

cout<< Grade; // Prints A, accessing value of variable Grade

cout<<*Ptr; // Prints A, accessing value of variable Grade

// through Pointer Ptr.

*Ptr='B'; // Updates the value of variable Grade to B;

Relation between Pointer and Array


The name of the array is a pointer and it points to the first element of the array.

Lets check the array declaration

int Arr[5]={20,50,3,578,88};

The name of the array Arr is a (constant)pointer which stores the address of Arr[0]

Now, consider the declaration of an integer pointer

int *Ptr;

So, the following line will be valid because both are of same type, pointer to integer

Ptr=Arr;

cout<<*Ptr; // Prints 20, the first element of the array.

Ptr++;

cout<<*Ptr; // Prints 50, Arrays are contiguous memory location

Arr++ ; // Generates error, array's are constant pointers.

Pointer Arithmetic
It is possible to perform certain arithmetic operations on pointers.

Consider a pointer declaration:

char *Ptr=&x;

It is possible to add and subtract numbers from the pointer as below:

Ptr = Ptr + 1 ; // Ptr now pointing

//value present in next address

Ptr--; // Ptr pointing value present in previous addr.

*Ptr++ // same as *(Ptr++): increment pointer,

// and dereference address

++*Ptr // Same as ++(*Ptr): dereference pointer,

// and increment the value it points to

NOT Allowed Operations on Pointers


Any operation not in the list of allowed operations!

1. multiplication or division on a pointer

2. addition or subtraction of two pointer values

3. assignment of a value other than 0 to a pointer

Difference between Pointer and References


It is very easy to get confused with Pointer and reference variable in c++. They both uses the ampersand(&) operator slightly different way.

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/pointers 55 / 79
Campus Commune 8/5/2014

A reference is an alias, or an alternate name to an existing variable. They are declared as :

int Num=50;

int &Ref=Num;

After created and initialized pointers can point to other variable, but Reference are once initialized cannot be re-referenced.

To extract the value from pointer de-reference(*) operator is used, value from reference variable can be extracted just like any other variable

Using pointer in function call


By default C++ performs only call by value, however, if a called function is to change the value of an object defined in the calling function, it can be
passed a value which is a pointer to the object. The called function can then dereference the pointer to access the variable indirectly.

A function can return one value only to the calling program, another utility of using pointers as return value from a function is, a called function can
effectively return several values.

Related Videos

Ask a doubt (Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune)

Open Doubts Closed Doubts


ARYAN SINGH
Failed because of incomplete questions and wrong answers.

about 8 hours ago

JERRY JACOB
90% of the questions are incomplete. how can one pass this quiz???

about 23 hours ago

ARYAN SINGH
same problem.......

ROHIT CHAUHAN
same problem mostly questions are incomplete and incorrect.I failed due to this.

GAURAV
FAILED because a LOT of questions where shown incomplete. Around 5-6 questions end abruptly at 'cout<...'. And thats not
all, many correct answers that are obvious to even a 2nd year student are marked wrong. Similar problems exist all
throughout this C++ module so failing and passing the tests is totally dependent on luck. Frustrating!

about 3 days ago

KUTHALINGAM K

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/pointers 56 / 79
Campus Commune 8/5/2014

FAILED because many questions are incomplete and correct answers were marked wrong.

about 7 days ago

SINDHU M
many of the questions are half wat to give answres?many have cout<????

about 21 days ago

ADITI TYAGI
I faced the same problem. Due to all this I failed in the quiz.

APURVA MISHRA
same problem

SUBATHRA SAKTHIVADIVELAN
Having the same problem will some please fix it soon my miles are not getting added.

SOUNDARAM N
same here! failed at last !

AKANKSHA MATHUR
I had also failed this quiz jst becoz of wrong answers. what to do???

about 21 days ago

RAVITEJA KAMMARI
Some questions are not complete, and some right answers also shown as wrong why is it so...!! Finally this Pointers sub
module was gone :(

about 26 days ago

PRANAV PANDEY
faced the same problem of cout and also negative marks for correct answers.

about 27 days ago

PRAGNYA NANDA
i also faced the same problem many questions have 'cout<' ??? what to answer for that ???

about 1 month ago

EUGINIA ROSAN
Not only the problem is with "cout<" type questions, even some one word question also earns negative marks while
choosing the correct one.. why is it so?

about 1 month ago

← Previous 1 2 Next →

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/pointers 57 / 79
Campus Commune 8/5/2014

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/pointers 58 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

8.2. Practice Problems


Topic: Introduction to Pointers

1. What is Pointer in c/c++?, Write code snippet for declaring pointer vaiable to integer variable and Assign to a Variable Value?

2. Write snippet to for the following


-Create / destroy memory dynamically for a pointer variable based on its Type?
-Creating / Destroy a memory for an Array dynamically?

3. Write a program to access and Display a value of a variable using Pointer?.

4. What is Memory Leak ,write a program which describes the problem?

5. What is Dangling Pointer,when will it occurs? ,write a sample Program?

6. Assume that there is a function(Add Five),which is changing the value[adding 5 for the existing Value of the variable]
of the variable, thefunction receives from a function call. If we want to reflect the changed value in the scope of Function call.
What passing mechanism ,you fill follow. Write a program for the Same?

7. Write a program to create/Destroy and access an array of integers using Pointers?

8. Write a program to access Static [Not Dynamically allocated] Array (which is Existing already) using Pointer?

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/practice-problems-15 59 / 79
Campus Commune 8/5/2014

9. Write a program to create an array in the "Scope of function call" and


Access/Traverse the Array in the function definition using Pointer?

10. Write a Program to create a pointer variable to an userdefined class and Access the members (data members and function) using the pointer to
the Class?

Click here to download the solutions

Ask a doubt (Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune)

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/practice-problems-15 60 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

9.C++ - Introduction to object oriented concepts


Objective
OOP Concepts

Understanding Objects and Classes

Elements of OOP

9.1 Object Oriented Programming

9.2 Practice Problems

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/c-introduction-to-object-oriented-concepts 61 / 79
Campus Commune 8/5/2014

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/c-introduction-to-object-oriented-concepts 62 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

9.1. Object Oriented Programming


OOP Concepts
OOP(Object Oriented Programming) is method of programming where a system is considered as a collection of objects that interact together to
accomplish certain tasks. Objects are entities that encapsulate data and procedures that operate on the data.

In OOPS first a concept known as "Object oriented analysis(OOA)" is used to specify the objects in term of real world requirements, their behaviour
and interactions required. The next concept would be the "Object oriented design(OOD)" that converts these real time requirements as a hierarchy
of objects in terms of software development requirement. Finally OOPS is used to implement the requirements using the C++ programming
language.

The main purpose of object oriented programming is to simplify the design, programming and most importantly debugging a program. So to
modify a particular data, it is easy to identify which function to use. To add additional features it is easy to identify where to add functions and its
related data

Understanding Objects
This is the basic unit of object oriented programming. That is both data and function that operate on data are bundled as a unit called as object.

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/11-object-oriented-programming 63 / 79
Campus Commune 8/5/2014

Definition (Object) : An object is an instance of a class. It can be uniquely identified by its name and it defines a state which is represented by the
values of its attributes at a particular time.
The state of the object changes according to the methods which are applied to it. We refer to these possible sequence of state changes as the
behaviour of the object:

Definition (Behaviourr) :The behaviour of an object is defined by the set of methods which can be applied on it.

Understanding Class
A class is

An abstract data type similar to a structure.

A representation of objects and the sets of operations that can be applied to such objects.

Class consists of Data members and methods.

Primary purpose of a class is to held data/information. This is achieved with attributes which is also known as data members.

The member functions determine the behaviourr of the class i.e. provide definition for supporting various operations on data held in form of an
object

Classes has the data and its associated function wrapped in it. Classes are also known as a collection of similar objects or objects of same type. In
the OOPs concept the variables declared inside a class are known as "Data Members" and the functions are known as "Member Functions".

This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what
operations can be performed on such an object.

Example 1

Consider we have a Class of Cars under which Mercedes and Audi represents individual Objects. In this context each Car Object will have its own,
Model, Year of Manufacture, Color, Top Speed, Engine Power etc., which form Properties of the Car class and the associated actions i.e., object
functions like Start, Move, and Stop form the Methods of Car Class.

Example 2

Syntax:

class class-name

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/11-object-oriented-programming 64 / 79
Campus Commune 8/5/2014

{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};

Example:

#include <iostream>
using namespace std;
class Square
{

private:

int side, a;
public:
int area(int side)
{
a =side*side;
return a;
}
void show()
{
cout << "The area is::" << a;
}

};

void main()
{
Square x;
x.area(10);
x.show();
}

Result:

The area is:: 100


In the above example the class "square" has functions "area" and "show" to calculate the area of the square and to display the area. so all these are obje
cts that are related to the class "Square".

Elements of OOP

1. Abstraction

1. Abstraction

2. Encapsulation

3. Polymorphism

4. Inheritance

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/11-object-oriented-programming 65 / 79
Campus Commune 8/5/2014

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 programming (and design) technique that relies on the separation of interface and implementation

Benefits of Abstraction:

Data abstraction provides two important advantages:

Class internals are protected from inadvertent user-level errors, which might corrupt the state of the object.

The class implementation may evolve over time in response to changing requirements or bug reports without requiring change in user-level code.

By defining data members only in the private section of the class, the class author is free to make changes in the data. If the implementation
changes, only the class code needs to be examined to see what affect the change may have. If data are public, then any function that directly
accesses the data members of the old representation might be broken.

Example:
Any C++ program where you implement a class with public and private members is an example of data abstraction. Consider the following
example:

#include <iostream>
using namespace std;

class Adder{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};

int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);

cout << "Total " << a.getTotal() <<endl;


return 0;
}

When the above code is compiled and executed, it produces the following result:

Total 60

Above class adds numbers together, and returns the sum. The public members addNum and getTotal are the interfaces to the outside world and
a user needs to know them to use the class. The private member total is something that the user doesn't need to know about, but is needed for
the class to operate properly.

It is the method of combining the data and functions inside a class. This hides the data from being accessed from outside a class directly, only
through the functions inside the class is able to access the information.

This is also known as "Data Abstraction", as it gives a clear separation between properties of data type and the associated implementation details.
There are two types, they are "function abstraction" and "data abstraction". Functions that can be used without knowing how its implemented is

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/11-object-oriented-programming 66 / 79
Campus Commune 8/5/2014

function abstraction. Data abstraction is using data without knowing how the data is stored.

Example:

#include <iostream>
using namespace std;
class Add
{
private:
int x,y,r;
public:
int Addition(int x, int y)
{
r= x+y;
return r;
}
void show( )
{ cout << "The sum is::" << r << "\n";}
}s;
void main()
{
Add s;
s.Addition(10, 4);
s.show();
}

Result:

The sum is:: 14

In the above encapsulation example the integer values "x,y,r" of the class "Add" can be accessed only through the function "Addition". These
integer values are encapsulated inside the class "Add".

Inheritance

The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is inheritance.

Inheritance lets you create new classes from existing class. Any new class that you create from an existing class is called derived class; existing
class is called base class.

In the above diagram represent the inheritance relationship. Mother and Father represent the base class and Daughter is the sub class.

The inheritance relationship enables a derived class to inherit features from its base class. Furthermore, the derived class can add
new features of its own. Therefore, rather than create completely new classes from scratch, you can take advantage of inheritance
and reduce software complexity.

Forms of Inheritance

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/11-object-oriented-programming 67 / 79
Campus Commune 8/5/2014

1. Single Inheritance:It is the inheritance hierarchy wherein one derived class inherits from one base class.

2. Multiple Inheritance: It is the inheritance hierarchy wherein one derived class inherits from multiple base class(es).

3. Hierarchical Inheritance:It is the inheritance hierarchy wherein multiple subclasses inherit from one base class.

4. Multilevel Inheritance:It is the inheritance hierarchy wherein subclass acts as a base class for other classes.

5. Hybrid Inheritance: The inheritance hierarchy that reflects any legal combination of other four types of inheritance.

In order to derive a class from another, we use a colon (:) in the declaration of the derived class using the following format :

class derived_class: memberAccessSpecifier base_class

...

};

Where derived_class is the name of the derived class and base_class is the name of the class on which it is based. The member Access Specifier may
be public, protected or private. This access specifier describes the access level for the members that are inherited from the base class.
Member Access How Members of the Base Class Appear in the
Specifier Derived Class
Private members of the base class are inaccessible to the
derived class.
Protected members of the base class become private
Private
members of the derived class.
Public members of the base class become private members
of the derived class.
Private members of the base class are inaccessible to the
derived class.
Protected members of the base class become protected
Protected
members of the derived class.
Public members of the base class become protected
members of the derived class.
Private members of the base class are inaccessible to the
derived class.
Protected members of the base class become protected
Public
members of the derived class.
Public members of the base class become public members of
the derived class.
In principle, a derived class inherits every member of a base class except constructor and destructor. It means private members are also become
members of derived class. But they are inaccessible by the members of derived class.

Following example further explains concept of inheritance :

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/11-object-oriented-programming 68 / 79
Campus Commune 8/5/2014

class Shape

protected:

float width, height;

public:

void set_data (float a, float b)

width = a;

height = b;

};

class Rectangle: public Shape

public:

float area ()

return (width * height);

};

class Triangle: public Shape

public:

float area ()

return (width * height / 2);

};

int main ()

Rectangle rect;

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/11-object-oriented-programming 69 / 79
Campus Commune 8/5/2014

Triangle tri;

rect.set_data (5,3);

tri.set_data (2,5);

cout << rect.area() << endl;

cout << tri.area() << endl;

return 0;

output :

15
5

The object of the class Rectangle contains :

width, height inherited from Shape becomes the protected member of Rectangle.

set_data() inherited from Shape becomes the public member of Rectangle

area is Rectangle’s own public member

The object of the class Triangle contains :

width, height inherited from Shape becomes the protected member of Triangle.

set_data() inherited from Shape becomes the public member of Triangle

area is Triangle’s own public member

set_data () and area() are public members of derived class and can be accessed from outside class i.e. from main()

1. Polymorphism

It is the ability of an object or reference to take many different forms at different instances. These are of two types one is the "compile time
polymorphism" and other one is the "run-time polymorphism".

Compile time polymorphism: In this method object is bound to the function call at the compile time itself.

Run time polymorphism: In this method object is bound to the function call only at the run time.

Example:

#include <iostream.h>

class Value

protected:

int val;

public:

void set_values (int a)

{ val=a;}

};

class Cube: public Value

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/11-object-oriented-programming 70 / 79
Campus Commune 8/5/2014

public:

int cube()

{ return (val*val*val); }

};

int main () {

Cube cb;

Value * ptr = &cb;

ptr->set_values (10);

cout << "The cube of 10 is::" << cb.cube() << endl;

return 0;

Result:

The cube of 10 is:: 1000

In the above OOPs example "Cube" is a derived class of "Value". To implement polymorphism a pointer "ptr" is used to reference to the members
of the class "Cube". This is an example for "Compile time polymorphism."

Constructors

It is a member function having same name as it’s class and which is used to initialize the objects of that class type with an initial value. Constructor
is automatically called when object is created.

Following example explains the concept of constructor:

Example

#include <iostream>

using namespace std;

class Line

public:

void setLength( double len );

double getLength( void );

Line(); // This is the constructor

private:

double length;

};

/ Member functions definitions including constructor

Line::Line(void)

cout << "Object is being created" << endl;

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/11-object-oriented-programming 71 / 79
Campus Commune 8/5/2014

void Line::setLength( double len )

length = len;

double Line::getLength( void )

return length;

// Main function for the program

int main( )

Line line;

// set line length

line.setLength(6.0);

cout << "Length of line : " << line.getLength() <<endl;

return 0;

When the above code is compiled and executed, it produces the following result:

Object is being created

Length of line : 6

Types of Constructor

Default Constructor-: A constructor that accepts no parameters is known as default constructor. If no constructor is defined then the compiler
supplies a default constructor.

student :: student()

rollno=0;

marks=0.0;

Parameterized Constructor -: A constructor that receives arguments/parameters, is called parameterized constructor.

Example

student :: student(int r)

rollno=r;

Example

class Point

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/11-object-oriented-programming 72 / 79
Campus Commune 8/5/2014

int xVal, yVal;

public:

Point (int x,int y)

xVal = x;

yVal = y;

} // constructor

void OffsetPt (int,int);

};

Now we can define objects of type Point and initialize them at once. This is in fact compulsory for classes that contain constructors that require
arguments:

Point pt1 = Point(10,20);

Point pt2; // illegal!

The former can also be specified in an abbreviated form.

Point pt1(10,20);

A class may have more than one constructor. To avoid ambiguity, however, each of these must have a unique signature.

For example,

class Point

int xVal, yVal;

public:

Point (int x, int y)

xVal = x;

yVal = y;

Point (float, float); // polar coordinates

Point (void)

xVal = yVal = 0;

} // origin

void OffsetPt (int, int);

};

Point::Point (float len, float angle) // polar coordinates

xVal = (int) (len * cos(angle));

yVal = (int) (len * sin(angle));

An object of type Point can be defined using any of these:

Point pt1(10,20);

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/11-object-oriented-programming 73 / 79
Campus Commune 8/5/2014

Point pt2(60.3,3.14);

Point pt3;

Copy Constructor-: A constructor that initializes an object using values of another object passed to it as parameter, is called copy constructor. It
creates the copy of the passed object.

student :: student(student &t)

rollno = t.rollno;

There can be multiple constructors of the same class, provided they have different signatures.

Destructors:

A destructor is a member function having sane name as that of its class preceded by ~(tilde) sign and which is used to destroy the objects that
have been created by a constructor. It gets invoked when an object’s scope is over.

~student() { }

Just as a constructor is used to initialize an object when it is created, a destructor is used to clean up the object just before it is destroyed. A
destructor always has the same name as the class itself, but is preceded with a ~ symbol. Unlike constructors, a class may have at most one
destructor. A destructor never takes any arguments

and has no explicit return type.

Destructors are generally useful for classes which have pointer data members which point to memory blocks allocated by the class itself. In such
cases it is important to release member-allocated memory before the object is destroyed. A destructor can do just that.

For example,

class Set

public:

Set (const int size);

~Set (void) {delete elems;} // destructor

private:

int *elems;

int maxCard; // maximum cardinality

int card; // set cardinality

};

Now consider what happens when a Set is defined and used in a function:

void Foo (void)

Set s(10);

//...

When Foo is called, the constructor for s is invoked, allocating storage for s.elems and initializing its data members. Next the rest of the body of Foo
is executed. Finally, before Foo returns, the destructor for s is invoked, deleting the storage occupied by s.elems. Hence, as far as storage allocation
is concerned, s behaves just like an automatic variable of a built-in type, which is created when its scope is entered and destroyed when its scope is
left.

In general, an object’s constructor is applied just before the object is destroyed. This in turn depends on the object’s scope. For example, a global
object is destroyed when program execution is completed; an automatic object is destroyed when its scope is left; and a dynamic object is
destroyed when the delete operator is applied to it.

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/11-object-oriented-programming 74 / 79
Campus Commune 8/5/2014

Example : In the following program constructors, destructor and other member functions are defined inside class definitions. Since we are using
multiple constructor in class so this example also illustrates the concept of constructor overloading

#include<iostream.h>

class student //specify a class

private :

int rollno; //class data members

float marks;

public:

student() //default constructor

rollno=0;

marks=0.0;

student(int r, int m) //parameterized constructor

rollno=r;

marks=m;

student(student &t) //copy constructor

rollno=t.rollno;

marks=t.marks;

void getdata() //member function to get data from user

cout<<"Enter Roll Number : ";

cin>>rollno;

cout<<"Enter Marks : ";

cin>>marks;

void showdata() // member function to show data

cout<<"\nRoll number: "<<rollno<<"\nMarks: "<<marks;

~student() //destructor

{}

};

int main()

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/11-object-oriented-programming 75 / 79
Campus Commune 8/5/2014

student st1; //defalut constructor invoked

student st2(5,78); //parmeterized constructor invoked

student st3(st2); //copy constructor invoked

st1.showdata(); //display data members of object st1

st2.showdata(); //display data members of object st2

st3.showdata(); //display data members of object st3

return 0;

Ask a doubt (Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune)

Open Doubts Closed Doubts


SINDHU M
during course completion without even completing the course,when i mwas about bto go for next question instead of
coming click non the next question it came one of bur attempt got over please help me so that i acn do the course again

about 21 days ago

BHARATHWAJ SUNDARESAN
The above provided material is not completely sufficient enough to attempt the quiz. and frequently the right answers are
declared wrong.

about 27 days ago

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/11-object-oriented-programming 76 / 79
Campus Commune 8/5/2014

Pre-ILP Home

Unix/C++/Oracle Lounge
Logout

C++
Q
1.Application Understanding

Q
2.Problem Solving Orientation

Q
3.C++ - Introduction

Q
4.C++ FUNDAMENTALS - OPERATORS

Q
5.C++ -Conditional Constructs

Q
6.C++ - Basic Iterations

Q
7.C++ - Functions

Q
8.C++ - Pointers

Q
9.C++ - Introduction to object oriented concepts

Course Completion Quiz

9.2. Practice Problems


Topic : Elements of OOP

1. Write a base class “Shapes” & Derived classes “Rectangle”, “Square” base should have Static Count Variable which keeps the track of the
Derived class object getting created and Implement the following

Make all the member variables as PRIVATE

1:- Area() of Rectangle & Square, making Area() of the class shapes as virtual.

2:- All constructors and Destructors of all the classes.

3:- getter and setter methods of all the private member functions.

4:- Display the count of the derived objects created

2.Create a Calculator class having functionality addition, multiplication, division and subtraction for two operands . The arguments and
operator to be passed by the user as input.

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/practice-problems-16 77 / 79
Campus Commune 8/5/2014

3.Create a class Student having the properties rollNo, name and a pointer which points to an array of marks.

a. Create a parameterized constructor which takes name and rollNo and initializes the corresponding members. The constructor also takes
length of the marks array as input and assigns default values of 0 for all the marks.

b. Add setter method for marks attribute which takes a position and the modified score as input and changes the score at the given position
with the given modified score

c. Add member function findGrade() which returns the character A, B, C, D, F based on the total score range “>=80”, “60–80”, “45–60”,
“35–45” and “< 35”.

d. Add destructor for deleting the array of marks

Write main( ) to test all the functionalities of the student class. Apply proper access specifier for the properties and behaviors of the student
class .

4.Write two functions having same name “findAverage” to find the average of three integers and the average of three type values calling the
functions. (Use the concept of function overloading).

5. To create Employee Class with properties EmpNo, Empname, Basic Pay, Increment, Variable Component, PF and net salary.

Write a method inside Employee class to calculate netsalary and set it to its corresponding attribute of the Employee class.

(Net salary = Basic pay + Increment +variable component – PF)

Click here to download the solutions

Topic: Classes and Objects

1. Create a class called Test to print – 'Welcome to Tata Consultancy Services' .

2. Teacher wants the contact details of each student in her class. She chose the Class leader to make the contact list. Help the class leader to define
a class StudentContact.

3. A Student has come to the library to get a book on Probability Theory. The student is very particular about the author, publication and edition of
the book. Define a class Book so that the librarian can inform the student about the availability of the book. (Hint: for the class Book, identify the
attributes and write).

4. The ILP Faculty coordinator wants to know the details of a faculty like name, competency skills, category (Permanent, Visiting, External), Base
Branch of faculty as well. Define a class Faculty that would help the Coordinator to meet his requirements.

5. Define a class Stock in C+ + with the following description:


Private Members
ICode of type integer (Item Code)
Item of type string (Item Name)
Price of type float(Price of each item)
Qty of type integer (quantity in stock)
Discount of type float (Discount percentage on the item)
A member function FindDisc( ) to calculate discount as per the following rule:
If Qty<=50 Discount is 0
If Qty (51 and100) Discount is 5
If Qty>100 Discount is 10
Public Members:
A function Buy( ) to allow user to enter values for ICode, Item, Price, Qty and call function FindDisc( ) to calculate the discount.
A Function ShowAll( ) to allow userto view the content of all the data members.

6. Create a class Student having the properties rollNo, name and mark1,mark2 and mark2 and total marks and has the following methods:Declare
the methods inside the class and define it outside the class.
i. Average(): which would accept marks of 3 examinations & return whether the student has passed or failed depending on whether he has scored
an average above 50 or not.
ii. GetDetails: which would accept the id,name and marks of the student.
iii. DisplayDetails :which would display the details about the student.

Click here to download the solutions

Topic : Constructors and Destructors

1) Create a class Tree which specifies the height of the tree. The default constructor should

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/practice-problems-16 78 / 79
Campus Commune 8/5/2014

print “Planting a seedling”. Another constructor should take an argument and initialize the height.
It should also print “Creating a new Tree that is h feet tall” where h is the height initialized in
this constructor.

2) Define a class complexnumber class having real and imaginary part.Implement the following functions

a) default constructor to initialize real and imaginary part with 0.


b) one argument constructor
c) two argument constructor
d) Add function - to add two complex numbers

3) Create a class to sort array using bubble sort algorithm.Create a default constructor which
should initialize the array elements with 0.Create methods to read input from the user, sort
and display the array elements.

4) Define a class trainee having properties name,id and stream.


Use constructors to initialize the values of the properties.Use getters to get values.
Write a program that instantiates objects of class and outputs all the information using getters in the main function.

5) Create a class “CStudent” which contains the following data items:


a. Student Name
b. Student Enrollment Number
c. Total Marks
d. Grade

Design and implement a constructor that initializes all the 3 data members.
Create a function to compute and display the grade along with all other details of student.

GRADE MARKS
A >90
B >80 and less than 91
C >70 and less than 81
D >60 and less than 71
E <60

6) Create a class Car having following properties


a)ModelID(int)
b)ModelName(char pointer)

Also add the following functions


a)default constructor
b)parameterized constructor
c)Copy constructor
d)Destructor
e)Read function to read input from the user
f)display - to display the properties of Car

Click here to download the solutions

Ask a doubt (Misuse of 'Ask a Doubt' Section will be dealt as per the Terms & Conditions of Campus Commune)

Open Doubts Closed Doubts


AKANKSHA MATHUR
Problem of wrong answershas lead me to not clearing 2 quizes and also lost 1 attempt in course completion. what to do???

about 21 days ago

https://campuscommune.tcs.com/communities/unix-c-oracle-lounge/content/practice-problems-16 79 / 79

Das könnte Ihnen auch gefallen