C++ Program Lecture 1
C++ Program Lecture 1
5.Bottom up approach
// 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;
}
Identifiers in C++
Any used defined name given to the program
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
Name
name
name_1
Int
INT
_SUM
Identifier
printf
Int
Pow
Sum$
Num^2
Num 1
2num
Data types
Primitive Built-in Types:
C++ offer the programmer a rich assortment
Type
Keyword
Boolean
bool
Character
char
Integer
int
Floating point
float
double
Valueless
void
Wide character
wchar_t
Type
char
1byte
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
4bytes
4bytes
0 to 4,294,967,295
float
4bytes
double
8bytes
long double
8bytes
#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
Enumerated Types:
An enumerated type declares an optional type
enum enum-name
{ list of names
} var-list;
= blue;
enum gender { male,female} ;
Gender g;
G=male;
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.
#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
Class. :
Class data types in C++ are an encapsulation of data members and
#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;
Varibales
cin>>obj.name;
cin>>obj.number;
getch();
return 0;
}
Structure. :
Structure data types in C++ are a collection
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.
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
Functions. :
Function data types in C++ are discrete
Pointers. :
Pointer data types in C++ are variables that
Constants
Constantsare expressions with a fixed value.
Literal constants can be classified into: integer,
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;
real constant.
#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;
}
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.
can be 1 character.
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
Variations of typedef
statement
Case 1:While declaring the type of variable
;
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.
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
No operator
is assumed to be
present. It
Variations
of arithmetic
Instructions
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);
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_t s =
sizeof(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
Left To
Right
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
Loops
A loop statement allows us to execute a
Loop Type
Description
while loop
for loop
do...while loop
nested loops
For loop
for ( variable initialization; condition; variable
#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
#include <iostream>
int main()
{
int x = 0; // Don't forget to declare variables
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
#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;
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();
Functions
In general, functions are blocks of code that
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
#include <iostream.h>
int mult ( int x, int y );
int main()
{
int x;
int y;
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.