Maths Project
Maths Project
Maths Project
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.
Overloading Arithmetic Operator
Arithmetic operator are most commonly used operator in C++. Almost all
arithmetic operator can be overloaded to perform arithmetic operation on
user-defined data type. In the below example we have overridden
the + operator, to add to Time(hh:mm:ss) objects.
Example: overloading '+' Operator to add two time object
#include< iostream.h>
#include< conio.h>
class time
{
int h,m,s;
public:
time()
{
h=0, m=0; s=0;
}
void getTime();
void show()
{
cout<< h<< ":"<< m<< ":"<< s;
}
time operator+(time); //overloading '+' operator
};
time time::operator+(time t1) //operator function
{
time t;
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.
Ran
Name Operator
k
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.
When a program calls a function, program control is transferred to the
called function. A called function performs defined task and when its
Page
21
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;
}
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
Page
22
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
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;
}
When the above code is compiled and executed, it produces the following
result:
Total value is :300
Total value is :120
Page
24
*****************
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.
Page
25
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
applies only if the const or volatile keyword follows the function's
argument list in the declaration.
Example
The following example illustrates how overloading can be used
// function_overloading.cpp
// compile with: /EHsc
#include <iostream>
#include <math.h>
// Prototype three print functions.
int print( char *s ); // Print a string.
int print( double dvalue ); // Print a double.
int print( double dvalue, int prec ); // Print a double with a
// given precision.
using namespace std;
int main( int argc, char *argv[ ] )
{
const double d = 893094.2987;
if( argc < 2 )
{
// These calls to print invoke print( char *s ).
print( "This program requires one argument." );
print( "The argument specifies the number of" );
print( "digits precision for the second number" );
print( "printed." );
exit(0);
}
// Invoke print( double dvalue ).
print( d );
// Invoke print( double dvalue, int prec ).
print( d, atoi( argv[1] ) );
}
// Print a string.
int print( char *s )
{
cout << s << endl;
Page
27
return cout.good();
}
// Print a double in default precision.
int print( double dvalue )
{
cout << dvalue << endl;
return cout.good();
}
// Print a double in specified precision.
// Positive numbers for precision indicate how many digits
// precision after the decimal point to show. Negative
// numbers for precision indicate where to round the number
// to the left of the decimal point.
int print( double dvalue, int prec )
{
// Use table-lookup for rounding/truncation.
static const double rgPow10[] = {
10E-7, 10E-6, 10E-5, 10E-4, 10E-3, 10E-2, 10E-1, 10E0,
10E1, 10E2, 10E3, 10E4, 10E5, 10E6
};
const int iPowZero = 6;
// If precision out of range, just print the number.
if( prec < -6 || prec > 7 )
return print( dvalue );
// Scale, truncate, then rescale.
dvalue = floor( dvalue / rgPow10[iPowZero - prec] ) *
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
28
*****************
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.
Page
29
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.
... .. ...
}
class Distance
{
private:
int meter;
public:
Distance(): meter(0) { }
Page
30
//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.
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>
Page
31
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);
};
int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
Output
Sum: 13
Page
32
In this program, classes A and B have declared add() as a friend function.
Thus, this function can access private data of both class.
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);.
class B
{
... .. ...
}
When a class is made a friend class, all the member functions of that class
becomes friend functions.
Page
33
*******************
Page
34
A virtual function is a member function in base class that you expect to
redefine in derived classes.
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 Gun : public Weapon
{
public:
void loadFeatures()
{ cout << "Loading gun 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!
However, our game project started getting bigger and bigger. And, we
decided to create a separate Loader class to load weapon features.
Page
36
class Loader
{
public:
void loadFeatures(Weapon *weapon)
{
weapon->features();
}
};
#include <iostream>
using namespace std;
class Weapon
{
public:
void features()
{ cout << "Loading weapon features.\n"; }
};
class Loader
{
public:
Page
37
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
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