C++

//Content under construction, as I’m migrating the data from my old website 🙂

Table of Contents
1. C Programming Basics
Basics
Comments
Variables [Integers – Short – Long — Char — Floating Point – double – long double — Boolean — unsigned data types — Type Conversion]
Casts
Output/Input
Arithmetic Operators
2. Loops & Decisions
Logical operators
Loops [For loop — While loop — Do loop]
Decisions [If — Switch]
Conditional operator — Logical Operator
Other Control Statements
3. Structures
Structures
Enumerations
4. Functions
No arguments
Passing constants as arguments
Passing variables
Overloaded functions
Inline functions
Default arguments
Variables and Storage Classes
Automatic
External
Static
Returning by reference
Const function arguments
5. Objects & Classes
C++ Objects as data types
Constructors
Destructors
Objects as function arguments
The default copy constructor
Returning objects from functions
Card game example
Structures and classes
Static class data – object, classes and memory
const and classes
const objects
6. Arrays & Strings
Arrays Fundamentals
Multidimensional arrays
Arrays as function arguments
Arrays of structures
Arrays as class member data
Arrays of objects
Arrays of cards
C-strings
7. Operator Overloading
8. Inheritance
9. Pointers
10. Virtual Functions
11. Streams & Files
12. Multi-file programs
13. Templates & Exceptions
14. Standard Template Library
15. Object-Oriented Design
Appendix: Necessary Notes
Header files needed for some library functions

 

1. C Programming Basics

 

Basics

#include <iostream>

 

using namespace std;

 

int main()

{

cout << “Hello world!” << endl;

return 0;

}

 

 

 

Comments

 

#include <iostream>

 

using namespace std;

 

int main()

{

cout << “Hello world!” << endl; //that’s a comment

return 0;

/*

and this is a multi-line

comment*/

}

 

 

 

 

Variables

 

Integers – Short – Long

 

#include <iostream>

using namespace std;

int main()

{

int x; //defining variable x as integer; check the size and limits of this variable type based on your OS, variable name is called identifier and it can be letters, numbers or _ and must start with letter or _ and can’t be any of keywords; it’s case sensitive!

int y; //this is called declaration and definition in the same time as it sets space for the variable in the memory; note that declaration need not be in the beginning of the program

short l; //that’s a different integer type, with fixed size and range

long p; //that’s a different integer type, with fixed size and range

x=20; //assigning 20 to x; it’s called assignment statement

y=x+10; //note that we must terminate with a semicolon; here x and 10 are considered integer constants

cout << “y=” ;

cout<<y<<endl;

return 0;

}

 

Char

 

#include <iostream>

using namespace std;

int main()

{

char a= ‘A’; //that’s called “initialization” as give a value with declaring it as a character variable (type of size 1 byte, can store characters as ASCII number)

char b=’\t’; // here \t is an escape sequence for tab; a: beep, b:backspace, f:formfeed, n:newline, r:return, \,’,””:as they are, xdd:hexadecimal notation

cout << a ;

cout<<b;

a=’\f’;

cout<<a;

cout<<‘\n’;

return 0;

}

 

Floating Point – double – long double

 

#include <iostream>

using namespace std;

int main()

{

float rad=5; //defining variable of type float (other types include long and double)

const float PI=3.14159F; //that’s a constant qualifier; makes sure PI doesnt change; note the F to make sure it’s float (compare to #define directive as #define PI 3.14)

float area = PI * rad * rad;

cout << “Area = ” <<area<<endl;

return 0;

}

 

 

Bool

 

Covered later

 

unsigned data types

 

#include <iostream>

using namespace std;

 

int main()

{

int signedVar = 1500000000; //that’s our regular signed integer variable (can have a sign + or -)

unsigned int unsignVar=1500000000; //now that’s unsigned variable, it has larger range

signedVar=(signedVar*2)/3; //this calculation exceeds the range for signed variable

unsignVar=(unsignVar*2)/3; //this, however is still in the range

cout<<signedVar<<”   “<<unsignVar<<endl; //that’s why signedVar is wrong and unsignVar is correct

return 0;

}

 

-431655765   1000000000

 

Process returned 0 (0x0)   execution time : 0.080 s

Press any key to continue.

 

Type Conversion

 

#include <iostream>

 

using namespace std;

 

int main()

{

int s=7;

float p=12.5F;

double t=s*p; //even though s and p are different variable types, C do it with no problem, other languages don’t permit it while it happens here automatically; the compiler changes the s type to float and then p to double (it goes from lowest to highest: char – short – int – long – float – double – double long

cout<<“T = 7*12.5 =  “<<t<<endl;

return 0;

}

 

 

T = 7*12.5 =  87.5

 

Process returned 0 (0x0)   execution time : 0.080 s

Press any key to continue.

 

Casts

 

#include <iostream>

 

using namespace std;

 

int main()

{

int x = 1500000000;

x=(x*10)/10; //doing the multiplication step will bring a number beyond range of integer variable type

cout<<“X = “<<x<<endl; //wrong answer of course

x=1500000000;

x=(static_cast<double>(x)*10)/10; //cast is used to manually convert a variable type, it has different kinds, here we use static cast; you use it in this form static_cast<VariableTypeYouWantToConvertTo>(VariableNameToBeConverted), y=static_cast<double>(x)

cout<<“X = “<<x<<endl; //correct answer; note that casting created a temporary variable that stored that big value

return 0;

}

 

X = 211509811

X = 1500000000

 

Process returned 0 (0x0)   execution time : 0.080 s

Press any key to continue.

Output/Input

 

#include <iostream>

using namespace std;

int main()

{

int ftemp;

cout<<“Welcome to Fahrenheit to Celsius program”<<endl<<“Please enter temperature in F\n”; //cout outputs stream to screen, here it outputs such a string constant and has the endl manipulator to make a new line or \n escape sequence to have a new line

cin>>ftemp; //store the input to the variable ftemp

int ctemp=(ftemp-32)*5/9; //calculating temperature in C

cout << “Temperature in C = ” <<ctemp<<endl; //cout can differentiate between a string constant and a variable, notice the insertion operator, <<, is cascaded here, >> can be cascaded too for cin

return 0;

}

 

Welcome to Fahrenheit to Celsius program

Please enter temperature in F

118

Temperature in C = 47

 

Process returned 0 (0x0)   execution time : 6.801 s

Press any key to continue.

 

 

 

#include <iostream>

using namespace std;

int main()

{

long pop1=2459517, pop2=18,pop3=9164; //note how we initialized the variables in same line

cout <<“Location “<<“Population”<<endl

<<“New York “<<pop1<<endl //see how it ignores the whitespace

<<“Chicago  “<<pop2<<endl //see how operator cascading is useful

<<“San Jose “<<pop3<<endl; //the outputs is not well organized; not aligned

return 0;

}

 

 

Location Population

New York 2459517

Chicago  18

San Jose 9164

 

Process returned 0 (0x0)   execution time : 0.080 s

Press any key to continue.

 

 

#include <iostream>

#include <iomanip> //we have to include this header file to use setw manipulator

using namespace std;

 

int main()

{

long pop1=2459517, pop2=18,pop3=9164;

cout <<setw(8)<<“Location”<<setw(12)<<“Population”<<endl //use setw manipulator to set the width for the output

<<setw(8)<<“New York”<<setw(12)<<pop1<<endl //we don’t need to add spaces in the strings anymore

<<setw(8)<<“Chicagoo”<<setw(12)<<pop2<<endl

<<setw(8)<<“San Jose”<<setw(12)<<pop3<<endl; //the output is lined up to the right

return 0;

}

 

 

Location  Population

New York     2459517

Chicagoo                18

San Jose             9164

 

Process returned 0 (0x0)   execution time : 0.094 s

Press any key to continue.

 

 

 

 

 

Arithmetic Operators

 

#include <iostream>

using namespace std;

int main()

{

cout<<6%8<<endl<<7%8<<endl<<8%8<<endl<<9%8<<endl<<10%8<<endl; //calculates and outputs the remainder; higher precedence than <<

int x=30;

x+=5; //arithmetic assignment operator, equivalent to x=x+5

cout<<“\nx=x+5=x+5″<<x<<endl; //same we can go for x*=5 x/=7 x%=3

int counter=1;

cout<<“\ncounter=”<<++counter<<endl; //increment operator, here prefix, so it increment variable before output

cout<<“counter=”<<counter++<<endl; //however here it’s postfix, so it increment variable after output

cout<<“counter=”<<counter<<endl; //now, it has been incremented, so it outputs 3

return 0;

}

 

6

7

0

1

2

 

x=x+5=x+535

 

counter=2

counter=2

counter=3

 

Process returned 0 (0x0)   execution time : 0.060 s

Press any key to continue.

 

 

 

2. Loops & Decisions

 

Logical operators

 

#include <iostream>

 

using namespace std;

 

int main()

{

cout<<“Enter a number”<<endl;

int x;

cin>>x;

cout<<“\nNumebr < 10 is counter=”<<(x<10)<<endl; //check if the number is < 10 and if true displays 1 and false 0

cout<<“\nNumebr = 10 is counter=”<<(x==10)<<endl; //check if the number equals 10 note we use == not = which is assignment

cout<<“\nNumebr > 10 is counter=”<<(x>10)<<endl; //check if the number is >10 note that 0 is false and any other value (-13 or 159) is true

return 0;

}

Enter a number

19

 

Numebr < 10 is counter=0

 

Numebr = 10 is counter=0

 

Numebr > 10 is counter=1

 

Process returned 0 (0x0)   execution time : 2.529 s

Press any key to continue.

 

Loops

 

For loop

 

 

#include <iostream>

using namespace std;

int main()

{

int x;

for (x=0; x<10; x++) //x=0 is initialization expression, x<10 is test expression, x++ is increment expression

cout<<x*x<<“\t”; //loop body

cout<<endl;

return 0;

}

 

0       1       4       9       16      25      36      49      64      81

 

Process returned 0 (0x0)   execution time : 0.419 s

Press any key to continue.

 

 

#include <iostream>

#include<iomanip>

using namespace std;

 

int main()

{

int x;

for (x=0; x<10; x++)

{ //we have multiple statements in the loop, so we  must use those curly brackets

cout<<setw(4)<<x; //those statements are called a block

int c=x*x*x; //and this variable is only seen visible within this block

cout<<setw(6)<<c<<endl;

} //and end them

cout<<endl;

return 0;

}

 

0     0

1     1

2     8

3    27

4    64

5   125

6   216

7   343

8   512

9   729

 

 

Process returned 0 (0x0)   execution time : 0.390 s

Press any key to continue.

 

 

 

 

#include <iostream>

using namespace std;

int main()

{

unsigned int x;

unsigned long factorial=1;

cout<<“Enter a number”<<endl;

cin>>x;

for (int i=x; i>0; i–) //note that we can define a variable here, but it’s seen in the whole program

{ //note that we can use more than an initialization expression and more than an increment expression, but only 1 test

factorial*=i;

} //or we can drop all expressions like for(;;)

cout<<“Factorial of “<<x<<” is “<<factorial<<endl;

return 0;

}

 

Enter a number

8

Factorial of 8 is 40320

 

Process returned 0 (0x0)   execution time : 2.713 s

Press any key to continue.

 

 

 

 

 

While loop

#include <iostream>

using namespace std;

int main()

{

int x=10;

cout<<“Enter any number, type 0 to terminate”<<endl;

while(x!=0) //while is a new kind of loops and it is not like for loop that runs certain number of times; it runs as long as the condition is true

cin>>x;

cout<<endl;

return 0;

}

 

Enter any number, type 0 to terminate

15

19

10

1954

46

0

 

Process returned 0 (0x0)   execution time : 14.132 s

Press any key to continue.

 

 

 

 

 

 

#include <iostream>

#include<iomanip>

using namespace std;

 

int main()

{

int x=1, p=1;

while(p<9999) //to make sure it fits into 4 digits format

{

cout<<setw(2)<<x;

cout<<setw(5)<<p<<endl;

p=x*x*x*x;

x++;

}

 

cout<<endl;

return 0;

}

 

1    1

2    1

3   16

4   81

5  256

6  625

7 1296

8 2401

9 4096

10 6561

 

Process returned 0 (0x0)   execution time : 0.479 s

Press any key to continue.

 

 

 

#include <iostream>

using namespace std;

 

int main()

{

unsigned long x=0,y=1;

const unsigned long l=999999999;

while(x<l/2) //see here the precedence; arithmetic operation has higher precedence

{

cout<<y<<” “;

long s=x+y;  //creates Fibonacci series which is next terms = summation of previous 2

x=y;

y=s;

 

}

 

cout<<endl;

return 0;

}

 

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 2

8657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702

887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 43

3494437 701408733

 

Process returned 0 (0x0)   execution time : 0.408 s

Press any key to continue.

 

Do loop

 

#include <iostream>

using namespace std;

int main()

{

long x,y;

char r;

do //use the do loop when you want the loop to run at least once

{

cout<<“Enter Dividend: “; cin>>x;

cout<<“Enter Divisor: “; cin>>y;

cout<<“The quotient is “<<x/y;

cout<<” ,remainder is “<<x%y;

cout<<“\nDo another? (y/n) “; cin>>r;

 

}

while(r!=’n’);

return 0;

}

 

 

Enter Dividend: 18

Enter Divisor: 2

The quotient is 9 ,remainder is 0

Do another? (y/n) y

Enter Dividend: 6

Enter Divisor: 5

The quotient is 1 ,remainder is 1

Do another? (y/n) y

Enter Dividend: 87

Enter Divisor: 3

The quotient is 29 ,remainder is 0

Do another? (y/n) y

Enter Dividend: 10

Enter Divisor: 4

The quotient is 2 ,remainder is 2

Do another? (y/n) n

 

Process returned 0 (0x0)   execution time : 58.066 s

Press any key to continue.

 

 

 

Decisions

 

If

 

#include <iostream>

using namespace std;

int main()

{

int x;

cout<<“Enter a number”<<endl;

cin>>x;

if(x>100)

{ //need curly brackets if more than one statement

cout<<“The number “<<x;

cout<<” is greater than 100″<<endl;

} //don’t forget to close them

return 0;

}

 

 

Enter a number

150

The number 150 is greater than 100

Process returned 0 (0x0)   execution time : 2.995 s

Press any key to continue.

 

 

 

#include <iostream>

#include<cstdlib> //needed for exit(0) function

using namespace std;

int main()

{

unsigned long x,j;

cout<<“Enter a positive number”<<endl;

cin>>x;

for(j=2;j<=x/2;j++) //note that we don’t need brackets for the for loop because the if statement is seen as single statement by the loop

if(x%j==0)

{

cout<<“It’s not prime”;

exit(0);

}

cout<<“It’s prime”;

return 0;

}

 

 

Enter a positive number

13

It’s prime

Process returned 0 (0x0)   execution time : 2.407 s

Press any key to continue.

 

Enter a positive number

20

It’s not prime

Process returned 0 (0x0)   execution time : 1.863 s

Press any key to continue.

 

 

 

#include <iostream>

using namespace std;

int main()

{

int x;

cout<<“Enter a number”<<endl;

cin>>x;

if(x>100)

cout<<“The number is > 100 “<<endl;

else

cout<<“The number is < 100″<<endl;

return 0;

}

 

Enter a number

81

The number is < 100

Process returned 0 (0x0)   execution time : 2.165 s

Press any key to continue.

 

Enter a number

113

The number is > 100

Process returned 0 (0x0)   execution time : 4.497 s

Press any key to continue.

 

 

 

#include <iostream>

#include<conio.h> //needed for getche() library function

using namespace std;

int main()

{

int c=0,w=1;

char m=’a’;

cout<<“Enter a phrase”<<endl;

while (m!=’\r’)

{

m=getche(); //that’s a new way to take input without waiting for the enter to be pressed, note the difference with getch() which doesn’t echo the character to the screen

if(m==’  ‘) //space means w new word

w++;  //so, update words counter

else //otherwise

c++; //update character counter

}

cout<<“\nNumber of words: “<<w<<” and number of characters: “<<c<<endl;

return 0;

}

 

Enter a phrase

i love programming

Number of words: 3 and number of characters: 17

 

Process returned 0 (0x0)   execution time : 10.718 s

Press any key to continue.

 

 

 

 

#include <iostream>

#include<conio.h>

using namespace std;

 

int main()

{

int c=0,w=1;

char m=’a’;

cout<<“Enter a phrase”<<endl;

while ((m=getche())!=’\r’) //this works as above, note we use parentheses because = lower precedence than !=

{

if(m==’  ‘)

w++;

else

c++;

}

cout<<“\nNumber of words: “<<w<<” and number of characters: “<<c<<endl;

return 0;

}

 

 

Enter a phrase

I still love programming

Number of words: 4 and number of characters: 21

 

Process returned 0 (0x0)   execution time : 10.542 s

Press any key to continue.

 

 

 

#include <iostream>

#include<conio.h>

using namespace std;

 

int main()

{

 

int x=10,y=10;

char d=’a’;

cout<<“Your location is: “<<x<<” ,”<<y<<endl;

 

cout<<“Type Enter to quit”<<endl;

while (d!=’\r’)

{

cout<<“\nYour location is: “<<x<<“,”<<y<<endl;

cout<<“\nType your direction key (n,s,e,w)”<<endl;

d=getche();

if(d==’n’)

y–;

else //take care of matching else with the correct if

if(d==’s’)

y++;

else

if(d==’e’)

x++;

else

if(d==’w’)

x–;

}

 

return 0;

}

 

 

 

Your location is: 10 ,10

Type Enter to quit

 

Your location is: 10,10

 

Type your direction key (n,s,e,w)

n

Your location is: 10,9

 

Type your direction key (n,s,e,w)

e

Your location is: 11,9

 

Type your direction key (n,s,e,w)

w

Your location is: 10,9

 

Type your direction key (n,s,e,w)

n

Your location is: 10,8

 

Type your direction key (n,s,e,w)

s

Your location is: 10,9

 

Type your direction key (n,s,e,w)

 

Process returned 0 (0x0)   execution time : 19.695 s

Press any key to continue.

 

 

 

 

 

 

 

 

 

 

 

Switch

 

 

#include <iostream>

#include<conio.h>

using namespace std;

 

int main()

{

 

int x=10,y=10;

char d=’a’;

cout<<“Your location is: “<<x<<” ,”<<y<<endl;

 

cout<<“Type Enter to quit”<<endl;

while (d!=’\r’)

{

cout<<“\nYour location is: “<<x<<“,”<<y<<endl;

cout<<“\nType your direction key (n,s,e,w)”<<endl;

d=getche();

switch(d)

{

case ‘n’: y–; break;

case ‘s’: y++; break;

case ‘e’: x++; break;

case ‘w’: x–; break;

case ‘\r’: cout<<“\nQuitting\n”; break;

default: cout<<“\nTry Again!”<<endl;

}

}

 

return 0;

}

 

 

Your location is: 10 ,10

Type Enter to quit

 

Your location is: 10,10

 

Type your direction key (n,s,e,w)

n

Your location is: 10,9

 

Type your direction key (n,s,e,w)

o

Try Again!

 

Your location is: 10,9

 

Type your direction key (n,s,e,w)

r

Try Again!

 

Your location is: 10,9

 

Type your direction key (n,s,e,w)

s

Your location is: 10,10

 

Type your direction key (n,s,e,w)

e

Your location is: 11,10

 

Type your direction key (n,s,e,w)

e

Your location is: 12,10

 

Type your direction key (n,s,e,w)

e

Your location is: 13,10

 

Type your direction key (n,s,e,w)

n

Your location is: 13,9

 

Type your direction key (n,s,e,w)

n

Your location is: 13,8

 

Type your direction key (n,s,e,w)

w

Your location is: 12,8

 

Type your direction key (n,s,e,w)

 

Quitting

 

Process returned 0 (0x0)   execution time : 32.634 s

Press any key to continue.

 

 

 

Conditional operator

 

#include <iostream>

using namespace std;

int main()

{

for(int j=0;j<80;j++)

{

char c= (j%8) ? ‘ ‘ : ‘x’; //that’s conditional operator; the variable c is assigned space or x depending on test expression j%8 if true it’s a space, if false, it’s x

cout<<c;

}

return 0;

}

 

 

#include <iostream>

using namespace std;

int main()

{

for(int j=0;j<80;j++)

{

cout<<((j%8) ? ‘ ‘ : ‘x’); // if true it’s a space, if false, it’s x

}

return 0;

}

 

 

 

 

 

x       x       x       x       x       x       x       x       x       x

 

Process returned 0 (0x0)   execution time : 0.138 s

Press any key to continue.

 

Logical Operator

 

#include <iostream>

#include<cstdlib>

#include<conio.h>

using namespace std;

int main()

{

int x=10,y=10;

char d=’a’;

cout<<“Type Enter to quit”<<endl;

while (d!=’\r’)

{

cout<<“\nYour location is: “<<x<<“,”<<y<<endl;

cout<<“\nType your direction key (n,s,e,w)”<<endl;

d=getche();

switch(d)

{

case ‘n’: y–; break;

case ‘s’: y++; break;

case ‘e’: x++; break;

case ‘w’: x–; break;

case ‘\r’: cout<<“\nQuitting\n”; break;

default: cout<<“\nTry Again!”<<endl;

}

if(x==7&&y==11)

{

cout<<“\nYou found the treasure! \n”;

exit(0);

}

if(x<5 || x>15)

cout<<“\nBEWARE dragon here!\n”;

if(!(x%7) && !(y%7))

cout<<“\nMushroom here!\n”;

}

return 0;

}

 

 

Type Enter to quit

 

Your location is: 10,10

 

Type your direction key (n,s,e,w)

n

Your location is: 10,9

 

Type your direction key (n,s,e,w)

n

Your location is: 10,8

 

Type your direction key (n,s,e,w)

n

Your location is: 10,7

 

Type your direction key (n,s,e,w)

w

Your location is: 9,7

 

Type your direction key (n,s,e,w)

w

Your location is: 8,7

 

Type your direction key (n,s,e,w)

w

Mushroom here!

 

Your location is: 7,7

 

Type your direction key (n,s,e,w)

e

Your location is: 8,7

 

Type your direction key (n,s,e,w)

e

Your location is: 9,7

 

Type your direction key (n,s,e,w)

e

Your location is: 10,7

 

Type your direction key (n,s,e,w)

e

Your location is: 11,7

 

Type your direction key (n,s,e,w)

e

Your location is: 12,7

 

Type your direction key (n,s,e,w)

e

Your location is: 13,7

 

Type your direction key (n,s,e,w)

e

Mushroom here!

 

Your location is: 14,7

 

Type your direction key (n,s,e,w)

e

Your location is: 15,7

 

Type your direction key (n,s,e,w)

e

BEWARE dragon here!

 

Your location is: 16,7

 

Type your direction key (n,s,e,w)

e

BEWARE dragon here!

 

Your location is: 17,7

 

Type your direction key (n,s,e,w)

e

BEWARE dragon here!

 

Your location is: 18,7

 

Type your direction key (n,s,e,w)

w

BEWARE dragon here!

 

Your location is: 17,7

 

Type your direction key (n,s,e,w)

w

BEWARE dragon here!

 

Your location is: 16,7

 

Type your direction key (n,s,e,w)

w

Your location is: 15,7

 

Type your direction key (n,s,e,w)

w

Mushroom here!

 

Your location is: 14,7

 

Type your direction key (n,s,e,w)

w

Your location is: 13,7

 

Type your direction key (n,s,e,w)

w

Your location is: 12,7

 

Type your direction key (n,s,e,w)

w

Your location is: 11,7

 

Type your direction key (n,s,e,w)

w

Your location is: 10,7

 

Type your direction key (n,s,e,w)

w

Your location is: 9,7

 

Type your direction key (n,s,e,w)

w

Your location is: 8,7

 

Type your direction key (n,s,e,w)

w

Mushroom here!

 

Your location is: 7,7

 

Type your direction key (n,s,e,w)

s

Your location is: 7,8

 

Type your direction key (n,s,e,w)

s

Your location is: 7,9

 

Type your direction key (n,s,e,w)

s

Your location is: 7,10

 

Type your direction key (n,s,e,w)

s

You found the treasure!

 

Process returned 0 (0x0)   execution time : 65.895 s

Press any key to continue.

 

 

 

Other Control Statements

 

#include <iostream>

#include<cstdlib>

#include<conio.h>

using namespace std;

int main()

{

const unsigned char w=219;

const unsigned char g=176;

unsigned char c;

for(int i=0;i<80*25-1;i++)

{

c=w;

for(int j=2;j<i;j++)

{

if(i%j==0)

{

c=g;

break; //get out the loop

}

}

cout<<c;

}

getch();

return 0;

}

 

 

████░█░█░░░█░█░░░█░█░░░█░░░░░█░█░░░░░█░░░█░█░░░█░░░░░█░░░░░█░█░░░░░█░░░█░█░░░░░█

░░░█░░░░░█░░░░░░░█░░░█░█░░░█░█░░░█░░░░░░░░░░░░░█░░░█░░░░░█░█░░░░░░░░░█░█░░░░░█░░

░░░█░░░█░░░░░█░░░░░█░█░░░░░░░░░█░█░░░█░█░░░░░░░░░░░█░░░░░░░░░░░█░░░█░█░░░█░░░░░█

░█░░░░░░░░░█░░░░░█░░░░░█░░░░░█░█░░░░░█░░░█░█░░░░░░░░░█░░░░░░░░░░░░░█░░░█░█░░░█░░

░░░░░░░░░░░█░░░░░█░░░░░░░░░█░█░░░█░░░░░█░░░░░░░█░░░░░█░░░░░█░░░█░░░░░█░░░░░░░█░░

░█░░░░░░░█░░░░░░░░░█░█░░░░░░░░░█░█░░░░░█░░░█░░░░░█░░░░░░░█░░░█░█░░░█░░░░░░░░░░░█

░░░░░░░█░░░█░░░░░░░█░░░█░░░░░█░░░░░░░░░░░█░█░░░░░░░░░░░░░░░░░█░░░░░█░░░░░░░░░█░░

░░░█░░░░░█░█░░░░░█░░░░░░░░░█░░░░░█░░░░░█░█░░░░░█░░░░░█░░░█░█░░░░░░░░░░░█░░░░░░░░

░█░█░░░█░░░░░█░░░░░█░█░░░░░░░░░░░█░░░█░░░░░█░░░░░░░█░░░░░░░░░█░░░░░░░█░░░░░░░░░█

░░░░░░░█░░░░░█░░░░░█░░░█░░░░░░░█░░░░░█░░░█░░░░░░░█░░░█░░░░░░░░░░░░░█░░░░░░░░░█░░

░░░░░░░░░█░█░░░░░░░░░█░█░░░█░█░░░░░░░░░█░░░░░░░░░░░░░█░░░█░█░░░█░░░░░░░░░░░░░█░░

░█░█░░░█░░░░░░░░░░░░░░░░░░░█░░░█░░░░░░░█░░░░░░░░░█░░░░░░░█░░░█░░░░░█░░░░░█░░░░░░

░░░░░░░█░░░█░░░░░█░░░░░█░░░░░░░█░░░░░█░░░░░░░░░░░█░░░█░░░░░█░█░░░░░░░░░█░█░░░░░█

░░░░░░░░░█░█░░░░░░░░░█░█░░░░░█░░░░░░░░░░░░░░░░░█░░░█░█░░░█░░░░░█░░░░░█░░░░░░░█░░

░░░█░░░░░█░░░░░░░░░░░░░░░░░░░░░█░█░░░░░░░░░█░░░░░░░█░░░░░░░░░█░░░░░█░░░░░█░░░░░░

░█░░░░░░░░░░░█░░░█░░░░░█░░░░░█░█░░░░░█░░░░░░░░░░░█░░░░░░░░░█░░░░░░░░░░░░░░░░░█░█

░░░█░░░░░█░█░░░░░█░░░█░█░░░█░░░░░░░░░░░█░█░░░░░█░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

░█░░░░░█░░░░░█░░░░░░░█░░░░░░░░░░░░░░░░░█░░░░░░░░░█░░░░░░░░░░░░░█░░░█░█░░░█░░░░░█

░░░░░░░█░░░█░█░░░░░█░░░░░░░░░░░█░░░░░░░░░█░█░░░█░█░░░█░░░░░█░░░░░░░░░░░█░░░░░░░░

░░░█░░░░░░░█░░░░░░░░░░░█░░░░░█░░░█░░░░░█░░░░░░░█░░░█░░░░░░░█░░░█░░░░░░░░░░░░░█░░

░█░░░░░█░█░░░█░░░░░█░█░░░░░█░░░░░░░░░█░░░░░░░░░░░░░░░░░░░█░░░░░█░░░█░█░░░░░░░░░░

░░░░░░░░░░░░░█░░░█░█░░░░░░░░░█░░░░░░░░░░░█░█░░░░░░░░░█░░░░░░░█░░░░░█░░░░░█░░░░░█

░░░░░░░░░░░░░░░░░█░░░░░█░░░█░█░░░░░░░░░░░█░░░░░░░░░█░░░░░░░░░░░█░░░░░░░█░░░░░░░░

░░░░░░░█░░░░░░░░░░░░░█░░░░░█░░░█░█░░░█░█░░░░░░░░░█░░░░░░░░░░░█░░░░░█░░░░░█░░░░░░

░░░░░░░░░░░█░█░░░░░░░░░░░░░░░█░█░░░░░░░░░░░░░░░░░░░░░█░░░░░█░░░░░░░█░░░░░█░░░█░

Process returned 0 (0x0)   execution time : 11.964 s

Press any key to continue.

 

 

 

#include<conio.h>

using namespace std;

 

int main()

{

long x,y;

char c;

do

{

cout<<“Enter dividened\n”; cin>>x;

cout<<“Enter divisor\n”; cin>>y;

if(y==0)

{

cout<<“\n Illegal divisor\n”<<endl;

continue; //will get us back in the beginning of the loop

}

cout<<“Quotient is: “<<x/y;

cout<<” and remainder is: “<<x%y;

cout<<“\nDo another? (y/n): “;

cin>>c;

}while(c!=’n’);

return 0;

}

 

 

Enter dividened

8

Enter divisor

2

Quotient is: 4 and remainder is: 0

Do another? (y/n): y

Enter dividened

9

Enter divisor

2

Quotient is: 4 and remainder is: 1

Do another? (y/n): y

Enter dividened

8

Enter divisor

0

 

Illegal divisor

 

Enter dividened

13

Enter divisor

3

Quotient is: 4 and remainder is: 1

Do another? (y/n): n

 

Process returned 0 (0x0)   execution time : 51.597 s

Press any key to continue.

 

 

 

The goto statement

Old-fashioned!

 

Precedence

Unary

!,++,–

Arithmetic

Multiplicative     *,/,%

Additive               +,-

Relational

Inequality            <,>,<=,>=

Equality                               ==,!=

Logical

And &&

Or   ||

Conditional         ?=

Assignment         =,+=,*=,/=%=

 

 

 

 

3. Structures

 

Structures

 

#include <iostream>

using namespace std;

 

struct part //declaring the structure; “part” is the structure name (or tag) a structure is a way to make user-defined variable type; class for data & functions

{

int modelnum; //those are

int partnum;    //structure

float cost;     //members

}; //don’t forget the semicolon here

 

int main()

{

part part1;

 

part1.modelnum=6244; //accessing structure members using the dot operator

part1.partnum=373; //in fact its name is member access operator

part1.cost=217.55F;

 

cout<<“Model “<<part1.modelnum<<“, part “<<part1.partnum<<” costs $”<<part1.cost<<endl;

 

return 0;

}

 

 

Model 6244, part 373 costs $217.55

 

Process returned 0 (0x0)   execution time : 0.301 s

Press any key to continue.

 

 

#include <iostream>

using namespace std;

 

struct  //note no name is given in declaration

{

int modelnum;

int partnum;

float cost;

}part1; //a name can be given here

 

int main()

{

part1.modelnum=6244;

part1.partnum=373;

part1.cost=217.55F;

 

cout<<“Model “<<part1.modelnum<<“, part “<<part1.partnum<<” costs $”<<part1.cost<<endl; //same output

 

return 0;

}

 

 

 

#include <iostream>

using namespace std;

 

struct part

{

int modelnum;

int partnum;

float cost;

};

 

int main()

{

part part1 = {6244, 373, 217.55F}; //initializing a structure variable

part part2;

 

cout<<“Model “<<part1.modelnum<<“, part “<<part1.partnum<<” costs $”<<part1.cost<<endl;

 

part2=part1;

 

cout<<“Model “<<part2.modelnum<<“, part “<<part2.partnum<<” costs $”<<part2.cost<<endl;

 

return 0;

}

 

 

 

Model 6244, part 373 costs $217.55

Model 6244, part 373 costs $217.55

 

Process returned 0 (0x0)   execution time : 0.321 s

Press any key to continue.

 

 

#include <iostream>

using namespace std;

 

struct dist

{

int ft;

float in;

};

 

int main()

{

dist d2= {11, 6.25};

dist d1,d3;

 

cout<<“Enter feet\n”; cin>>d1.ft;

cout<<“Enter inches\n”; cin>>d1.in;

 

d3.in=d1.in+d2.in; //note that you can’t type d3=d1+d2 however classes will enable us to do operations on user-defined data

d3.ft=0;

if(d1.in>12)

{

d3.in-=12;

d3.ft++;

}

 

d3.ft+=d1.ft+d2.ft;

 

cout<<d1.ft<<“\’-“<<d1.in<<“\” + “<<d2.ft<<“\’-“<<d2.in<<“\” = “<<d3.ft<<“\’-“<<d3.in<<“\”” <<endl;

 

return 0;

}

 

Enter feet

18

Enter inches

16

18′-16″ + 11′-6.25″ = 30′-10.25″

 

Process returned 0 (0x0)   execution time : 8.922 s

Press any key to continue.

 

 

 

 

#include <iostream>

using namespace std;

 

struct dist

{

int ft;

float in;

};

 

struct room //nested structures

{

dist length;

dist width;

};

 

int main()

{

room dinning;

 

dinning.length.ft=13; //equivalent to room dinning = {{13,6.5},{10,0}}

dinning.length.in=6.5;

dinning.width.ft=10;

dinning.width.in=0.0;

 

float l=dinning.length.ft+dinning.length.in/12; //note the type conversion

float w=dinning.width.ft+dinning.width.in/12;

 

cout<<“Dinning room area = “<<l*w<<” sq ft”<<endl; //type conversion happens here too

 

return 0;

}

 

 

Dinning room area = 135.417 sq ft

 

Process returned 0 (0x0)   execution time : 0.290 s

Press any key to continue.

 

 

 

#include <iostream>

using namespace std;

 

const int clubs=0;

const int diamonds=1;

const int hearts=2;

const int spades=3;

 

const int jack=11;

const int queen=12;

const int king=13;

const int ace=14;

 

struct card

{

int number;

int suit;

};

 

 

int main()

{

card temp,chosen,prize;

int pos;

 

card card1={7,clubs};

cout<<“Card 1 is the 7 of clubs\n”;

 

card card2={jack, hearts};

cout<<“Card 2 is the jack of hearts\n”;

 

card card3={ace, spades};

cout<<“Card 3 is the ace of spades\n”;

 

prize=card3;

 

cout<<“I’m swapping card 1 and card 3\n”;

temp=card3; card3=card1; card1=temp;

 

cout<<“I’m swapping card 2 and card 3\n”;

temp=card3; card3=card2; card2=temp;

 

cout<<“I’m swapping card 1 and card 2\n”;

temp=card2; card2=card1; card1=temp;

 

cout<<“Where is the ace of spades? “; cin>>pos;

 

switch(pos)

{

case 1: chosen=card1; break;

case 2: chosen=card2; break;

case 3: chosen=card3; break;

}

 

if(chosen.number==prize.number && chosen.suit==prize.suit)

cout<<“\nCorrect! You win!\n”;

else

cout<<“\nSorry! You lose!\n”;

 

return 0;

}

 

 

 

Card 1 is the 7 of clubs

Card 2 is the jack of hearts

Card 3 is the ace of spades

I’m swapping card 1 and card 3

I’m swapping card 2 and card 3

I’m swapping card 1 and card 2

Where is the ace of spades? 2

 

Correct! You win!

 

Process returned 0 (0x0)   execution time : 1.717 s

Press any key to continue.

 

 

Card 1 is the 7 of clubs

Card 2 is the jack of hearts

Card 3 is the ace of spades

I’m swapping card 1 and card 3

I’m swapping card 2 and card 3

I’m swapping card 1 and card 2

Where is the ace of spades? 1

 

Sorry! You lose!

 

Process returned 0 (0x0)   execution time : 1.503 s

Press any key to continue.

 

 

 

Enumerations

 

#include <iostream>

using namespace std;

 

enum wkdys {Sun, Mon, Tues, Wed, Thurs, Fri, Sat};  //declaring an enumeration:: Sun, Mon, … Sat are ‘enumerators’

 

int main()

{

wkdys day1,day2; //defining a variable of type wkdys; note that it has a certain range of values to take, not like integer

 

day1=Mon;

day2=Fri;

 

int diff=day2-day1; //note that enumerators actually takes numeric values starting from 0

 

cout<<“Days between = “<<diff<<endl;

 

if(day1<day2)

cout<<“Day 1 comes first”<<endl;

 

return 0;

}

 

Days between = 4

Day 1 comes first

 

Process returned 0 (0x0)   execution time : 0.357 s

Press any key to continue.

 

 

 

 

 

 

 

#include <iostream>

#include <conio.h>

using namespace std;

 

enum isword {Y, N};

 

int main()

{

isword chkw = N;

 

char chr=’a’;

int cnt=0;

 

cout<<“Enter a phrase”<<endl;

 

do

{

chr=getche();

if (chr==’  ‘ || chr==’\r’)

{

if (chkw==Y) //check if chkw is YES to check if this space has a space before it (N) or character(Y)

{

cnt++;

chkw=N; //in case a second successive space is countered, it won’t get here and increment the counter

}

}

else   //if it’s a character

if (chkw==N)

chkw=Y;   //then reset chkw to Y

}while(chr!=’\r’);

 

cout<<“\nword counter: “<<cnt<<endl;

 

 

return 0;

}

 

Enter a phrase

word1 2space   word3    many spaces   in between     let’s see

word counter: 9

 

Process returned 0 (0x0)   execution time : 32.170 s

Press any key to continue.

 

 

 

 

 

 

#include <iostream>

using namespace std;

 

const int jack=11, queen=12, king=13, ace=14;

 

enum suit {clubs=1, diamonds, hearts, spades};   //recall how we did it before; we defined integer variables, note that we can customize the first variable value to start from a certain number not 0

 

struct card

{

int num;

suit suitt;

};

 

 

int main()

{

card temp,chosen,prize;

int pos;

 

card card1={7,clubs};

cout<<“Card 1 is the 7 of clubs\n”;

 

card card2={jack, hearts};

cout<<“Card 2 is the jack of hearts\n”;

 

card card3={ace, spades};

cout<<“Card 3 is the ace of spades\n”;

 

prize=card3;

 

cout<<“I’m swapping card 1 and card 3\n”;

temp=card3; card3=card1; card1=temp;

 

cout<<“I’m swapping card 2 and card 3\n”;

temp=card3; card3=card2; card2=temp;

 

cout<<“I’m swapping card 1 and card 2\n”;

temp=card2; card2=card1; card1=temp;

 

cout<<“Where is the ace of spades? “; cin>>pos;

 

switch(pos)

{

case 1: chosen=card1; break;

case 2: chosen=card2; break;

case 3: chosen=card3; break;

}

 

if(chosen.num==prize.num && chosen.suitt==prize.suitt)

cout<<“\nCorrect! You win!\n”;

else

cout<<“\nSorry! You lose!\n”;

 

 

return 0;

}

 

 

 

Card 1 is the 7 of clubs

Card 2 is the jack of hearts

Card 3 is the ace of spades

I’m swapping card 1 and card 3

I’m swapping card 2 and card 3

I’m swapping card 1 and card 2

Where is the ace of spades? 2

 

Correct! You win!

 

Process returned 0 (0x0)   execution time : 5.987 s

Press any key to continue.

4. Functions

 

No arguments

 

#include <iostream>

using namespace std;

 

void starline(); //function declaration; it has no arguments and doesn’t return any values

 

int main()

{

starline(); //calling the function

 

cout<<“Data Type\tRange\n”;

 

starline(); //unlike library function, like getche(), the code for starline must be here [getche() code in is conio.h]

 

cout<<“char\t\t-128 to 127\nshort\t\t-32,768 to 32,767\nint\t\tSystem Independent\nlong\t\t-2,147,483,648 to -2,147,483,647\n”;

 

starline();

 

return 0;

}

 

void starline() //the function definition; note that we could have made it earlier, but that’s always better

{

for(int j=0;j<45;j++)

cout<<“*”;

cout<<endl;

}

 

 

 

*********************************************

Data Type       Range

*********************************************

char            -128 to 127

short           -32,768 to 32,767

int             System Independent

long            -2,147,483,648 to -2,147,483,647

*********************************************

 

Process returned 0 (0x0)   execution time : 0.130 s

Press any key to continue.

 

 

 

Passing constants as arguments

 

#include <iostream>

using namespace std;

 

void starline(char, int); //here the function has 2 arguments of type character and integer

 

int main()

{

starline(‘-‘,30); //here, I’m passing – as a character and 30 as integer, so starline will print 30 dashes

 

cout<<“Data Type\tRange\n”;

 

starline(‘*’,40); //note that you can change the arguments in each call

 

cout<<“char\t\t-128 to 127\nshort\t\t-32,768 to 32,767\nint\t\tSystem Independent\nlong\t\t-2,147,483,648 to -2,147,483,647\n”;

 

starline(‘+’,50);

 

return 0;

}

 

void starline(char ch,int x)

{

for(int j=0;j<x;j++)

cout<<ch;

cout<<endl;

}

 

 

 

——————————

Data Type       Range

******************************

char            -128 to 127

short           -32,768 to 32,767

int             System Independent

long            -2,147,483,648 to -2,147,483,647

++++++++++++++++++++++++++++++++++++++++++++++++++

 

Process returned 0 (0x0)   execution time : 0.113 s

Press any key to continue.

 

 

Passing variables

 

#include <iostream>

using namespace std;

 

void starline(char, int); //here the function has 2 arguments of type character and integer

 

 

int main()

{

char chn;

int xn;

cout<<“Enter a character\n”; cin>>chn;

cout<<“Enter a number\n”; cin>>xn;

 

cout<<endl;

 

starline(chn,xn); //here we’re passing variables not constants like previous

 

cout<<“Data Type\tRange\n”;

 

starline(chn,xn);

 

cout<<“char\t\t-128 to 127\nshort\t\t-32,768 to 32,767\nint\t\tSystem Independent\nlong\t\t-2,147,483,648 to -2,147,483,647\n”;

 

starline(chn,xn);

 

return 0;

}

 

void starline(char ch,int x)

{

for(int j=0;j<x;j++)

cout<<ch;

cout<<endl;

}

 

 

 

Enter a character

^

Enter a number

50

 

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Data Type       Range

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

char            -128 to 127

short           -32,768 to 32,767

int             System Independent

long            -2,147,483,648 to -2,147,483,647

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

 

Process returned 0 (0x0)   execution time : 11.098 s

Press any key to continue.

 

 

 

 

#include <iostream>

using namespace std;

 

struct dist

{

int ft;

float in;

};

 

void edisp(dist); //function can take structure as an argument

 

int main()

{

dist d1,d2;

 

cout<<“Enter first distance feet\n”; cin>>d1.ft;

cout<<“Enter first distance inches\n”; cin>>d1.in;

cout<<“Enter second distance feet\n”; cin>>d2.ft;

cout<<“Enter second distance inches\n”; cin>>d2.in;

 

cout<<“\nd1 = “;

edisp(d1);

 

cout<<“\nd2 = “;

edisp(d2);

 

cout<<endl;

 

return 0;

}

 

void edisp(dist dd)

{

cout<<dd.ft<<“\’ – “<<dd.in<<“\””;

}

 

 

Enter first distance feet

16

Enter first distance inches

23

Enter second distance feet

19

Enter second distance inches

19

 

d1 = 16′ – 23″

d2 = 19′ – 19″

 

Process returned 0 (0x0)   execution time : 12.638 s

Press any key to continue.

 

 

 

 

 

#include <iostream>

#include<msoftcon.h> //needed for graphics functions; note: must add msoftcon.cpp source file to the project

using namespace std;

 

struct circ

{

int xC,yC,r;

color fc;

fstyle fs;

};

 

void circdrw(circ c) //here we eliminate the declaration and placed the function definition before the first call

{

set_color(c.fc);

set_fill_style(c.fs);

draw_circle(c.xC,c.yC,c.r);

}

 

int main()

{

init_graphics();

 

circ c1={15,7,5,cBLUE,X_FILL};

circ c2={41,12,7,cRED,O_FILL};

circ c3={65,18,4,cGREEN,MEDIUM_FILL};

 

circdrw(c1);

circdrw(c2);

circdrw(c3);

 

return 0;

}

 

 

 

 

 

 

#include <iostream>

 

using namespace std;

 

 

float lbtkg(float); //here the function is returning a value of type float

 

 

int main()

{

float kgs,lbs;

cout<<“Enter weight in pounds\n”; cin>>lbs;

kgs=lbtkg(lbs);

cout<<“\nWeight in kilograms = “<<kgs<<endl;

 

return 0;

}

 

float lbtkg(float pounds)

{

float kilograms;

kilograms=0.453592*pounds;

return kilograms; //that’s the value the function will return; note that functions return ONLY 1 value

}

 

 

 

Enter weight in pounds

1235

 

Weight in kilograms = 560.186

 

Process returned 0 (0x0)   execution time : 4.631 s

Press any key to continue.

 

 

 

 

 

#include <iostream>

 

using namespace std;

 

float lbtkg(float);

 

int main()

{

float lbs;

cout<<“Enter weight in pounds\n”; cin>>lbs;

cout<<“\nWeight in kilograms = “<<lbtkg(lbs)<<endl; //here we eliminated the kgs variable listed earlier; concise version of the earlier verbose one

 

return 0;

}

 

float lbtkg(float pounds)

{

 

return 0.453592*pounds; //here also we eliminated kilograms;; brevity-vs-clarity is a question of style

}

 

 

Enter weight in pounds

1000

 

Weight in kilograms = 453.592

 

Process returned 0 (0x0)   execution time : 2.377 s

Press any key to continue.

 

 

 

 

 

 

#include <iostream>

 

using namespace std;

 

struct dist

{

int ft;

float in;

};

 

 

dist addeng(dist, dist); //here the function is returning a structure and accepting 2 structure arguments

void edisp(dist);

 

int main()

{

dist d1,d2,d3;

 

cout<<“Enter first distance feet\n”; cin>>d1.ft;

cout<<“Enter first distance inches\n”; cin>>d1.in;

cout<<“Enter second distance feet\n”; cin>>d2.ft;

cout<<“Enter second distance inches\n”; cin>>d2.in;

 

d3=addeng(d1,d2);

 

cout<<“\n”;

edisp(d1);

 

cout<<” + “;

edisp(d2);

 

cout<<” = “;

edisp(d3);

 

 

cout<<endl;

 

 

 

return 0;

}

 

dist addeng(dist dd1, dist dd2)

{

dist dd3;

dd3.in=dd1.in+dd2.in;

dd3.ft=0;

if(dd3.in>12)

{

dd3.in-=12;

dd3.ft++;

}

 

dd3.ft+=dd1.ft+dd2.ft;

 

return dd3;

 

}

 

void edisp(dist dd)

{

cout<<dd.ft<<“\’-“<<dd.in<<“\””;

}

 

 

 

 

 

Enter first distance feet

14

Enter first distance inches

4

Enter second distance feet

20

Enter second distance inches

11

 

14′-4″ + 20′-11″ = 35′-3″

 

Process returned 0 (0x0)   execution time : 9.848 s

Press any key to continue.

 

 

 

 

 

#include <iostream>

using namespace std;

 

int main()

{

void intfrac(float, float&, float&); //that’s called passing by reference; adding ampersand after float makes it reference

float n,ip,fp;

 

cout<<“Enter a real number\n”;

cin>>n;

 

intfrac(n,ip,fp); //calling the function which has access to the variable, not only its value (in fact its memory location)

 

cout<<“Integer part is: “<<ip<<” and fractional part is: “<<fp<<endl;

 

return 0;

}

 

void intfrac(float num, float& intprt, float& fracprt)

{

long temp=static_cast<long>(num); //casting float to int gives us the integer part only

intprt=static_cast<float>(temp); //now the variable is updated in main() too

fracprt=n-ip; //note that intprt and ip and fracprt and fp are names for same variables in memory

 

}

 

 

 

Enter a real number

18.743215

Integer part is: 18 and fractional part is: 0.743216

 

Process returned 0 (0x0)   execution time : 5.362 s

Press any key to continue.

 

 

 

 

 

#include <iostream>

using namespace std;

 

 

int main()

{

void order(int&, int&); //prototype:: passing by reference

int n1=99,n2=11,n3=22,n4=88;

 

order(n1,n2); //order the numbers ascending

order(n3,n4);

 

cout<<“n1=”<<n1<<“\tn2=”<<n2<<“\nn3=”<<n3<<“\tn4=”<<n4<<endl;

 

return 0;

}

 

void order(int& num1, int& num2)

{

if(num1>num2)

{

int temp=num1;

num1=num2;

num2=temp;

}

}

 

 

n1=11   n2=99

n3=22   n4=88

 

Process returned 0 (0x0)   execution time : 0.699 s

Press any key to continue.

 

 

 

 

 

 

 

 

#include <iostream>

using namespace std;

 

struct dist

{

int ft;

float in;

};

 

void edisp(dist);

void scale(dist&, float);

 

int main()

{

dist d1={12,6.5},d2={10,5.5};

 

cout<<“d1 = “;

edisp(d1);

 

cout<<“\nd2 = “;

edisp(d2);

 

scale(d1,0.5);

scale(d2,0.25);

 

cout<<“\nd1 = “;

edisp(d1);

 

cout<<“\nd2 = “;

edisp(d2);

 

cout<<endl;

 

return 0;

}

 

void scale(dist& dd, float fac)

{

float inch=(dd.ft*12+dd.in)*fac;

dd.ft=static_cast<int>(inch/12);

dd.in=inch-dd.ft*12;

}

 

void edisp(dist dd)

{

cout<<dd.ft<<“\’ – “<<dd.in<<“\””;

}

 

 

d1 = 12′ – 6.5″

d2 = 10′ – 5.5″

d1 = 6′ – 3.25″

d2 = 2′ – 7.375″

 

Process returned 0 (0x0)   execution time : 0.345 s

Press any key to continue.

 

Overloaded functions

 

 

#include <iostream>

using namespace std;

 

void repchar();

void repchar(char);

void repchar(char, int);

 

int main()

{

repchar();

repchar(‘=’);

repchar(‘+’,30);

 

return 0;

}

 

void repchar()

{

for(int j=0;j<45;j++)

cout<<“*”;

cout<<endl;

}

 

void repchar(char ch)

{

for(int j=0;j<45;j++)

cout<<ch;

cout<<endl;

}

 

void repchar(char ch, int x)

{

for(int j=0;j<x;j++)

cout<<ch;

cout<<endl;

}

 

 

 

*********************************************

=============================================

++++++++++++++++++++++++++++++

 

Process returned 0 (0x0)   execution time : 0.457 s

Press any key to continue.

 

 

 

 

 

#include <iostream>

using namespace std;

 

struct dist

{

int ft;

float in;

};

 

void edisp(dist);

void edisp(float);

 

int main()

{

dist d1;

float d2;

 

cout<<“Enter first distance feet\n”; cin>>d1.ft;

cout<<“Enter first distance inches\n”; cin>>d1.in;

cout<<“Enter second distance in inches\n”; cin>>d2;

 

cout<<“\nd1 = “;

edisp(d1);

 

cout<<“\nd2 = “;

edisp(d2);

 

cout<<endl;

 

return 0;

}

 

void edisp(dist dd)

{

cout<<dd.ft<<“\’ – “<<dd.in<<“\””;

}

 

void edisp(float dd)

{

int feet=static_cast<int>(dd/12);

float inch=dd-feet*12;

cout<<feet<<“\’ – “<<inch<<“\””;

}

 

 

 

 

 

Enter first distance feet

16

Enter first distance inches

8.6

Enter second distance in inches

86

 

d1 = 16′ – 8.6″

d2 = 7′ – 2″

 

Process returned 0 (0x0)   execution time : 16.630 s

Press any key to continue.

 

 

Inline functions

 

#include <iostream>

using namespace std;

 

inline float lbtkg(float pounds) //making the function an inline one

{

return 0.453592*pounds;

}

 

 

int main()

{

float kgs,lbs;

cout<<“Enter weight in pounds\n”; cin>>lbs;

kgs=lbtkg(lbs);

cout<<“\nWeight in kilograms = “<<kgs<<endl;

 

return 0;

}

 

 

 

Enter weight in pounds

500

 

Weight in kilograms = 226.796

 

Process returned 0 (0x0)   execution time : 2.392 s

Press any key to continue.

 

 

Default arguments

 

#include <iostream>

using namespace std;

 

void repchar(char ch=’*’, int x=50); //assigning default values to the function arguments

 

int main()

{

repchar(); //we can call it without any arguments

repchar(‘=’); //or give one argument; the compiler will assume we don’t supply the LAST argument

repchar(‘+’,30);

 

return 0;

}

 

void repchar(char ch, int x)

{

for(int j=0;j<x;j++)

cout<<ch;

cout<<endl;

}

 

 

 

**************************************************

==================================================

++++++++++++++++++++++++++++++

 

Process returned 0 (0x0)   execution time : 0.400 s

Press any key to continue.

 

 

 

Variables and Storage Classes

 

Automatic

 

void function1()

{

auto int var1; //default variable storage class is automatic (no need to add auto before int)

auto float var2 //automatic variables are created when the function is called and destroyed when control gets back to main; its lifetime is time of executing; automatic variables visibility (or scope) is local; only within the function; automatic variables are initiated to 0 or any other garbage value

}

 

External

 

#include <iostream>

using namespace std;

 

int x,y; //external variables are seen by the whole program

char c; //their lifetime is the time of the program

int main()

{

x=10 ; //they are initalized to 0

 

return 0;

}

 

void function1()

{

c=’h’;

}

void function2()

{

cout<<c;

}

 

 

 

Static

 

float function1()

{

static int var1; //static variables are created when the function is called but never destroyed

auto float var2 //

}

 

 

  Automatic Static Auto
Visibility Function Function File
Lifetime Function Function Program
Initialized value Not initialized 0 0
Storage Stack Heap Heap
Purpose Variable used by single function Same as auto, but keeps it value even when function terminate Used by many functions in the program

 

 

Returning by reference

 

#include <iostream>

using namespace std;

 

int x; //global variable

 

int& setx(); //that’s a function that returns by reference

 

 

int main()

{

setx()=92; //here, the function is on left side of equal sign because a function that returns by reference is treated as a variable

cout<<“x=”<<x;

 

return 0;

}

 

int& setx()

{

return x; //note that the return statement must return a variable, not a constant (you cant say return 5) and the variable can’t be automatic

}

 

 

 

 

 

x=92

Process returned 0 (0x0)   execution time : 0.365 s

Press any key to continue.

 

 

 

Const function arguments

 

#include <iostream>

using namespace std;

 

void function1(int& a, const int& b); //here b is constant argument, when passed to function1, can’t be modified

 

 

int main()

{

int alpha=9, beta=8;

function1(alpha,beta);

 

return 0;

}

 

function1(int& a, const int& b)

{

a=20;

b=13; //this creates an error; we can’t modify it!

}

 

 

 

 

 

D:\cg\main.cpp|18|error: assignment of read-only reference ‘b’|

||=== Build failed: 4 error(s), 1 warning(s) (0 minute(s), 2 second(s)) ===|

5. Objects & Classes

 

 

 

#include <iostream>

using namespace std;

 

class class1 //declaring a class; key feature of OOP is having data and functions in 1 entity

{

private: //private means it can be accessed ONLY within this class

int somedata; //member data of the class

public: //public means it can be accessed within the program

void setdata(int d) //member functions

{

somedata=d;

}

void showdata() //member functions are normally inline functions

{

cout<<“Data is “<<somedata<<endl;

}

};

 

int main()

{

class1 obj1, obj2; //defining 2 objects of the class class1 that are instances of the same class

 

obj1.setdata(1200); //calling the first function in the object with passing 1200 as an argument

obj2.setdata(1500);

 

obj1.showdata(); //calling second function of the object (note using the dot operator)

obj2.showdata();

 

return 0;

}

 

 

Data is 1200

Data is 1500

 

Process returned 0 (0x0)   execution time : 0.217 s

Press any key to continue.

 

 

 

 

#include <iostream>

using namespace std;

 

class part

{

private:

int modelnumber, partnumber;

float cost;

public:

void setpart(int mn, int pn, float c)

{

modelnumber=mn;

partnumber=pn;

cost=c;

}

void showpart()

{

cout<<“Model “<<modelnumber<<“, part number “<<partnumber<<” costs $”<<cost<<endl;

}

};

 

int main()

{

part p1;

 

p1.setpart(74123, 542, 127.18F);

 

p1.showpart();

 

 

return 0;

}

 

 

 

Model 74123, part number 542 costs $127.18

 

Process returned 0 (0x0)   execution time : 0.380 s

Press any key to continue.

 

 

 

#include <iostream>

#include<msoftcon.h> //needed for graphics functions; note: must add msoftcon.cpp source file to the project

using namespace std;

 

class circle

{

protected:

int xC,yC,rad;

color fcol;

fstyle fsty;

 

public:

void circset(int x, int y, int r, color fc, fstyle fs)

{

xC=x;

yC=y;

rad=r;

fcol=fc;

fsty=fs;

}

void circdrw()

{

set_color(fcol);

set_fill_style(fsty);

draw_circle(xC,yC,rad);

}

 

};

 

int main()

{

init_graphics();

 

circle c1, c2, c3;

 

c1.circset(15,7,5,cBLUE,X_FILL);

c2.circset(41,12,7,cRED,O_FILL);

c3.circset(65,18,4,cGREEN,MEDIUM_FILL);

 

c1.circdrw();

c2.circdrw();

c3.circdrw();

 

 

return 0;

}

 

 

 

 

 

 

 

C++ Objects as data types

 

 

#include <iostream>

using namespace std;

 

class dist

{

private:

int feet;

float inch;

public:

void setdist(int ft, float in)

{

inch=in;

feet=ft;

}

void getdist()

{

cout<<“Enter distance feet “; cin>>feet;

cout<<“\nEnter distance inch “; cin>>inch;

}

void dispdist()

{

cout<<“\nFeet = “<<feet<<“\’ – “<<inch<<“\””<<endl;

}

 

};

 

int main()

{

dist d1, d2;

 

d1.setdist(16,5.3);

d2.getdist();

 

cout<<“\nFirst distance:”;

d1.dispdist();

cout<<“\nSecond distance:”;

d2.dispdist();

 

 

return 0;

}

 

 

 

 

 

 

Enter distance feet 19

 

Enter distance inch 3.4

 

First distance:

Feet = 16′ – 5.3″

 

Second distance:

Feet = 19′ – 3.4″

 

Process returned 0 (0x0)   execution time : 4.681 s

Press any key to continue.

 

 

 

 

 

Constructors

 

 

#include <iostream>

using namespace std;

 

class Counter

{

private:

unsigned int cntr;

public:

Counter() : cntr(0) // that’s z constructor; its name must be exactly same as class and doesn’t return any variables; here we initialize the variable cntr to 0 in the statement cntr(0); if you have multiple variables to initialize, separate them with commas like: v1(3), v2(9), v3(13)

{

cout<<“I’m the constructor\n”;

}

void incrC()

{

cntr++;

}

int getC()

{

return cntr;

}

 

};

 

int main()

{

Counter c1, c2; //creating the 2 objects will also run the constructors immediately

 

cout<<“\nInitially:\nC1 = “<<c1.getC();

cout<<“\nC2 = “<<c2.getC()<<endl;

 

c1.incrC();

c2.incrC();

c2.incrC();

c2.incrC();

 

cout<<“\nFinally:\nC1 = “<<c1.getC();

cout<<“\nC2 = “<<c2.getC()<<endl;

 

 

return 0;

}

 

 

 

 

I’m the constructor

I’m the constructor

 

Initially:

C1 = 0

C2 = 0

 

Finally:

C1 = 1

C2 = 3

 

Process returned 0 (0x0)   execution time : 0.096 s

Press any key to continue.

 

 

 

 

 

 

 

 

#include <iostream>

#include<msoftcon.h> //needed for graphics functions; note: must add msoftcon.cpp source file to the project

using namespace std;

 

class circle

{

protected:

int xC,yC,rad;

color fcol;

fstyle fsty;

 

public:

circle(int x, int y, int r, color fc, fstyle fs) : xC(x), yC(y), rad(r), fcol(fc), fsty(fs) //here the constructor initializes the variables with the arguments passed to it when the objects are created

{

 

}

 

void circdrw()

{

set_color(fcol);

set_fill_style(fsty);

draw_circle(xC,yC,rad);

}

 

};

 

 

int main()

{

init_graphics();

 

circle c1(15,7,5,cBLUE,X_FILL), c2(41,12,7,cRED,O_FILL), c3(65,18,4,cGREEN,MEDIUM_FILL); //creating the objects while passing arguments for constructors to initialize variables

 

c1.circdrw();

c2.circdrw();

c3.circdrw();

 

return 0;

}

 

 

 

 

 

 

 

Destructors

 

class class1

{

private:

int x,y;

public:

class1() : x(1), y(6) //constructor as before

{    }

-class1()  //that’s a destructor; carries same name of class with a tilde – before it

{    }

 

};

 

 

 

Objects as function arguments

 

 

#include <iostream>

using namespace std;

 

class dist

{

private:

int feet;

float inch;

public:

dist():feet(0), inch(0.0) //that’s z no-argument constructor; note that in case you didn’t create a constructor, there’s a “default” constructor

{

 

}

dist(int ft, float in) : feet(ft), inch(in) //constructor overloading!

{

 

}

 

void getdist()

{

cout<<“Enter distance feet “; cin>>feet;

cout<<“\nEnter distance inch “; cin>>inch;

}

void dispdist()

{

cout<<“\nFeet = “<<feet<<“\’ – “<<inch<<“\””<<endl;

}

void adddist(dist, dist); //declaring a function that is to be defined outside z class; note that it has 2 arguments as objects

 

};

void dist::adddist(dist d2, dist d3) //see the :: that’s called scope resolution operator; it tells us that adddist function is associated with the dist class

{

inch=d2.inch+d3.inch; //note that inch and feet variables here are those of the object for which the function is called

feet=0;

if(inch>=12)

{

inch-=12;

feet++;

}

feet+=d2.feet+d3.feet;

}

 

int main()

{

dist d1, d3; //here the no-argument constructor

dist d2(21,7.34); //here the 2 arguments constructor

 

d1.getdist();

 

d3.adddist(d1,d2);

 

cout<<“\nFirst distance:”;

d1.dispdist();

cout<<“\nSecond distance:”;

d2.dispdist();

cout<<“\nTotal distance:”;

d3.dispdist();

 

return 0;

}

 

 

 

Enter distance feet 14

 

Enter distance inch 9.21

 

First distance:

Feet = 14′ – 9.21″

 

Second distance:

Feet = 21′ – 7.34″

 

Total distance:

Feet = 36′ – 4.55″

 

Process returned 0 (0x0)   execution time : 18.879 s

Press any key to continue.

 

 

 

The default copy constructor

 

#include <iostream>

using namespace std;

 

class dist

{

private:

int feet;

float inch;

public:

dist():feet(0), inch(0.0)

{

 

}

dist(int ft, float in) : feet(ft), inch(in)

{

 

}

 

void getdist()

{

cout<<“Enter distance feet “; cin>>feet;

cout<<“\nEnter distance inch “; cin>>inch;

}

void dispdist()

{

cout<<“\nFeet = “<<feet<<“\’ – “<<inch<<“\””<<endl;

}

 

};

 

int main()

{

dist d1(15,23.14);

dist d2(d1); //note that we didn’t define a 1-argument constructor in our class; however, this works fine thanks to the default copy constructor

dist d3=d1; //note that this is NOT an assignment operator

 

cout<<“\nFirst distance:”;

d1.dispdist();

cout<<“\nSecond distance:”;

d2.dispdist();

cout<<“\nThird distance:”;

d3.dispdist();

 

return 0;

}

 

 

 

 

First distance:

Feet = 15′ – 23.14″

 

Second distance:

Feet = 15′ – 23.14″

 

Third distance:

Feet = 15′ – 23.14″

 

Process returned 0 (0x0)   execution time : 0.473 s

Press any key to continue.

 

 

 

 

 

 

 

 

 

Returning objects from functions

 

 

#include <iostream>

using namespace std;

 

class dist

{

private:

int feet;

float inch;

public:

dist():feet(0), inch(0.0)

{

 

}

dist(int ft, float in) : feet(ft), inch(in)

{

 

}

 

void getdist()

{

cout<<“Enter distance feet “; cin>>feet;

cout<<“\nEnter distance inch “; cin>>inch;

}

void dispdist()

{

cout<<“\nFeet = “<<feet<<“\’ – “<<inch<<“\””<<endl;

}

dist adddist(dist); //now this function will return object of class dist

 

};

dist dist::adddist(dist d2) //note here the function is accepting only 1 argument and returning an object of dist class

{

dist temp; //temporary object of class dist (no argument; inch and feet are initialized to 0)

temp.inch=inch+d2.inch; //here inch variable is of the object for which adddist function is called

if(temp.inch>=12)

{

temp.inch-=12;

temp.feet=1;

}

temp.feet+=feet+d2.feet;

return temp;

}

 

int main()

{

dist d2(15,4.14);

dist d1,d3;

 

d1.getdist();

d3=d1.adddist(d2); //here, in adddist function, the inch and feet variables are of the d1 object, so it adds them to those of the argument passed here, the d2 and the function returns the temp object and assigns it to d3 object

 

cout<<“\nFirst distance:”;

d1.dispdist();

cout<<“\nSecond distance:”;

d2.dispdist();

cout<<“\nTotal distance:”;

d3.dispdist();

 

return 0;

}

 

 

 

 

Enter distance feet 30

 

Enter distance inch 9.14

 

First distance:

Feet = 30′ – 9.14″

 

Second distance:

Feet = 15′ – 4.14″

 

Total distance:

Feet = 46′ – 1.28″

 

Process returned 0 (0x0)   execution time : 14.693 s

Press any key to continue.

 

 

Card game example

 

#include <iostream>

using namespace std;

 

const int jack=11, queen=12, king=13, ace=14;

 

enum suit {clubs=1, diamonds, hearts, spades};   //enumerators, remember?

 

class card

{

private:

int num;

suit st;

public:

card()

{

 

}

card(int n, suit s) : num(n), st(s)

{

 

}

 

void disp();

bool iseq(card);

};

 

void card::disp()

{

if(num>=2 && num<=10)

cout<<num<<” of “;

else

switch(num)

{

case jack: cout<<“jack of “; break;

case queen: cout<<“queen of “; break;

case king: cout<<“king of “; break;

case ace: cout<<“ace of “; break;

}

switch(st)

{

case clubs: cout<<“clubs”; break;

case diamonds: cout<<“diamonds”; break;

case hearts: cout<<“hearts”; break;

case spades: cout<<“spades”; break;

}

}

 

bool card::iseq(card c2)

{

return (num==c2.num && st==c2.st) ? true : false; //check if the num and st of the object for which the function is called matches those of the object passed as argument (c2 here)

}

 

int main()

{

card temp,chosen,prize;

int pos;

 

card card1(7,clubs);

cout<<“Card 1 is the “;

card1.disp();

 

card card2(jack, hearts);

cout<<“\nCard 2 is the “;

card2.disp();

 

card card3(ace, spades);

cout<<“\nCard 3 is the “;

card3.disp();

 

prize=card3;

 

cout<<“\n\nI’m swapping card 1 and card 3\n”;

temp=card3; card3=card1; card1=temp;

 

cout<<“I’m swapping card 2 and card 3\n”;

temp=card3; card3=card2; card2=temp;

 

cout<<“I’m swapping card 1 and card 2\n”;

temp=card2; card2=card1; card1=temp;

 

cout<<“\nWhere is the “;

prize.disp();

cout<<” ? “;

cin>>pos;

 

switch(pos)

{

case 1: chosen=card1; break;

case 2: chosen=card2; break;

case 3: chosen=card3; break;

}

 

if(chosen.iseq(prize))

cout<<“\nCorrect! You win!\n”;

else

cout<<“\nSorry! You lose!\n”;

 

cout<<“You chose “;

chosen.disp();

cout<<endl;

 

return 0;

}

 

 

 

 

 

 

 

Card 1 is the 7 of clubs

Card 2 is the jack of hearts

Card 3 is the ace of spades

 

I’m swapping card 1 and card 3

I’m swapping card 2 and card 3

I’m swapping card 1 and card 2

 

Where is the ace of spades ? 3

 

Sorry! You lose!

You chose jack of hearts

 

Process returned 0 (0x0)   execution time : 9.067 s

Press any key to continue.

 

 

 

 

Card 1 is the 7 of clubs

Card 2 is the jack of hearts

Card 3 is the ace of spades

 

I’m swapping card 1 and card 3

I’m swapping card 2 and card 3

I’m swapping card 1 and card 2

 

Where is the ace of spades ? 2

 

Correct! You win!

You chose ace of spades

 

Process returned 0 (0x0)   execution time : 3.083 s

Press any key to continue.

 

 

 

 

 

Structures and classes

 

class cls

{

private: //private keyword is unnecessary since the default is to be private

int num;

public:

void func();

};

 

 

struct cls //we can use structure as classes, but not preferred (classes for data & functions where structure for data)

{

void func();

private: //private keyword is a must since default is public

int num;

};

 

 

 

Static class data – object, classes and memory

 

#include <iostream>

using namespace std;

 

class blue

{

private:

static int counter; //static variable is created only once for all objects (compare to automatic variables that each object has a separate set of; note that member functions are created only once for all objects)

public:

blue() //the constructor increments the counter

{

counter++;

}

int getcount()

{

return counter;

}

};

 

int blue::counter=0; //NOTE: static variable MUST be defined outside the class (only declared inside the class)

 

int main()

{

blue b1, b2, b3; //creating 3 objects will increment the counter to 3; if counter were automatic, it would b 1

 

cout<<“Counter is: “<<b1.getcount();

cout<<endl;

 

cout<<“Counter is: “<<b2.getcount();

cout<<endl;

 

cout<<“Counter is: “<<b3.getcount();

cout<<endl;

 

 

 

return 0;

}

 

 

 

 

 

 

 

Counter is: 3

Counter is: 3

Counter is: 3

 

Process returned 0 (0x0)   execution time : 0.401 s

Press any key to continue.

 

 

const and classes

 

#include <iostream>

using namespace std;

 

class dist

{

private:

int feet;

float inch;

public:

dist():feet(0), inch(0.0) //no-argument constructor

{    }

dist(int ft, float in) : feet(ft), inch(in) //2-argument constructor

{    }

 

void getdist()

{

cout<<“Enter distance feet “; cin>>feet;

cout<<“\nEnter distance inch “; cin>>inch;

}

void dispdist() const //adding the const keyword will prevent this function from modifying any object data

{

cout<<“\nFeet = “<<feet<<“\’ – “<<inch<<“\””<<endl;

}

dist adddist(const dist&) const; //for the function to be const, its arguments should be const too as shown

 

};

dist dist::adddist(const dist& d2) const//note here we must add const keyword too

{

dist temp;

temp.inch=inch+d2.inch;  //a statement like feet=0 or d2.inch=0.0 will flag an error

if(temp.inch>=12)

{

temp.inch-=12;

temp.feet=1;

}

temp.feet+=feet+d2.feet;

return temp;

}

 

int main()

{

dist d2(15,4.14);

dist d1,d3;

 

d1.getdist();

d3=d1.adddist(d2);

 

cout<<“\nFirst distance:”;

d1.dispdist();

cout<<“\nSecond distance:”;

d2.dispdist();

cout<<“\nTotal distance:”;

d3.dispdist();

 

return 0;

}

 

 

 

 

const objects

 

#include <iostream>

using namespace std;

 

class dist

{

private:

int feet;

float inch;

public:

 

void getdist() //for a const object, such a non-const function can’t operate

{

cout<<“Enter distance feet “; cin>>feet;

cout<<“\nEnter distance inch “; cin>>inch;

}

void dispdist() const //defining a const object will make ONLY const function operate

{

cout<<“\nFeet = “<<feet<<“\’ – “<<inch<<“\””<<endl;

}

};

 

int main()

{

const dist football(300,0); //const object

 

//football.getdist(); //ERROR!

 

cout<<“Football  =  “;

football.dispdist();//this works fine, since dispdist is a const function

 

return 0;

}

 

 

 

6. Arrays & Strings

 

Arrays Fundamentals

 

#include <iostream>

using namespace std;

 

int main()

{

int age[4]; //defining an array of type integer and size 4; they are called elements (compare to structure “members”)

 

for(int j=0;j<4;j++)

{

cout<<“\nEnter an age “;

cin>>age[j];  //j is the array index

}

 

cout<<endl;

 

for(int i=0;i<4;i++)

cout<<“Age#”<<i+1<<” is: “<<age[i]<<endl;

 

return 0;

}

 

 

 

 

 

 

Enter an age 30

 

Enter an age 19

 

Enter an age 51

 

Enter an age 48

 

Age#1 is: 30

Age#2 is: 19

Age#3 is: 51

Age#4 is: 48

 

Process returned 0 (0x0)   execution time : 6.099 s

Press any key to continue.

 

 

 

 

 

#include <iostream>

using namespace std;

 

int main()

{

const int s=6;

 

double prices[s];

 

cout<<“Enter prices for 6 days”<<endl;

 

for(int j=0;j<s;j++)

{

cin>>prices[j];

}

 

double tot=0;

 

for(int i=0;i<s;i++)

tot+=prices[i];

 

double avg=tot/s;

 

cout<<“\nAverage = “<<avg;

 

return 0;

}

 

 

 

 

 

 

Enter prices for 6 days

30

20

15.3

16.26

19.21

91.23

 

Average = 32

Process returned 0 (0x0)   execution time : 14.680 s

Press any key to continue.

 

 

 

 

 

#include <iostream>

using namespace std;

 

int main()

{

const int dym[12] = {31, 28, 31, 30, 31, 30,31,31,30,31,30,31}; //initializing an array

 

int dy,mo,tot;

 

cout<<“Enter day”<<endl;

cin>>dy;

 

cout<<“Enter month”<<endl;

cin>>mo;

 

tot=dy;

 

for(int i=0;i<mo-1;i++)

tot+=dym[i];

 

cout<<“\nTotal number of days from the beginning of the year is “<<tot<<” day(s)”<<endl;

 

return 0;

}

 

 

 

 

 

 

 

Enter day

14

Enter month

4

 

Total number of days from the beginning of the year is 104 day(s)

 

Process returned 0 (0x0)   execution time : 5.275 s

Press any key to continue.

 

 

 

 

 

 

 

Multidimensional arrays

 

#include<iostream>

#include<iomanip>

using namespace std;

 

const int districts=4;

const int months=3;

 

int main()

{

double sales[districts][months]; //defining a 2D array

 

int d,m;

 

for(d=0;d<districts;d++)

for(m=0;m<months;m++)

{

cout<<“Enter sales for district “<<d+1<<“, month “<<m+1<<“: “;

cin>>sales[d][m];

}

 

cout<<“\n\n                         Month\n              1          2          3″<<endl;

 

for(d=0;d<districts;d++)

{

cout<<“District “<<d+1;

for(m=0;m<months;m++)

cout<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<setw(10)<<sales[d][m]; //setiosflags: iosfixed to not be exponential and showpoint to always use point, setprecision(2) makes it always display 2 digits right to point and setw(10) is to set width to 10

cout<<endl;

}

 

return 0;

}

 

 

 

 

 

 

 

Enter sales for district 1, month 1: 1921.06

Enter sales for district 1, month 2: 2105.26

Enter sales for district 1, month 3: 2401.26

Enter sales for district 2, month 1: 7501.32

Enter sales for district 2, month 2: 8410.36

Enter sales for district 2, month 3: 9102.36

Enter sales for district 3, month 1: 21052.65

Enter sales for district 3, month 2: 24105.36

Enter sales for district 3, month 3: 23169.915

Enter sales for district 4, month 1: 512.3

Enter sales for district 4, month 2: 412.36

Enter sales for district 4, month 3: 654.61

 

 

Month

1          2          3

District 1   1921.06   2105.26   2401.26

District 2   7501.32   8410.36   9102.36

District 3  21052.65  24105.36  23169.92

District 4    512.30    412.36    654.61

 

Process returned 0 (0x0)   execution time : 83.367 s

Press any key to continue.

 

 

 

 

 

 

 

#include<iostream>

#include<iomanip>

using namespace std;

 

const int districts=4;

const int months=3;

 

int main()

{

double sales[districts][months]={{1624.3,16.3,169},{169.3,156,169.3258},{165.324,1697,1632.02},{165,136.21054,163.1}}; //initializing 2D array

 

int d,m;

 

 

cout<<”                        Month\n              1          2          3″<<endl;

 

for(d=0;d<districts;d++)

{

cout<<“District “<<d+1;

for(m=0;m<months;m++)

cout<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<setw(10)<<sales[d][m];

cout<<endl;

}

 

return 0;

}

 

 

 

 

 

 

 

 

 

Month

1          2          3

District 1   1624.30     16.30    169.00

District 2    169.30    156.00    169.33

District 3    165.32   1697.00   1632.02

District 4    165.00    136.21    163.10

 

Process returned 0 (0x0)   execution time : 0.629 s

Press any key to continue.

 

 

 

Arrays as function arguments

 

#include<iostream>

#include<iomanip>

using namespace std;

 

const int districts=4;

const int months=3;

 

void disp(double[districts][months] ); //functions can take arrays as argument; note that we can ignore [districts]

int main()

{

double sales[districts][months]={{1624.3,16.3,169},{169.3,156,169.3258},{165.324,1697,1632.02},{165,136.21054,163.1}}; //initializing 2D array

 

disp(sales);

 

return 0;

}

 

void disp(double arr[districts][months])

{

int d,m;

 

 

cout<<”                        Month\n              1          2          3″<<endl;

 

for(d=0;d<districts;d++)

{

cout<<“District “<<d+1;

for(m=0;m<months;m++)

cout<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<setw(10)<<arr[d][m];

cout<<endl;

}

}

 

 

 

 

 

 

Month

1          2          3

District 1   1624.30     16.30    169.00

District 2    169.30    156.00    169.33

District 3    165.32   1697.00   1632.02

District 4    165.00    136.21    163.10

 

Process returned 0 (0x0)   execution time : 0.451 s

Press any key to continue.

 

 

 

 

 

 

Arrays of structures

 

 

#include<iostream>

#include<iomanip>

using namespace std;

 

const int s=3;

 

struct part

{

int partnum;

int modelnum;

float cost;

};

 

 

 

int main()

{

part aprt[s];

int i;

 

for(i=0;i<s;i++)

{

cout<<“\nEnter model number: “;

cin>>aprt[i].modelnum;

cout<<“\nEnter part number: “;

cin>>aprt[i].partnum;

cout<<“\nEnter cost: “;

cin>>aprt[i].cost;

}

cout<<endl;

for(i=0;i<s;i++)

{

cout<<“Model number: “<<aprt[i].modelnum<<“, part number: “<<aprt[i].partnum<<” costs $”<<aprt[i].cost<<endl;

}

 

return 0;

}

 

 

 

 

 

 

 

 

 

Enter model number: 16

 

Enter part number: 23

 

Enter cost: 16.25

 

Enter model number: 16

 

Enter part number: 26

 

Enter cost: 18.62

 

Enter model number: 19

 

Enter part number: 26

 

Enter cost: 18.75

 

Model number: 16, part number: 23 costs $16.25

Model number: 16, part number: 26 costs $18.62

Model number: 19, part number: 26 costs $18.75

 

Process returned 0 (0x0)   execution time : 31.130 s

Press any key to continue.

 

 

 

 

Arrays as class member data

 

#include<iostream>

using namespace std;

 

class stackk

{

private:

static const int maxx=10;

int st[maxx];

int top;

public:

stackk()

{

top=0;

}

void push(int var)

{

st[++top]=var;

}

int pop()

{

return st[top–];

}

};

 

int main()

{

stackk s1;

 

s1.push(15);

s1.push(49);

cout<<“1: “<<s1.pop()<<endl;

cout<<“2: “<<s1.pop()<<endl;

 

s1.push(14);

s1.push(4);

s1.push(28);

s1.push(7);

cout<<“3: “<<s1.pop()<<endl;

cout<<“4: “<<s1.pop()<<endl;

cout<<“5: “<<s1.pop()<<endl;

cout<<“6: “<<s1.pop()<<endl;

 

 

return 0;

}

 

 

 

 

 

 

 

1: 49

2: 15

3: 7

4: 28

5: 4

6: 14

 

Process returned 0 (0x0)   execution time : 0.468 s

Press any key to continue.

 

 

 

 

 

Arrays of objects

 

 

#include<iostream>

using namespace std;

 

class dist

{

private:

int feet;

float inch;

public:

 

void getdist()

{

cout<<“\n    Enter distance feet “; cin>>feet;

cout<<”    Enter distance inch “; cin>>inch;

}

void dispdist() const

{

cout<<feet<<“\’ – “<<inch<<“\””<<endl;

}

};

 

int main()

{

dist dis[100]; //an array of 100 objects of class dist; take care, exceeding the 100 bound may crash the system!

int i=0;

char ans;

 

do

{

cout<<“Enter distance number “<<i+1;

dis[i++].getdist();

cout<<“\nDo another? (y/n)”;

cin>>ans;

cout<<endl;

}while(ans!=’n’);

 

for(int j=0;j<i;j++)

{

cout<<“\nDistance number “<<j+1<<” is: “;

dis[j].dispdist();

}

 

 

return 0;

}

 

 

 

 

 

 

 

 

Enter distance number 1

Enter distance feet 19

Enter distance inch 3.21

 

Do another? (y/n)y

 

Enter distance number 2

Enter distance feet 37

Enter distance inch 2.15

 

Do another? (y/n)y

 

Enter distance number 3

Enter distance feet 64

Enter distance inch 8.94

 

Do another? (y/n)n

 

 

Distance number 1 is: 19′ – 3.21″

 

Distance number 2 is: 37′ – 2.15″

 

Distance number 3 is: 64′ – 8.94”

 

Process returned 0 (0x0)   execution time : 32.237 s

Press any key to continue.

 

 

Arrays of cards

 

 

#include<iostream>

#include<cstdlib> //for srand() and rand()

#include<ctime> //for time for srand()

using namespace std;

 

const int jack=11, queen=12, king=13, ace=14;

 

enum suit {clubs, diamonds, hearts, spades};   //enumerators, remember?

 

class card

{

private:

int num;

suit st;

public:

card()

{    }

 

void set(int n, suit s)

{

num=n;

st=s;

}

 

void disp();

 

};

 

void card::disp()

{

if(num>=2 && num<=10)

cout<<num;

else

switch(num)

{

case jack: cout<<“J”; break;

case queen: cout<<“Q”; break;

case king: cout<<“K”; break;

case ace: cout<<“A”; break;

}

switch(st)

{

case clubs: cout<<char(5); break;

case diamonds: cout<<char(4); break;

case hearts: cout<<char(3); break;

case spades: cout<<char(6); break;

}

}

 

 

int main()

{

card deck[52]; //array of cards

int j,nm;

suit sut;

 

for(j=0;j<52;j++) //display the cards

{

sut=suit(j/13); //loop through 0 to 3 for 13 times (13 zeros, then 13 ones, …)

nm=(j%13)+2; //loop through 2 to 14 for 4 times

deck[j].set(nm,sut); //assigning values of number and suit for our objects

}

 

for(j=0;j<52;j++)

{

deck[j].disp();

cout<<” “;

if((j+1)%13==0) //new line every 13 cards

cout<<endl;

}

 

srand(time(NULL)); //feed random numbers with time

 

for(j=0;j<52;j++) //shuffle the cards randomly

{

int l = rand() % 52;

card temp = deck[j];

deck[j]=deck[l];

deck[l]=temp;

}

 

cout<<“\n\nShuffled:\n”;

 

for(j=0;j<52;j++) //display the shuffled cards

{

deck[j].disp();

cout<<” “;

if((j+1)%13==0)

cout<<endl;

}

 

 

return 0;

}

 

 

 

 

2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣ Q♣ K♣ A♣

2♦ 3♦ 4♦ 5♦ 6♦ 7♦ 8♦ 9♦ 10♦ J♦ Q♦ K♦ A♦

2♥ 3♥ 4♥ 5♥ 6♥ 7♥ 8♥ 9♥ 10♥ J♥ Q♥ K♥ A♥

2♠ 3♠ 4♠ 5♠ 6♠ 7♠ 8♠ 9♠ 10♠ J♠ Q♠ K♠ A♠

 

 

Shuffled:

5♣ J♥ A♠ 4♣ 9♣ 6♦ 7♣ 7♦ 9♦ Q♥ J♠ 7♠ 8♦

A♦ 6♥ 5♠ 8♣ 3♠ 5♦ 10♥ J♣ 2♠ 3♥ 7♥ Q♠ 10♣

2♥ 4♥ 9♠ Q♣ A♥ 2♦ 8♠ 3♦ K♠ 10♦ K♥ Q♦ 10♠

K♣ 6♣ 9♥ 2♣ 4♠ 8♥ J♦ 4♦ 6♠ 5♥ K♦ 3♣ A♣

 

Process returned 0 (0x0)   execution time : 0.187 s

Press any key to continue.

 

 

 

 

 

C-strings

 

 

 

7. Operator Overloading

 

 

 

8. Inheritance

 

 

 

9. Pointers

 

 

 

10. Virtual Functions

 

 

 

11. Streams & Files

 

 

 

12. Multi-file programs

 

 

 

13. Templates & Exceptions

 

 

 

14. Standard Template Library

 

 

 

15. Object-Oriented Design

 

 

 

Appendix: Necessary Notes

 

Header files needed for some library functions

#include<cstdlib>:   for setwidth( function)

#include<conio.h>:  for getche() function

 

 

 

 

Advertisements