0% found this document useful (0 votes)
45 views

C++ Program Lecture 1

The document discusses the differences between C and C++ programming languages. It covers topics like procedural vs object-oriented nature, presence of features like virtual functions, polymorphism, operator overloading in C++. It also discusses other differences in input/output functions, memory allocation and exception handling between the two languages.

Uploaded by

indrani sen
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

C++ Program Lecture 1

The document discusses the differences between C and C++ programming languages. It covers topics like procedural vs object-oriented nature, presence of features like virtual functions, polymorphism, operator overloading in C++. It also discusses other differences in input/output functions, memory allocation and exception handling between the two languages.

Uploaded by

indrani sen
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 87

C++ program

Prof Indrani Sen,MCA,MPhil COmputer


Science

Difference between c and


C++
1.C is Procedural
Language.
2.No virtual Functions are
present in C.
3.In C, Polymorphism is not
possible
4.Operator overloading is
not possible in C.

1.C++ is non Procedural i.e.

Object oriented Language.


2.The concept of virtual
Functions are used in C++.
3.The concept of
polymorphism is used in C+
+.
4.Operator overloading is
one of the greatest Feature
of C++.

Prof Indrani Sen,MCA,MPhil COmputer


Science

5.Bottom up approach

5.Top down approach is


used in Program design
6.No namespace Feature is
present in C Language.
7.Multiple Declaration of
global variables are
allowed.
8.In C scanf() Function
used for Input.printf()
Function used for output.
9.Mapping between Data
and Function is difficult and
complicated.

adopted in Program Design.


6.Namespace Feature is
present in C++ for avoiding
Name collision.
7.Multiple Declaration of
global varioables are not
allowed.
8.In C++ Cin>> Function
used for Input.Cout<<
Function used for output.
9.Mapping between Data
and Function can be used
using "Objects"

Prof Indrani Sen,MCA,MPhil COmputer


Science

10.In C++, we cannot call

10.In C, we can call main()

Function through other


functions
11.C requires all the
variables to be defined at the
starting of a scope
12.No inheritance is possible
in C 13.In C, malloc() and
calloc() Functions are used for
Memory Allocation and free()
function for 14.It supports
built-in and primitive data.
15.In C, Exception Handling
is not present.

main() Function through


other functions.
11.C++ allows the
declaration of variable
anywhere in the scope i.e at
time of its First use.
12.Inheritance is possible in
C++
.13.In C++, new and delete
operators are used for
Memory Allocating and
Deallocating.
14.It support both built-in
and userdefine datatypes.
15.In C++, Exception
Handling is done with Try
and Catch block.

Prof Indrani Sen,MCA,MPhil COmputer


Science

What is a preprocessor directive


Preprocessor directives are lines included in the code of

programs preceded by a hash sign (#).


These lines are not program statements but directives for
thepreprocessor.
The preprocessor examines the code before actual
compilation of code begins and resolves all these directives
before any code is actually generated by regular statements.
No semicolon (;) is expected at the end of a preprocessor
directive.
preprocessor replacements happen before any C++ syntax
check.

Prof Indrani Sen,MCA,MPhil COmputer


Science

// function macro
#include <iostream.h>
#define max(a,b) ((a)>(b)?(a):(b))
int main()
{
int x=5, y=7;
int z= max(x,y);
cout <<" max=" <<+z<< endl;
return 0;
}

Prof Indrani Sen,MCA,MPhil COmputer


Science

Prof Indrani Sen,MCA,MPhil COmputer


Science

Identifiers in C++
Any used defined name given to the program

element is called asidentifier. (i.e Program


elements are identified by program with the
identifier name)
It is name given to program element.
Identifier are the names is given by the
programmer.
An identifier is used for any variable, function,
data definition etc.
We can give any valid name to the identifier.
Prof Indrani Sen,MCA,MPhil COmputer
Science

The rules in C++ for identifiers are :


Only Alphabets, Digits and Underscores are

permitted.
Identifier name cannot start with a digit.
Key words cannot be used as a name.
Upper case and lower case letters are distinct.
Special Characters are not allowed

Prof Indrani Sen,MCA,MPhil COmputer


Science

Name

Capital Letter and Small Letters are Allowed

name

Small Letters are allowed

name_1

Digits and Underscore is allowed along with alphabets

Int

Keywords are allowed but we have to change case of


any letter or complete word

INT

Keywords are allowed but we have to change case of


any letter or complete word

_SUM

Underscore at the first position is allowed in C++


language

sum_of_the_numbe We can concatenate multiple words with underscore


rs
firstName

Best Style to concatenate multiple words (Changing


case of First Letter of Successive Word)

Identifier

We can give concept name as Identifier name

printf

As we are not going to include stdio.h header file we

Prof Indrani Sen,MCA,MPhil COmputer


can use printf as identifier.
Science

Int
Pow
Sum$
Num^2
Num 1
2num

Prof Indrani Sen,MCA,MPhil COmputer


Science

Data types
Primitive Built-in Types:
C++ offer the programmer a rich assortment

of built-in as well as user defined data types.


Following table lists down seven basic C++
data types:

Prof Indrani Sen,MCA,MPhil COmputer


Science

Type

Keyword

Boolean

bool

Character

char

Integer

int

Floating point

float

Double floating point

double

Valueless

void

Wide character

wchar_t

Prof Indrani Sen,MCA,MPhil COmputer


Science

Several of the basic types can be modified

using one or more of these type modifiers:


signed
unsigned
short
long

Prof Indrani Sen,MCA,MPhil COmputer


Science

Type

Typical Bit Width Typical Range

char

1byte

-127 to 127 or 0 to 255

unsigned char

1byte

0 to 255

signed char

1byte

-127 to 127

int

4bytes

-2147483648 to 2147483647

unsigned int

4bytes

0 to 4294967295

signed int

4bytes

-2147483648 to 2147483647

short int

2bytes

-32768 to 32767

long int

4bytes

-2,147,483,647 to 2,147,483,647

signed long int

4bytes

same as long int

unsigned long int

4bytes

0 to 4,294,967,295

float

4bytes

+/- 3.4e +/- 38 (~7 digits)

double

8bytes

+/- 1.7e +/- 308 (~15 digits)

long double

8bytes

+/- 1.7e +/- 308 (~15 digits)

Prof Indrani Sen,MCA,MPhil COmputer


Science

#include <iostream.h>
int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;

return 0;
}
Prof Indrani Sen,MCA,MPhil COmputer
Science

Prof Indrani Sen,MCA,MPhil COmputer


Science

Prof Indrani Sen,MCA,MPhil COmputer


Science

Enumerated Types:
An enumerated type declares an optional type

name and a set of zero or more identifiers that


can be used as values of the type.
Each enumerator is a constant whose type is
the enumeration.
To create an enumeration requires the use of
the keywordenum.

Prof Indrani Sen,MCA,MPhil COmputer


Science

enum enum-name
{ list of names
} var-list;

Prof Indrani Sen,MCA,MPhil COmputer


Science

enum color { red, green, blue } c; c

= blue;
enum gender { male,female} ;
Gender g;
G=male;

Prof Indrani Sen,MCA,MPhil COmputer


Science

By default,
the value of the first name is 0,
the second name has the value 1,
the third has the value 2, and so on.

Prof Indrani Sen,MCA,MPhil COmputer


Science

#include <iostream.h>
int main()
{
enum note { sa,re,ga,ma,pa,dha,ni} ;
note n;
n=ni;
cout<<"the number of the music note

is"<<n<<endl;
return 0;
}
Prof Indrani Sen,MCA,MPhil COmputer
Science

Prof Indrani Sen,MCA,MPhil COmputer


Science

User defined data types


C++ allows you to use one or more data

types, group them as one, to create a new


data type as you see fit.
C++ offers three techniques of defining a new
data type: a structure, a class, and a union.
These are also referred to as composite data
types.

Prof Indrani Sen,MCA,MPhil COmputer


Science

Class. :
Class data types in C++ are an encapsulation of data members and

functions that manipulate the data.


Classes can also have some other important members which
arearchitecturallyimportant.
The data members can be of any valid data type, a class type, a struct
type, etc.
They can also bedeclaredas pointers and they can be accessed
normally as like other data members.
Access Level : The classes in C++ have 3 importantaccess levels.
They are Private, Protected and Public.
Private The members are accessible only by the member functions or
friend functions.
Protected The members are accessible by the member functions of
the class and the classes which are derived from this class.
Public Accessible by any external member.
Prof Indrani Sen,MCA,MPhil COmputer
Science

#include <iostream.h>
#include<conio.h>
// Class Declaration
class person
{
//Access - Specifier
public:
//Varibale Declaration
char name[30];
int number;
};

//Main Function
int main()
{ // Object Creation For Class

person obj;

//Get Input Values For Object

Varibales

cout<<"Enter the Name :";

cin>>obj.name;

cout<<"Enter the Number :";

cin>>obj.number;

//Show the Output

cout << obj.name << ": " <<


obj.number << endl;

getch();

return 0;
}

Prof Indrani Sen,MCA,MPhil COmputer


Science

Prof Indrani Sen,MCA,MPhil COmputer


Science

Structure. :
Structure data types in C++ are a collection

of data items having different data types.


Structure is a collection of variables under a
single name.
Variables can be of any type such as int, float,
char, etc.
The main difference between structure and
array is that arrays arecollections ofsame
data type and
structure is a collection of variables having
Prof Indrani
Sen,MCA,MPhil
COmputer
different data
types
under
a single name.
Science

The structure isdeclaredby using the keyword

struct followed by structure name, also called a


tag.
Then the structure members ( variables) are
defined with their type and variable names inside
the open and closebraces{ and }.
Finally, the closedbracesend with a semicolon
denoted as ; following the statement.
Structure data types in C++ are defined as. :

Prof Indrani Sen,MCA,MPhil COmputer


Science

struct student
{
private :
char name[20];
long phone;
public :
void display (void)
{
cout<<phone;
}
};
Prof Indrani Sen,MCA,MPhil COmputer
Science

Struct vs class
Members of a class are private by default and members of
struct are public by default.
For example program 1 fails in compilation and program 2
works fine.

Prof Indrani Sen,MCA,MPhil COmputer


Science

class
// Program 1
#include <stdio.h>

class Test {
int x; // x is private
};
int main()
{
Test t;
t.x = 20; // compiler error because x is private
getchar();
return 0;
}
Prof Indrani Sen,MCA,MPhil COmputer
Science

Struct
// Program 2
#include <stdio.h>
struct Test {
int x; // x is public
};
int main()
{
Test t;
t.x = 20; // works fine because x is public
getchar();
return 0;
}
Prof Indrani Sen,MCA,MPhil COmputer
Science

Derived Data Types:


Data types that are derived from the built-in

data types are known as derived data types.


The various derived data types provided by
C++ arearrays, junctions,
referencesandpointers.

Prof Indrani Sen,MCA,MPhil COmputer


Science

Arrays and Strings :


Array data types in C++ are same as arrays in C. They are

a collection of elements having similar data types.


In C, array size is exact same length of the string constant.
E.g. char string [5] = abcde;
this is valid in C.
But in C++ that array size is onelargerthan thenumberof
characters present in it. Here, \o is treated as a character
in the array.
E.g. char string [5] = abcde;
this is invalid in C++.
char string [5] = abcd;
this is valid in C++.
Prof Indrani Sen,MCA,MPhil COmputer
Science

Functions. :
Function data types in C++ are discrete

blocks of statements that perform certain


tasks.
Once a function has been written to play a
particular role in a program.
It can be called upon repeatedly throughout
the program.
Syntax. :return_type function_name
(parameters);
E.g. int max (int x, int y);
Prof Indrani Sen,MCA,MPhil COmputer
Science

Pointers. :
Pointer data types in C++ are variables that

represent the location (rather than the value)


of a data item such as a variable or an array
element.

Prof Indrani Sen,MCA,MPhil COmputer


Science

Prof Indrani Sen,MCA,MPhil COmputer


Science

Constants
Constantsare expressions with a fixed value.
Literal constants can be classified into: integer,

floating-point, characters, strings, Boolean,


pointers, and user-defined literals.
Sometimes, it is just convenient to give a name
to a constant value:
const double pi = 3.1415926;
const char tab = '\t';

Prof Indrani Sen,MCA,MPhil COmputer


Science

Rules of declaring constants and


variables
Rules for Constructing Integer Constants
An integer constant must have at least one digit.
It must not have a decimal point.
It can be either positive or negative.
If no sign precedes an integer constant it is

assumed to be positive.
No commas or blanks are allowed within an
integer constant.
The allowable range for integer constants is
-32768 to 32767.

Integer constants
Integer Numerals
1

2
3
1776 707 -273
These are numerical constants that identify integer values.
they are not enclosed in quotes or any other special
character;
they are a simple succession of digits representing a whole
number in decimal base;

Prof Indrani Sen,MCA,MPhil COmputer


Science

Octal and hexa decimals


In addition to decimal numbers (those that most of us use every

day), C++ allows the use of octal numbers (base 8)


and hexadecimal numbers (base 16) as literal constants.
For octal literals, the digits are preceded with a0(zero) character.
And for hexadecimal, they are preceded by the
characters0x(zero, x).
For example, the following literal constants are all equivalent to
each other:
75 // decimal
0113 // octal
0x4b // hexadecimal

Prof Indrani Sen,MCA,MPhil COmputer


Science

Rules for Constructing Real or


floating point Constants
A real constant must have at least one digit.
It must have a decimal point.
It could be either positive or negative.
Default sign is positive.
No commas or blanks are allowed within a

real constant.

Prof Indrani Sen,MCA,MPhil COmputer


Science

#include <iostream.h>
#define PI 3.14159
#define NEWLINE '\n
int main ()
{
double r=5.0;
// radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
}

Prof Indrani Sen,MCA,MPhil COmputer


Science

Prof Indrani Sen,MCA,MPhil COmputer


Science

Exponential constants
The mantissa part and the exponential part should

be separated by a letter e.
The mantissa part may have a positive or negative
sign.
Default sign of mantissa part is positive.
The exponent must have at least one digit, which
must be a positive or negative integer. Default
sign is positive.
Range of real constants expressed in exponential
form is -3.4e38 to 3.4e38.

Rules for Constructing


Character Constants
A character constant is a single alphabet, a

single digit or a single special symbol


enclosed within single inverted commas.
The maximum length of a character constant

can be 1 character.

Rules for Constructing Variable


Names
The first character in the variable name

must be an alphabet or underscore. No


digits are allowed.
No commas or blanks are allowed within a
variable name.
No special symbol other than an
underscore (as in gross_sal) can be used in
a variable name.
Keywords not allowed as variable name

C++ Instructions
There are basically four types of instructions

in C++:
Type Declaration Instruction
Input/output Instruction
Arithmetic Instruction
Control Instruction

C++
Instructions
Type declaration instruction -To declare the type of

variables used in a C ++program.


Arithmetic instruction -To perform arithmetic operations

between con-stants and variables.


Input/Output Instruction-To take the input from the

standard input or keyboard and display the output on


standard output ie monitor.
Control instruction -To control the sequence of execution of

various state-ments in a C++ program.

Type Declaration Instruction


This instruction is used to declare the type of

variables being used in the program.


Any variable used in the program must be
declared before using it in any statement.
In C++ it is allowed to Declare the variable
just before using it.
int bas ;
float rs, grosssal ;
char name, code ;

Variations of typedef
statement
Case 1:While declaring the type of variable

we can also initialize it as shown below.


int i = 10, j = 25 ;
float a = 1.5, b = 1.99 + 2.4 * 1.44 ;

Variations of typedef statement


Case 2:The order of defining the variables:int i = 10, j = 25 ; is same as int j = 25, i = 10

;
However, float a = 1.5, b = a + 3.1 ; is not
the same as float b = a + 3.1, a = 1.5 ;
The second expression will give us a compiler
error as a is used undefined.

Variations of typedef statement


Case 3: Initialisation of multiple variables with

one value.
int a, b, c, d ;
a = b = c = 10 ;
But int a=b=c=10; is not allowed

Arithmetic Instruction
A C++ arithmetic instruction consists of a

variable name on the left hand side of = and


variable names & constants on the right hand
side of =.
The variables and constants appearing on the
right hand side of = are connected by
arithmetic operators like +, -, *, and /.

No operator
is assumed to be
present. It
Variations
of arithmetic
Instructions

must be written explicitly.


a = c.d.b(xy) usual arithmetic statement
b = c * d * b * ( x * y ) //C++ statement
Unlike other high level languages, there is
no operator for performing exponentiation
operation.
following statements are invalid.
a = 3 ** 2 ;
b = 3 ^ 2 ;

Computing power or
exponentiation
pow( ) function: It is a standard library

function .
It is included in the header file Math.h
Prototype of the function is
Double pow(double base,double
exponent);

Program to compute the power of a


number
#include <math.h>
#include <iostream.h>
Void main( )
{
int a ;
a = pow ( 3, 2 ) ;
Cout<<a;
}

Program to compute the square


root of a number
#include <math.h>
#include <iostream.h>
Void main( )
{
int a ,b;
Cin>>a;
b = sqrt ( a ) ;
Cout<<b;
}

Which of the following are invalid


variable names and why?

Point out the errors, if any, in the following C


statements:

(a) int = 314.562 * 150 ;


(b) name = Ajay ;
(c) varchar = 3 ;
(d) 3.14 * r * r * h = vol_of_cyl ;
(e) k = ( a * b ) ( c + ( 2.5a + b ) ( d + e ) ;
(f) m_inst = rate of interest * amount in rs ;

Precedence of
operators C++

Preceden
ce

Operator

Description
Class::age = 2;
Std::cout<<Enter
age:;

left to right

1.::

Scope
resolution
operator

2.()

Function
call

printf(Hello
world\n);

left to right

++

Postincrement

i++

left to right

--

Postdecrement

i--

3.!

Logical
negation

!(a>b)

Bitwise
complemen
t

~(100101)

++

Preincrement

++i

--

Predecrement

--i

Associativ
ity

left to right
right to left
right to left
right to left
right to left

Preceden
ce

Operator

Description

Associativ
ity

4.*

Dereference

Int
*intptr,data,x;
X=10;
Intdata=&x;
int data =
*intPtr;

Right to left

&

Address of

int *intPtr =
&data;

Right to left

sizeof

Size (of the


type) of the
operand in
bytes

size_t s =
sizeof(int);

Right to left

Int *x=new int(); Right to left

new

Dynamic
memory
allocation
Dynamic
memory
allocation

Delete x

Delete

Right to left

Preceden
ce

Operator

Description

Associativ
ity

6.+

Addition

int i = 2 + 3;

Left To
Right

Subtraction

int i = 5 - 1;

7.<<

Bitwise shift
left

int flags = 33
<< 1;

>>

Bitwise shift
right

int flags = 33
>> 1;

8.<

Comparison
less-than

<=

Comparison
less-than-orequal-to

>

Comparison
greater-than

Left To
Right
Left To
Right
Left To
Right

if (i < 42)

Left To
Right

if (i <= 42) ...

Left To
Right

if (i > 42) ...

Left To
Right

Preceden
ce

Operator

Description

Associativ
ity

9.==

Comparison
equal-to

if (i == 42) ...

Left to right

!=

Comparison
not-equal-to

if (i != 42) ...

&&

AND

Left to right

||

OR

Left to right

?:

Ternery
operator

Assignment

int i = a > b ?
a : b;

Left to right

Left to right
Right to left

Convert the following statements


into C++ statements

Loops
A loop statement allows us to execute a

statement or group of statements multiple


times
and following is the general from of a loop
statement in most of the programming
languages:

Prof Indrani Sen,MCA,MPhil COmputer


Science

Prof Indrani Sen,MCA,MPhil COmputer


Science

Loop Type

Description

while loop

Repeats a statement or group of statements while a


given condition is true. It tests the condition before
executing the loop body.

for loop

Execute a sequence of statements multiple times


and abbreviates the code that manages the loop
variable.

do...while loop

Like a while statement, except that it tests the


condition at the end of the loop body

nested loops

You can use one or more loop inside any another


while, for or do..while loop.

Prof Indrani Sen,MCA,MPhil COmputer


Science

For loop
for ( variable initialization; condition; variable

update ) { Code to execute while the


condition is true }

Prof Indrani Sen,MCA,MPhil COmputer


Science

#include <iostream.h>
int main()
{
// The loop goes while x < 10, and x increases by one every loop
for ( int x = 0; x < 10; x++ ) {
// Keep in mind that the loop condition checks
// the conditional statement before it loops again.
// consequently, when x equals 10 the loop breaks.
// x is updated before the condition is checked.
cout<< x <<endl;
}
cin.get();
}
Prof Indrani Sen,MCA,MPhil COmputer
Science

While
WHILE - WHILE loops are very simple. The basic structure is
while ( condition ) { Code to execute while the condition is true }
The true represents a boolean expression which could be
x == 1 or while ( x != 7 )
(x does not equal 7).
It can be any combination of boolean statements that are legal.
Even, (while x ==5 || v == 7) which says execute the code while

x equals five or while v equals 7.


Notice that a while loop is the same as a for loop without the
initialization and update sections.
However, an empty condition is not legal for a while loop as it is
with a for loop.
Prof Indrani Sen,MCA,MPhil COmputer
Science

#include <iostream>
int main()
{
int x = 0; // Don't forget to declare variables

while ( x < 10 ) { // While x is less than 10


cout<< x <<endl;
x++;
// Update x so the condition can be met

eventually
}
cin.get();
}
Prof Indrani Sen,MCA,MPhil COmputer
Science

DO..WHILE
DO..WHILE loops are useful for things that want to loop at

least once.
The structure is do { } while ( condition );
Notice that the condition is tested at the end of the block
instead of the beginning, so the block will be executed at
least once.
If the condition is true, we jump back to the beginning of the
block and execute it again.
A do..while loop is basically a reversed while loop.
A while loop says "Loop while the condition is true, and
execute this block of code",
a do..while loop says "Execute this block of code, and loop
while the condition is true".
Prof Indrani Sen,MCA,MPhil COmputer
Science

#include <iostream.h>
int main()
{
int x;
x = 0;
do {
// "Hello, world!" is printed at least one time
// even though the condition is false
cout<<"Hello, world!\n";
} while ( x != 0 );
cin.get();
}
Prof Indrani Sen,MCA,MPhil COmputer
Science

switch case in C++


Switch case statements are a substitute for long
if statements that compare a variable to several

"integral" values ("integral" values are simply values


that can be expressed as an integer, such as the value
of a char).
The basic format for using switch case is outlined
below.
The value of the variable given into switch is
compared to the value following each of the cases,
and when one value matches the value of the variable,
the computer continues executing the program from
that point.
Prof Indrani Sen,MCA,MPhil COmputer
Science

#include <iostream.h>
void playgame()
{
cout << "Play game called";
}
void loadgame()
{
cout << "Load game called";
}
void playmultiplayer()
{
cout << "Play multiplayer game called";
}
Prof Indrani Sen,MCA,MPhil COmputer
Science


int main()
{
int input;

cout<<"1. Play game\n";


cout<<"2. Load game\n";
cout<<"3. Play multiplayer\n";
cout<<"4. Exit\n";
cout<<"Selection: ";
cin>> input;
Prof Indrani Sen,MCA,MPhil COmputer
Science

switch ( input ) {
case 1:
// Note the colon, not a semicolon
playgame();

break;
case 2:
// Note the colon, not a semicolon
loadgame();
break;
case 3:
// Note the colon, not a semicolon
playmultiplayer();
break;
case 4:
// Note the colon, not a semicolon
cout<<"Thank you for playing!\n";
break;
default:
// Note the colon, not a semicolon
cout<<"Error, bad input, quitting\n";
break;
}
cin.get();

Prof Indrani Sen,MCA,MPhil COmputer


Science

Functions
In general, functions are blocks of code that

perform a number of pre-defined commands


to accomplish something productive.

Prof Indrani Sen,MCA,MPhil COmputer


Science

Working of function
Functions that a programmer writes will generally

require a prototype.
Just like a blueprint, the prototype tells the compiler
what the function will return, what the function will
be called, as well as what arguments the function
can be passed.
When I say that the function returns a value, I mean
that the function can be used in the same manner
as a variable would be.
For example, a variable can be set equal to a
function that returns a value between zero and four.
Prof Indrani Sen,MCA,MPhil COmputer
Science

The general format for a prototype is

simple:return-type function_name ( arg_type


arg1, ..., arg_type argN );

Prof Indrani Sen,MCA,MPhil COmputer


Science

#include <iostream.h>
int mult ( int x, int y );
int main()
{
int x;
int y;

cout<<"Please input two numbers to be multiplied: ";


cin>> x >> y;

cout<<"The product of your two numbers is "<< mult ( x, y ) <<"\n";


cin.get();
}
int mult ( int x, int y )
{
return x * y;
}

Prof Indrani Sen,MCA,MPhil COmputer


Science

C++ program exercises


The distance between two cities (in km.) is input through the keyboard. Write a program to

convert and print this distance in meters, feet, inches and centimeters.
If the marks obtained by a student in five different subjects are input through the keyboard,
find out the aggregate marks and percentage marks obtained by the student. Assume that
the maximum marks that can be obtained by a student in each subject is 100.
Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a program
to convert this temperature into Centigrade degrees.
The length & breadth of a rectangle and radius of a circle are input through the keyboard.
Write a program to calculate the area & perimeter of the rectangle, and the area &
circumference of the circle.
Two numbers are input through the keyboard into two locations C and D. Write a program to
interchange the contents of C and D.
If a five-digit number is input through the keyboard, write a program to calculate the sum of
its digits. (Hint: Use the modulus operator %)
If a five-digit number is input through the keyboard, write a program to reverse the number.
If a four-digit number is input through the keyboard, write a program to obtain the sum of
the first and last digit of this number.

You might also like