Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

3 - C++ Programming

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 44

C++ Programming

Simple C++ Program


#include <iostream> // include header file using namespace std; int main( ) { cout << C++ is better than C. \n; // C++ Statement return 0; } // End of example

What problem do namespaces solve?


Well, suppose that you buy two different general-purpose class libraries from two different vendors, and each library has some features that you'd like to use. You include the headers for each class library:

#include "vendor1.h" #include "vendor2.h" and then it turns out that the headers have this in them: // vendor1.h ... various stuff ... class String { ... }; // vendor2.h ... various stuff ... class String { ... }; This usage will trigger a compiler error, because class String is defined twice
3

The namespace feature gets around this difficulty by means of separate named namespaces: // vendor1.h ... various stuff ... namespace Vendor1 { class String { ... }; } // vendor2.h ... various stuff ... namespace Vendor2 { class String { ... }; } There are no longer two classes named String, but instead there are now classes named Vendor1::String and Vendor2::String.
4

How would you actually use the String classes in these namespaces?
Qualify the class name with the namespace name: Vendor1::String s1, s2, s3; This usage declares three strings, each of type Vendor1::String. Another approach is to use a using directive: using namespace Vendor1; Such a directive specifies that the names in the namespace can be used in the scope where the using directive occurs. using namespace Vendor1; String s1, s2, s3; and pick up the String class found in the Vendor1 namespace.

Commonly used Header Files


< iostream > - Standard input and standard output functions <time.h> - Manupulating the time and date < fstream > - Functions that perform input from files on disk and output to files on disk < cstdlib > - Conversion of text to numbers, numbers to text, random numbers and memory allocation

Example 1
// Example - Display #include <iostream> using namespace std; int main ( ) { cout << "Hello World!"; return 0; }
Hello World!

Example 2
/* Example Display */ #include <iostream> using namespace std; int main ( ) { cout << "Hello World! "; // prints Hello World! cout << "I'm a C++ programmer"; // prints I'm a C++ programmer return 0; }
Hello World! I'm a C++ program
8

Reading Inputs through Keyboard and Finding the Average


#include <iostream> using namespace std; int main( ) { float number1, number2, sum, average; cout << Enter two numbers: ; //prompt cin >> number1; // Reads numbers cin >> number2; // from keyboard sum = number1+number2; average = sum/2; cout << sum = << sum << \n; cout << Average = << average << \n; return 0; }
9

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

10

Initialization of variables
// Initialization of variables #include <iostream> using namespace std; int main ( ) { int a=5; // initial value = 5 int b(2); // initial value = 2 int result; // initial value undetermined a = a + 3; result = a - b; cout << result; return 0; }
6

11

Introduction to strings
// String #include <iostream> #include <string> using namespace std; int main ( ) { string mystring = "This is a string"; cout << mystring; return 0; }

12

Defined Constants
#include <iostream> using namespace std; #define PI 3.14159 #define NEWLINE '\n' int main ( ) { double r=5.0; // radius double circle; circle = 2 * PI * r; cout << circle; cout << NEWLINE; return 0; } 31.4159

** You can define your own names for constants that you use very often without having to resort to memory-consuming variables, simply by using the #define preprocessor directive.

13

Compound Assignment
When we want to modify the value of a variable by performing an operation on the value currently stored in that variable we can use compound assignment operators:

Expression

Is equivalent to

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

value = value + increase;


a = a - 5; a = a / 5; price = price * (unit+1);

14

Compound Assignment Operator


// compound assignment operators #include <iostream> using namespace std; int main ( ) { int a, b=3; a = b; a+=2; // equivalent to a=a+2 cout << a; return 0; } 5

15

Increase and Decrease Operator


A++ A += 1 A = A +1 A=2 B = ++A A =3 B =3 A=2 B = A++ A =3 B =2 A-A -= 1 A = A -1 A=2 B = --A A =1 B =1 A=2 B = A-A =1 B =2
16

Relational and Equality Operators


== != > < >= <=
Equal to Not equal to Greater than Less than Greater than or equal to Less than or equal to

(7 == 5) // evaluates to false. (5 > 4) // evaluates to true. (3 != 2) // evaluates to true. (6 >= 6) // evaluates to true. (5 < 5) // evaluates to false.
17

Conditional Operators
condition ? result1 : result2

7= =5 ? 4 : 3 7= =5+2 ? 4 : 3 5>3? a:b a>b? a:b

// returns 3, since 7 is not equal to 5. // returns 4, since 7 is equal to 5+2. // returns the value of a, since 5 is greater than 3. // returns whichever is greater, a or b.

18

Conditional Operators
// conditional operator #include <iostream> using namespace std; int main ( ) { int a, b, c; a=2; b=7; c = (a>b) ? a : b; cout << c; return 0; } 7

19

Expressions and Their Types


An expression is a combination of operators, constants and variables arranged as per the rules of the language It may also include function call which return values Types of Expressions Constant expressions Integral expressions Float expressions Pointer expressions Relational expressions Logical expressions Bitwise expressions
20

Constant Expressions Consists of only constant values . 15, 20+5/2 x Integral Expressions Produces integer results after implementing all the automatic and explicit type conversions. m, m*n-5 m+x Float Expressions Produce floating point result, after all conversions. x+y 10.75 x+y/10 Pointer Expressions Produce address values. &m ptr (where m is a variable and ptr is a pointer)

21

Relational Expressions yield results of type bool which take a value true or false x <= y a+b = = c+d (Boolean expressions) Logical Expressions combine two or more relational expressions and produces bool type results a>b && x = = 10 x = = 10 || y = = 5 Bitwise Expressions used to manipulate data at bit level x << 3 y >> 1

22

Special Assignment Expressions


Chained Assignment x = ( y = 10 ); or x = y = 10; Embedded Assignment x = ( y = 50 ) + 10; Compound Assignment x += 10;

23

Control Structures

24

Control Structure

Selection

Sequence

Loop

If-else

switch

do-while

while, for

25

Simple if and if else statement


if (x == 100) cout << "x is 100"; if (x == 100) { cout << "x is "; cout << x } if (x > 0) cout << "x is positive"; else if (x < 0) cout << "x is negative"; else cout << "x is 0";

if (x == 100) cout << "x is 100"; else cout << x is not 100;
26

The while loop


// custom countdown using while #include <iostream> using namespace std; int main ( ) { int n; cout << "Enter the starting number > "; cin >> n; while (n > 0) { cout << n << ", "; -- n; } cout << "FIRE! \n"; return 0; } Enter the starting number > 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

** When creating a while-loop, we must always consider that it has to end at some point, therefore we must provide within the block some method to force the condition to become false at some point, otherwise the loop will continue looping forever.
27

The do-while loop


// number echoer #include <iostream> using namespace std; 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 (0 to end): 12345 You entered: 12345 Enter number (0 to end): 160277 You entered: 160277 Enter number (0 to end): 0 You entered: 0

**
The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end. 28

The for loop


// countdown using a for loop #include <iostream> using namespace std; int main ( ) { for (int n=10; n > 0; n --) { cout << n << ", "; } cout << "FIRE! \n"; return 0; } 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

29

The break statement


// break loop example #include <iostream> using namespace std; int main ( ) { int n; for (n=10; n>0; n--) { cout << n << ", "; if (n==3) { cout << "countdown aborted!"; break; } } return 0; }
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!

** Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end.

30

The continue statement


// continue loop example #include <iostream> using namespace std; int main ( ) { for (int n=10; n>0; n--) { if (n= =5) continue; cout << n << ", "; } cout << "FIRE!\n"; return 0; }

10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!

** The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration. For example, we are going to skip the number 5 in our countdown:
31

The goto statement


// goto loop example #include <iostream> using namespace std; int main ( ) { int n=10; loop: cout << n << ", "; n--; if (n>0) goto loop; cout << "FIRE!\n"; return 0; } 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

** goto allows to make an absolute jump to another point in the program. You should use this feature with caution since its execution causes an unconditional jump ignoring any type of nesting limitations. The destination point is identified by a label, which is then used as an argument for the goto statement. A label is made of a valid identifier followed by a colon (:)
32

The switch statement


// Demonstrates switch statement #include <iostream.h> int main( ) { unsigned short int number; cout << "Enter a number between 1 and 5: "; cin >> number; switch (number) { case 0: cout << "Too small, sorry!"; break; case 5: cout << "Good job!\n"; case 4: cout << "Nice Pick!\n"; case 3: cout << "Excellent!\n"; case 2: cout << "Masterful!\n"; case 1: cout << "Incredible!\n"; break; default: cout << "Too large!\n"; break; } cout << "\n\n"; return 0; }

Output: Enter a number between 1 and 5: 3 Excellent! Masterful! Incredible! Enter a number between 1 and 5: 8 33 Too large!

Arrays

34

Arrays
An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier.

A typical declaration for an array in C++ is: type name [elements]; int billy [5];

35

Initializing Array Elements


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

When an initialization of values is provided for an array, C++ allows the possibility of leaving the square brackets empty [ ]. In this case, the compiler will assume a size for the array that matches the number of values included between braces { }

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

36

Accessing the Values of an Array

billy[2] = 75; a= billy[2]; At this point it is important to be able to clearly distinguish between the two uses that brackets [ ] have related to arrays. They perform two different tasks: one is to specify the size of arrays when they are declared; and the second one is to specify indices for concrete array elements. ** Do not confuse these two possible uses of brackets [ ] with arrays. int billy[5]; billy[2] = 75; // declaration of a new array // access to an element of the array.

37

Array Example
#include <iostream> using namespace std; int billy [ ] = {16, 2, 77, 40, 12071}; int n, result=0; int main ( ) { for ( n=0 ; n<5 ; n++ ) { result += billy[n]; } cout << result; return 0; } 12206

38

Multidimensional Arrays
Multidimensional arrays can be described as "arrays of arrays" int jimmy [3][5];

jimmy [1][3]

39

Multidimensional Array
#define WIDTH 5 #define HEIGHT 3 int jimmy [HEIGHT][WIDTH]; int n, m; int main ( ) { for (n=0; n<HEIGHT; n++) for (m=0; m<WIDTH; m++) { jimmy[n][m] = (n+1) * (m+1); } return 0; }

40

Pointers

41

Reference Operator (&) / Dereference operator (*)


andy = 25;

fred = andy;
ted = &andy;

The variable that stores the reference to another variable is called as pointer

beth = *ted;

42

Pointers Example 1
#include <iostream> using namespace std; int main ( ) { int firstvalue, secondvalue; int * mypointer;

Firstvalue is 10 Secondvalue is 20

mypointer = &firstvalue; *mypointer = 10; mypointer = &secondvalue; *mypointer = 20;


cout << "firstvalue is " << firstvalue << endl; cout << "secondvalue is " << secondvalue << endl; return 0; }
43

44

You might also like