97
CHAPTER THREE CHAPTER THREE An Overview of An Overview of C++ C++

c++ chapter 3

Embed Size (px)

DESCRIPTION

C++ lessons chapter 3

Citation preview

Page 1: c++ chapter 3

CHAPTER THREECHAPTER THREEAn Overview of C++An Overview of C++

Page 2: c++ chapter 3

PART ONEPART ONESimple ProgramsSimple Programs

Page 3: c++ chapter 3

3.1.1 Your First C++ ProgramBefore getting into any theory, let’s look at a simple C++ program.

Page 4: c++ chapter 3

Example(1)Example(1)Program #1 – A first C++ programProgram #1 – A first C++ program..**//

Enter this program/, then compile and run itEnter this program/, then compile and run it..

/*/*

include <iostream.hinclude <iostream.h<<# #

include <conio.hinclude <conio.h<<# #

main ( ) is where program execution beginsmain ( ) is where program execution begins.. // //

( ) ( ) int mainint main

Page 5: c++ chapter 3

{{

;";" . .cout << "This is my First C++ Programcout << "This is my First C++ Program

getchgetch; ( ); ( )

return 0return 0; ;

}}

Page 6: c++ chapter 3

When run, this program displays the following text on the screen:

. This is my First C++ Program

Before we continue, it is necessary to define two terms.

source code:

which is the version of your program that humans can read. The preceding listing is an example of source code.

Object code or executable code :

which is the executable version of your program (source code) and it is created by the compiler when it compiles your program.

Page 7: c++ chapter 3

Object

Code

Source

Code

C++

Compiler

Page 8: c++ chapter 3

Exercise:Write a C++ program to print the following statement on the screen

" Hi, my name is Saied , What is your name"?

Page 9: c++ chapter 3

3.1.2 A second simple program

Example( 2)

The following program creates a variable called value, gives it the value 1023, and then display the message "This program prints the value: 1023" on the screen.

Page 10: c++ chapter 3

// //program #2 –using a variableprogram #2 –using a variable

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

# #include < conio.hinclude < conio.h<<

int mainint main( ) ( )

{{

int value ; // this declares a variableint value ; // this declares a variable

value = 1023 ; // this assigns 1023 to valuevalue = 1023 ; // this assigns 1023 to value

cout << " This program prints the valuecout << " This program prints the value;"=;"=

cout << value ; // This displays 1023cout << value ; // This displays 1023

getchgetch;( ) ;( )

return 0return 0;;

}}

Page 11: c++ chapter 3

The output of this program is:

This program prints the value = 1023

Page 12: c++ chapter 3

3.1.33.1.3 A more practical exampleA more practical example

Example( 3)Example( 3)

Write a program to convert gallons to litersWrite a program to convert gallons to liters

( (gallon = 4 litersgallon = 4 liters))

Page 13: c++ chapter 3

The program: //This program converts gallons to liters.

#include < iostream.h< #include <conio.h<

int main ( ) {

; int gallons , literscout << "Enter number of gallons;": cin >> gallons ; // this inputs from the user

liters = gallons * 4 ; // convert to liters ; cout << "Liters = " << liters

}

getch;( ) return 0;

Page 14: c++ chapter 3

The output is:

Enter number of gallons: 10

Liters = 40

Page 15: c++ chapter 3

3.1.43.1.4 A Quick ReviewA Quick ReviewLet us review the general form of a C++ programLet us review the general form of a C++ program..

# #include < iostream.hinclude < iostream.h<<

# #include <conio.hinclude <conio.h<<

( )( ) int mainint main

{{

int … , … ; // integer data typeint … , … ; // integer data type

typetype float … , … ; // floating point datafloat … , … ; // floating point data

; ; .………… .…………

; ; .………… .…………

; ; .….…………………

coutcout; -------- >>" ">>; -------- >>" ">>

getchgetch;( );( )

return 0return 0;;{{

Page 16: c++ chapter 3

ExercisesExercises::11 - -Explain the above program. And use float value instead of Explain the above program. And use float value instead of

integer valueinteger value

22 - -Write C++ program converting US dollars)$( to Egyptian Write C++ program converting US dollars)$( to Egyptian poundspounds

( (1$1$==5.525.52 Egyptian poundsEgyptian pounds))

33 - -Write C++ program converting Egyptian pounds to US dollarsWrite C++ program converting Egyptian pounds to US dollars

( ( $ $ 0.10.181159428115942 ((1Egyptian pound1Egyptian pound==

44 - -Write C++ program converting Kilo Bytes to BytesWrite C++ program converting Kilo Bytes to Bytes

( ( 11 K.B. = 1024 BK.B. = 1024 B) )

55 - -Write C++ program converting Mega Bytes to Kilo BytesWrite C++ program converting Mega Bytes to Kilo Bytes

((11 M.B.= 1024 K.BM.B.= 1024 K.B

Page 17: c++ chapter 3

6 -Write C++ program converting Gega Bytes to Mega Bytes

(1G.B. = 1024 M.B.)

7 -Write C++ program converting Tera Bytes to Gega Bytes

( 1T.B. = 1024 G.B.)

Page 18: c++ chapter 3

88 - -Correct the following statements if it has errors according Correct the following statements if it has errors according to C++ rulesto C++ rules..

/* /*commentcomment */ */

Correction is : Correction is : /*/* comment comment */*/ OR OR ////commentcomment

// ??????????*/// ??????????*/

Correction isCorrection is ??????????*/ : ??????????*/ : /*/*

But this correction is wrong: ?????????? // whyBut this correction is wrong: ?????????? // why!!!!!!

*/AAAAAA/**/AAAAAA/*

Correction is : Correction is : /*/*AAAAAAAAAAAA*/*/ OR OR ////AAAAAAAAAAAA

Page 19: c++ chapter 3

include <iostream.kinclude <iostream.k ; < ; <

Correction is: Correction is: ## include <iostream. include <iostream.hh<<

* * include <iostream.hinclude <iostream.h<<

Correction is: Correction is: ## include <iostream.h include <iostream.h<<

# #include <iosteram.hinclude <iosteram.h ;< ;<

Correction is: # include <iostCorrection is: # include <iostreream.ham.h<<

# #inklude <isotream.hinklude <isotream.h;<;<

Correction is: # inCorrection is: # incclude <ilude <iosostream.htream.h<<

# #include>conio.kinclude>conio.k>>

Correction is: # include Correction is: # include <<conio.hconio.h <<

Page 20: c++ chapter 3

int mainint main

Correction isCorrection is: int main: int main( ) ;( ) ;

ind main[ ] ;ind main[ ] ;

Correction is: inCorrection is: intt main main( ) ( ) ;;

int mainint main;} { ;} {

Correction is: int mainCorrection is: int main( )( ); ;

int mainint main( ) ( )

Correction is: int main( ) Correction is: int main( ) ;;

int mainint main ( ) ( )

Correction is: int mainCorrection is: int main ( ) ( );;

Page 21: c++ chapter 3

return oreturn o ; ;

Correction is: return Correction is: return 00 ; ;

return 0return 0 , ,

Correction is: return 0Correction is: return 0 ;;

return 0return 0;;

The statement is correct The statement is correct

Page 22: c++ chapter 3

gtchgtch ( ) ( )

Correction is : gCorrection is : geetchtch ( ) ( );;

getkhgetkh ; ( ) ; ( )

Correction is : getCorrection is : getcchh ; ( ) ; ( )

getchgetch ,( ) ,( )

Correction is : getch ( )Correction is : getch ( );;

getch ( );getch ( );

The statement is correctThe statement is correct

Page 23: c++ chapter 3

cout<"Hicout<"Hi ," ,"

Correction is : cout<Correction is : cout<<<"Hi"Hi " " ; ;

cout << "Hi";cout << "Hi";

The statement is correctThe statement is correct

cout << "Hicout << "Hi ; ;

Correction is : cout << "HiCorrection is : cout << "Hi"" ; ;

cout <<"Hicout <<"Hi ;" ;"

The statement is correctThe statement is correct

Page 24: c++ chapter 3

cin <<gallons;cin <<gallons;

Correction is : cinCorrection is : cin>>>>gallons;gallons;

cim>>gallonscim>>gallons ; ;

Correction is : ciCorrection is : cinn>>gallons>>gallons;;

cin>>gallons;cin>>gallons;

The statement is correctThe statement is correct

Page 25: c++ chapter 3

99 - -Correct the following C++ program and find its output as Correct the following C++ program and find its output as the computer dothe computer do..

# #include<iostream.hinclude<iostream.h<<

# #include<conio.hinclude<conio.h<<

( ) ( )int mainint main

int valueint value; ;

value = 100value = 100; ;

;; cout << cout << "" value = value = "" value value

; ( ); ( ) getchgetch

;; return 0return 0

Page 26: c++ chapter 3

The correction of (9)

#include<iostream.h< #include<conio.h<

) (int main {

int value ; value = 100;

; cout << " value = " <<value ; getch) ( ; return 0

}the output is value = 100

Page 27: c++ chapter 3

PART TWOPART TWOFUNCTIONSFUNCTIONS

Page 28: c++ chapter 3

A C++ program is constructed from building blocks called functions .

A function is a subroutine that contains one or more C++ statements and performs only one task .

Each function has a name that is used to call it.

In general, you can give a function whatever name you please .

Remember that there are words reserved for C++ built in functions such as main . ) (

You do not use the reserved words as a function name but you can change the reserved word )deleting some letters or adding some letters( before use it.

Page 29: c++ chapter 3

3.2.1 A Program with Two Functions3.2.1 A Program with Two Functions

The following program contains two functions : The following program contains two functions : main( ) and myfunc( ).main( ) and myfunc( ).

Before running this program, examine it closely Before running this program, examine it closely and try to figure out exactly what it displays on and try to figure out exactly what it displays on the screen.the screen.

Page 30: c++ chapter 3

Example(4)

*/ This program contains two functions :main( ) and myfunc( )

/*

# include <iostream.h<

# include <conio.h<

void myfunc;( )

int main( )

{

cout <<"In main;" ( )

( ) myfunc( ) ; // call myfunc

cout<< " Back in main;"

getch;( )

Page 31: c++ chapter 3

;; return 0return 0

}}

void myfuncvoid myfunc( ) ( )

{{

cout << " Inside myfunccout << " Inside myfunc;" ( );" ( )

}}

Page 32: c++ chapter 3

The program works like this .

First, main) ( begins, and it executes the first cout statement .

Next , main ) ( calls myfunc .) (

Next , myfunc) ( executes its cout statement, and then returns to main ) ( at the line of code immediately following the call .

Finally, main) ( executes its second cout statement and then terminates .

The output on the screen is this:

In main ) ( Inside myfunc) ( Back in main) (

As you can see, myfunc) ( does not contain a return statement and does not return a value .

In C++, functions that don’t return values are declared as void.

Page 33: c++ chapter 3

3.3.2 Function ArgumentsIt is possible to pass one or more values to a function.

A value passed to a function is called an argument.

In the programs that you have studied so far, none of the functions) main) ( and myfunc) ( (take any arguments .

However, functions in C++ can have one or more arguments .

The upper limit of an arguments number is determined by the compiler you are using, but Standard C++ specifies that a function

must be able to take at most 256 arguments .

When you create a function that takes one or more arguments, the variables that will receive those arguments must also

declared .

These variables are called parameters of the function.

Page 34: c++ chapter 3

Example(5)

//A simple program for a function of two arguments.

#include<iostream.h<

# include<conio.h<

void mul (int x , int y):

int main( )

{

mul (10,20);

mul (5 , 6);

;( mul (8 , 9

getch;( )

return 0;

Page 35: c++ chapter 3

}}

void mul (int x , int y)void mul (int x , int y)

{{

cout << x * ycout << x * y;" ">>;" ">>

}}

Page 36: c++ chapter 3

This program will print 200, 30 and 72 on the screen. When mul( ) is called, the C++ compiler copies the value of each argument into the matching parameter. That is, in the first call to mul( ), 10 is copied into x and 20 is copied into y. In the second call, 5 is copied into x and 6 into y. in the third call, 8 is copied into x and 9into y.

REMEMBER:The term argument refers to the value that is used to call a function. The variable that receives the value of an argument is called a parameter.

Page 37: c++ chapter 3

3.2.33.2.3 Functions Returning ValuesFunctions Returning ValuesMany of the C++ library functions that you use will return Many of the C++ library functions that you use will return values. Functions you write may also return values to the values. Functions you write may also return values to the calling routinecalling routine..

In C++, a function uses a return statement to return a value. In C++, a function uses a return statement to return a value. The general form of return is: Return valueThe general form of return is: Return value;;

Where value is the value being returned . To illustrate the Where value is the value being returned . To illustrate the process of functions returning values ,the last program can be process of functions returning values ,the last program can be rewritten as shown next . In this version, mul( ) returns the rewritten as shown next . In this version, mul( ) returns the product of its argumentsproduct of its arguments..

Page 38: c++ chapter 3

Example(6) //Returning a value

#include<iostream.h<

#include<conio.h<

int mul (int x , int y);

int main( )

{

; int answer

answer = mul( 10 , 11) ; // assign return value

cout<< "The answer is " << answer;

getch;( )

return0;

Page 39: c++ chapter 3

{{

// //This function returns a valueThis function returns a value..

int mul ( int x , int y)int mul ( int x , int y)

{{

return x * y ; // return product of x and yreturn x * y ; // return product of x and y

}}

The output of the program isThe output of the program is::

The answer is 110The answer is 110

Page 40: c++ chapter 3

Example(7)Write C++ program which containing 4-functions for addition ,

subtraction, multiplication and division of two numbers x , y.

The program #include<iostream.h<

#include<conio.h<

; int add (int x , int y)

; int sub (int x , int y)

; ( int mul (int x , int y

int div (int x , int y);

int main( )

{

Page 41: c++ chapter 3

int answer;

answer = add (10 , 2);

; cout <<" answer+ = " << answer

answer = sub (10 , 2);

; cout << " answer- =" << answer

answer = mul (10 , 2);

cout << " answer* = " << answer;answer = div (10 , 2);

; cout << " answer/ = " << answergetch;( )

; return 0 }

( int add ( int x , int y {

; return x+y }

Page 42: c++ chapter 3

int sub ( int x , int y) {

; return x-y }

int mul ( int x , int y) {

; return x*y }int div( int x , int y) {

; return x/y }

Page 43: c++ chapter 3

The output is:

answer+ = 12 answer- = 7 answer* = 20 answer/ = 5

3.2.4 Some Output Options

To put a new line character into a string, use this code: \n )a backslash followed by a lowercase n(.

Page 44: c++ chapter 3

Example(8)To see an example, try the following program.

*/This program demonstrates the \n code, which generates a new line/*.

#include<iostream.h<

#include<conio.h<

( ) int main

{

;" cout << "one\n

;" cout << "two\n

;" cout << "three

cout << "four;"

getch;( )

Page 45: c++ chapter 3

return 0;

}

This program produces the following output:

one

two

threefour

Example(9)Write C++ program which prints the statements Hi ,My name is Saied, What is your name?. Each statement in a separate line.

Page 46: c++ chapter 3

The program#include<iostream.h<

#include<conio.h<

int main( )

{

cout << "Hi\n; "

; " cout << "My name is Saied\n

cout << "What is your name; "

; getch( )

; return 0

}

Page 47: c++ chapter 3

Example(10)Write C++ program which containing 4-functions for addition, subtraction, multiplication and division of two numbers x , y.

The program #include<iostream.h<

#include<conio.h <

;( int add (int x , int y

; ( int sub (int x , int y

; ( int mul (int x , int y

int div (int x , int y);

int main( )

{

Page 48: c++ chapter 3

int answer ;

answer = add (10 , 2);

cout <<" answer+ = " << answer;

;( answer = sub (10 , 2

cout << "\n answer- =" << answer;

; )10 , 2 (answer = mul

; cout << "\n answer* = " << answer

answer = div (10 , 2);

; cout << "\n answer/ = " << answer

getch;( )

return 0; }

Page 49: c++ chapter 3

}

( int add ( int x , int y

{

return x+y;

}

int sub ( int x , int y)

{

return x-y;

int mul ( int x , int y)

{

; return x*y

}

Page 50: c++ chapter 3

int div( int x , int y)int div( int x , int y)

{{

return x/yreturn x/y;;

}}

Guess its outputGuess its output??

Page 51: c++ chapter 3

Exercise: 1 -Write a program which displays the following figure on the screen

* * *

* * *

* * * * * *

* * * * *

* * * * * *

* * * * * *

Page 52: c++ chapter 3

2 -Discuss the following program and find its final outputa) #include<iostream.h<

# include<conio.h<

int main ( )

{

cout << "one\n \n";

cout << "two\n \n";

"; cout <<"three\n \n

cout << "four\n \n";

getch;( )

; return 0

}

Page 53: c++ chapter 3

b) #include<iostream.h<

# include<conio.h<

int main ( )

{

"; cout <<"\n\n one \n\n

"; cout << "\n\n two \n\n

"; cout << "three\n \n

"; cout << "four\n \n

getch;( )

return 0;

}

Page 54: c++ chapter 3

PART THREEPART THREEif Statement & for Loopif Statement & for Loop

Page 55: c++ chapter 3

Conditions, Logical Expressions, and selection Conditions, Logical Expressions, and selection control Structurescontrol Structures

1.1. To be able to construct To be able to construct truetrue and and falsefalse statements statements to evaluate a given condition. to evaluate a given condition.

2. To be able to construct 2. To be able to construct ifif statements to perform a statements to perform a specified task.specified task.

3. To be able to construct 3. To be able to construct if-elseif-else statements to statements to perform a specified task. perform a specified task.

4. To be able to nested 4. To be able to nested ifif statements to perform a statements to perform a specified task.specified task.

5. To be able to design and implemente a test plan.5. To be able to design and implemente a test plan.6. To be able to debug a program with a selection 6. To be able to debug a program with a selection

control structure.control structure.

Page 56: c++ chapter 3

Conditions, Logical Expressions, and Conditions, Logical Expressions, and selection control Structuresselection control Structures

Condition

TrueFalse Statements

Executed when condition is true

Page 57: c++ chapter 3

3.3.1 The if Statement3.3.1 The if Statement

The C++ The C++ if if statement operates in much the same way that an statement operates in much the same way that an if statement operates in any other language. if statement operates in any other language. Its simplest form is : Its simplest form is :  if(condition) statement ;if(condition) statement ;  Where condition is an expression that is evaluated to be either true Where condition is an expression that is evaluated to be either true

or false.or false. In C++, true is non-zero and false is zero. If the condition is true, In C++, true is non-zero and false is zero. If the condition is true,

then the statement will execute. then the statement will execute. If it is false, then the statement will not execute.If it is false, then the statement will not execute. if(10 < 11 ) cout″ 10 is less than 11″ ;if(10 < 11 ) cout″ 10 is less than 11″ ; if(10 < 11 ) x=x+5 ;if(10 < 11 ) x=x+5 ;

Page 58: c++ chapter 3

The comparison operators:

> Greater than

>= Greater than or equal

< Less than

<= Less than or equal

== Equality

Page 59: c++ chapter 3

Example(11)The following program shows an example of the if statement. It

prompts the userfor two numbers, and reports if the first value is less than the

second.

// This program illustrates the if statement.#include<iostream.h>#include<conio.h> int main ( ) } int a , b ; cout << ″ Enter first number : ″; cin >> a ; cout << ″ Enter second number : ″; cin >> b ; if( a < b ) cout << ″First number is less than second number ″;

Page 60: c++ chapter 3

getch ( ) ; return 0 ;{

The output of this program is :

Enter first number : 4Enter second number : 9First number is less than second number

Page 61: c++ chapter 3

3.3.2 The for Loop

The for loop is used to repeat a statement a specified number of times .

Its simplest form is for ( initialization ;condition ;increment) statement ;

Here, initialization sets a loop control variable to an initial value.

Condition is an expression that is tested each time the loop repeats.As long as condition is true (non-zero), the loop keeps running. Increment is an expression that determines how the loop controlvariable is incremented each time the loop repeats.

Page 62: c++ chapter 3

Example(12)

The following program prints the numbers 1 through 100 on the screen.

//This program illustrates the for loop statement.#include<iostream.h>#include<conio.h> int main ( ) } int count ; for( count=1;count<=100;count=count+1)cout<<count<<″ ″; getch ( ) ; return 0 ; {

Page 63: c++ chapter 3

The output is :

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 5051 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

Exercise:Write a program that prints the numbers 122 through 1000 on the screen.

Page 64: c++ chapter 3

Remark:

count=count + 1 equivalent to count ++

count=count - 1 equivalent to count - -

Page 65: c++ chapter 3

3.3.3 Blocks of CodesBecause C++ is a structured language, it supports the creation ofblocks of code. A block is a logically connected group of programstatements that is treated as a unit. In C++, a code block is created by placing a sequence of statements between opening and closing curly braces. In this example,

if(x<10) } cout<<″ too low , try again″ ; cin>> x ; {

Page 66: c++ chapter 3

The two statements after the if and between the curly braces are both executed only if x is less than 10.

These two statements, together with the braces, represent a block of code.

Page 67: c++ chapter 3

Example(13)The following program uses a block of code. Enter and run the

program so that you can see the effect of the block.

//This program demonstrates a block of code.#include<iostream.h>#include<conio.h> int main ( ) } int a , b ; cout << ″ Enter first number : ″; cin >> a ; cout << ″ Enter second number : ″; cin >> b ; if( a < b ) } cout << ″First number is less than second number.\n ″; cout<<″ Their difference is : ″<<b-a ;

Page 68: c++ chapter 3

{ getch ( ) ; return 0 ;{

The output is:

Enter first number : 4Enter second number : 9First number is less than second number.Their difference is : 5

Page 69: c++ chapter 3

3.3.4 Semicolons and PositioningIn C++, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon.C++ does not recognize the end of the line as a terminator.

For example, x = y ; y = y + 1 ; mul( x , y ) ;is the same as x = y ; y = y +1 ; mul( x , y ) ;to a C++ compiler.

Exercise:Use the above section in all pervious programs.

Page 70: c++ chapter 3

PART FOURPART FOURArraysArrays

Page 71: c++ chapter 3

3.4 ARRAYSThis section discusses the array. An array is a collection of variables of the same type that are referredto by a common name.

In C++, arrays may have from one to several dimensions, although the one-dimensional array is the most common.

Page 72: c++ chapter 3

3.4.1 One-Dimensional Arrays:A one-dimensional array is a list of related variables.The general form of a one-dimensional array declaration is: type name [size] ;Here, type declares the base type of the array. The base type determines

the data type of each element that comprises the array. name defines the array name. size

defines how many elements the array will hold.

For examples, int sample [10] ;declares an integer one-dimensional array named sample that is ten

elements long.Sample[0] Sample[1] Sample[2] Sample[3] Sample[4] Sample[5] Sample[6] Sample[7] Sample[8] Sample[9]

Page 73: c++ chapter 3

Where sample[0], sample[1], sample[2], sample[3], sample[4], sample[5], sample[6], sample[7], sample[8] and sample[9] are called the elements of the sample array.

float list [7] ; declares a floating one-dimensional array named list that is seven

elements long.

List[0] List[1] List[2] List[3] List[4] List[5] List[6]

Page 74: c++ chapter 3

Example(14)The following program loads the array sample with the numbers 0through 9:

#include <iostream.h>#include <conio.h>int main ( )} int sample[10];//this reserves 10 integer elements int t; for (t=0;t<10;t++)sample[t]=t;//load the array for (t=0;t<10;t++)cout<<sample [t]<<" ";//display the array getch( ) ; return 0 ;{

Page 75: c++ chapter 3

0Sample[0]

1SAMPLE}!{

2Sample[2]

3Sample[3]

4Sample[4]

5Sample[5]

6Sample[6

7SAMLE}7]

8Sample[8

9Sample[9]

In C++, all arrays consist of contiguous memory locations. That is, all array elements reside next to each other in memory. The lowest address corresponds to the first element, and the highest address to the last element.

Page 76: c++ chapter 3

Example(14.1)#include <iostream.h>#include <conio.h>int main ( )} int sample[10];//this reserves 10 integer elements int t; for (t=0;t<10;t++)sample[t]=9-t;//load the array for(t=0;t<10;t++)cout<<"sample["<<t<<"]="<<sample[t]<<"\n ";//display the array getch( ) ; return 0 ;{

Page 77: c++ chapter 3

Example(14.2)#include <iostream.h>#include <conio.h>int main ( )} int sample[10];//this reserves 10 integer elements int t; for (t=0;t<10;t++)sample[t]=9-t;//load the array for(t=0;t<10;t++)cout<<"sample["<<t<<"]="<<sample[t]<<"\n

";//display the array getch( ) ; return 0 ;{

Page 78: c++ chapter 3

Example(15)

The following program creates an array of ten elements, assigns each element a random value, and then calculates and displays its maximum and minimum values.

#include <iostream.h>#include <iostream.h>#include <conio.h>#include <conio.h>#include <stdlib.h>//Header for the function rand( )#include <stdlib.h>//Header for the function rand( )int main ( )int main ( )}} int i, minvalue , maxvalue;int i, minvalue , maxvalue; int list[10];int list[10];

Page 79: c++ chapter 3

for (i=0;i<10;i++)list[i]=rand( ); //find minimum value minvalue =32767; for (i=0;i<10;i++)if(minvalue> list[i]) minvalue= list[i] ; cout<<"minimum value="<<minvalue<<"\n"; //find maximum value maxvalue =0; for (i=0;i<10;i++)if(maxvalue< list[i]) maxvalue=list[i]; cout<<"maximum value="<<maxvalue<<"\n"; getch( ) ; return 0 ;{

Page 80: c++ chapter 3

Example(16)Write a program to find the maximum and minimum values for the arraycalled saied with 12 elements such that:

22 4 9 55 1 6 27 15 99 3 -2 51

Page 81: c++ chapter 3

#include <iostream.h>#include <conio.h>int main ( )} int i, minvalue ,maxvalue; int saied[12]; saied[0]=22;saied[1]=4;saied[2]=9;saied[3]=55;saied[4]=1; saied[5]=6;saied[6]=27;saied[7]=15;saied[8]=99;saied[9]=3; saied[10]=-2;saied[11]=51; for (i=0;i<12;i++)cout<< saied[i]<<" "; //display the array //find minimum value minvalue=100; for (i=0;i<12;i++)if(minvalue> saied[i]) minvalue= saied[i]; cout<<"minimum value="<<minvalue<<"\n";

Page 82: c++ chapter 3

//find maximum value maxvalue=0; for (i=0;i<12;i++)if(maxvalue< saied[i]) maxvalue= saied[i]; cout<<"maximum value="<<maxvalue<<"\n"; getch( ) ; return 0 ;{

Page 83: c++ chapter 3

3.4.2Array InitializationC++ allows the initialization of arrays. The general form of array initialization

is Similar to that of other variables, as shown here: type array name [size] = } value list{ ;

Where the value list is a comma-separated list of constants that are type-compatible

with the base type of the array. The first constant will be placed in the first position of the array, the second

constant in the second position , and so on.

In the following example, a 10-element integer array is initialized with the numbers

1through 10 :

Page 84: c++ chapter 3

int i[10] =}1,2,3,4,5,6,7,8,9,10{ ;This means that i[0] will have the value 1 , and i[9] will have the value

10.

Example(16.1)Use the above notation in example(16)

#include <iostream.h>#include <conio.h>int main ( )} int i, minvalue ,maxvalue; int saied[12]=}22,4,9,55,1,6,27,15,99,3,-2,51{;for (i=0;i<10;i++)cout<< saied[i]<<" "; //display the array //find minimum value minvalue=100; for (i=0;i<12;i++)if(minvalue> saied[i]) minvalue= saied[i]; cout<<"minimum value="<<minvalue<<"\n";

Page 85: c++ chapter 3

//find maximum value maxvalue=0; for (i=0;i<12;i++)if(maxvalue< saied[i]) maxvalue= saied[i]; cout<<"maximum value="<<maxvalue<<"\n"; getch( ) ; return 0 ;{Example(17)The following program sorts an array of integers (ascending order) thatcontains random values.

// ascending order#include<iostream.h>#include<conio.h>#include<stdlib.h>int main( )

Page 86: c++ chapter 3

} int nums[10]; int a ,b ,t ,size; size=10;//number of elements to sort for (t=0;t< size; t++) nums[t]=rand( );//loading the array //displaying the array cout<<" original array is : "; for (t=0;t< size; t++) cout<<nums[t]<<" "; cout<<"\n";

//sorting the array for (a=1;a< size ;a++) for (b=size-1;b>=a ;b--)} if(nums[b-1]> nums [b])} //exchange elements t=nums[b-1]; nums[b-1]=nums[b]; nums[b]=t; { {

Page 87: c++ chapter 3

//displaying sorted array cout<<"Sorted array is: "; for (t=0;t< size; t++) cout<< nums[t]<<" "; getch( ); return 0; {

Page 88: c++ chapter 3

EXERCISE:Write a program for sorting an array of random integers (descending order) with size 10

// descending order#include<iostream.h>#include<conio.h>#include<stdlib.h>int main( ) } int nums[10]; int a ,b ,t ,size; size=10;//number of elements to sort for (t=0;t< size; t++) nums[t]=rand( );//loading the array //displaying the array cout<<" original array is : "; for (t=0;t< size; t++) cout<<nums[t]<<" "; cout<<"\n";

Page 89: c++ chapter 3

//sorting the array for (a=1;a< size ;a++) for (b=size-1;b>=a ;b--)} if(nums[b-1]< nums [b])} //exchange elements t=nums[b-1]; nums[b-1]=nums[b]; nums[b]=t; { {

//displaying sorted array cout<<"Sorted array is: "; for (t=0;t< size; t++) cout<< nums[t]<<" "; getch( ); return 0;{

Page 90: c++ chapter 3

PART FIVEPART FIVEStringString

Page 91: c++ chapter 3

3.5 StringsIn C++, a string is defined as a character array that is terminated by a null. A null is specified using ‘\0’ , and is zero. Because of the null terminator, it is necessary to declare a character arrayto be one character longer than the largest string that it would hold. Forexample, if you want to declare an array str that could hold a 10character string, you would write: char str[11] ;Specifying the size as 11 makes room for the null at the end of the string. A string constant is a list of characters enclosed in double quotes. Here are some examples:“ HELLO”“ I like C++ ““#$%@@#$”like this:

Page 92: c++ chapter 3

“ “ is called a null string. It contains only the null terminator, and no other characters.

Null strings are useful because they represent the empty string.

It is not necessary to manually add the null onto the end of string constants ;

\the C++ compiler does this for you automatically.

Therefore, the string “ HELLO” will appear in memory

H E L L O ‘\0’

Page 93: c++ chapter 3

3.5.1Reading a string from the keyboardThe easiest way to read a string entered from the keyboard is to make the array that will receive the string the target of cin statement.Example(18)The following program reads a string entered by the user://Using cin to read a string from the keyboard.#include<iostream.h>#include<conio.h>int main( ) } char str[80]; cout<<" Enter a string: "; cin>>str ; //read string from keyboard cout<< "Here is your string : "; cout<<str ; getch( ) ; return 0 ; {

Page 94: c++ chapter 3

Although this program is technically correct, there still a problem. To see what it is, run the program and try entering the string “ This is a

test “ . As you will see, when the program redisplays your string, it will show

only the word “This”, not the entire sentence. The reason for this is that the C++ I/O system stops reading a string

when the first white space character is encountered. White space characters include spaces, tabs, and new lines.To solve the white space problem, you will need to use another of C++

‘s library functions, gets( ). The general form of a gets( ) call is: gets( array name ) ;The header used by gets( ) is <stdio.h>

Page 95: c++ chapter 3

Example(19)This version of the preceding program uses gets( ) to allow the entry of the strings containing spaces.

//Using gets( ) to read a string from the keyboard.#include<iostream.h>#include<conio.h>#include<stdio.h>int main( ) } char str[80]; cout<<" Enter a string: "; gets (str) ; //read string from keyboard cout<< "Here is your string : "; cout<<str ; getch( ) ; return 0 ; {

Page 96: c++ chapter 3

Example(20)Write a program to read a string from the keyboard using cin.

The Program//Using cin to read a string from the keyboard.#include<iostream.h>#include<conio.h>int main( )} char name[80]; cout<<″What is your name? ″; cin>>name; cout<<″ Here is your name :″; cout<<name; getch( ); return 0 ; {

Page 97: c++ chapter 3

Example(20.1)Write a program to read a string from the keyboard using gets.

The Program//Using gets to read a string from the keyboard.#include<iostream.h>#include<conio.h>#include<stdio.h>int main( ) } char name[80]; cout<<" What is your name? "; gets(name) ; cout<< "Here is your name : "; cout<<name ; getch( ) ; return 0 ; {