Sie sind auf Seite 1von 67

C++

Programming with C++


Introduction POP Procedure oriented programming With fns. Data insecure, addition of functions and data need whole program to be modified OOP Object oriented programming With classes and objects Inheritance, pointers, data encapsulation, etc

Identifiers and keywords


How to write programming statements in C++ ? Identifiers and keywords Identifiers Formed using combinations of A,B,CZ, 0,1,29, _ e.g., my, cdw, velocity, NO1, N0_1 etc. User defined keywords Reserved identifiers (not user defined) e.g., float, continue, while, class, operator etc.

Constants in C++
String constants e.g., the result is = Rs. 2000.00 My name is

Numeric constants

Integer, short integer, long integer Float, double, long double e.g., 11, 2000, 4 11.2, 2000.234, 322.12

Character constants A, a, Formats

int, float, long int, short int float double, long double
6

C++ operators
For doing mathematical and logical operations operators are needed Arithmetic Assignment +, -, *, /, % (remainder) = (RHS to LHS), +=, -=, *=, /=, %= etc Comparison <, >, <=, >=, ==, != Logical &&, !!, !
7

Simple C++ programs


Header file Declaration of all the variables C++ Statements iostream.h contains s set of small and specific information and functions for handling input and output data Borland C++ - iostream.h, ios.h, iomanip.h Turbo C++ - iostream.h, ios.h, iomanip.h UNIX C++ - stream.h
8

e.g. program # include <iostream.h> header file inclusion Void main (void) main program in the syntax of a fn. { cout << My name is computer; } cout command for displaying on screen open and close { } compound statements ; after each C++ statement
9

Program to display the contents of a variable # include <iostream.h> Void main (void) { int a,b; a and b are integers (without decimal points) a = 300; b = 200; cout << a << b<< endl; } or cout << a << b << \n;

10

Manipulator functions

endl setbase setw setfill setprecision etc

to set new line to set the base of no. (dec, hex, oct ) to set the width of numbers to fill empty spaces with another character to set the no. of decimel points

11

# include <iostream.h> Void main (void) { int value; cout << enter a number << endl; cin >> value; cout << decimal base = <<dec<<value<<endl; cout<<hexadecimal base = <<hex<< value<< endl; cout << octal base = << oct << value << endl; }

12

Example - setwidth
# include <iostream.h> # include <iostream.h> Void main (void) { int a, b; a = 300; b = 200; cout << setw (5) << a << cout << setw (6) << a << cout << setw (7) << a << cout << setw (8) << a << } to use manipulator functions

setw setw setw setw

(5) (6) (7) (8)

<< << << <<

b b b b

<< << << <<

endl; endl; endl; endl;

13

Output
3 0 0 3 0 0 2 0 0 2 0 0

3 0 0
3 0 0

2 0 0
2 0 0

14

Example - setfill
# include <iostream.h> # include <iostream.h> Void main (void) { int a, b; a = 300; b = 200; cout << setfill ( * ); cout << setw (5) << a << cout << setw (6) << a << cout << setw (7) << a << cout << setw (8) << a << } to use manipulator functions

setw setw setw setw

(5) (6) (7) (8)

<< << << <<

b b b b

<< << << <<

endl; endl; endl; endl;

15

* * 3 0 0 * * 2 0 0 * * * * * * * * * 3 0 0 * * * 2 0 0 * * * * * * * * 3 0 0 * * * * 2 0 0 * * * * * * * 3 0 0 * * * * * 2 0 0

16

Control statements
Conditional if, if else, switch case Loop - for, while, do while Breaking control break, continue, goto If syntax

if (expression) { statement1; --------------}


17

if else
if (expression) statement1; else statement2; if (a>b) big = a; else big = b;

18

Switch case
switch (expression) { case 1: statement case 2: statement -------}
19

#include<iostream.h> void main(void) { int day; cout<<"Enter a number between 1&7\n"; cin>>day; switch(day) { case 1: cout<<"MONDAY\n"; break; case 2: cout<<"TUESDAY\n"; break; case 3: cout<<"WEDNESDAY\n"; break; case 4: cout<<"THURSDAY\n"; break; case 5: cout<<"FRIDAY\n"; break; case 6: cout<<"SATURDAY\n"; break; case 7: cout<<"SUNDAY\n"; break; default: cout<<"enter a correct number 1 and 7\n";}}

20

Simple Arithmetic operations #include <iostream.h> #include <iomanip.h> void main () { int a, b, sum, sub, mul, div; cout <<"enter two numbers \n"; cin>>a>>b; sum=a+b; sub=a-b; mul=a*b; div=a/b; cout<<"a="<<a<<"b="<<b<<"sum="<<sum<<endl; cout<<"a="<<a<<"b="<<b<<"sub"<<sub<<endl; cout<<"a="<<a<<"b="<<b<<"mul="<<mul<<endl; cout<<"a="<<a<<"b="<<b<<"div="<<div<<endl; }

21

For loop
Syntax for (expression1; expression2; expression3) statement Or for (initial condition; test condition; incrementer or decrementer) { statement ------------------------------------}

22

e.g. program
#include<iostream.h> #include<iomanip.h> void main(void) { for (int i=0; i<=10; ++i) { cout << I; } }

23

Program to find sum and average using for loop


#include<iostream.h> #include<iomanip.h> void main(void) { int n; cout >> How many numbers ? \n cin >> n; float sum = 0; float a = 0; for (int i=0; i<=n-1; ++i) { cout << enter a number \n; cin >> a; sum = sum + a; } av = sum/n; cout >> sum = << sum <<< endl; cout >> average = << av << endl; }

24

While loop

while (condition) statement; or while (condition) { statement 1; ----------}


25

Program to find first 100 natural numbers # include<iostream.h> void main(void) { int sum, digit; sum = 0; digit = 1; while (digit <= 100) { sum += digit; digit++; } cout<<1+2+3+100="<<sum<<endl; }
26

Do while

Syntax

do { statement 1; statement 1; ---------} while (expression);


27

Sum and average # include<iostream.h> void main(void) { int n, i; float av, a,sum; cout <<"enter the number\n"; cin>> n; i = 0; sum = 0; do { cout <<"enter a number\n"; cin >> a; sum = sum + a; i++; } while ( i<=n-1); av=sum/n; cout <<"sum ="<<sum <<endl; cout<<"average="<<av<<endl; }
28

Break switch (day) { case 1: cout << Monday \n; break; cout << Tues day \n; break:

}
29

Continue

if (value <=0) { cout << Zero or negative value found \n; continue; } i++;

30

Goto

e.g.,

{ start; cout << My name is X \n; go to start; }

31

Function in C++
Syntax: function_type function_name (data_type argument1, data_type argument2..) { return syntax eg. Body of the function return; -----return (54); -----return (x+y); . return (++i); return something return (x+y); }

32

e.g., Function type int, float, char, long int, short int, double Function name Any user given name Data type int, float, char, long int, short int, double Arguments Any user given names Thus e.g.- float stud(int count, float no)
33

Example program to study a function


Function declaration to declare the existence Function calling to call and get values from fn. to main Function definition to specify what is happening inside fn. #include <iostream.h> void main (void) { void display (void); --- Fn. declaration display (); --- Fn. Calling } void display (void) --- Fn. definition { cout<<this is a test program for fn \n; }
34

Program to find the largets of three numbers using function in C++ #include <iostream.h> void main(void) { float max (float a,float b,float d); float x,y,z,maxx; cout<<"enter three numbers\n"; cin>>x>>y>>z; maxx = max(x,y,z); cout<<"largest value is="<<maxx<<endl; } float max (float a,float b,float d) { if (a>b) { if (a>d) return(a); else return(d); } else { if (b>d) return(b); else return(d);}}

35

#include<iostream.h> #include<iomanip.h> void main (void) { for(int i=0;i<=10;++i) { cout << "This is a Test for C++" << endl; } }

36

Arrays
Collection of identical data stored in consecutive memory locations under a common name Four points in specifying arrays 1. Type of Array int, float, char etc 2. Array name - Any used defined name 3. Dimensionality of array, i.e., no. of subscripts 1d, 2d, .. 4. Total number of memory locations in the array e.g., int marks[300], char line [90], float speed [900] 1d int marks [20] [20], char line [3][3], float sp [21][22] 2d

37

Array initialization syntax data_type array_name [expression] = {element1, element2, element3..element n}; e.g., int count [4] = {10, 111, 21, 34} Means count [0] will assume a value of 10 count [1] = 111 count [2] = 21 count [3] = 34

38

#include <iostream.h> int main() { int ar[2][2] = {1,2,3,4}; for (int i=0; i<2; i++) for (int j=0; j<2; j++) { cout << ar[i][j]<< endl; } return 0; }

Here, ar [0][0] ar [0][1] ar [1][0] ar [1][1]

= = = =

1 2 3 4

39

Program to read nos and to find the largest

#include <iostream.h> Void main () { int a[100]; cout << How many nos. in the array? << endl; cin >> n; cout << Enter the elements of array << endl; for (i=0; i<=n-1; ++i) { cin >> a [i]; }
40

cout << contents of array << endl; for (i=0; i<=n-1; ++i) { cout << a [i] << \t; } larg = a[0]; for (i=0; i<=n-1; ++i) { if (larg < a[i] ) larg = a[i]; } cout << largest no is = << larg; }
41

Pointers and address operators in C++


int x, y; ----- normal variables int *x, *y ----- pointer variables - ? which can store the memory address of other variables * pointer operator & address operator

A variable can be declared as a pointer variable in c++ as above. Here x and y are two pointer variables. e.g., int x, y; int *ptr1, *ptr2; ptr1 and ptr2 are declared as pointer variables (can store addresses) ptr1 = & x; ptr2 = & y; Memory Addresses of x and y are put in the pointer variables ptr1 and ptr2
42

Program to display the address and contents of a pointer variable #include <iostream.h> Void main () { int x; int *ptr; x = 10; ptr = &x; cout << value of x = << x << endl; cout << content of ptr = << *ptr << endl; cout << address of ptr = << ptr << endl; }
43

Struture and union


Array in c++ --- collection of homogeneous data (all the data in the array are int or float or char etc. Examples int number [10] all the 10 data are integers float frac [4] all the 4 data are floating points Structure ---- collection of heterogeneous data Syntax: struct name { member1; member2; member3; };
44

Example; 1. struct student { int rollno; int age; int sex; float height; float weight; }

2. struct date { int day; int month; int year; }

45

Assigning values to the members of structure or initialization e.g., program #include <iostream.h> Void main () { struct sample { int x; float y; }; struct sample stud; --- using variable stud, stud.x = 10; members of the structure stud.y = 20.23; can be accessed cout << content of x= << stud.x << endl; cout << content of y= << stud.y << endl;}
46

Struture tag #include <iostream.h> Void main () { struct sample { int x; float y; } stud; structure tag (using tag stud, members of the structure can be accessed) stud.x = 10; stud.y = 20.23; cout << content of x= << stud.x << endl; cout << content of y= << stud.y << endl;}

47

Structure initialization
#include <iostream.h> Void main () { struct sample1 { int rollno; int age; char sex; float height; float weight;}; sample1 stud = {95001, 24, M, 167.9, 56.7}; cout << content of structure \n; cout << Rollno = << stud.rollno << endl; cout << Age = << stud.age << endl; cout << Sex = << stud.sex << endl; cout << Height = << stud.height << endl; cout << Weight = << stud.weight << endl; }
48

Arrays of structure #include <iostream.h> #define max 3 ------- preprocessing command Void main ( ) { struct sample1 { int rollno; int age; char sex; float height; float weight;}; sample1 stud[max] = { {95001, 24, M, 167.9, 56.7}, {95002, 25, F, 156.6, 45.2}, {95003, 24, M, 189.4, 78.7} }; for (int i =0; i<= max-1; ++i) { cout << content of structure \n; cout << Rollno = << stud[i].rollno << endl; cout << Age = << stud[i].age << endl; cout << Sex = << stud[i].sex << endl; cout << Height = << stud[i].height << endl; cout << Weight = << stud[i].weight << endl; }}
49

Classes and objects Class collection of data (called member data of a class) and methods (functions called member functions of a class) operating on the member data The construction of class supports for 1. Data abstraction - methods for collection of data & fn. 2. Data hiding data can be declared as Private, protected and Public private member data can only accessed by member functions and friend functions of the class public member data can be accessed by any function outside the class protected - member data can only accessed by member functions and friend functions of the class and member functions and friend functions of a class derived from the parent class 50

3. Data encapsulation the internal (member data) of a class are first separated from outside world (outside access). Then they are put along with member functions as in a capsule 4. Inheritance Technique used to build hierarchy of classes Classes can be derived from parent classes and the characteristics of the parent class are passed on to the derived classes 5. Polymorphism Different processing steps of a function having same messages (tasks)

51

Class Syntax class user_defined_name { private: data_type member1; data_type member2; implementaions list of friend functions; public: data_type member1; data_type member2; implementaions protected: data_type member1; implementaions } class user_defined_name variable1, variable2, variable3, ..;

52

variable1, variable2, variable3 etc - objects of the class similar to tags. Using objects one can access the member data and member functions of a class example program for class #include <iostream.h> Void main () { class date { public: int day; int month; int year; };
53

class date today; ( today --- object of the class) today.day = 10; today.month = 2; today.year = 2007; cout << todays date is = << today.day << /<< today.month << /<< today.year << endl; }

54

Member data and member functions within the scope of the class #include <iostream.h> class date { private: int day; int month; int year; public: void getdata (void) { cout << enter the date << endl; cin >> day >> month >> year; }; void display (void) { cout << todays date is = << today.day << /<< today.month << /<< today.year << endl; }; } Void main (void) { class date today; today.getdata(); today.diaplay(); }
55

Member data and member functions outside the scope of the class #include <iostream.h> class date { private: int day; int month; int year; public: void getdata ( ); void display ( ); } Void main (void) { class date today; today.getdata(); today.diaplay(); } void date::getdata ( ) { cout << enter the date << endl; cin >> day >> month >> year; }; Void date::Void display ( ) { cout << todays date is = << today.day << /<< today.month << /<< << endl; };

today.year

56

Program to do simple arithmetic operations using class concept #include <iostream.h> class sample { private: int x; int y; public: void getinfo () { cout << enter any two numbers << endl; cin >> x>>y; }
57

void display ( ) { cout << x = << x << endl; cout << y = << y << endl; cout << sum = << sum ( ) << endl; cout << difference = << diff ( ) << endl; cout << multiplication = << mul ( ) << endl; cout << division = << div ( ) << endl; } int sum( ) { return (x+y); }
58

int dif( ) { return (x-y); } int mul( ) { return (x*y); } int div( ) { return (x/y); } };
59

void main ( ) { class sample obj1; obj1.getinfo ( ); obj1.display ( ); obj1.sum ( ); obj1.dif ( ); obj1.mul ( ); obj1.div ( ); }

(or, sample obj1;)

60

Inheritance single inheritance, multiple inheritance Process of deriving new class from the base class(es) Single Process of creating new class from an existing base class
Multiple - Process of creating a new class from more than a base class (two or more classes) The inheritance can be private, public and protected (refer rules in text books)

61

#include <iostream.h> #include <iomanip.h> class basic_info { private: char name [20]; long int rollno; char sex; public: void getdata ( ); void display ( ); };

Inheritance eg program base class

class physical_fit : public basic_info { private: float height; float weight; public: void getdata( ); void display ( ); };

derived class

62

Void basic-info:: getdata ( ) { cout << enter a name \n; cin >> name; cout >> rollno ? \n; cin >> rollno; cout << sex ? \n; cin >> sex; } Void basic-info:: display ( ) { cout << name; cout << rollno; cout <<sex; }
63

Void physical_fit :: getdata ( ) { basic_info::getdata ( ); cout << Height \n; cin >> height; cout >> Weight ? \n; cin >> weight; } Void physical_fit:: display ( ) { basic_info::display ( ); cout << height; cout << weight; }
64

Void main (void) { class physical_fit a; a.getdata ( ); a.dispaly ( ); cout<<endl; }

65

Input output operations


Header file for I/O --- fstream.h both for reading and writing from/to files ifstream ---- to read from a file ofstream ---- to write to a file open ( ) member fn of fstream to open a file close ( ) member fn of fstream to close a file Opening a file e.g; # include <fstream.h> void main ( ) { ofstream infile; infile open(datafile); -----}
66

Storing a text on a file e.g., #include <fstream.h> Void main void ( ) { ofstream outfile; (similar to class and object) outfile.open (text) outfile <<this is a test \n; }

67