Top Banner
06/06/22 1 Software Engineering DDE 2023 Noraimi Bin Shafie ext 4638 [email protected] Adopted from course dde2023-KST
97

Software Engineering( C++) DDE 2023

Nov 24, 2014

Download

Documents

Kilon88
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Software Engineering( C++) DDE 2023

04/08/23 1

Software Engineering

DDE 2023

Noraimi Bin Shafie

ext 4638

[email protected]

Adopted from course dde2023-KST

Page 2: Software Engineering( C++) DDE 2023

04/08/23 2

RevisionChapter 1Chapter 1

Page 3: Software Engineering( C++) DDE 2023

04/08/23 3

Revison/* This is a program that computes the sum of two integer number*/

#include <iostream.h> //this is a preprocessorMain() // include directive{

int x,y,sum;cout<<“\nEnter first number : “; // this is a promptcin>>x; // input from consolecout<<“\nEnter second number : “;sum=x+y; // adding x and ycout<<“\nSum = “<<sum; // output to consoleReturn 0; // returning the value to the environment

}

Comment

Preprocessor directive

Function name

Begin block

Function body

End block

Page 4: Software Engineering( C++) DDE 2023

04/08/23 4

Data typesData types C++ keywords Bits ranges

Integer Int 16 -32768 t 32767

Long integer Long 32

Short integer Short 8 -128 to 127

Unsigned integer Unsigned 16 0 to 65535

Character Char 8 0 to 255

Floating point Float 32 Approx 6 digits of precision

Double floating point

double 64 Approx 12 digits of precision

Page 5: Software Engineering( C++) DDE 2023

04/08/23 5

ConstantsConstant type C++ keywords

Integer Constant• short integer• integer• unsigned integer• long integer

-99 -35 0 45

- 999 –1 0 555 32767

1 256 11000 59874

203 12 3345 8989898

Character constant ‘$’,’*’,’d’,’H’

string constant “name”,”telephone”

Floating-point constants 0.008 0.254E8, 4.25E2

Page 6: Software Engineering( C++) DDE 2023

04/08/23 6

Escape Sequences

Code Meaning Code Meaning

\a Audible bell \t Horizontal tab

\b Backspace \\ Backslash

\f Form feed \’ Single quote

\n New line \” Double quote

\r Carriage return \0 Null ASCII

Page 7: Software Engineering( C++) DDE 2023

04/08/23 7

Input output stream• Must include header file <iostream.h>• cin – function for input device (from keyboard)• cout – functin for output device (display onto the screen)

example

cin>>varible; // input to one variable

cin>>variable1>>variable2>>variable3

// input to several variables.

cout<<variable; // output from one variable

//output of several items (message or variable)

cout<<item1<<item2<<item3;

Page 8: Software Engineering( C++) DDE 2023

04/08/23 8

Input output stream#include<iostream.h>

void main()

{

int a,b;

cin>>a;

cin>>a>>b;

cout>>”The value of a and b are “ << a << b;

}

Page 9: Software Engineering( C++) DDE 2023

04/08/23 9

Program Control Structure• Consist of:

– Sequence structure– Selection structure

• If structure• If-else structure• Nested if-else structure• Swicth

– Repetition structure• While• Do-while• For structure• Nested for stucture

Page 10: Software Engineering( C++) DDE 2023

04/08/23 10

Program control structureIf – else structure

If(condition)

statement1;

else

statment2;

#include<iostream.h>

void main()

{

int magic=123;

int guess;

cin>>guess;

if(guess==magic)

cout<<“$$Right$$”;

else

cout<<“!!Wrong…”;

}

Page 11: Software Engineering( C++) DDE 2023

04/08/23 11

Program control structureIf – else if structure

if(condition)

statement1;

else if(condition2)

statment2;

else if(condition3)

statement3;

else

default_statement;

#include<iostream.h>void main()

{int magic=123;int guess;cout<<"\nGuess the magic number!!!";cout<<"\nEnter the number.. : ";cin>>guess;if(guess==magic)

{ cout<<"\n Right!!!!"; cout<<magic<< "is the magic "; cout<<" number";

}else if(guess>>magic) cout<<"Wrong!!!.. Too high"; else cout<<"Wrong!!!..To low";

Page 12: Software Engineering( C++) DDE 2023

04/08/23 12

Program control structureNested IF

If(x==7)

{

if(y==3)

{

cout”\nMalaysia”;

}

}

else

cout<“\nKL”;

If(x==7)

if(y==3)

cout<<”\nMalaysia”;

else

cout<<“\nKL”;

\\else for the nearest if

Page 13: Software Engineering( C++) DDE 2023

04/08/23 13

Program control structureSwicth()

Switch(variable)

{

case constant1 : statement sequence;

break();

:

:

case constantN : statement sequence;

break();

default : statement sequence

}

• Test for equality

• No two indentical constant

• Character constant will be converted to interger

Page 14: Software Engineering( C++) DDE 2023

04/08/23 14

Program control structure

#include<iostream.h>

void main()

{

char ch;

cout<<“\n1 . Malaysia”;

cout<<endl<<“2 . KL”;

cout<<“\nEnter your choice : “;

Cin>>ch; // read the selection

// from the keyboard

}

Swicth(ch)

{

case ‘1’ : cout<<“\nMalaysia”;

break();

case ‘2’ : cout<<“\nKuala Lumpur”;

break();

default : cout<<“\nThank you”;

}

Page 15: Software Engineering( C++) DDE 2023

04/08/23 15

Program control structurefor statement

For(initialization;condition;increment)

{

statement;

}

Example:

for(x=1;x<=100;x++)

printf(“%d”,x);

• Intialization– Assignment statement to set the loop

variable

• Condition– Relational expression determines when the

loop will exit

• Increment– How the loop variable will change,

Page 16: Software Engineering( C++) DDE 2023

04/08/23 16

Program control structureWhile structure

while(condition)

{

statement;

}

* Test the condition at the top

void main()

{

int t=0;

while(t<10)

{

cout<<endl<<t;

t++;

}

}

Page 17: Software Engineering( C++) DDE 2023

04/08/23 17

Program control structureDo/While structure

do {

statement;

}

while(condition)

• Test the condition at the bottom

#include<iostream.h>

void main()

{

char ch;

do

{

cout<<“1.Malaysia”<<endl;

cout<<“2.Kuala Lumpur”<<endl;

cout<<“E.Exit”;

cin>>ch;

if(ch==‘1’)

cout<<“\nMalaysia”;

if(ch==‘2’)

cout<<“\nKuala Lumput”:

}

while(Ch!=‘E’)

}

Page 18: Software Engineering( C++) DDE 2023

04/08/23 18

Program control structureInfinite loop

#include<iostream.h>

void main()

{

while(1)

{

char ch;

cin>>ch;

if(ch==‘A’)

break;

}

}

#include<iostream.h>

void main()

{

for(;;) //loop without condition

{

char ch;

cin>>ch;

if(ch==‘A’)

break;

}

}

Page 19: Software Engineering( C++) DDE 2023

04/08/23 19

Program control stucture• //program to illustrate a selection from a menu

#include<iostream.h>#include<conio.h>main()

{ char selection; cout<<"\n Menu"; cout<<"\nA - Append"; cout<<"\nM - Modify"; cout<<"\nD - Delete"; cout<<"\nX - Exit";

cout<<"\n\nEnter your selection"; cin>>selection;

switch(selection) { case 'A' : cout<<"\nTo append a record"; break; case 'M' : cout<<"nTo modify a record"; break; case 'D' : cout<<"\nTo delete a record"; case 'X' : cout<<"\nTo exit the menu"; break; default : cout<<"\nInvalid selection"; //No break in the default case } return 0; while(!kbhit()); }

Page 20: Software Engineering( C++) DDE 2023

04/08/23 20

Tutorial 11. Write a program to convert miles to kilometers. (recall that 1 mi = 1.6093440 km)

2. Write a program to convert meter to miles.(recall that 1 mi = 1.6093440 km)

3. Write a program to convert degrees Celsius (TC) to degrees Fahrenheit (TF). (recall that TF = (9/5)TC + 32)

4. Write a program to compute the area A of rectangle with sides a and b. (recall A = a*b).

5. Write a program to compute the area A of a circle with radius r. (recall A = r2).

Temperature conversition

TF = TR – 459.67 degrees Rankin

TF = (9/5)TC + 32 degrees Fahrenheit

TR = (9/5)TK

note : TF – temperature in Fahrenheit : TR – temperature in Rankin

: TC - Temperature in Celsius : TK – temperature in Kelvin

6. Write a program to generate a table of conversion from Fahrenheit to Celsius for values from 0 degrees F to 100 degrees F. Print a line in the table for each 5-degree change. Use while loop in your solution

7. Write a program to generate a table of conversion from Fahrenheit to Kelvin for value from 0 degree F to 200 degree F. Allow the user to enter the increment in degrees Fahrenheit between lines. Use do while loop in your solution

8. Write a program to generate a table of conversion from Celsius to Rankin. Allow the user to enter the starting temperature and increment between lines. Print 25 lines in the table.

Page 21: Software Engineering( C++) DDE 2023

04/08/23 21

Header files and function

Chapter 2Chapter 2

Page 22: Software Engineering( C++) DDE 2023

04/08/23 22

Standard header files• C++ provides a set of predefined function• function stored in header files ( extension .h)• contains that related to a particular application.• example header file math.h contain function for taking

the square root, logarithm and absolute value of number• iostream.h use for cin>> and cout• include directive has a general from

#include<header file name>

exp #include<iostream.h>

#include<math.h>

Page 23: Software Engineering( C++) DDE 2023

04/08/23 23

Standard header files• Some common header files

conio.h screen handling function

dos.h dos interface function

graphics.h graphics function

iostream.h defines I/O stream class (C++)

ctype.h character-handling functions

stdio.h declaration for standard I/O stream

time.h system time function

math.h various definition used by the math library

Page 24: Software Engineering( C++) DDE 2023

04/08/23 24

Standard header files• some function in ctype.h

isupper(c) non-zero if c is uppercase letter; 0 otherwise

isdigit(c) non-zero if c is a digit; 0 otherwise

toupper(c) uppercase equivalent of c if is a letter; unchanged otherwise

tolower(c) lowercase equivalent of c if it a letter ; unchanged otherwise

Page 25: Software Engineering( C++) DDE 2023

04/08/23 25

Standard header files• some function in ctype.h#include<iostream.h>#include <ctype.h>{

char ch=‘A’;if(isupper(ch))

cout<<ch<< “ is an uppercase letter\n”;else

cout<<ch<<“ is not uppercase letter\n”;if(isdigit(ch))

cout<<ch<< “ is a digit \n”;else

cout<<ch<<“ is not a digit\n”;ch=tolower(ch);//covert to lower case

cout<<ch<<“ is a lowercase letter\n”;else

cout<<ch<<“ is not a lowercase letter \n”;return 0;

}

Page 26: Software Engineering( C++) DDE 2023

04/08/23 26

Standard header files• some function in stdlib.h

abs(i) converts to the absolute value of i

atof(i) converts (string) s to a float(double)

atoi(i) converts s to integer

atol(i) converts s to long interger

exit(i) terminates program after closing all files and buffers

rand() returns a random positive integer between 0 and RAND_MAX(32767)

srand() initialize the random number generator rand()

Page 27: Software Engineering( C++) DDE 2023

04/08/23 27

Standard header filesexample// display randomnumber between 0-9

#include<iostream.h>#include<stdlib.h>#include<conio.h>

main(){

for (int i=0;i<=10;i++){

cout<<i<<" : "<<random(10)<<endl;// } while(!kbhit()); }

Page 28: Software Engineering( C++) DDE 2023

04/08/23 28

Standard header files• some function in math.h

acos(d) arc cosine of d

asin(d) arc sin of d

atan(d) arc tangent of d

ceil(d) smallest integer greater than d

cos(d) cosine of d

exp(d) exponential of d

log(d) natural logarithm of d(d>0)

log10(d) base logarithm of d(d>0)

pow(d1,d2) d1 raised to the power of d

sqrt(d) square root of d

sin(d) sine of d

Page 29: Software Engineering( C++) DDE 2023

04/08/23 29

Standard header filesexample#include<iostream.h>#include<math.h>#include<conio.h>

// program example using the header file math.hvoid main()

{double d;

d=100.0;

cout<< "\tSquare root of "<<d<<" : "<< sqrt(d)<<endl; cout<<"\tcosine : "<<cos(d); while(!kbhit());// kbhit-keyboard hit use in header file conio}

Page 30: Software Engineering( C++) DDE 2023

04/08/23 30

Standard header filesTime.h• ctime()- convert data and time to a 26-character string such as

Wed Dec 03 09:20:35 2003example://program to uses time manipulation function#include <time.h>#include<iostream.h>#include<conio.h>void main(){do{time_t now;now = time(NULL);cout<<“\nCurrent date and time :”<<ctime(&now);

}while(!kbhit());}output : Curren date and time : Tue Jun 03 11:15:03 2003

Page 31: Software Engineering( C++) DDE 2023

04/08/23 31

User-Defined Header Files• user can defines program segments and store them in files.• include just like any standard header files in their program.• example

#include<iostrem.h>#include”myfiles.h” \\ from another program

\\ enlosed with “”, not<>{

}

Page 32: Software Engineering( C++) DDE 2023

04/08/23 32

User-Defined FunctionChapter 3Chapter 3

Page 33: Software Engineering( C++) DDE 2023

04/08/23 33

defining functionfunction definition takes the formreturn_type function_name(parameter_list){

variable declarationstatementsreturn expression

}where :• return_type is any valid C++ data type (void etc)• function_name is any valid C++ identifier• parameter_list is a list of a parameter separated by commas• variable declaration – list of variable within the function• return is a C++ keyword• expression is the value returned by the function

float average(float x, float y) // example function

Page 34: Software Engineering( C++) DDE 2023

04/08/23 34

making function calls

• when function call-program temporarily leaves the current function to execute the called function

• called function terminates; program control returns to the calling function

void main()

{

. . .

another() // call another

. . .

}

type another()

{

. . .

return // return to main()

}

Page 35: Software Engineering( C++) DDE 2023

04/08/23 35

Passing arguments to function : by value

#include<iostream.h>

void prt(int)

void main()

{

int x=12; // defines an integer variable

prt(x) // call prt() and passes it x

}

void prt(int y)// the prt() function definition

{

cout<<y; // display the value of y

}

//value x copied to y

/* any change made by called funct. d’not effect the variable in calling funct.*/

passing by value

Page 36: Software Engineering( C++) DDE 2023

04/08/23 36

Passing arguments to function : by reference

• passing by value : calling function passed arguments (values of variables) to the corresponding parameters in the called function

Page 37: Software Engineering( C++) DDE 2023

04/08/23 37

Passing arguments to function : by reference// passing argument by reference

#include<iostream.h>

void main()

{

int x, y, min,max;

void max_min(int, int, int&, int&); // funct prototype

cout<<“\t\nEnter two numbers :”;

cin>>x>>y;

// function call: x and y are passes by value;

/* max and min are passed by references; & prefix for max and min is needed*/

max_min(x,y,max,min)

cout<<“\t\nMaximum = “<<max;

cout<<“\t\nMinimum = “<<min;

}

// x and y are value parameter

// max and min are references parameters

void max_min(int x, int y, int& max, int& min)

{

if(x>y) max=x;

else max=y;

if (x<y) min=x;

else min=y;

}

Page 38: Software Engineering( C++) DDE 2023

04/08/23 38

sending values back from a function

• a function may or may not return a value

• type void• does not return a value

• not have expression part in return statement • return (variable)

• function returns a value to the calling function

Page 39: Software Engineering( C++) DDE 2023

04/08/23 39

sending values back from a function

// program 4.9 page 4-18

#include<iostream.h>

#include<conio.h>

void main()

{

do

{

char lower,upper;

char lower_to_upper(char);

cout<<"\nPlease enter a lower case character : ";

cin>>lower;

upper = lower_to_upper(lower);

cout<<"\nThe upper case equivalent is : "<<upper;

}

while(!kbhit());

}

char lower_to_upper(char c1)

{

char c2;

c2 = (c1 >= 'a' && c1 <= 'z') ? ('A' + c1 - 'a') : c1;

return(c2);

}

return value in variable c2 to

main

Page 40: Software Engineering( C++) DDE 2023

04/08/23 40

Macros

• use #define compiler directive• example to obtain area of triangle

#define area(base,height) (0.5*base*height)• area – macro name• base and height – arguments• (0.5*base*height) – macro definition

#include<iostream.h>#define area(base,height) (0.5*base*height)

void main()

{

cout<<"area = "<<area(4,6);

}

Page 41: Software Engineering( C++) DDE 2023

04/08/23 41

Inline function

• difference between ordinary function• ordinary function – does not substitute code for it wherever it is

invoked in the program• inline function – substitutes the codes for it wherever it it invoked.

• diadvantage • if the function call frequently, program become large as the

functions are automatically expanded.

Page 42: Software Engineering( C++) DDE 2023

04/08/23 42

Inline function//area of triangle using inline function

// program 4.13 pg 4-24 C++ by P. Sellapan

#include<iostream.h>

inline double triangle_area(double base, double height)// inline function

{

double area;

area=0.5 * base * height;

return area;

}

void main()

{

double b,h,a;

b=4;

h=6;

//compiler will substitute the inline function code

a=triangle_area(b,h);

cout<<"\n area = "<<a;

}

Page 43: Software Engineering( C++) DDE 2023

04/08/23 43

Arrays & StringChapter 4Chapter 4

Page 44: Software Engineering( C++) DDE 2023

04/08/23 44

Whats Is An Arrays.

• is a collection of a data elements of the same type that are referenced by a common name. All the elements of an array occupy a set of contiguous memory.

• example

mark1 = 10; mark[i]={10,14,15,9}

mark2 = 14;

mark3 = 15;

amrk4 = 9;

mark[3]mark[0]

Page 45: Software Engineering( C++) DDE 2023

04/08/23 45

one-dimensional array.

• declaration one-dimensional array, form of:

type var_name[size];

• example: to declare an array of 20 characters

char ch[20] // first location character ch[0]

// last location character ch[19]• another example

int x[20],y[50]; // declare two arrays x and y

double price[10]; // declare 10 floating point values.

Page 46: Software Engineering( C++) DDE 2023

04/08/23 46

one-dimensional array. - initialisation

• the form

type_specifier array_name[size]={value_list}• example

int id[7] = {1,2,3,4,5,6,7};

int No[]={3,4,5,2,6,7,2,9,7};

double x[5] = {5.5,4.4,3.5,6.8,1.0};

char vowel[6]= {‘a’,’e’,’I’,’o’,’u’,’\0’};

char vowel[6]=“aeiou”; // assigned char string

// C++ supply automatically supplies the NULL character(‘\0’)

Page 47: Software Engineering( C++) DDE 2023

04/08/23 47

Example :one-dimensional array.

// display the value of int Values

#include <iostream>

int main()

{

int Values[] = {1,2,3,5,8,13,21};

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

cout << Values[i] << endl;

return 0;

}

output

1

2

3

5

8

13

21

Page 48: Software Engineering( C++) DDE 2023

04/08/23 48

Example :one-dimensional array.

// program to find the total of all elements in array y

#include<iostream.h>

#define n 5 // define n=5

void main()

{

int I, total=0;

int Value[n]={9,6,20,5,12};

for (I=0;I<n;I++)

total=total+y[I];

cout<<“\nTotal = “ << total;

}

output

Total = 52

for each loop, the value accessed is added to the variable total

Page 49: Software Engineering( C++) DDE 2023

04/08/23 49

Example :one-dimensional array.

//program to find the smallest number in array balance

#include <iostream.h>

#define n 6

void main()

{

int i;

double small, balance[n]={100,25,12,75,20.4,62.12,10.1};

small = balance[0]; // insert 100 to small

for(i=1;i<n;i++)

{

if(small>balance[i])// compared small with balance

small=balance[i];

cout<<“smallest value :”<<small;

}

}

output

smallest value : 10.1

Page 50: Software Engineering( C++) DDE 2023

04/08/23 50

Example :one-dimensional array. sorting variables

1. sorting algorithm• compare first element with second elements

• if first bigger than the second : interchange• if first small than the second : no change made

2. compare the first element with third element, repeat previous step

3. continues the process of comparing with first element with all the rest of the elements, interchange them whenever an element is smaller than the current first

4. in the pass. repeat the process on the reduces list (i.e without the first element). This would place the next smallest element in the second position

5. continuous this process until we finish comparing, the second last element with last element

Page 51: Software Engineering( C++) DDE 2023

04/08/23 51

sorting variables

//this program will sort a list

#include<iostream.h>

#include<conio.h>

#define n 5

main()

{

int temp,i,j,list[n]={5,4,3,2,1};

//sort the numbers

{

for(i=0;i<n-1;i++)

for(j=i+1;j<n;j++)

if(list[i] > list[j])

{

temp = list[i]; //These three line

list[i]=list[j]; //interchange the elements

list[j]=temp; //list[i] and list[j]

}

cout<<"\nSorted list : ";

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

cout<<" "<<list[i];

}

getch();

return 0;

}

Page 52: Software Engineering( C++) DDE 2023

04/08/23 52

Two-dimensional array.

• has two subscripts(indexes)• first subscript – row• second subscript – column• takes form of :

type array_name[size1][size2]• example :

int x[3][4] // declare array with 3 rows and 4 columns

• intialize character

char name[4][10]

columns

rows 0 1 2 3

0 [0][0] [0][1] [0][2] [0][3]

1 [1][0] [1][1] [1][2] [1][3]

2 [2][0] [2][1] [2][2] [2][3]

Page 53: Software Engineering( C++) DDE 2023

04/08/23 53

Two-dimensional array.

• declaration and initialize array

int x[3][4]={1,2,3,4,5,6,7,8,9,10,11,12}

int x[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};

the result for both case above would as follows:

x[0][0]=1 x[0][1]=2 x[0][2]=3 x[0][3]=4

x[1][0]=5 x[1][1]=6 x[1][2]=7 x[1][3]=8

x[2][0]=9 x[2][1]=10 x[2][2]=11 x[2][3]=12

if the number of values assigned is insufficient to fill the whole arrays, zero would be added automatically

example int x[3][4]={1,2,3,4,5,6,7,8,9,10}

x[2][2]=0 x[2][3]=0 //added zero

Page 54: Software Engineering( C++) DDE 2023

04/08/23 54

Two-dimensional array.

• fill whole array with zero

int x[3][4]={0};• array of string

char name[3][10]={“Ah Born”,”Ah Chong”,”Ah Wie”};

Page 55: Software Engineering( C++) DDE 2023

04/08/23 55

Two-dimensional array. #include <iostream.h>

float Revenues[3][8] = {

{ 45.33, 55.55, 78.00, 37.26, 98.35, 23.55, 45.65, 22.00 },

{ 35.43, 45.45, 79.00, 30.26, 47.55, 34.65, 52.79, 32.50 },

{ 55.37, 75.05, 68.10, 31.27, 62.36, 53.56, 43.68, 24.06 }

};

int main()

{

for (int mon = 0; mon < 3; mon++)

{

cout << mon+1 << ':';

for (int cc = 0; cc < 8; cc++)

cout << ' ' << Revenues[mon][cc];

cout << endl;

}

return 0;

}

Page 56: Software Engineering( C++) DDE 2023

04/08/23 56

Two-dimensional array.

output

45.33 55.55 78.00 37.26 98.35 23.55 45.65 22.00

35.43 45.45 79.00 30.26 47.55 34.65 52.79 32.50

55.37 75.05 68.10 31.27 62.36 53.56 43.68 24.06

Page 57: Software Engineering( C++) DDE 2023

04/08/23 57

//program that multiplies matrix x and y and stores result in matix z//program 8.6 page 160 C++ through example by P.Sellapan#include<iostream.h>#include<conio.h>#define m 3#define c 2#define n 4main(){int i,j,k;int x[m][c]={1,2,3,4,5,6},

y[c][n]={7,8,9,10,11,12,13,14}, z[m][n];  for (i=0;i<m;i++) for(j=0;j<n;j++) { z[i][j]=0; for(k=0;k<c;k++) z[i][j]+=x[i][k]*y[k][j]; } cout<<"\nThe matixproduct is : "; for(i=0;i<m;i++) { cout<<"\n"; for(j=0;j<n;j++) cout<<" "<<z[i][j]; } getch(); return 0; }

Page 58: Software Engineering( C++) DDE 2023

04/08/23 58

String

• a sequence of character such as name of a person or country or a sentences

• store in arrays of type char.• predefined standard library functions – string.h and ctype.h• string constants

“Java Programming” “Malaysia”

“UTM KL” “Pulai Spring”

“123456” “&&***%888”

Page 59: Software Engineering( C++) DDE 2023

04/08/23 59

String Variables

• string variables – an array of type char that can store a sequence of characters.

• the length of the string – limited to the size of the array.

//read a string from keyboard and display it

#include<iostream.h>

void main()

{

char name[15];

cout<<“\nEnter your name : “;

cin>>name;

cout<<“\nHello “<<name;

}

//C++ automatically store NULL ‘\0’ at the end of the string!!!

Enter your name : Jamri

Hello Jamri

Page 60: Software Engineering( C++) DDE 2023

04/08/23 60

Initializing String

• initializing like array

char color[]=“purple”;• must be surrounded by double quotes.• not necessary to insert the NULL character (‘\0’)• coz C++ automatically add a NULL character to the string.• [ ] – omit the array size –save us the trouble to counting the number of

characters.

Page 61: Software Engineering( C++) DDE 2023

04/08/23 61

Initializing String

• example#include<iostream.h>

void main()

{

char name[31], greet[]=“Hello, “;

cout<<“\nEnter your name : “;

cin>>name;

cout<<greet;

cout<<name<< “ !”;

}

Enter you name : Joyah

Hello Joyah !

Page 62: Software Engineering( C++) DDE 2023

04/08/23 62

• example#include<iostream.h>

#include<conio.h>

void main()

{

char name[5]= “UTMKL”;

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

cout<<endl<<name[i];

getch();

}

U

T

M

K

L

output

Page 63: Software Engineering( C++) DDE 2023

04/08/23 63

Built in string functionstrcat() appends one string to another

strchr() scans a string for the first occurrence of a given character

strcmp(s1,s2) compares one string to another

strcmpi(s1,s2) compares one string to another without case sensitivity

strcpy(s1,s2) copies one string to another

strlen(s) calculates the length of a string

strlwr() converts uppercase to lowercase string

strrev(s) reverses the string

strset(s,c) sets all characters in a string to a given character

strstr() scans a string for the occurrence of a given sub string

Page 64: Software Engineering( C++) DDE 2023

04/08/23 64

Built-in String function• stored in the header file string.h

strcpy(x,y)• copying the content of string y into x• programmer ensure the receiving array x large enough to hold the

string contained in y.//program to copy a string

#include<iostream.h>

#include<string.h>

void main()

{

char str[];

strcpy(str,”Allooooowwww!!”);

cout<<str;

}

Allooooowwww!!

Page 65: Software Engineering( C++) DDE 2023

04/08/23 65

Built-in String functionstrcat(s1,s2)

• function appends s2 to s1• string s2 remains unchanged

• string s1 large enough to contain the new extended string

//program to copy a string

#include<iostream.h>

#include<string.h>

void main()

{

char s1[20],s2[10];

strcpy(s1,”Hello”);

strcpy(s2,”There”);

strcat(s1,s2)

cout<<s1;

}

Hello There

Page 66: Software Engineering( C++) DDE 2023

04/08/23 66

Built-in String functionstrcmp(s1,s2);

• compare two string s2 and s1• return value 0 if they are equal

• a positive number if s1 is greater then s2• negative number if s1 is less than s2

Returned Value Meaning

Less than zero s1 less than s2

Zero s1 identical s2

greater than zero s1 greater than s2

Page 67: Software Engineering( C++) DDE 2023

04/08/23 67

Built-in String function#include<iostream.h>

#include<string.h>

#include<conio.h>

 

void main()

{

char s1[31],s2[31];

cout<<"\nEnter fisrt name : ";

cin>>s1;

cout<<"\nEnter second name : ";

cin>>s2;

 

if(strcmp(s1,s2)) //Test the return value from strcmp()

cout<<"\nThe name are different.";

//display if the value is non zero (true)

else

//display if the value is zero(false)

cout<<"\nThe names are same!!";

getch();

}

Enter first name : Juliana

Enter second name : Bonos

The name are different.

Page 68: Software Engineering( C++) DDE 2023

04/08/23 68

Example// convert lower case to upper case using toupper

// convert each letter in str from lowercase to uppercase

#include<ctype.h>

#include<conio.h>

void main()

{

char str[80];

strcpy(str,“pengaturcaraan");

for(int i=0;str[i];i++)

str[i]=toupper(str[i]);

cout<<str;

getch();

}

PENGATURCARAAN

Page 69: Software Engineering( C++) DDE 2023

04/08/23 69

Example#include <iostream.h>

#include <string.h>

#include<conio.h>

int main()

{

int len;

char msg[] = "Wrong!!!";

  cout << "Password? ";

char pwd[40];

cin >> pwd;

// --- find string length

len = strlen(pwd);

// --- compare string with string constant

if (strcmp(pwd, "utm123") == 0)

// --- copy constant to message

strcpy(msg, "OK.");

cout << msg << " You typed " << len << " characters";

getch();

return 0;

}

Password? utm123

OK You typed 6 characters

Page 70: Software Engineering( C++) DDE 2023

04/08/23 70

Example//another example of string comparison

//program request input from keyboard until the word ‘quit’ is entered

#include<<iostream.h>

#include<string.h>

#include<conio.h>

main()

{

char s[80];

for (: :)

{

cout<<“Enter a string”;

get(s);

if(!strcmp(“quit”,s))

break();

}

return 0;

}

Enter a string quit

Page 71: Software Engineering( C++) DDE 2023

04/08/23 71

Array of string• to store an array of string

• use the declaration statement

char menu[6][30];

// store 6 item(string) which each string can hold maximum 29 character

• to access an individual item

cin >> menu[3];

cin >> menu[3][0];

• to display the item

cout<<menu[0];

cout<<menu[2];

Page 72: Software Engineering( C++) DDE 2023

04/08/23 72

Array of string

//program to display from an array of string

#include<<iostream.h>

void main()

{

char item[3][20] = {“Radio”,”Komputer”,”Notebook”}

cout<<endl<<item[0];

cout<<endl<<item[1];

cout<<endl<<item[2];

}

Page 73: Software Engineering( C++) DDE 2023

04/08/23 73

Array of string

example1.cpp

#include <iostream>

#include<conio.h>

 

int main()

{

char str[] = "Hello, Dolly";

int i = 0;

while (str[i] != '\0')

cout << str[i++];

getch();

return 0;

}

 

Page 74: Software Engineering( C++) DDE 2023

04/08/23 74

//enter and display strings;taken from program 5.13 pg 5-18 OOP

#include<iostream.h>

#include<string.h>

#include<conio.h>

void main()

{

int i;

char choice[30], found='0';

char menu[6][30] ={"Add","Delete","Modify","Enquiry","Help","Exit"};

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

cout<<"\n\t"<<menu[i];

cout<<"\nEnter your selection :";

cin>>choice;

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

{ if(!(strcmp(choice,menu[i])))//return value 1 for ifstatement

found = '1';

break; }

if(found=='1')

cout<<"\nItem in menu";

else

cout<<"\nItem not in the menu";

getch();

}

Page 75: Software Engineering( C++) DDE 2023

04/08/23 75

//program to sort a list of string entered by user sorted_string.cpp

#include<iostream.h>

#include<string.h>

#include<conio.h>

 

main()

{

char tname[20],name[20][20];

int i,j,n;

cout<<"\nEnter the numbers of names: ";

cin>>n;

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

{ cout<<"\nEnter the name of person :"<<i+1<<" : ";

cin>>name[i]; }

//sorting

for(i=0;i<n-1;i++)

for(j=i+1;j<n;j++)

if(strcmp(name[i],name[j])>0)

{ strcpy(tname,name[i]);

strcpy(name[i],name[j]);

strcpy(name[j],tname); }

cout<<"\nSorted by names\n";

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

cout<<"\n"<<i+1<<" : "<<name[i];

getch();

return 0;

}

Page 76: Software Engineering( C++) DDE 2023

04/08/23 76

structuresChapter 5Chapter 5

Page 77: Software Engineering( C++) DDE 2023

04/08/23 77

structure

This chapter will discuss the following:

• structure declaration

• structure manipulation

• passing structure to function

Page 78: Software Engineering( C++) DDE 2023

04/08/23 78

Declaring structure Variable• structure – a collection of related data items stored in one place and referenced

number under one name

• no all same type

• first define a template.

• example - to store and process a student record containing id, name, gander and age.

struct student

{

char id[25];

char name[25];

char gender;

int age;

}stud_1,stud_2;

declared structure template

tag that identified its data

structure elements

(members)

declaring structure variables

Page 79: Software Engineering( C++) DDE 2023

04/08/23 79

accessing structure elements• accessed by using the structure variables name, the dot operator (.) and the

desired element name.

struct student

{

char id[25];

char name[25];

char gender;

int age;

}stud_1,stud_2;• for example to access structure student above:

stud_1.name=“Kamarul Arifin”;

• assign string Kamarul Arifin to structure element name in the structure variable stud_1

struc variable

struc element

assign string

Page 80: Software Engineering( C++) DDE 2023

04/08/23 80

example3#include<iostream.h>

#include<conio.h>

 

// ---- declare a struct

struct Date {

short int month, day, year;

};

 int main()

{

Date dt; // a Date variable

// --- assign values to the struct members

dt.month = 6;

dt.day = 24;

dt.year = 1940;

// --- display the struct

cout << dt.month << '/' << dt.day << '/' << dt.year;

getch();

return 0;

}

output

6/24/1940

Page 81: Software Engineering( C++) DDE 2023

04/08/23 81

example4//initialize a structure

#include<iostream.h>

#include<conio.h>

// ---- declare a struct

struct Date {

short int month, day, year;

};

 

int main()

{

// an initialized Date variable

Date dt = { 11, 17, 1941 };

// --- display the struct

cout << dt.month << '/' << dt.day << '/' << dt.year;

getch();

return 0;

}

output

11/17/1940

Page 82: Software Engineering( C++) DDE 2023

04/08/23 82

array of structure• C++ lets create an array of structure. Example to store information of 50 student

• could use any of two structure declaration

• to print the name of the seventh student

cout>>stud[6].name;

struct student

{

char id[5];

char name[25];

char gender;

int age;

}stud[50];

struct student

{

char id[5];

char name[25];

char gender;

int age;

};

struct student stud[50];

Page 83: Software Engineering( C++) DDE 2023

04/08/23 83

example1//program structure

#include<iostream.h>

#include<conio.h>

 

struct student

{

char name[20];

int age;

};

struct student stud[2];

void main()

{

strcpy(stud[0].name,"ali bin abu");

strcpy(stud[1].name,"ghazali yahya");

 

stud[0].age=45;

stud[1].age=10;

cout<<"\n\t\tName"<<"\t\tAge";

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

{

cout<<"\n\t\t"<<stud[i].name;

cout<<"\t"<<stud[i].age;

}

cout<<endl;

getch();

}

Page 84: Software Engineering( C++) DDE 2023

04/08/23 84

example2#include<iostream.h>

#include<conio.h>

#include<stdio.h>

struct student

{

char name[20];

int age;

};

struct student stud[2];

 

void main()

{

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

{char s[20];

cout<<"\nInput next student name :";

gets(s);

strcpy(stud[i].name,s);

cout<<"\nInput next student age :";

cin>>stud[i].age;

clrscr();

}

cout<<"n\t\t\Student name "<<"\tAge";

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

{

cout<<"\n\t\t"<<stud[i].name<<"\t\t"<<stud[i].age;

}

  getch();

}

Page 85: Software Engineering( C++) DDE 2023

04/08/23 85

Passing Structure to Function• individual structure or entire structure can pass to function

• example to modify the name of the seventh student, function call could write

modify(stud[6].name);• pass structure element name of the seventh student to function modify.

• change made in called function will not effect name in calling function.

modify(stud[6]);

• copy of the structure passed to the function.

• change made in called function will not effect the structure in calling function

modify(&stud[6]);

• the address of the structure is passed.

• any change made to the structure within the called function will also change the structure in the calling function as they refer to the same memory location.

Page 86: Software Engineering( C++) DDE 2023

04/08/23 86

Passing Structure to Function -example5.cpp#include <iostream.h>

#include<conio.h>

 

struct Date {

int month, day, year;

};

 

Date GetToday(void);

void PrintDate(Date);

 

int main()

{

Date dt = GetToday();

PrintDate(dt);

getch();

return 0;

}

 

// ---- function that returns a struct

Date GetToday(void)

{

Date dt;

cout << "Enter date (mm dd yy): ";

cin >> dt.month >> dt.day >> dt.year;

return dt;

}

// ---- function that has a struct parameter

void PrintDate(Date dt)

{

cout << dt.month << '/' << dt.day << '/' << dt.year;

}

 

Page 87: Software Engineering( C++) DDE 2023

04/08/23 87

Passing Structure to Function -example5a.cpp//demostrate passing structure to

functions//pogram 6.1 pg 6-5 OOP by C++ by

P.Sellapan#include<iostream.h>#include<math.h>#include<conio.h> struct vegetable //define strcuture{char name[30];float price;};void main(){struct vegetable veg1,veg2; //delcare 2

structure variablestruct vegetable addname(); //declare

function prototypevoid list_func(vegetable); // declare

function prototype veg1 = addname();veg2 = addname();cout<<"\nVegetables for sales\n";list_func(veg1);list_func(veg2);getch();}

 

/This function returns a structurestruct vegetable addname(){

char tmp[20]; struct vegetable vege; //declare a

structure variable cout<<"\nEnter name of vegetable : "; cin>>vege.name; cout<<"\Enter price (per 100gm) : "; cin>>tmp; vege.price = atof(tmp); // converts

string to floating point return(vege);} void list_func(vegetable list) // struct

passed from main(){cout<<"\nVegetable name : "<<list.name;cout<<"\nVegetableprice :

$"<<list.price;return;}

 

Page 88: Software Engineering( C++) DDE 2023

04/08/23 88

Structure within Structure• nested structure • declare structure within another structure

struct student{char id[5];char name[25];char gender;int age;};struct detail{char id[5];char name[25];int age;char course[10];}StudDetail1StudId=StudDetail1.id

struct student{char id[5];char name[25];char gender;int age;};struct detail{struct student Stud1;char course[10];}StudDetail1StudId=StudDetail1.id

Page 89: Software Engineering( C++) DDE 2023

04/08/23 89

Structure within structure –example6.cpp#include <iostream.h>

#include<conio.h>

 

// ---- Date struct

struct Date {

int month, day, year;

};

// ---- Employee struct

struct Employee {

int emplno;

float salary;

Date datehired;

};

 

int main()

{

// --- an initialized Employee struct

Employee joe = { 123, 35500, {5, 17, 82} };

// --- display the Employee

cout << "Empl #: " << joe.emplno << endl

<< "Salary: " << joe.salary << endl

<< "Date hired: "

<< joe.datehired.month << '/'

<< joe.datehired.day << '/'

<< joe.datehired.year << endl;

getch();

return 0;

}

 

Page 90: Software Engineering( C++) DDE 2023

04/08/23 90

Structure within structure –example7.cpp//program 6.2 pg 6-8 taking from OOP by

// example (P.Sellapan)

#include<iostream.h>

#include<conio.h>

//declare structure type

struct country

{

char name[30];

int areacode;

};

 

struct position

{

struct country north;

struct country south;

};

//delcaring and initializing structure

struct position t={{"Thailand",12}, {"Singapore",02}};

void main()

{

cout<<"\nCOUNTRY UP NORTH\n";

cout<<"\nName : "<<t.north.name;

cout<<"\nArea Code : "<<t.north.areacode;

cout<<"\nName : "<<t.south.name;

cout<<"\nArea Code : "<<t.south.areacode;

getch();

}

 

 

 

 

Page 91: Software Engineering( C++) DDE 2023

04/08/23 91

Structure within structure –example7.cpp

OUTPUT

COUNTRY UP NORTH

Name : ThailandArea Code : 12Name : ThailandArea Code : 12

Page 92: Software Engineering( C++) DDE 2023

04/08/23 92

Example –example8.cpp#include<iostream.h>#include<conio.h>#include<stdio.h> struct biodata{char name[50];int age;};void display(biodata); void main(){//char tmp[50];struct biodata personal[2];  //char tmp="Haliamah"; strcpy(personal[0].name,"halimah"); strcpy(personal[1].name,"Halimahtul"); personal[0].age=43; personal[1].age=34; display(personal[2]); getch(); }

void display(biodata person[2])

{

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

{

cout<<"\nName: "<<person[i].name;

cout<<"\nAge : "<<person[i].age;

cout<<endl;

}

}

 

 

 

Page 93: Software Engineering( C++) DDE 2023

04/08/23 93

Exercise

1. Write a program using a structure comprising club member’s names, area codes and telephone numbers. Input values for these members and display them by area code.

2. Initialize the structure that has the members’ names and birthdays. Given a date, display the names of people who were born on this date.

3. Declare nested structure for the following student data:

Student ID

Name made up of first name, middle name, last name

Gender

Date of birth made up of day, month and year

An array of ten courses

An array of ten grades

Page 94: Software Engineering( C++) DDE 2023

04/08/23 94

Exercise

4. Given the following structure;

struct account

{

char acc_no[7];

char acc_type[20];

char name[30];

float balance;

};

Create an array of accounts, assign data for the members of this structure and display the information with suitable headings

Page 95: Software Engineering( C++) DDE 2023

04/08/23 95

TitleChapter 6Chapter 6

Page 96: Software Engineering( C++) DDE 2023

04/08/23 96

TitleChapter 7Chapter 7

Page 97: Software Engineering( C++) DDE 2023

04/08/23 97

TitleChapter 8Chapter 8