Professional Documents
Culture Documents
Soniya
INDEX
Page 1
INDEX
3 Control Statement
7-19
Page 2
Operator Overloading
Same operator but different behaviour is called operator overloading. In
other words , Operator overloading is a technique by
which operators used in a programming language are implemented in
user-defined types with customized logic that is based on the types of
arguments passed.
Almost all the operators can be overloaded in infinite different ways.
Following are some examples to learn more about operator overloading.
All the examples are closely connected.
Page 3
int a,b;
a=s+t1.s;
t.s=a%60;
b=(a/60)+m+t1.m;
t.m=b%60;
t.h=(b/60)+h+t1.h;
t.h=t.h%12;
return t;
}
void time::getTime()
{
cout<<"\n Enter the hour(0-11) ";
cin>>h;
cout<<"\n Enter the minute(0-59) ";
cin>>m;
cout<<"\n Enter the second(0-59) ";
cin>>s;
}
void main()
{
clrscr();
time t1,t2,t3;
cout<<"\n Enter the first time ";
t1.getTime();
cout<<"\n Enter the second time ";
t2.getTime();
t3=t1+t2; //adding of two time object using '+' operator
cout<<"\n First time ";
t1.show();
cout<<"\n Second time ";
t2.show();
cout<<"\n Sum of times ";
t3.show();
getch();
}
*****************
Page 4
Operator Precedence
Definition: Precedence is the order in which a program performs the
operations in a formula. If one operator has precedence over another
operator, it is evaluated first.
Operator Precedence.
Rank Name Operator
1 scope resolution ::
2 member selection, subscripting, . ->
function calls, postfix increment ()
and decrement ++ --
3 sizeof, prefix increment and decrement, ++ --
complement, and, not, unary minus and plus, ^!
address of and dereference, new, new[],
-+
delete,
delete[], casting, sizeof(), &*
()
4 member selection for pointer .* ->*
5 multiply, divide, modulo */%
6 add, subtract +-
7 shift << >>
8 inequality relational < <= > >=
9 equality, inequality == !=
10 bitwise AND &
11 bitwise exclusive OR ^
12 bitwise OR |
13 logical AND &&
14 logical OR ||
Page 5
15 conditional ?:
16 assignment operators = *= /= %=
+= -= <<=
>>=
&= |= ^=
17 throw operator throw
18 comma ,
*****************
Page 6
Control Statement/Control Structures
Control statements enable us to specify the flow of program control; ie,
the order in which the instructions in a program must be executed. They
make it possible to make decisions, to perform tasks repeatedly or to jump
from one section of code to another. Following are the type of control
statement.
1. If statement
2. Switch case statement
If statement :-
An if statement is a programming conditional statement that, if proved
true, performs a function or displays information. Below is a general
example of an if statement, not specific to any particular programming
language.
Types of If statement :-
1. Simple if statement
2. If else statement
3. Nested if statement
4. Else if statement
If statement
Syntax
if (testExpression)
{
// statements
}
Page 7
Flowchart of if statement
#include <stdio.h>
int main()
{
int number;
Page 8
{
printf("You entered %d.\n", number);
}
return 0;
}
Output 1
Enter an integer: -2
You entered -2.
The if statement is easy.
When user enters -2, the test expression (number < 0) becomes true.
Hence, You entered -2 is displayed on the screen.
Output 2
Enter an integer: 5
The if statement in C programming is easy.
When user enters 5, the test expression (number < 0) becomes false and
the statement inside the body of if is skipped.
If...else statement
The if...else statement executes some code if the test expression is true
(nonzero) and some other code if the test expression is false (0).
Syntax of if...else
if (testExpression) {
// codes inside the body of if
}
else {
// codes inside the body of else
}
Page 9
If test expression is false, codes inside the body of else statement is
executed and, codes inside the body of if statement is skipped.
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
Page
10
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
The nested if...else statement allows you to check for multiple test
expressions and execute different codes for more than two conditions.
Page
11
// statements to be executed if testExpression1 and testExpression2 is
false and testExpression3 is true
}
.
.
else
{
// statements to be executed if all test expressions are false
}
Example #3: C Nested if...else statement
// Program to relate two integers using =, > or <
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
return 0;
}
Page
12
Output
Enter two integers: 12
23
Result: 12 < 23
Loop
Loops are used in programming to repeat a specific block of code
Loops are used in programming to repeat a specific block until some end
condition is met. There are three loops in C programming:
1. for loop
2. while loop
3. do...while loop
For Loop
Then, the test expression is evaluated. If the test expression is false (0), for
loop is terminated. But if the test expression is true (nonzero), codes inside
the body of for loop is executed and the update expression is updated.
The for loop is commonly used when the number of iterations is known.
Page
13
For loop Flowchart
#include <stdio.h>
int main()
{
int num, count, sum = 0;
Page
14
// for loop terminates when n is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
return 0;
}
Output
Enter a positive integer: 10
Sum = 55
The value entered by the user is stored in variable num. Suppose, the user
entered 10.
The count is initialized to 1 and the test expression is evaluated. Since, the
test expression count <= num (1 less than or equal to 10) is true, the body
of for loop is executed and the value of sum will equal to 1.
Then, the update statement ++count is executed and count will equal to 2.
Again, the test expression is evaluated. Since, 2 is also less than 10, the
test expression is evaluated to true and the body of for loop is executed.
Now, the sum will equal 3.
This process goes on and the sum is calculated until the count reaches 11.
Page
15
How while loop works?
If the test expression is true (nonzero), codes inside the body of while loop
is evaluated. The test expression is evaluated again. The process goes on
until the test expression is false.
#include <stdio.h>
int main()
{
int number;
long long factorial;
Page
16
printf("Enter an integer: ");
scanf("%d",&number);
factorial = 1;
return 0;
}
Output
Enter an integer: 5
Factorial = 120
The do..while loop is similar to the while loop with one important
difference. The body of do...while loop is executed once, before checking
the test expression. Hence, the do...while loop is executed at least once.
Page
17
How do...while loop works?
The code block (loop body) inside the braces is executed once.
Then, the test expression is evaluated. If the test expression is true, the
loop body is executed again. This process goes on until the test expression
is evaluated to 0 (false).
#include <stdio.h>
int main()
{
double number, sum = 0;
Page
18
do
{
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
}
Output
Enter a number: 1.5
Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70
*******************
Page
19
Function in C ++
Page
20
Function Body: The function body contains a collection of
statements that define what the function does.
Example
Following is the source code for a function called max(). This function
takes two parameters num1 and num2 and returns the maximum between
the two:
// function returning the max between two numbers
return result;
}
Function Declarations
A function declaration tells the compiler about a function name and how
to call the function. The actual body of the function can be defined
separately.
A function declaration has the following parts:
return_type function_name( parameter list );
For the above defined function max(), following is the function
declaration:
int max(int num1, int num2);
Parameter names are not importan in function declaration only their type
is required, so following is also valid declaration:
int max(int, int);
Function declaration is required when you define a function in one source
file and you call that function in another file. In such case, you should
declare the function at the top of the file calling the function.
Calling a Function
While creating a C++ function, you give a definition of what the function
has to do. To use a function, you will have to call or invoke that function.
Page
21
When a program calls a function, program control is transferred to the
called function. A called function performs defined task and when its
return statement is executed or when its function-ending closing brace is
reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along
with function name, and if function returns a value, then you can store
returned value. For example:
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;
return 0;
}
return result;
Page
22
}
I kept max() function along with main() function and compiled the source
code. While running final executable, it would produce the following
result:
Max value is : 200
Function Arguments
If a function is to use arguments, it must declare variables that accept the
values of the arguments. These variables are called the formal
parameters of the function.
The formal parameters behave like other local variables inside the
function and are created upon entry into the function and destroyed upon
exit.
While calling a function, there are two ways that arguments can be passed
to a function:
Call Type Description
Page
23
the function and above mentioned example while calling max() function
used the same method.
Default Values for Parameters
When you define a function, you can specify a default value for each of
the last parameters. This value will be used if the corresponding argument
is left blank when calling to the function.
This is done by using the assignment operator and assigning values for
the arguments in the function definition. If a value for that parameter is
not passed when the function is called, the default given value is used, but
if a value is specified, this default value is ignored and the passed value is
used instead. Consider the following example:
#include <iostream>
using namespace std;
result = a + b;
return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;
return 0;
}
Page
24
When the above code is compiled and executed, it produces the following
result:
Total value is :300
Total value is :120
*****************
Page
25
Function Overloading
C++ allows specification of more than one function of the same name in
the same scope. These are called overloaded functions and are described in
detail in Overloading. Overloaded functions enable programmers to supply
different semantics for a function, depending on the types and number of
arguments.
For example, a print function that takes a string (or char *) argument
performs very different tasks than one that takes an argument of
type double. Overloading permits uniform naming and prevents
programmers from having to invent names such as print_sz or print_d. The
following table shows what parts of a function declaration C++ uses to
differentiate between groups of functions with the same name in the same
scope.
Overloading Considerations
Page
26
Function Declaration Element Used for Overloading?
Example
The following example illustrates how overloading can be used
// function_overloading.cpp
// compile with: /EHsc
#include <iostream>
#include <math.h>
Page
27
// Invoke print( double dvalue ).
print( d );
// Print a string.
int print( char *s )
{
cout << s << endl;
return cout.good();
}
Page
28
rgPow10[iPowZero - prec];
cout << dvalue << endl;
return cout.good();
}
The preceding code shows overloading of the print function in file scope.
The default argument is not considered part of the function type.
Therefore, it is not used in selecting overloaded functions. Two functions
that differ only in their default arguments are considered multiple
definitions rather than overloaded functions.
*****************
Page
29
FRIEND FUNCTION IN C++
The complier knows a given function is a friend function by the use of the
keyword friend.
For accessing the data, the declaration of a friend function should be made
inside the body of the class (can be anywhere inside class either in private
or public section) starting with keyword friend.
Declaration of friend function in C++
class class_name
{
... .. ...
friend return_type function_name(argument/s);
... .. ...
}
Now, you can define the friend function as a normal function to access the
data of the class. No friend keyword is used in the definition.
class className
{
... .. ...
friend return_type functionName(argument/s);
... .. ...
}
return_type functionName(argument/s)
{
... .. ...
// Private and protected data of className can be accessed from
// this function because it is a friend function of className.
... .. ...
}
Page
30
Example 1: Working of friend Function
class Distance
{
private:
int meter;
public:
Distance(): meter(0) { }
//friend function
friend int addFive(Distance);
};
int main()
{
Distance D;
cout<<"Distance: "<< addFive(D);
return 0;
}
Output
Distance: 5
Here, friend function addFive() is declared inside Distance class. So, the
private data meter can be accessed from this function.
Page
31
Though this example gives you an idea about the concept of a friend
function, it doesn't give show you any meaningful use.
#include <iostream>
using namespace std;
// forward declaration
class B;
class A {
private:
int numA;
public:
A(): numA(12) { }
// friend function declaration
friend int add(A, B);
};
class B {
private:
int numB;
public:
B(): numB(1) { }
// friend function declaration
friend int add(A , B);
};
Page
32
return (objectA.numA + objectB.numB);
}
int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
Output
Sum: 13
Here, add() function adds the private data numA and numB of two
objects objectA and objectB, and returns it to the main function.
This is because class B is referenced within the class A using code: friend
int add(A , B);.
Page
33
class B
{
... .. ...
}
When a class is made a friend class, all the member functions of that class
becomes friend functions.
*******************
Page
34
Virtual Function in C++
Before going into detail, let's build an intuition on why virtual functions
are needed in the first place.
Example
We created the Weapon class and derived two classes Bomb and Gun to
load features of respective weapons.
#include <iostream>
using namespace std;
class Weapon
{
public:
void loadFeatures()
{ cout << "Loading weapon features.\n"; }
};
Page
35
class Bomb : public Weapon
{
public:
void loadFeatures()
{ cout << "Loading bomb features.\n"; }
};
int main()
{
Weapon *w = new Weapon;
Bomb *b = new Bomb;
Gun *g = new Gun;
w->loadfeatures();
b->loadFeatures();
g->loadFeatures();
return 0;
}
Output
Loading weapon features.
Loading bomb features.
Loading gun features.
Works perfectly!
Page
36
However, our game project started getting bigger and bigger. And, we
decided to create a separate Loader class to load weapon features.
class Loader
{
public:
void loadFeatures(Weapon *weapon)
{
weapon->features();
}
};
#include <iostream>
using namespace std;
class Weapon
{
public:
void features()
{ cout << "Loading weapon features.\n"; }
};
Page
37
{ cout << "Loading gun features.\n"; }
};
class Loader
{
public:
void loadFeatures(Weapon *weapon)
{
weapon->features();
}
};
int main()
{
Loader *l = new Loader;
Weapon *w;
Bomb b;
Gun g;
w = &b;
l->loadFeatures(w);
w = &g;
l->loadFeatures(w);
return 0;
}
Output
Loading weapon features.
Loading weapon features.
Loading weapon features.
Initially, the Weapon object w is pointing to the b object (of Bomb) class.
And, we tried to load the features of Bomb object by passing it
to loadFeatures() function using l object to pointer (of Loader class).
Page
38
However, the loadFeatures() function of the Loader class takes pointer to
object of a Weapon class as an argument:
void loadFeatures(Weapon *weapon)
That's the reason weapon features are loaded 3 times. To solve this issue,
we need to make function of base class (Weapon class) virtual using
virtual keyword.
class Weapon
{
public:
virtual void features()
{ cout << "Loading weapon features.\n"; }
};
******************
Page
39