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

Software Engineering (C++) DDE 2023

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

DDE 2023

Software Engineering

Noraimi Bin Shafie


ext 4638
noraimi@ic.utm.my
12/08/21 1
Adopted from course dde2023-KST
Revision
Chapter 1

12/08/21 2
Revison
/* This is a program that computes the sum of two integer number*/

#include <iostream.h> //this is a preprocessor


Comment Main() // include directive
{
Preprocessor int x,y,sum;
directive
cout<<“\nEnter first number : “; // this is a prompt
Function
cin>>x; // input from console
name
cout<<“\nEnter second number : “;
Begin block sum=x+y; // adding x and y
cout<<“\nSum = “<<sum; // output to console
Function Return 0; // returning the value to the environment
body }

End block

12/08/21 3
Data types
Data 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 double 64 Approx 12 digits of
point precision

12/08/21 4
Constants
Constant type C++ keywords
Integer Constant
• short integer -99 -35 0 45
• integer - 999 –1 0 555 32767
• unsigned integer 1 256 11000 59874
• long integer 203 12 3345 8989898
Character constant ‘$’,’*’,’d’,’H’
string constant “name”,”telephone”
Floating-point constants 0.008 0.254E8, 4.25E2

12/08/21 5
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

12/08/21 6

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;

12/08/21 7
Input output
#include<iostream.h>
stream
void main()
{
int a,b;
cin>>a;
cin>>a>>b;
cout>>”The value of a and b are “ << a << b;
}

12/08/21 8
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

12/08/21 9
Program control structure
If – else structure #include<iostream.h>
void main()
If(condition) {
statement1; int magic=123;
else int guess;
statment2; cin>>guess;
if(guess==magic)
cout<<“$$Right$$”;
else
cout<<“!!Wrong…”;
}

12/08/21 10
Program control structure
#include<iostream.h>
If – else if structure void main()

{
if(condition) int magic=123;int guess;
cout<<"\nGuess the magic number!!!";
statement1;
cout<<"\nEnter the number.. : ";
else if(condition2) cin>>guess;
if(guess==magic)
statment2;
{
else if(condition3) cout<<"\n Right!!!!";
statement3; cout<<magic<< "is the magic ";
cout<<" number";
else }
default_statement; else if(guess>>magic)
cout<<"Wrong!!!.. Too high";
else
cout<<"Wrong!!!..To low";

12/08/21 11
Program control structure
Nested IF If(x==7)
if(y==3)
cout<<”\nMalaysia”;
If(x==7) else
{
cout<<“\nKL”;
if(y==3)
{
cout”\nMalaysia”; \\else for the nearest if
}
}
else
cout<“\nKL”;

12/08/21 12
Program control structure
Swicth() • Test for equality
• No two indentical constant
Switch(variable)
• Character constant will be converted
{
to interger
case constant1 : statement
sequence;
break();
:
:
case constantN : statement
sequence;
break();
default : statement sequence

12/08/21 13
Program control structure

#include<iostream.h> Swicth(ch)
void main() {
{ case ‘1’ : cout<<“\nMalaysia”;
char ch; break();
cout<<“\n1 . Malaysia”; case ‘2’ : cout<<“\nKuala Lumpur”;
cout<<endl<<“2 . KL”; break();
cout<<“\nEnter your choice : “; default : cout<<“\nThank you”;
Cin>>ch; // read the selection }
// from the keyboard
}

12/08/21 14
Program control structure
for statement • Intialization
– Assignment statement to set the loop
variable
For(initialization;condition;increment)
• Condition
{ – Relational expression determines when the
statement; loop will exit
} • Increment
– How the loop variable will change,

Example:
for(x=1;x<=100;x++)
printf(“%d”,x);

12/08/21 15
Program control structure
While structure void main()
{
while(condition) int t=0;
{ while(t<10)
statement; {
} cout<<endl<<t;
t++;
* Test the condition at the top }
}

12/08/21 16
Program control structure
Do/While structure #include<iostream.h>
void main()
{
do {
char ch;
statement;
do
} {
while(condition) cout<<“1.Malaysia”<<endl;
cout<<“2.Kuala Lumpur”<<endl;
• Test the condition at the bottom cout<<“E.Exit”;
cin>>ch;
if(ch==‘1’)
cout<<“\nMalaysia”;
if(ch==‘2’)
cout<<“\nKuala Lumput”:
}
while(Ch!=‘E’)
}

12/08/21 17
Program control structure
Infinite loop #include<iostream.h>
void main()
#include<iostream.h> {
void main() for(;;) //loop without condition
{ {
while(1) char ch;
{ cin>>ch;
char ch; if(ch==‘A’)
cin>>ch; break;
if(ch==‘A’) }
break;
} }
}

12/08/21 18

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());
}

12/08/21 19
Tutorial 1
1. 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.

12/08/21 20
Header files and function
Chapter 2

12/08/21 21
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>

12/08/21 22
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

12/08/21 23
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

12/08/21 24
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;
}

12/08/21 25
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()
12/08/21 26
Standard header files
example
// 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());

12/08/21 27
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

12/08/21 28
Standard header files
example
#include<iostream.h>
#include<math.h>
#include<conio.h>

// program example using the header file math.h


void 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
}

12/08/21 29
Standard header files
Time.h
• ctime()- convert data and time to a 26-character string such as
Wed Dec 03 09:20:35 2003
example:
//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

12/08/21 30
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<>
{

12/08/21 31
User-Defined Function
Chapter 3

12/08/21 32
defining function
function definition takes the form
return_type function_name(parameter_list)
{
variable declaration
statements
return 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

12/08/21 33
making function calls
void main()
{
. . .
another() // call another
. . .
}

type another()
{ • when function call-program
. . . temporarily leaves the current
function to execute the called
return // return to main() function
} • called function terminates; program
control returns to the calling function

12/08/21 34
Passing arguments to function : by
value
#include<iostream.h>
void prt(int)
passing by void main()
value {
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.*/

12/08/21 35
Passing arguments to function : by reference
• passing by value : calling function passed arguments (values of variables)
to the corresponding parameters in the called function

12/08/21 36
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;
}
12/08/21 37
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

12/08/21 38
sending values back from a function

// program 4.9 page 4-18 char lower_to_upper(char c1)


#include<iostream.h> {
#include<conio.h> char c2;
void main() c2 = (c1 >= 'a' && c1 <= 'z') ? ('A' + c1 - 'a') : c1;
{ return(c2);
do }
{
char lower,upper;
char lower_to_upper(char);
cout<<"\nPlease enter a lower case character : ";
cin>>lower;
upper = lower_to_upper(lower); return value in
cout<<"\nThe upper case equivalent is : "<<upper; variable c2 to
} main
while(!kbhit());
}

12/08/21 39
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);
}

12/08/21 40
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.

12/08/21 41
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;
}

12/08/21 42
Arrays & String
Chapter 4

12/08/21 43
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]

12/08/21 44
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.

12/08/21 45
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’)

12/08/21 46
Example :one-dimensional array.
// display the value of int Values output
#include <iostream>
int main() 1
{ 2
int Values[] = {1,2,3,5,8,13,21}; 3
for (int i = 0; i < 7; i++) 5
cout << Values[i] << endl; 8
return 0; 13
} 21

12/08/21 47
Example :one-dimensional array.
// program to find the total of all output
elements in array y

Total = 52
#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;
}

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

12/08/21 48
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
12/08/21 49
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

12/08/21 50
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;
}
12/08/21 51
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

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]
• intialize character
char name[4][10]

12/08/21 52
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

12/08/21 53
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”};

12/08/21 54
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;
}

12/08/21 55
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

12/08/21 56
//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 4
main()
{
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;
12/08/21 } 57
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”

12/08/21 58
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>
Enter your name : Jamri
void main()
{ Hello Jamri
char name[15];
cout<<“\nEnter your name : “;
cin>>name;
cout<<“\nHello “<<name;
}
//C++ automatically store NULL ‘\0’ at the end of the string!!!

12/08/21 59
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.

12/08/21 60
Initializing String
• example
#include<iostream.h> Enter you name : Joyah
Hello Joyah !
void main()
{
char name[31], greet[]=“Hello, “;
cout<<“\nEnter your name : “;
cin>>name;
cout<<greet;
cout<<name<< “ !”;
}

12/08/21 61
output
• example
#include<iostream.h> U
#include<conio.h>
T
void main()
{ M
char name[5]= “UTMKL”; K
for(int i=0;i<=5;i++)
L
cout<<endl<<name[i];
getch();
}

12/08/21 62
Built in string function
strcat() 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

12/08/21 63
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> Allooooowwww!!
#include<string.h>
void main()
{
char str[];
strcpy(str,”Allooooowwww!!”);
cout<<str;
}

12/08/21 64
Built-in String function
strcat(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>
Hello There
void main()
{
char s1[20],s2[10];
strcpy(s1,”Hello”);
strcpy(s2,”There”);
strcat(s1,s2)
cout<<s1;
}

12/08/21 65
Built-in String function
strcmp(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

12/08/21 66
Built-in String function
#include<iostream.h>
Enter first name : Juliana
#include<string.h>
#include<conio.h> Enter second name : Bonos
 
The name are different.
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();
}
12/08/21 67
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() PENGATURCARAAN


{
char str[80];
strcpy(str,“pengaturcaraan");
for(int i=0;str[i];i++)
str[i]=toupper(str[i]);
cout<<str;
getch();
}

12/08/21 68
Example
#include <iostream.h>
#include <string.h>
Password? utm123
#include<conio.h>
int main() OK You typed 6 characters
{
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;
}
12/08/21 69
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>
Enter a string quit
main()
{
char s[80];
for (: :)
{
cout<<“Enter a string”;
get(s);
if(!strcmp(“quit”,s))
break();
}
return 0;

12/08/21 70
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];

12/08/21 71
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];

12/08/21 72
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;
}
 

12/08/21 73
//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();
12/08/21 } 74
//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;
12/08/21 75
}
structures
Chapter 5

12/08/21 76
structure
This chapter will discuss the following:
• structure declaration
• structure manipulation
• passing structure to function

12/08/21 77
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.
tag that identified its
struct student
data
declared structure {
template char id[25];
structure elements
char name[25];
char gender; (members)
int age;
}stud_1,stud_2;

declaring structure
variables
12/08/21 78
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; struc element
int age;
}stud_1,stud_2;
• for example to access structure student above: assign
string
struc variable stud_1.name=“Kamarul Arifin”;

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


variable stud_1

12/08/21 79
example3
#include<iostream.h>
#include<conio.h>
  output
// ---- declare a struct
struct Date {
6/24/1940
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;
}

12/08/21 80
example4
//initialize a structure
#include<iostream.h>
#include<conio.h> output
// ---- declare a struct
struct Date {
11/17/1940
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;
}

12/08/21 81
array of structure
• C++ lets create an array of structure. Example to store information of 50 student
• could use any of two structure declaration

struct student struct student


{ {
char id[5]; char id[5];
char name[25]; char name[25];
char gender; char gender;
int age; int age;
}stud[50]; };
struct student stud[50];
• to print the name of the seventh student
cout>>stud[6].name;

12/08/21 82
example1
//program structure void main()
#include<iostream.h> {
#include<conio.h> strcpy(stud[0].name,"ali bin abu");
  strcpy(stud[1].name,"ghazali yahya");
struct student  
{ stud[0].age=45;
char name[20]; stud[1].age=10;
int age; cout<<"\n\t\tName"<<"\t\tAge";
}; for(int i=0;i<2;i++)
struct student stud[2]; {
cout<<"\n\t\t"<<stud[i].name;
cout<<"\t"<<stud[i].age;
}
cout<<endl;
getch();
}

12/08/21 83
example2
#include<iostream.h> void main()
#include<conio.h> {
#include<stdio.h> for(int i=0;i<2;i++)
struct student {char s[20];
{ cout<<"\nInput next student name :";
char name[20]; gets(s);
int age; strcpy(stud[i].name,s);
}; cout<<"\nInput next student age :";
struct student stud[2]; 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();
}
12/08/21 84
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.

12/08/21 85
Passing Structure to Function -example5.cpp
#include <iostream.h> // ---- function that returns a struct
#include<conio.h> Date GetToday(void)
{
 
Date dt;
struct Date {
cout << "Enter date (mm dd yy): ";
int month, day, year; cin >> dt.month >> dt.day >> dt.year;
}; return dt;
  }
Date GetToday(void); // ---- function that has a struct
parameter
void PrintDate(Date);
void PrintDate(Date dt)
 
{
int main() cout << dt.month << '/' << dt.day <<
{ '/' << dt.year;
Date dt = GetToday(); }
PrintDate(dt);  

getch();
return 0;
}
 12/08/21 86
Passing Structure to Function -example5a.cpp
//demostrate passing structure to /This function returns a structure
functions
//pogram 6.1 pg 6-5 OOP by C++ by
struct vegetable addname()
P.Sellapan {
#include<iostream.h> char tmp[20];
#include<math.h> struct vegetable vege; //declare a
#include<conio.h> structure variable
  cout<<"\nEnter name of vegetable : ";
struct vegetable //define strcuture
{
cin>>vege.name;
char name[30]; cout<<"\Enter price (per 100gm) : ";
float price; cin>>tmp;
}; vege.price = atof(tmp); // converts
void main() string to floating point
{ return(vege);
struct vegetable veg1,veg2; //delcare 2 }
structure variable
struct vegetable addname(); //declare  
function prototype void list_func(vegetable list) // struct
void list_func(vegetable); // declare passed from main()
function prototype {
 
veg1 = addname();
cout<<"\nVegetable name : "<<list.name;
veg2 = addname(); cout<<"\nVegetableprice :
cout<<"\nVegetables for sales\n"; $"<<list.price;
list_func(veg1); return;
list_func(veg2); }
getch();  
}
 

12/08/21 87
• nested structure
Structure within Structure
• declare structure within another structure

struct student struct student


{ {
char id[5]; char id[5];
char name[25]; char name[25];
char gender; char gender;
int age; int age;
}; };
struct detail struct detail
{ {
char id[5]; struct student Stud1;
char name[25]; char course[10];
int age; }StudDetail1
char course[10]; StudId=StudDetail1.id
}StudDetail1
StudId=StudDetail1.id
12/08/21 88
Structure within structure –example6.cpp
#include <iostream.h> int main()
#include<conio.h> {
// --- an initialized Employee struct
 
Employee joe = { 123, 35500, {5, 17,
// ---- Date struct 82} };
struct Date { // --- display the Employee
int month, day, year; cout << "Empl #: " << joe.emplno << endl
}; << "Salary: " << joe.salary << endl
// ---- Employee struct << "Date hired: "
<< joe.datehired.month << '/'
struct Employee {
<< joe.datehired.day << '/'
int emplno;
<< joe.datehired.year << endl;
float salary; getch();
Date datehired; return 0;
}; }
   

12/08/21 89
Structure within structure –example7.cpp
//program 6.2 pg 6-8 taking from OOP by void main()
// example (P.Sellapan) {
#include<iostream.h> cout<<"\nCOUNTRY UP NORTH\n";
#include<conio.h> cout<<"\nName :
"<<t.north.name;
//declare structure type cout<<"\nArea Code :
struct country "<<t.north.areacode;
cout<<"\nName :
{
"<<t.south.name;
char name[30];
cout<<"\nArea Code :
int areacode; "<<t.south.areacode;
}; getch();
  }
struct position  
{  
struct country north;  
struct country south;  
};
//delcaring and initializing structure
struct position t={{"Thailand",12},
{"Singapore",02}};
12/08/21 90
Structure within structure –example7.cpp

OUTPUT

COUNTRY UP NORTH

Name : Thailand
Area Code : 12
Name : Thailand
Area Code : 12

12/08/21 91
Example –example8.cpp
#include<iostream.h> void display(biodata person[2])
#include<conio.h> {
#include<stdio.h>
  for(int i=0;i<2;i++)
struct biodata {
{ cout<<"\nName: "<<person[i].name;
char name[50]; cout<<"\nAge : "<<person[i].age;
int age; cout<<endl;
};
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();
 }

12/08/21 92
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

12/08/21 93
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

12/08/21 94
Title
Chapter 6

12/08/21 95
Title
Chapter 7

12/08/21 96
Title
Chapter 8

12/08/21 97

You might also like