Você está na página 1de 69

1

// my first program in C++ #include <iostream.h> int main () { cout << "Hello World!"; return 0; }

Hello World!

// my first program in C++ //

#include <iostream.h> # #include <iostream>

int main ()

()

{}

4
cout << "Hello World";

cout Hello World

return 0; 0

// # cout {}

int main () { cout << " Hello World "; return 0; }

int main () { cout << "Hello World"; return 0; }

// my second program in C++ #include <iostream.h> int main () { cout << "Hello World! "; cout << "I'm a C++ program"; return 0; }

Hello World! I'm a C++ program

5
int main () { cout << "Hello World!"; cout << "I'm a C++ program"; return 0; }

# ;

// line comment /* block comment */ // /* */

/* my second program in C++ with more comments */ #include <iostream.h> int main () { cout << "Hello World! "; // prints Hello World! cout << "I'm a C++ program"; // prints I'm a C++ program return 0; }

Hello World! I'm a C++ program

a = 5; b = 2; a = a + 1; result = a - b;

_ _

asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile, wchar_t, while

and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq

RESULT

result

Result

char int short short long long bool float double long double wchar_t int int

short

long

short int

long int

int a; float mynumber; int float mynumber mynumber a a

int a, b, c;

8
a b int a; int b; int c; char short long signed unsigned int c

unsigned short int NumberOfSisters; signed int MyAccountBalance; signed unsigned

int MyAccountBalance; signed char unsigned char char

signed short

signed char unsigned long short

short int

long

long int

short Year; short int Year; signed unsigned unsigned int signed

int

unsigned NextYear; unsigned int NextYear;

// operating with variables #include <iostream.h> int main () { // declaring variables: int a, b, result; // process: a = 5; b = 2; a = a + 1; result = a - b; // print out the result: cout << result; // terminate the program: return 0; }

a b

result

int

main

10
main main

type identifier = initial_value ;

int a = 0;

() type identifier (initial_value) ;

int a (0);

// initialization of variables #include <iostream.h> int main () { int a=5; int b(2); int result; a = a + 3; result = a - b; cout << result; return 0; }

// initial value = 5 // initial value = 2 // initial value undetermined

11

a = 5; 5

1776 707 -273

" 1776

0 0x 75 0113 0x4b // decimal // octal // hexadecimal

int l 75 75u 75l 75ul // // // // int unsigned int long unsigned long

12

e e 3.14159 6.02e23 1.6e-19 3.0 e // // // // 3.14159 6.02 x 1023 1.6 x 10-19 3.0

double 3.14159L 6.02e23f // long double // float

double l

float

long

e f l

'z' 'p' "Hello world" "How do you do?"

' "

\n \r \t \v \b \f \a \' \" \? \\

' " ? \

13

bool true false

#define #define identifier value

#define PI 3.14159265 #define NEWLINE '\n' PI NEWLINE

// defined constants: calculate circumference #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; cout << r; return 0; }

31.4159 5.0000

#define PI NEWLINE 3.14159 #define ; ; '\n'

const const int pathwidth = 100; const char tabulator = '\t'; const zipcode = 12440; int.

14

a = 5; a =

a = b; a a b b a a b

// assignation operator #include <iostream.h> int main () { int a, b; // a = 10; // b = 4; // a = b; // b = 7; // cout cout cout cout << << << << "a:"; a; " b:"; b;

a:4 b:7

a:?, a:10, a:10, a:4, a:4,

b:? b:? b:4 b:4 b:7

return 0; } a b 4 a = b b 7 a

15

a = 2 + (b = 5);

b = 5; a = 2 + b; 5 b a b 7 a 2

a = b = c = 5; 5 a b c

a = 11 % 3; a 2 2 11 3

value += increase; value a -= 5; a = a a /= b; a = a price *= units + 1; price

= / =

value + increase; 5; b; price * (units + 1);

// compund assignation

16
#include <iostream.h> int main () { int a, b=3; a = b; a+=2; // equivalent to a=a+2 cout << a; return 0; }

++ +=1 c++; c+=1; c=c+1;

--=1

++a ++a

a++

a++

a++

B=3; B=3; A=++B; A=B++; // A contains 4, B contains 4 // A contains 3, B contains 4 B B A B A

17

(7 (5 (3 (6 (5

== 5) > 4) != 2) >= 6) < 5)

// // // // //

evaluates evaluates evaluates evaluates evaluates

to to to to to

false. true. true. true. false.

a=2 b=3

c=6 // // // // = ((b=2) == a) 2 2 b evaluates evaluates evaluates evaluates to to to to false since a is not equal to 5. true since (2*3 >= 6) is true. false since (3+4 > 2*6) is false. true. == == a

(a == 5) (a*b >= c) (b+4 > a*c) ((b=2) == a)

!(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true. !(6 <= 4) // evaluates to true because (6 <= 4) would be false. !true // evaluates to false !false // evaluates to true. && && && a && b ||

|| a || b

18

( (5 == 5) && (3 > 6) ) ( (5 == 5) || (3 > 6) )

// evaluates to false ( true && false ). // evaluates to true ( true || false ).

condition ? result1 : result2 condition result1 result2 7 is not equal to 5. 7 is equal to 5+2. a, since 5 is greater than 3. is greater, a or b.

(7==5) ? 4 : 3 ; // returns 3, since (7==5+2) ? 4 : 3; // returns 4, since (5>3) ? a : b; // returns the value of (a>b) ? a : b // returns whichever // conditional operator #include <iostream.h> int main () { int a,b,c; a=2; b=7; c = (a>b) ? a : b; cout << c; return 0; } a 7 2 b 7 7

a>b b

19

a = (b=3, b+2); 3 5 b b 3 b+2 a a

a = sizeof (char); 1 sizeof a = sizeof (double); 8 a = sizeof (int); 4 int will take 4 bytes in memory. it prints 2 double will take 8 bytes in memory. char

a = sizeof (short); cout<< a; //

20
// Here is an exercize for using of different operators #include <conio.h> #include <iostream.h> #include <iomanip.h> int main() { cout << 10+6<<endl; // 16 will be displayed cout << 10-2<<endl; // 8 will be displayed cout << 6*10<<endl; // 60 will be displayed cout << 10/6<<endl; // 1 will be displayed cout << 10/4.0<<endl; // 2.5 will be displayed cout << 10 % 6<<endl; // 4 will be displayed cout << 10 % 5<<endl; // 0 will be displayed cout << 10 % -4<<endl; // 2 will be displayed cout << -10 % -4<<endl; // -2 will be displayed cout << -10 % 4<<endl; // -2 will be displayed cout << (10 == 4)<<endl; // 0 will be displayed cout << (10 > 4)<<endl; // 1 will be displayed cout << (10 == 4 && 5 < 13 )<<endl; // 0 displayed cout << (10 > 4 && 5 < 13 )<<endl; // 1 displayed cout << (10 < 4 || 5 > 13 )<<endl; // 0 displayed cout << (10 > 4 || 5 > 13 )<<endl; // 1 displayed cout << (10 > 4 || 5 < 13 )<<endl; // 1 displayed int n=44; cout<< n<<endl; // prints 44 n+=9; cout<< n<<endl; // prints 53 n-=5; cout<< n<<endl; // prints 48 n*=2; cout<< n<<endl; // prints 96 n%=10; cout<< n<<endl; // prints 6 float x = 24.0; cout << x << endl; // displays 24 cout << setiosflags(ios::showpoint); cout << x << end1; // displays 24.0000 x = 24.5678; cout << setiosflags(ios::showpos) ; cout << x << end1; // displays +24.5678 cout << setprecision(2)<< x <<endl; //display +24.56 cout << sizeof(int); // display 4 cout << sizeof(short); // display 2 cout << sizeof(double); // display 8 cout << sizeof(char); // display 1 return 0; }

21

iostream

cout cout <<

cout << "Output sentence"; // prints Output sentence on screen cout << 120; // prints number 120 on screen cout << x; // prints the content of x on screen << Output sentence cout " 120 x "

cout << "Hello"; cout << Hello; <<

// prints Hello // prints the content of Hello variable

cout << "Hello, " << "I am " << "a C++ statement"; Hello, I am a C++ statement <<

cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode; age 24 zipcode 90064

Hello, I am 24 years old and my zipcode is 90064

22
cout

cout << "This is a sentence."; cout << "This is another sentence.";

This is a sentence.This is another sentence. cout cout \n cout << "First sentence.\n "; cout << "Second sentence.\nThird sentence.";

First sentence. Second sentence. Third sentence. endl cout << "First sentence." << endl; cout << "Second sentence." << endl;

First sentence. Second sentence. endl \n '\n' cout endl

>> int age; cin >> age;

cin

int

age

cin

cin cin

RETURN RETURN

23
cin

// i/o example #include <iostream.h> int main () { int i; cout<<"Enter an integer value: "; cin >> i; cout<<"Value you entered is " << i; cout<<"\n its double is " << i*2 <<".\n"; return 0; }

Enter an integer value: 7 Value you entered is 7 its double is 14.

cin cin stringstream

cin >> a >> b;

cin >> a; cin >> b; a b

// program to get length and width // of a rectangle and calculate // its area #include <iostream.h> int main () { float length, width, area; cout << "Enter Length: "; cin >> length; cout << "Enter width: "; area = length * width; cout << "Area : " << area<< endl; return 0; }

Enter length: 12.3 Enter width: 7.5 Area : 92.2500

24

{ } { statement1; statement2; statement3; }

{} {}

if if (condition) statement; condition statement statement

x is 100 100 if (x == 100) cout << "x is 100";

{ } if (x == 100) { p++; cout << "x is "; cout << x; cout << "welcome"; } else if if (condition) statement1 else statement2

25
if (x == 100) cout << "x is 100"; else cout << "x is not 100"; x is 100 is not 100 if & else x if (x > 0) cout << "x else if (x < cout << "x else cout << "x x 100 x

is positive"; 0) is negative"; is 0";

#include<iostream.h> #include<conio.h> int main (void) // program to test nested if statement { int score; cout<< "Enter the test score: "; cin >> score; if(score > 100) cout<< " Error: Score is out of range. "<<endl; else if(score >= 90) cout<< "You got grade \'A\' "<<endl; else if(score >= 80) cout<< "You got grade \'B\' "<<endl; else if(score > 70) cout<< "You got grade \'C\' "<<endl; else if(score > 60) cout<< "You got grade \'D\' "<<endl; else if(score >= 0) cout<< "You got grade \'F\' "<<endl; else cout<< " Error: Score is out of range. "<<endl; return 0; } { }

while (expression) statement;

// custom countdown using while #include <iostream.h>

Enter the starting number > 8


8, 7, 6, 5, 4, 3, 2, 1, Go ...!

26
int main () { int n; cout << "Enter the starting number > "; cin >> n; // 8 while (n>0) { cout << n << ", "; --n; } cout << "Go...!"; return 0; } while n>0 n>0 n

n n>0

cout << n << ", "; --n; n

--n; n n 0 n>0

do {statement(s)} while (condition); condition statement condition 0

27
// number echoer #include <iostream.h> int main () { unsigned long n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "\n"; } while (n != 0); return 0; }
Enter number You entered: Enter number You entered: Enter number You entered: (0 to end): 12345 12345 (0 to end): 160277 160277 (0 to end): 0 0

for (initialization; condition; increase/decreese) statement; statement for condition initialization

increase

initialization condition statement increase statement { }

// countdown using a for loop #include <iostream.h> int main () { int n; for (n=10; n>0; n--) { cout << n << ", "; } cout << "\nGo . . .!"; return 0;}} initialization, condition

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, Go . . .!

increase for (;n<10;) for (;n<10;n++)

28
for , initialization ,

for ( n=0, i=100 ; n!=i ; n++, i-- ) { // whatever here... } n i

n i i 50

100

n!=i

n n

break

// break loop example #include <iostream.h> int main () { int n; for (n=10; n>0; n--) { cout << n << ", "; if (n==5) { cout << "countdown aborted!"; break; } } return 0; }

10, 9, 8, 7, 6, 5, countdown aborted!

continue

29
// continue loop example #include <iostream.h> int main () { for (int n=10; n>0; n--) { if (n==7 || n==5|| n==2) continue; cout << n << ", "; } cout << "Go!"; return 0; } 10, 9, 8, 6, 4, 3, 1, Go!

exit exit Exit ( 0 ); 0

stdlib.h> and also in <process.h>

if else if switch (expression) { case constant1: group of statements 1; break; case constant2: group of statements 2; break; . . . default: default group of statements } expression group of statements 1 switch constant1 group of statements 2 switch expression case default: constant1 break

break

constant2

30

switch (x) { if (x == 1) { case 1: cout << "x is 1"; cout << "x is 1"; } break; else if (x == 2) { case 2: cout << "x is 2"; cout << "x is 2"; } break; else { default: cout << "value of x unknown"; cout << "value of x unknown"; } } switch break switch break switch break { } break

switch

switch (x) { case 1: case 2: case 3: cout << "x is 1, 2 or 3"; break; default: cout << "x is not 1, 2 nor 3"; }

case n:

case (1..3):

#include <iostream.h> int main () { int choice; // variable for user input int i; // variable for loops and output do // loop until a valid choice is entered { cout << \n\n\n\n\n; cout << which series do you wish to display?\n; cout << 1- Odd numbers from 1 to 30\n; cout << 2 Even numbers from 1 to 30\n; cout << 3 All numbers from 1 to 30\n; cin >> choice; // get choice from user if(choice < 1 || choice > 3) cout << \n\nChoice must be 1, 2, or 3\n; }while (choice < 1 )|| choice > 3); switch (choice) { case 1: for (i = 1; i <= 30; i+=2) cout << i << , ; cout << end1;

31
case 2: break; for (I = 2; i <= 30; i+=2) cout << i << , ; cout << end1; break; for (i = 1; i <= 30; i++) cout << i << , ; cout << end1; break;

case 3:

} return 0; }

# include <iostream.h> int main( ) { int d; cout << put a day number, assume 1 for Saturday : ; cin>> d; switch(d) { case 1: cout << Saturday \n; break; case 2: cout<< Sunday \n; break; case 3: cout << Monday \n; break; case 4: cout<< Tuesday \n; break; case 5: cout<< Wednesday\; break; case 6: cout << Thursday \n; break; case 7: cout << Friday \n; break; default: cout<< Wrong day number\n; } return 0; }

#include <iostream.h> int main( ) { char grade; cout << Put your letter grade: ; cin >> grade; switch (grade) //grade is of type char { case A : case B : cout<<Good work!<<endl; break; case C : cout<<Average work<<endl; break; case D : case F : cout<<Poor work<<endl; break; default : cout<<grade<< not a valid letter grade.; break; } }

32
type name ( parameter1, parameter2, ...) { statement }

type name parameters int x

statements

{ }

// function example #include <iostream.h>


int addition(int, int); //functioin prototyping / declaration

The result is 8

int main () { int z; z = addition (5,3); // function cout << "The result is " << z; return 0; }

call

int addition (int a, int b) // function definition { int r; r=a+b; return (r); }

main main addition z int

main 5 3 int a main 5 int b main 3

addition

addition int b

int a

33
addition r 8 int r a b a b 5 r=a+b 3

return (r); addition main addition r return (r); return addition 8

addition (5, 3) addition (5,3)

8 8

Cout << "The result is " << z;

a b

main z

addition addition

main

34

// function example #include <iostream.h> int subtraction (int a, int b) { int r; r=a-b; return (r); } int main () { int x=5, y=3, z; z = subtraction (7,2); cout << "The first result is " << z << '\n';
cout << "The second result is " << subtraction (7,2) << '\n'; cout << "The third result is " << subtraction (x,y) << '\n';

The The The The

first result is 5 second result is 5 third result is 2 fourth result is 6

z= 4 + subtraction (x,y); cout << "The fourth result is " << z << '\n'; return 0; } subtraction

main subtraction

35
z = subtraction (7,2); cout << "The first result is " << z; 5 z = 5; cout << "The first result is " << z;

Cout << "The second result is " << subtraction (7,2); subtraction cout Cout << "The second result is " << 5; 5 subtraction (7,2)

Cout << "The third result is " << subtraction (x,y); subtraction subtraction y 5 3 2

z = 4 + subtraction (x,y);

z = subtraction (x,y) + 4; ;

z = 4 + 2; z = 2 + 4;

type name ( argument1, argument2 ...) statement type

36
void

// void function example #include <iostream.h> void printmessage (); int main () { printmessage (); return 0; } void printmessage () { cout << "I'm a function!"; }

I'm a function!

void printmessage void printmessage (void) { cout << "I'm a function!"; } void

printmessage printmessage ();

Printmessage ;

37
// here its another example program #include <iostream.h> #include <process.h> void void void int { ODD_Numbers ( void); EVEN_Numbers ( void); ALL_Numbers ( void); main () int choice; for void functions

//

variable for user input

while(1) // loop until a valid choice is entered { cout << \n\n\n\n\n; cout << which series do you wish to display?\n; cout << 1- Odd numbers from 1 to 30\n; cout << 2 Even numbers from 1 to 30\n; cout << 3 All numbers from 1 to 30\n; cout << 4- Stop program \n; cout<< \n\n your choice: ; cin >> choice; // get choice from user switch (choice) { case 1: ODD_Numbers ( ); // function call break; case 2: EVEN_Numbers ( ); break;

case 3: ALL_Numbers ( ); break; case 4: exit(0); default: cout<<\n\n\n } // end of switch } // end of loop return 0; end of main() function Invalid Choice\n;

//

void ODD_Numbers ( void) { int i; for (i = 1; i <= 30; i+=2) cout << end1; }

cout

<<

<<

void EVEN_Numbers ( void) { int i; for (i = 2; i <= 30; i+=2) { cout cout << end1; } void ALL_Numbers ( void) { int i; for (i = 1; i <= 30; i++) cout cout << end1; }

<<

<<

;}

<<

<<

38

// function call by values #include <iostream.h> int AA (int , int ); int main () { int x=5, y =3; cout<<\n\n value before call x=<<x<<\ty= <<y<<endl; cout<<\ total = <<AA(x,y)<<endl; cout<<\n\n value after call x=<<x<<\ty= <<y<<endl; return 0; } // function definition int AA(int x, int y) // { int r; r=x+y; x=x+3; y =y+2; return r; }

function header

OUTPUT
Value before Total = 8 Value after call x= 5 y= 3

call

x= 5

y= 3

39
// function call by Refernce #include <iostream.h> int AA (int &, int &); int main () { int x=5, y =3; cout<<\n\n value before call x=<<x<<\ty= <<y<<endl; cout<<\ total = <<AA(x,y)<<endl; cout<<\n\n value after call x=<<x<<\ty= <<y<<endl; return 0; } // function definition int AA(int &x1, int &y1) { int r; r = x1 + y1; x1 = x1 + 3; y1 = y1 + 2; return r; }

//

function header

OUTPUT
Value before Total = 8 Value after call x= 5 y= 3

call

x= 8

y= 5

40

int int int billy

int 0 4 0

type type

name

[SIZE]; int float [] billy name

int billy [5]; SIZE []

{ } int billy [5] = { 16, 2, 77, 40, 12071 };

41
{ } [ ] { } billy

[ ] { } int billy [] = { 16, 2, 77, 40, 12071 }; billy

name[index] billy int

75 billy[2] = 75;

billy

billy a = billy[2]; billy[2] billy billy[1] billy[2] billy[2] billy int

billy[0] billy[4]

[ ] [ ] int billy[5]; billy[2] = 75; // declaration of a new Array // access to an element of the Array.

42
// arrays example #include <iostream.h> // if SIZE is not given then SIZE depends on // number of values. In following example, SIZE=5 int billy [] = {6, 2, 7, 4, 10}; int n, result=0; int main () { for ( n=0 ; n<5 ; n++ ) { result += billy[n]; } cout << result; return 0; } 29

billy[0] = a; billy[a] = 75; b = billy [a+2]; billy[billy[a]] = billy[2] + 5;

B u b b le S o r t
Pass = 1 2 1 5 7 4 3 1 2 5 7 4 3 Pass = 2 1 2 5 4 3 7 1 2 5 4 3 7 1 2 5 4 3 7 1 2 4 5 3 7 1 2 4 3 5 7 Pass = 3 1 2 4 3 5 7 1 2 4 3 5 7 1 2 4 3 5 7 1 2 3 4 5 7 Pass=4 1 2 3 4 5 7 1 2 3 4 5 7 1 2 3 4 5 7

1 2 5 7 4 3 1 2 5 7 4 3 1 2 5 4 7 3 1 2 5 4 3 7

U n d e r lin e d p a ir s s h o w th e c o m p a r is o n s . F o r e a c h p a s s th e r e a r e s iz e - 1 c o m p a r is o n s . To ta l n u m b e r o f c o m p a r is o n s = ( s iz e - 1 ) 2

43
/* This program sorts the array elements in the ascending order using bubble sort method */ #include <stdio.h> #define SIZE 6 void BubbleSort(int [ ], int); int main() { int a[SIZE]= {77,42,35,12,101,6};// array initilization int i; cout<< The elements of the array before sorting\n; for (i=0; i<= SIZE-1; i++) cout << a[i] << , ; BubbleSort(a, SIZE); // calling function cout<< \n\nThe elements of the array after sorting <<endl; for (i=0; i<= SIZE-1; i++) cout << a[i] << , ; return 0; } void BubbleSort(int A[ ], int N) { int i, pass, hold; for (pass=1; pass<= N-1; pass++) { for (i=0; i<= SIZE-pass; i++) { if(A[i] >A[i+1]) { hold =A[i]; A[i]=A[i+1]; A[i+1]=hold; } } } }

44

private public

protected

private protected public

45

class Rectangle { private: int length; int width; int area;

// class definition

//

Private Data members of the class

public: // Public functions/methods of the class void set_values (int a, int b) { length = a; width = b; } int area () { area = length * width; return area; } }; int main () { Rectangle rect; // rect is an object of Rectangle class rect.set_values (3,4); // calling the function cout << "area: " << rect.area();// [.] dot is called member operatior return 0; }

46
recta area: 12 rectb area: 30 rectc area: 27

// example: one class, two objects #include <iostream.h> class Rectangle { Privat: int length, width, area; public: int t; void set_values (int, int); // prototyping int C_area () { area= length * width; return area; } }; void Rectangle::set_values (int a, int b) { length = a; width = b; } int main () { Rectangle recta, rectb, rectc; recta.set_values (3,4); rectb.set_values (5,6); rectc.set_values (9, 3); cout << "recta area: " << recta.C_area() << endl; cout << "rectb area: " << rectb.C_area() << endl; cout << "rectc area: " << rectc.C_area() << endl; recta.t=25; // you can access t because it is public rectb.t=12; // you can access t because it is public rectc.t= recta.t + rectb.t; // t is public cout<<recta.t<<\t<<rectb.t<<\t<<rectc.t<<endl; return 0; }

recta length 3 width 4 area 12 t 25 rectb Length 5 Width 6 Area 30 t 12 rectc length 9 width 3 area 27 t 37

Output: recta area: 12 Rectb area: 30 Rectc area: 27 25 12 37

47
// Program to accept and display employee information #include <iostream.h> class emp // class definition { private : // private data, functions int eno; char name[10]; float sal; public : // public data, functions void getdata(); void putdata(); }; void emp::getdata() // function defined outside of class using :: operator { cout<<Enter Employee No: ; cin >> eno; cout<< Enter Employee Name: ; cin >> name; cout<< Enter Salary: ; cin >> sal; } void emp::putdata() // function defined outside of class using :: operator { cout << eno << name << sal; } int main() { emp e; e.getdata(); e.putdata(); return 0; }

48

#include <iostream.h> class ABC { private: // Access Specifier int size; int a; int b; int c; public: // Access Specifier constructor

ABC () // { size=50; }

void get_values ( ) { cout<< put value for a, cin>>a>>b; }

b: ;

int sum () { c = a + b + size; cout<< \n Total of a, b and size = << c<<endl; return c; } void display( ) { cout<< \n I like c++ very much\n; Cout<< I am student of computer science.\n; } int JJJ( ) { cout<< \n C++ is an intresting language\n; return(3+5); } }; int main () { ABC M; // create an object and at this moment constructor // will aoutomatically executes. M.display(); cout<<M.JJJ(); M.get_values(); // calling the function M.sum(); return 0; }

49

Another example of constructor


#include <iostream.h> class XYZ { public: // Access Specifier

XYZ () // constructor method { cout<< Hello Student\; } void jjjj() { cout<< I am student of computer science.\n;} };

int main () { XYZ M, K ; // creating two objects M.jjjj(); XYZ P; // creating an other object Return; }

OUTPUT
Hello Student Hello Student I am student of computer science. Hello Student

#include <iostream.h> class XYZ { public: // Access Specifier

XYZ () // constructor method { cout<< "Hello Student\n"; } void jjjj() { cout<< "I am student of computer science.\n";} ~XYZ () { }; // Destructor definition cout << "\n This is destructor \n"; }

50
int main () { XYZ M; // creating object and constructor will run M.jjjj(); { cout<<"\n Inner Block \n"; XYZ P; // creating an other object, start scope of P } // This is the end scope of P, here destructor for P will execute cout<< "\nOut of inner scope\n"; return 0; } // end scope of objects M

OUTPUT
Hello Student Student of computer. Inner Block Hello Student This is destructor Out of inner scope This is destructor

#include <iostream.h> int sum (int, int); int sum (int, int, double sum (double,

int); double,

int);

int main( ) { cout<< \n Sum of three integers are = << sum( 2, 4, 3)<< endl; cout<< \n Sum of two double and one int values = << sum(12.5, 5.3,2)<<endl; cout<< \n sum of two integer values = << sum(4, 7)<<endl; return 0; } int sum( int x, int y, int z ) { return ( x + y + z ); } int sum( int x, int y) { return ( x + y ); } double sum ( double x, double y, int z ) { return ( x + y

) ; }

51
#include <iostream.h> void display ( ); // prototyping of function void display(char); // prototyping of function void display(char, int); // prototyping of function int main() { display ( ); display (=); display (+, 30); return 0; } // Following void display { for (int cout << } // Following void display { for (int cout << } // Following void display { for (int Cout << } overloaded prints 45 * ( ) j=1 ; j <= 45 ; j++) cout << *; endl;

function prints specified character (char ch ) j=1 ; j <= 45 ; j++) cout << ch; endl;

45

Times

function prints specified character specified times (char ch, int n ) j=1 ; j <= n ; j++) cout << ch; endl;

#include <iostream.h> class Func_Overloaded { public: // Following overloaded prints 45 * void display ( ) { for (int j=1 ; j <= 45 ; j++) cout << endl; } // Following function prints specified void display (char ch ) { for (int j=1 ; j <= 45 ; j++) cout << endl; } // Following function prints specified void display (char ch, int n ) { for (int j=1 ; j <= n ; j++) cout << endl; } }; // end of class int main() { Func_Overloaded obj; // obj.display ( ); obj.display (=); obj.display (+, 30); return 0; }

cout << *;

character

45

Times

cout << ch;

character specified times cout << ch;

Object Created.

52 OUTPUT OF THE ABOVE PROGRAM


********************************************* ============================================= ++++++++++++++++++++++++++++++

#include <iostream.h> class sum { public: sum (int l, int m, int n) { cout<< Sum of three integers is = <<(l + m + n) << endl; } sum (int l, int m) { cout<< Sum of two integers is = <<(l + m) << endl; } }; // end of class

int main() { sum X(6, 2); sum Y(3, 7, 4); return 0; }

#include <iostream.h> class FindBig { private: int mx; public: FindBig (int x, int y, int z) { if ( x > y && x > z) mx = x; else if ( y > z ) mx = y; else mx = z; cout<< Biggest among three values is = << mx<<endl; } FindBig (int x, int y) { if ( x > y ) mx = x; else mx = y; cout<< Biggest between two values is = << mx<<endl; } }; // end of class

53
int main() { int a=5, b=3, c=21; FindBig AA(6, 2); FindBig BB(a, b, c); return 0; }

OUTPUT OF THE ABOVE PROGRAM


Biggest between two values is = 6 Biggest between three values is = 21

54

55

56

57

Pointers
Pointers are a fundamental part of C. If you cannot use pointers properly then you have basically lost all the power and flexibility that C allows. The secret to C is in its use of pointers. C uses pointers a lot. Why?: It is the only way to express some computations. It produces compact and efficient code. It provides a very powerful tool. C uses pointers explicitly with: Arrays, Structures, Functions. NOTE: Pointers are perhaps the most difficult part of C to understand. C's implementation is slightly different from other languages.

What is a Pointer?
A pointer is a variable which contains the address in memory of another variable. We can have a pointer to any variable type. The operator & gives the address of a variable. The indirection or dereference operator * gives the contents of an object pointed to by a pointer. To declare a pointer to a variable do:
int *p;

NOTE: We must associate a pointer to a particular type: You can't assign the address of a short int to a long int, for instance.

58 Consider the effect of the following code:


int x = 1, y = 2; int *ip; ip = &x; y = *ip; x = 5; *ip = 3;

It is worth considering what is going on at the machine level in memory to fully understand how pointer work. Consider following Fig. Assume for the sake of this discussion that variable x resides at memory location 100, y at 200 and ip at 1000. Note A pointer is a variable and thus its values need to be stored somewhere. It is the nature of the pointers value that is new.

Now the assignments x = 1 and y = 2 obviously load these values into the variables. ip is declared to be a pointer to an integer and is assigned to the address of x (&x). So ip gets loaded with the value 100 which is the address of x. Next y gets assigned to the contents of ip. In this example ip currently points to memory location 100 -- the location of x. So y gets assigned to the values of x -- which is 1. After that assignment of 5 to variable x. Finally we can assign a value 3 to the contents of a pointer (*ip).

59
IMPORTANT: When a pointer is declared it does not point anywhere. You must set it to point somewhere before you use it. So ... int *ip; *ip = 50; will generate an error (program crash!!). The correct use is: int *ip; int x; ip = &x; // setting the pointer *ip = 100; Here is another example program which will describes the usage of pointers and the contents of pointers. #include <stdio.h> int main ( ) { int a=3, b=5, S=0, D=0, M=0; int *p1, *p2, *p3, *p4, *p5; // five pointers are declared // assigning address of a, b, S, D and M to these pointers p1 = &a; p2= &b; p3 = &S; p4 = &D; p5=&M; *p3 = *p1 + *p2; // same as s = a + b; printf(%d, *p3); // it prints 8 printf(%p , p1); // it prints the address of a D = *p1 - b; // it calculates -2 printf(\n %d, *p4); // it prints -2 *p5 = a * *p2; // it calculates 15 printf(\n %d , M); // it prints 15 }

Pointers and Arrays

int a[12]= { 5, 2 , 6, 9, 12,

7, 56, 34,

11,

76,

37, 55,69};

a[0]

a[1]

a[2]

a[3]

. . . . . .

. .

a[11]

Following is the c-language code which prints contents of all elements using pointers.

60
#include <stdio.h> int main( ) { int a[12]= { 5, 2 , 6, 9, 12, int i, *p;

7, 56, 34,

11,

76,

37, 55,69};

// printing array elements using index / subscript for ( i = 0 ; i < 12 ; i++) printf (%d,

, a[i]);

// Following will store the address of a[0] into p (pointer) p = a; // same as p = a[0]; for ( i = 0 ; i < 12 ; i++) {printf (%d, , *p); // prints the contents of the address p++; // it shift the pointer to next element of the array } return 0;

}
WARNING: There is no bound checking of arrays and pointers so you can easily go beyond array memory and overwrite other things. C however is much more fine in its link between arrays and pointers. For example we can just type p = a; // here p is pointer and a is an array. instead of p = &a[0]; A pointer is a variable. We can do p = a and p++. An Array is not a variable. So a = p and a++ ARE ILLEGAL. This stuff is very important. Make sure you understand it. We will see a lot more of this.

Pointer and Functions


Let us now examine the close relationship between pointers and C's other major parts. We will start with functions. When C passes arguments to functions it passes them by value. There are many cases when we may want to alter a passed argument in the function and receive the new value back once to function has finished. C uses pointers explicitly to do this. The best way to study this is to look at an example where we must be able to receive changed parameters. Let us try and write a function to swap variables around? Pointers provide the solution: Pass the address of the variables to the functions and access address in function. Thus our function call in our program would look like this:
swap(&x, &y);

The Code to swap is fairly straightforward:

61
// This program swap / interchange the values of two variables #include <stdio.h> void swap( int *, int *); // function prototyping int main( ) { int a, b; a = 1; b = 999; cout<< a = << a << and b= <<b<<endl; swap( &a, &b); cout<< \n After Swaping the new values of a and b \n; cout<< a = << a << and b= <<b<<endl; return 0; } void swap(int *px, int *py) { int temp; /* contents of pointer */ temp = *px; *px = *py; *py = temp; } The explanation of the above program is given on the next page:

62

63

o o

o o

#include <iostream.h> class y; class z; class x { private: int m; public: x( ) { m=100; } friend int abc(x, y, z); // friend function declaration }; // end of x class class y { private: int n; public: y( ) { n=10; } friend int abc(x, y, z); // friend function declaration }; class z { private: int t; public: z( ) { t=20; } friend int abc(x, y, z); // friend function declaration }; // end of z class int abc (x s1, y s2, z s3) { return (s1.m + s2.n + s3.t); } int main( ) { x a; // object of class x y b; z c; cout<< sum of these numbers = << abc(a, b, c); return 0; }

64 In the above program, the function abc is a friend function. The a, b, c are the objects of classes x, y, z respectively. These objects are passed to the friend function abc to calculate the sum of the private data members m, n, and t of classes x, y and z respectively. The initial values in m, n and t are initialized automatically by the constructor of the classes.

//

#include <iostream.h> class second; class first { int a; public: first(int temp) { a = temp; } friend void max(first, second); }; class second { int b; public: second(int temp) { b = temp; } friend void max(first, second); }; void max(first f, second s) { if ( f.a > s.b ) // both first, second data members can be cout << Max << f.a; // accessed thru friend max function else cout << Max << s.b; } int main() { first f(20); max(f, s); } second s(30); return 0;

65

66

67
/* program to accept and display a student record #include <iostream.h> */

class add { private : char str[20]; char city[20]; int pin; public : void get_add() { cout << "Enter Address street,city,pin"; cin >> street >>city>>pin; } void put_data() { cout << "Address is "<< str <<endl<<city <<endl<<pin; } }; class stud : public add { private : int sno; char name[20]; int m1,m2,m3; public : void get_data() { cout << "Enter Student No. "; cin >> sno; cout << "Enter Student Name "; cin >> name; cout << "Enter Student 3subjects marks "; cin >> m1 << m2 << m3; } void put_data() { cout << "Student number :" << sno; cout << "Student name :" << name; cout << "Student marks :" << m1 << " " <<m2<<" }

"<<m3;

}; int main() { stud s; s.get_add(); s.get_data(); s.put_add(); s.put_data(); return 0; }

68

69

Você também pode gostar