The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Wan Anisha, 2022-04-10 10:17:12

C++ eBook

C++ eBook 2022

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3

› The program below will display “You PASSED!” if the evaluated expression returns true.
“Thank you.” will always be displayed, even if the expression returns false.

› Example below shows a program that has a group of statements which are executed if the
Boolean expression returns true.

48 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
› If there is more than one statement, braces are used to contain the statements.

› Examples below shows programs that use more than one if selection.
› Each if statement is evaluated one by one in the program given.

2.1.2 Two-way selection
› Often it is desirable for a program to take one branch if the condition is true and another if
it is false.
› A two-way selection is where statements will be executed for both true and false evaluation
of the Boolean expression. The else keyword introduces the alternative statement.

49 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3

› Compare two selection which is written in a statement of the form:

if (boolean-expression)
statement-1;

else
statement-2;

Ex}ample :

cin>>marks;

if (marks>=50)
cout<<”PASS ”;

else
cout<<”FAIL”<<endl;

› If a sequence of statements is to be executed, this is done by making a compound statement
by using braces to enclose the sequence:

if (boolean-expression)
{

statements;
}
else
{

statements;
}

}
Example :

cin>>marks;

if (marks>=50)
{

cout<<”CONGRATULATION!”;
cout<<”YOU PASSED ”;
}
else
cout<<”FAIL”<<endl;

50 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
› Flowchart below show the general syntax of if two-way selection.

› The program in Example below evaluates whether a number entered by the user is a positive
or negative number.

› The Boolean expression num >= 0 is used to identify whether the number is positive or
negative

51 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
› Next example states the pass or fail status based on the marks enter by the user

2.1.3 Multiple-way selection
› Multiple-way selection statements allow more than one selection. Using if or switch
selections, we can perform many different actions based on a set of possible values.
› In multiple-way selections, the Boolean expressions are checked in sequential order until
the correct match is found. If the first Boolean expression is true, the program will ignore
the following else if. But if the firsts expression is false, the program continues to check the
else if statement and continue until an expression returns true.
› The last else at the end of the selection is executed when none of the Boolean expressions
checked earlier are trueCompare more than two selections which is written in a statement
of the form

52 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
› Below is the general syntax of writing the multiple selection:

if (boolean-expression-1)
Statement-1;

else if (boolean-expression-2)
Statement-2;

else
Statement-N;

› Below is the general syntax of flowchart for multiple-way selection:

› Example below show a program displays appropriate messages based on the response
about bill payment

53 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3

2.2 switch Statement
› This last category of selection enables the program to select one of many options or cases.
› An alternative to the if selection is the switch statement. It can be used even if the condition
does not involve relational or logical operators.
› Normally we use switch statement to replace if statement if the condition does not involve
with relational or logical operator (used for integer numbers and single char only)
› This switch statement allows the compiler to choose among many options or alternatives.
› The switch statement can evaluate integers and characters only.
› The switch statement cannot evaluate ranges of values.
› The syntax for switch statement is as followed:

switch (selector variable)
{

case value for case 1:
Statement 1;
.......;
break; //to stop case1

case value for case n:
Statement n;
.......;
break; //to stop case n

default: //works as else in switch statement
statement;
break; //to stop default statement

}

2.2.1 break statement usage
› The words break, case, default and switch are the reserved keywords used in the switch

statement.
› The keyword switch is placed at the start of the switch statement to perform the evaluation

based on the selector variable.
› The selector variable is usually an identifier. The selector variable can accept all data types

except float or double. The selector variable also determines the value to be evaluated in the
conditions in the case statement.
› The keyword case determines each of the possible values from the selector variable.
› The word break is placed between the case statements to show the limitation of each case
statement. The break statement also is used to break out of each of the case statements.

54 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
› The keyword default is used if none of the case statements is equivalent to the selector

variable.
› Below shows the flowchart for switch statement.

› Below shows an example of program that evaluates the variable of data type char.
› The purpose of the program is to identify the category names based on the category code.

55 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
› As C++ is case sensitive, there is difference between uppercase and lowercase characters.
› To overcome this, we can write the case statement twice, for both the lowercase and

uppercase characters, as shown in example below.

› The break statement causes the program to stop the particular case statements.
› A missing break statement between the cases is not considered an error by the compiler.
› Let’s see what happens if we do not put in the break statement.
› Example below does not use the break statement while the next example is the same

program using the break statement.

56 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3

3. Nested Selection (Multi-way Selection)
› Nested can be defined as something contained within something else. So, in nested selections
there are conditions inside other conditions and we have to fulfill the one condition before
we continue to the next condition.
› A nested if selection means there is an if selection written inside another if selection.
› We can combine switch and if selections to perform nested selection.
› To get a clear view of nested selections, the program should be indented correctly. Blocks or
braces are also very important to separate the nested statements.
› Occasionally a decision has to be made on the value of a variable which has more than two
possibilities.
› This can be done by placing if statements within other if-else constructions. This is commonly
known as nesting and a different style of indentation is used to make the multiple-selection
functionality much clearer.
› Additional decision options can be achieved by using nested if statements.
› Nested selection can also be applied using switch statement.
› A nested if statement is simply an if statement within an if statement.
› Written in a statement of the form:

57 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
if (boolean-expression-1)

if (boolean-expression-1)
Statement-1;

else
Statement-2;

else
Statement-3;

› Below is the flowchart for multi way statement:

› Below is an example program to identify whether a number is odd or event:

58 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 3
› Below is a program to find ticket price based on the category for AMM Theme Park:

59 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 4

CHAPTER 4
REPETITION CONTROL STRUCTURE
Chapter Outline
1. Introduction
- Loop Control Variable (LCV)
2. Repetition/Iteration Control Structure
- Repetition using the while loop
- Repetition using the do..while statement
- Repetition using the for statement
3. Ways of Writing a Repetition Control Structure
- Counter-controlled structure
- Sentinel-controlled structure
- Flag-controlled structure
4. Nested Loop
5. Using break and continue in Looping
- break statement
- continue statement
At the end of this class, student should be able to:
i. Differentiate between the four types of repetition control structure.
ii. Differentiate between counter–controlled structure, sentinel-controlled structure and flag-
controlled structure
iii. Produce programs using repetition control structure

1. Introduction
› In repetition control structure, if a user wants to enter more than one value at a time, the
best way is by using repetition control structure.
› Similar to selection control structure, repetition or iteration control structure allows user
to enter a statement or a group of statements based on certain condition.
› For example, if we were to enter the heights of 30 students in a class and find the average,
the most efficient way to run the program is by using repetition control structure.
› Three types of repetition control structure in C++ are the while loop, do..while loop
and for loop.

60 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

The differences between for, while and do..while loop

for Loop while Loop do…while Loop
Pretest Loop
• The condition is place at the Posttest Loop Pretest Loop

top of the loop. • The condition is placed at the • The condition is placed on
• If the condition is false, the
end of the loop. top of the loop.
loop will not be executed
even once. • If the condition is false, the • If the condition is false, the
int x;
for (x=1; x<=5; x++) loop will still be executed at loop will not be executed
{
cout<<“x=”<<x<<endl; least once. even once.
} int x=1; int x=1;
while( x<=5) do
{ {

cout<<“x=”<<x<<endl; cout<<“x=”<<x<<endl;
x++; x++;
} } while( x<=5);

The differences between programs using sequential and repetition control structures

1.1 Loop Control Variable (LCV) CHAPTER 4
› Repetition/Iteration or loop is a control structure that allows a statement or group of
statements to be executed repeatedly based on the Boolean test.
› It is important to be aware of how many iteration a given loop is expected to perform.
› If a loop does not iterate a finite number of times, it is considered to be an infinite loop.
› Loop Control Variable (LCV) is a variable that is used to control the flow of a program.
› LCV consists of three processes which are initialization, evaluation and updating.

61 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 4

1.1.1 Initialization
› Initial value for a variable
› Starting value
› Example: num=0; total=10; ans=’Y’

1.1.2 Evaluation
› Boolean test (evaluation)
› Used to verify how many loops will be done
› Example: num<=10; total>=1; ans==’Y’;

1.1.3 Updating
› Counter (updating)
• Will update the initial value either increase or decrease until meet the ending
value (when Boolean test is false)
• Example: num=num+2; total--; cin>>ans;

2. Repetition/Iteration Control Structure
› A repetition/iteration control structure or loop allows a statement or group of statement to
be executed repeatedly based on certain Boolean conditions.

2.1 Repetition using the while Loop
› A while loop does not necessarily iterate a specified number of times.
› As long as its condition is true, a while loop will continue to iterate.
› A while loop is considered to be an indeterminate or indefinite loop because usually only
at run time can be determined how many times it will iterate.
› A while loop is also considered to be a top checking (pretest) loop, since the control
expression is located on the first line of code with the while keyword.
› That is, if the control expression initially evaluates to FALSE, the loop will not iterate even
once.

62 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

› The while statement has the form:

initial value;
while (condition/boolean test)
{

satements;
..........;
counter;
}

› If the condition is false, the loop is skipped. If the condition is true, the loop body is executed,
and we then go back to testing the condition, etc.

Initial value

Boolea False
n test

True

Statements

Counter
Next statement

Example 1: CHAPTER 4

› Consider this segment of code, what will be displayed?
int number = 1;
int sum = 0;
while(number<=10)
{
sum=sum+number;
number++;
}
cout<<“The sum is: " <<sum<<endl;

63 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

Example 2: Output
Enter your favorite number: 5
Coding I’m a good student
int main () I’m a good student
{ I’m a good student
I’m a good student
int a; I’m a good student
cout<<"Enter your favorite number:"; WOW..
cin >> a;
while (a>0)
{

cout<<”I ‘m a good student\n”;
a = a - 1;
}
cout << “\nWOW…”;
}

Example 3:

#include<iostream>
using namespace std;

int main()
{

char ans='Y';
int num1,num2,sum;

while (ans=='Y')
{

cout<<”Enter 2 numbers to find the sum:”;
cin>>num1>>num2;

sum=num1+num2;

cout<<"Do you want to try again?(Y/N):";
cin>>ans;

}

cout<<”Thank you"<<endl;
}

} CHAPTER 4

64 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

2.2 Repetition using the do..while statement
› Does not necessarily iterate a specified number of times.
› However, it is guaranteed that a do while loop will iterate at least once because its condition
is placed at the end of the loop.
› Useful when the iteration is guaranteed to run at least once.
› Like a while loop, a do while loop is considered to be indeterminate or indefinite loop.
› A do while loop is considered to be a bottom-checking (posttest) loop, since the control
expression is located after the body of the loop after the while keyword.
› A do while loop is guaranteed to iterate at least once even if the condition evaluates to
FALSE.
› The do while statement has the form:

do Initial value
{
counter
Statement 1; Boolean test
Statement...n;
}while (Boolean test);

Initial value

Statements
True Counter

Boolean False CHAPTER 4
test

Next statement

65 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

Example 1: Output

Coding 0
1
int x = 0; 2
do 3
{ 4

cout << x << endl;
x++;

} while (x < 5);

Example 2:

#include<iostream>
using namespace std;
int main()
{

char ans;
do
{

cout<<”\n\nRoses are red \n Violets are blue”;
cout<<”I like C++ \n How about you?”<<endl;

cout<<”\n\n Want to see my poem again?”;
cout<<”y=yes, n=no:”;
cin>>ans;

}while (ans == ‘y’ || ans == ‘Y’);/*loop will continue if
the user press y or Y*/

cout<<”\n OK. Thank you. Bye.”<<endl;
}

OUTPUT

} Roses are red
Violets are blue
66 | P a g e I like C++
How about you?

Want to see my poem again? y=yes, n=no:y

Roses are red CHAPTER 4
Violets are blue
I like C++
How about you?

Want to see my poem again? y=yes, n=no:n
OK. Thank you. Bye.

INTRODUCTION TO C++ FOR BEGINNERS

Example 3:

#include<iostream>
using namespace std;
int main()
{

int a=0;
do
{

cout<<”Enter an integer between 1 and 10:”;
cin>>a;
cout<<”You entered:”<<a<<endl<<endl;
if((a<1)||(a>10))
{

cout<<”Your value for a is not between 1 and 10”<<endl;
cout<<”Please re-enter the number\n”<<endl;
}
}while((a<1)||(a>10));

cout<<”Thank you for entering a valid number!”<<endl;
}

OUTPUT

Enter an integer between 1 and 10: 24
You entered: 24
Your value for a is not between 1 and 10
Please re-renter the number
Enter an integer between 1 and 10: 7
You entered: 7
Thank you for entering a valid number

2.3 Repetition using the for statement CHAPTER 4
› Always executes a specific number of iterations.
› Used when you know exactly how many times a set of statements must be repeated.
› A for loop is called a determinate or definite loop because the programmer knows
exactly how many times it will iterate.
› The for statement has the form:

for (initial_value; boolean_test; counter)
{

//loop body
}
67 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

› initial_value sets up the initial value of the loop counter.
› Boolean_test this is the condition that is tested to see if the loop is executed again.
› counter this describes how the initial value is changed on each execution of the loop.

Initial value

Boolean True Counter
test Execute loop body

False

Next statement

Example 1:

Initial value Boolean test counter

for (t=1;t<=10;t++)
{

cout<<t<<”,”;
}
cout<<”FIRE!”;

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

Descending t=t-1

for (t=10;t>=0;t--)
}{

cout<<t<<”,”;
}
cout<<”FIRE!”;

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

68 | P a}g e

INTRODUCTION TO C++ FOR BEGINNERS

› Loop variable can be increment more than 1 or can be decrement less than 1.
Example 2:

Coding Output

for (int i=1; i<=10; i=i+2) 1
{ 3
5
cout << i << endl; 7
} 9

Exercise:

› Write a program to generate multiplication table. Prompt user to input any integer
number, then your program will generate appropriate multiplication table.

Enter a number:2 6x2=12
Output: 7x2=14
1x2=2 8X2=16
2x2=4 9x2=18
3x2=6 10x2=20
4x2=8 11x2=22
5x2=10 12X2=24

Answer 1: Output CHAPTER 4

//program using for loop 1x2=2
#include<iostream> 2x2=4
using namespace std; 3x2=6
int main() 4x2=8
{ 5x2=10
6x2=12
int num, total; 7x2=14
for(num=1;num<=12;num++) 8X2=16
{ 9x2=18
10x2=20
total=num*2; 11x2=22
cout<<num<<”x”<<”2=”<<total<<endl; 12X2=24
}
}

69 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

3. Ways of Writing a Repetition Control Structure

› There are three ways to write a repetition control structure in C++ which is counter
controlled structure, sentinel-controlled structure and flag-controlled structure.

3.1 Counter-controlled structure

› A counter-controlled structure is a loop that we know how many times it will executed.

counter=0; //initialize the loop control variable

while (counter<10) //test the loop control variable
{

...
counter++; //update the loop control variable
...
}

Example: #include<iostream>
using namespace std;
int main()
{

int num=1;
while (num<=8)
{

cout<<num<<endl;
num++;
}
}

3.2 Sentinel-controlled structure

› A sentinel-controlled structure does not know how many data to be read because it will be
based on the valu}e entered by the user.

› The value can be a special value, called sentinel.
› A sentinel value can be either YES/NO while a sentinel number is any number that the user

may seldom entered (example: -1, -999, etc)

CHAPTER 4

70 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 4

//initialize a sentinel number
int sentinel=-1;
//user enters value
cin>>value;
//test the loop
while (value!=sentinel)
{

...
cin>>value; //update the loop
...
}

Example:

#include<iostream>
using namespace std;

int main ()
{

const int sentinel=-999;
int num,sum=0,count=0;

cout<<“Enter a number ending with:”<<sentinel<<endl;
cin>>num;

while(num!=sentinel)
{

sum = sum + num;
count++; //equal to count=count+1
cin>>num;
}
cout<<“The sum of “<<count<<“ numbers is “<<sum<<endl;
}

}

71 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

3.3 Flag-controlled structure
› A flag-controlled structure uses a bool (data type for true or false) variable to control the
loop.

//declare and initialize variable
bool result;
result=false;

while (!result) //test the loop
{

...
if(boolean test)

result=true;//update the loop
...
}

Example:

#include<iostream>
using namespace std;
int main()
{

bool guess;
guess = false;
int value=15;
int num;

while (!guess)
{

cout<<"Enter an integer between 0-20:";
cin>>num;

if(num==value) CHAPTER 4
{

cout<<"\nYou guess a correct number.\n";
guess=true;
}
else if(num<value)
cout<<"\nYour guess is lower than num.\nGuess again!\n";
else
{
cout<<"\nYour guess is higher than num.
Cout<<”\nGuess again!\n";
}

}
}

72 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

4. Nested Loop

› The placing of one loop inside the body of another loop is called nesting.
› When you "nest" two loops, the outer loop takes control of the number of complete

repetitions of the inner loop.
› While all types of loops may be nested, the most commonly nested loops are for loops.

for (initial_value;boolean_test;counter)

{

for(initial_value;boolean_test;counter)

Outer Inner {
loop
loop } loop body;

}

Example 1:

for (value1=0;value1<5;value1++)

{

for(value2=0;value2<4;value2++)

Outer {
loop
Inner cout<<value1<<””<<value2<<endl;
loop
}
}

Memory value2 (inner) Output CHAPTER 4
value1 (outer)
0 00
0 1 01
2 02
1 3 03
4end loop
2 10
73 | P a g e 0 11
1 12
2 13
3
4end loop 20
21
0 22
1
2

INTRODUCTION TO C++ FOR BEGINNERS

3 3 23
4end loop
4 30
5 end of loop 0 31
1 32
2 33
3
4end loop 40
41
0 42
1 43
2
3
4end loop

Example:

#include<iostream> CHAPTER 4
using namespace std;

int main()
{

int marks, sum=0;
char ans;
double average;

do
{

for(int i=1;i<=3;i++)
{

cout<<"Enter test "<<i<<" marks:";
cin>>marks;

sum=sum+marks;
}

average=sum/3;

cout<<"The average marks is:"<<average<<endl;

cout<<"Do you want to repeat?:";
cin>>ans;

}while(ans=='Y'||ans=='y');

cout<<"Thank you"<<endl;

}

74 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 5

5. Using break and continue in Looping
5.1 break statement

› Instead of using break in the switch statement, break can also be used in the if..else
statement as long as the statement is inside the loop.

› The function of a break statement is to terminate a loop.

Example:
Identify whether a number is a prime number.
Hint: A prime number is a number that is divisible only by 1 and itself

#in›clude<iostream>
usi›ng namespace std;



int› main()
{›

› int num, i;
› bool prime=true;



› cout<<”Enter a number:”;
› cin>>num;

for(i=2;i<=num/2;i++)
{

if(num%i==0)
{

prime=false;
break;
}
}
if(prime)
cout<<”This is prime number.”;
else
cout<<”This is not a prime number.”;
return 0;
}

75 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 5
5.2 continue statement

› The continue statement is used to skip certain conditions within a loop.
› Similar to break, the continue statement is used in an if..else statement inside a

loop.
Example:
Display all even numbers from 1 to 10

#in›clude<iostream>
usi›ng namespace std;



int› main()
{›

› for (int i=1; i<=10; i++)
›{
› if(i%2!=0)
›{
› continue;

}
cout<<i<<”\t”;
}
return 0;
}

76 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

CHAPTER 5
FUNCTIONS

Chapter Outline
1. Introduction to Functions
2. Function Types

- Predefined Functions
- User-defined Functions
3. Types of Variables and Their Scope
4. Parameter Passing

At the end of this chapter, student should be able to:
i. Understand the two types of functions.
ii. Identify the three function elements.
iii. Develop a program using function

1. Introduction to Functions CHAPTER 5
› Most computer programs that solve real-world problem are large, containing thousand to
million lines of codes and developed by a team of programmers.
› The best way to develop and maintain a large program is to construct it from smaller pieces
or modules, each of which is more manageable than the original program.
› Functions can divide problems into sub-problems.
› In C++, all sub-problems called functions (corresponding to both functions and procedures in
Pascal and some other programming languages).
› Function is a program segment that can do particular task.
› Each of the smaller tasks (subtasks) can be coded as C++ functions that go together with the
main function to make up a structured program.
› Advantages of using function (user-defined functions)
i. Breaking program to smaller items which will be easier to code, test and debug.
ii. Reusable of certain function.
iii. To avoid repeating code in a program.
› A C++ program is a function define collection that must consist of at least main () function.
› C++ program execution starts by calling the main () function.

77 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

1.1 Functions Types
› There are two categories of functions:
i. Predefined functions - available in the C/C++ standard library such as stdio.h, math.h,
string.h etc.
ii. User-defined functions – functions that the programmers create for specialized tasks.

2. Function Types
2.1 Predefined Functions

› In C++, predefined functions are organized into separate libraries.
› Also known as library functions.
› Function defined in math.h header.

Function Description Type Example Value
sqrt (x) double sqrt(4.0)
pow (x, y) squarerootx double 2.0
fabs (x) power xy double pow (2.0,3.0)
8.0
absolute value for fabs(-3.5)
double fabs (3.5) 3.5
3.5
ceil (x) ceiling (round up) double ceil (3.4)
floor (x) floor (round down) double ceil (3.8) 4.0
4.0
floor (3.1) 3.0
floor (3.8) 3.0

› Function defined in stdlib.h header

Function Description Example Value

abs (x) absolute value for x, abs (-5) 5
labs (x) x an integer abs (5) 5
rand()
absolute value for x, labs (-50000) 50000
x a long labs (50000) 50000

Any random number, integer type rand() any number

CHAPTER 5

78 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

Example 1: FABS: 4.5
CEIL: 6
#include <iostream> FLOOR: 5
#include <math.h>
using namespace std;

int main()
{

double a,b,c;
a=fabs (-4.5);
b=ceil(6.3);
c=floor(5.7);

cout<<”FABS: ”<<a<<endl;
cout<<”CEIL: ”<<b<<endl;
cout<<”FLOOR: ”<<c<<endl;

}

Example 2: LABS: 7000
FABS: 9
#include <iostream> RAND 1: 41
#include <stdlib.h> RAND 2: 18467
using namespace std;

int main()
{

long x;
int y;
x=labs (-70000);
y=abs(-9);

cout<<“LABS: ”<<x<<endl;
cout<<“ABS: ”<<y<<endl;
cout<<“RAND 1: ”<<rand()<<endl;
cout<<“RAND 2: ”<<rand()<<endl;

}

› Function defined in string.h header

Function Description
strcmp(string1, string2) returns true if the two strings are different;
otherwise returns 0
strcpy(string1, string2)
strlen(string) assign the value of string2 into string1
strcat(string1,string2) return the length of the string
combine both string and assign it to string1

CHAPTER 5

79 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 5

Example 1: (strcpy and strcmp)

#include<iostream>
#include<string.h>
using namespace std;

int main()
{

char name1[15];
char name2[15];
int result;

cout<<"Please enter your first name:";
cin.getline(name1, 15);
cout<<name1;

cout<<"\nPlease enter your second name:";
cin.getline(name2,15);
cout<<name2<<endl<<endl;

strcpy(name1, name2);
cout<<name1<<endl;

result = strcmp(name1, name2);
cout<<result<<endl;
}

Example 2: (strlen)

#include<iostream>
#include<string.h>
using namespace std;

int main()
{

char name1[15];
char name2[15];
int sizename1, sizename2;

cout<<"Please enter your first name:";
cin.getline(name1, 15);
cout<<name1;

cout<<"\nPlease enter your second name:";
cin.getline(name2,15);
cout<<name2<<endl<<endl;

sizename1 = strlen(name1);
sizename2 = strlen(name2);

cout<<"Size of name 1 is:"<<sizename1;
cout<<“\nSize of name 2 is:“ <<sizename2<<endl;
}

80 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

Example 3: (strcat)

#include<iostream>
#include<string>
using namespace std;
int main()
{

char name1[15];
char name2[15];

cout<<"Please enter your first name:";
cin.getline(name1, 15);
cout<<name1;

cout<<"\nPlease enter your second name:";
cin.getline(name2,15);
cout<<name2<<endl<<endl;

strcat(name1, name2);
cout<<name1<<endl<<endl;
}

› Function defined in ctype.h header Description
returns the lowercase value of x
Function
tolower(x) returns the uppercase value of x
toupper (x) determines if a character is uppercase.
isupper(x) determines if a character is lowercase
islower(x) determines if a character is a letter (a-z, A-Z)
isalpha(x) determines if a character is a digit (0-9)
isdigit(x)

Example 1: TOLOWER: g
ISUPPER: 1
#include<iostream> ISDIGIT: 0
using namespace std; ISDIGIT:1
#include<ctype.h>
int main() CHAPTER 5
{

char k,y;
int l,m;

k=tolower(‘G’);
l=isupper(‘B’);
m=isdigit(5);
y=isdigit('7');

cout<<”TOLOWER: ”<<k<<endl;
cout<<”ISUPPER: ”<<l<<endl;
cout<<”ISDIGIT: ”<<m<<endl;
cout<<”ISDIGIT: ”<<y<<endl;
}

81 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 5

2.2 User defined function
› Functions are given a valid identifier names, just like variables.
› However, a function name must be followed by parentheses.
› User defined function has the following characteristics:
i. A function is named with unique name.
• By using the name, the program can execute the statements contained in the function,
a process known as calling the function. A function can be called from within another
function.
ii. A function performs a specific task.
• Task is a discrete job that the program must perform as part of its overall operation,
such as sending a line of text to the printer, sorting an array into numerical order, or
calculating a cube root, etc.
iii. A function is independent.
• A function can perform its task without interference from or interfering with other
parts of the program. The main program, main() is also a function.
iv.A function may receive values from the calling program.
• Calling program can pass values to function for processing whether directly or
indirectly (by reference).
v. A function may return a value to the calling program.
• When the program calls a function, the statements it contains are executed. These
statements can pass something back to the calling program.
› In C++ programming, every module in modular program is executed as a function. All function
must have unique name.
› One of the modules is main.
› There are 3 elements related to functions:
i. Function prototype/declaration
ii. Function call
iii. Function definition

82 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 5

Example 1:

#include<iostream>
using namespace std;
//function declaration/prototype
int a();
void b(int,double);

int main()
{

//function call
a( );
b(x,y);

}

//function definition without parameter
//function must return value
int a()
{

statements;
}

//function definition with 2 parameters
//function definition does not return value
void b (int x,double y)
{

statements;
}

Example 2: (function declaration/prototype not required)

#include<iostream>
using namespace std;

//function definition without parameter
//function must return value
int a()
{

statements;
}

//function definition with 1 parameter
//function definition does not return value
void b (char k)
{

statements;
}

int main( )
{

//function call
a();
b(n);
}

83 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 5

2.2.1 Function declaration/prototype
› C++ programmers generally add functions to the bottom of a C++ program after the main

function.
› This makes your code easier to read and follow by programmers.
› If a function's body is placed after the main function, then the function prototype (also called

the function declaration) must be placed at the top of the program, above the main function.
› The function prototypes "warn" the compiler about the eventual use of the prototyped

function and allocate memory.
› An error will definitely result if you call a function from within the main function that has not

been prototyped.
› A form for called function must be declared first:

data_type function_name(parameter_list)
parameter_list – consists of data type for every parameter which is a function input.
› Example:
// count area is a function that receive a parameter radius and return its value type
float count_area (int radius);
› Declaring a function is by preparing prototype for the function.

2.2.2 Function definition
› Function is a subprogram which is executed as a logical module in modular program.
› Below is a function general format.
› Function definition form:

function_type function_name(formal_parameter_lists)
{

compound statements;
}

› Function definition contains elements such as:
i. Function type
ii. Function name
iii. Formal parameter lists
iv. Compound statements

84 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 5

2.2.3 Function call
› Function call needs function name followed by lists of actual parameter.
› Function definition in program can be called by any function including main function.
› Format for function call:

function_name(actual_parameter_lists);

› Function name – name for called function, both name in function definition and function call
must be the same.

› actual_parameter_lists
• Parameter which will be sent to function as input.
• This list consists of identifier and constant.
• Separated by comma.

› When we want to execute the function, we have to call the function.
Example 1:
cout<<count_area(radius);
• count_area function are called by main function.
• Main function is a caller function for count_area function.
• count_area function is a called function.
print_msg();
Hasil= count_count(x, y);
Example 2:

#include<iostream>
using namespace std;
//function declaration/prototype
show_sign(char,int)

int main()
{

show_sign(‘k’,9); //right function call
show_sign(2,6); // wrong function call
}
//function definition
void show_sign(char sign_type, int num)
{
cout<<”The sign is:”<<sign_type<<endl;
cout<<”The number is:”<<num<<endl;
}

85 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 5

Exercise:
› The following program includes a function prototype which "declares" to the program the

existence of the function MyName which is detailed below the main function. The main
function "calls" MyName and sends the argument No which is being prompt by the user.
Next, MyName receives the value and stores it in the parameter NumTimes. The function
then prints out the string "Nelly” according to the NumTimes using a for loop.

3. Types of Variable and Their Scope
› Value will be returned based on data type such as:
i. int
ii. char
iii. double/float
› Variable scope is an area where it can be used legally. Variable scope starts at the location it
is declared.
› There are 2 ways to declare a function:
i. through global variable
ii. through local variable using parameter

3.1 Through Global Variable
› Global variable is a variable that can be declared outside of the function (outside declaration).
› By declaring variable as global, variables can be used in many functions.
› A variable is declared as a global variable when the functions created do not involve any
parameters.

3.2 Through Local Variable
› Local variable is a variable that must be declared in any block.
› Its scope starts at its declaration point until the end of the block.
› It can only be used in that function.
› Local variable belongs to the function where it is declared and can’t be shared or used by any
other function including main function.
› If the same variable name is declared as a local variable in few functions, the variable wil
be assumed as a different one.

86 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

3.3 Function with return statement
› A function which type is int, char, double or float must return values to the function call.
› Contains at least one return statement.
› Syntax:
return expression;
› Example:
return total;
return 0;
› Expression must produce value that match with its type.
› Value will be returned to call function – return statement will stop the function execution
› Example 1:
Function TotalCount() will return integer value where sum must be integer type.

› If return is used in selection control structure, only the true statement will return the value.
Example 2:

double absolute_value(double no)
{

if(no>=0)
return no;

else
return 0;

}

3.4 Funtion without return statement

› A function which starts with the word void in front does not have to return a value to the

function call.

› However, return statement can also be used in function that doesn’t return any value(void

function).

› Return will be used to stop function execution and doesn’t return any value. Any statement

after return will not be executed.

Example 1: void PrintResult ( )
{
CHAPTER 5
cout<<”Total is:”<<total<<endl;
return;
cout<<”This will not be printed”;
}

87 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

› Example 2:
Differences between function with and without return statement
Function TotalCount() will display integer value of sum

//Example 1 //Example 2
//function definition //function definition
int TotalCount( ) void TotalCount( )
{ {

sum=num1+num2; sum=num1+num2;
return sum; cout<<”Sum is:”<<sum<<endl;

} }

4. Parameter Passing
› If global variable is not in use, we can use function parameter method.
› We have to define and declare function with the parameter and call with parameter.
› There are three important things about parameter:
i. Number of actual parameter and formal parameter must be the same in function call
and function definition.
ii. Relation between actual parameter and formal parameter is one-to-one. First actual
parameter must be the same with first formal parameter and so on.
iii. Type for every actual parameter must be the same with formal parameter or type that
can be changed by compiler.

5.2 Parameter passing – passing by value
› Value parameter is only used for value input to function but not to output the value to
actual parameter.

#include<iostream> OUTPUT
using namespace std;
void PrintResult (double a) 2.5
{ 2.5

a=5.5; CHAPTER 5
}

int main()
{

double a=2.5;
cout<<a<<endl;
PrintResult(a);
cout<<a;
}

88 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

5.3 Parameter passing – passing by reference

› A function can return a value by using return statement.
› To return more than one value, reference parameter is used.
› It is a formal parameter that represents the same memory location as the actual parameter.
› Any changes to formal parameter will also happened to actual parameter.
› & operator will be used to declare reference parameter.
› Program example:

#include<iostream> OUTPUT
using namespace std;
void PrintResult (double &a) 2.5
{ 5.5

a=5.5;
}

int main()
{

double a=2.5;
cout<<a<<endl;
PrintResult(a);
cout<<a;
}

Example 1: (1 function, 1 main): CHAPTER 5

#include<iostream>
using namespace std;
int area(int length, int width); //function prototype

//main program
int main()
{

int length1, int width1;
cout<<”Enter length:”;
cin>>length1;
cout<<”Enter width:”;
cin>>width1;
cout<<”\nThe area of:”<<length1<<”x”<<width1;
cout<<”room is:”<<area(length1,width1);//function call
return 0;
}

//function to calculate area
//function definition
int area(int length, int width)
{

int result;
result = length * width;
return result;
}

89 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

Example 2: (3 functions, 1 main): //function to getinput
void getinput()
#include<iostream> {
using namespace std;
cout<<”Enter length:”;
//function prototype cin>>length;
cout<<”Enter width:”;
void getinput(); cin>>width;
int area(); cout<<”\n”;
void printarea(); }

int length, width; //function to calculate area
int area()
//main program {
int main()
{ int result;
result = length * width;
getinput(); return result;
printearea(); }
}

//function to print area
void printarea()
{

cout<<”Area is:”<<area()<<endl;
}

Example 3: OUTPUT

Function Without Value Returned And Parameter Welcome to CSC128 class
Hope you enjoy this class!
#include<iostream> Welcome to CSC128 class
suing namespace std;
//function prototype
void message();

int main()
{

message(); //function call
cout<<”Hope you enjoy this class!”;
message();
}

void message()
{

cout<<”Welcome to CSC128 class”;
}

CHAPTER 5

90 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

Example 4: OUTPUT

Function Has Value Returned But Without Parameter OPTION OPERATION

#include <iostream> 1 Addition
using namespace std;
int Menu(); 2 Subtraction
int main ()
{ 3 Multiply

int selection; 4 Divide
selection = Menu();
cout<<"Your choice is number: " Pick a selection: 4

<< selection <<endl; Your choice is number 4
}
int Menu()
{

int option;
cout <<"\tOPTION \tOPERATION"<<endl;
cout <<"\t 1 \tAddition "<<endl;
cout <<"\t 2 \tSubtraction "<<endl;
cout <<"\t 3 \tMultiply "<<endl;
cout <<"\t 4 \tDivide "<<endl;
cout <<"Pick a selection: ";
cin >> option;
return option;
}

Example 5:
Function Without Value Returned But With Parameter

#include <iostream> Output
using namespace std; Enter mark: 51
void findStatus(int); Pass

int main () CHAPTER 5
{

int mark;
cout<<"Enter mark: ";
cin>>mark;
findStatus(mark);
}
void findStatus(int value)
{
if (value>=80)

cout <<"Excellent";
else if(value>=60)

cout <<"Good";
else if(value>=50)

cout <<"Pass";
else

cout<<"Fail";
}

91 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

Example 6:

Function Has Value Returned But Without Parameter

#include <iostream> int main()
using namespace std; {
int selection;
int Menu() int no1, no2;
{ cout<<"Enter number 1:";
cin>>no1;
int option; cout<<"Enter number 2:";
cout <<"\tOPTION\tOPERATION\n"; cin>>no2;
cout <<"\t 1 \tAddition\n"; selection = Menu();
cout <<"\t 2 \tSubtraction\n”; cout<<"Your choice is number: "
cout <<"\t 3 \tMultiply\n”;
cout <<"\t 4 \tDivide\n”; << selection<<endl;
cout <<"Pick a selection: "; cout<<"The result for:"<< no1
cin >> option;
return option; <<insert()<<no2 << "is:"
} <<cal(no1,no2)<<endl;
}

char insert() int cal(int no1, int no2)
{ {

char icon; int result;
if (selection==1) if (selection==1)

icon='+'; result=no1+no2;
if (selection ==2) if (selection==2)

icon='-'; result=no1-no2;
if(selection==3) if(selection==3)

icon='*'; result=no1*no2;
if(selection ==4) if(selection==4)

icon='/'; result=no1/no2;
return result;
return icon; }

}

//OR CHAPTER 5

void getinput()
{

cout<<"Enter number 1:";
cin>>no1;
cout<<"Enter number 2:";
cin>>no2;
}

int main()
{

getinput();

selection = Menu();

cout<<"Your choice is number: " << selection <<endl;

cout<<"The result for:"<< no1 << insert()
<<no2 << "is:"<< cal(no1,no2)<<endl;

}

92 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS

Example 7 :
Function With Value Returned and Parameter

#include <iostream> Output
using namespace std; The result is 45
int add (int, int, int, int);

int main ()
{

int sum;
sum = add(5, 10, 6, 24);
cout << "The result is " <<sum;
}

int add (int a, int b, int c, int d)
{

int s;
s = a + b + c + d;
return s;
}

Example 8 :

Function Without Value Returned but with 2 Parameters

#include <iostream>
using namespace std;

void add (int, double)
int main ()
{

int sum,x=3;
double y=4.5;

add(x,y);
}

void add (int a, double b)
{

double total;
total = a + b;
cout<<”The result is:”<<total<<endl;
}

CHAPTER 5

93 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 5

Example 9 :
Function using pass by value and pass by reference
Write a program to calculate the volume of a cone and cylinder. Use function getValue() to get
the radius and height from the user. Function calVolume() will calculate and return the volume
of the cone and the cylinder. Then display the volume of the cone and the cylinder in function
display().

#include <iostream>
#include <math.h>
using namespace std;
void getValue (int &r, int &h);
void calVolume (int r, int h, double &cone, double &cylinder);
void display (double c, double s);
int main ()
{

//declare variables with no values
int radius, height;
double cone, cylinder;
//function call
/*variables radius and height with no values are passed to function
getValues()*/
getValues(radius, height);
/*main receives updated values for radius and height and passes to
function calVolume()*/
calVolume (radius, height, cone, cylinder);
/*main receives updated values for cone and cylinder and passes to
function main */
display (cone, cylinder);
return 0;
}

94 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 5

//getValue() receives the location to store radius and height
void getValue(int &r, int &h)
{

cout<<”Enter radius:”;
cin>>r;
cout<<”Enter height:”;
cin>>h;
}
/*calVolume() receives values for radius and height to calculate the
volume for cone and cylinder*/
/*calVolume() receives the locations to store the values of cone and
cylinder after they are calculated. */
void calVolume (int r, int h, double &cone, double &cylinder)
{
const double PI=3.142;
cone=(1/3.0)*PI*pow(r,2)*h;
cylinder=PI*pow(r,2)*h;
{
/*display() receives values for volume of cone and cylinder and display
the result*/
void display(double c, double s)
{

cout<<”\nVolume of a cone is “<<cone<<endl;
cout<<”\nVolume of a cylinder is “<<cylinder<<endl;
}

95 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6

CHAPTER 6
ARRAYS

CHAPTER OUTLINE
1. Introduction to array
2. One-dimensional Arrays

- Array Declaration
- Array Initailization
- Restrictions in Array Operation
- Accessing Array Elements
3. Two-dimensional Arrays
- Accessing and Initialization of 2D Array Components
4. Array of Characters
- Accessing and Initialization of String
5. Array operations
- Summation
- Finding the maximum
- Finding the minimum
6. Passing arrays to a function

At the end of this chapter, student should be able to:
i. Understand the concept of an array
ii. Perform array declaration and initialization
iii. Access elements in an array
iv. Understand two dimensional arrays
v. Use an array for string
vi. Perform operation (find summation, maximum & minimum) in an array

vii. Pass an array to a function

96 | P a g e

INTRODUCTION TO C++ FOR BEGINNERS CHAPTER 6
1. Introduction to array

› In C++ programming, an array is a data structure. It is process of group the same categories
of data.

› Array is a collection of data of the same data type. An array allows us to group and store
same variables which have a same data type.

› Usually a variable can hold one value at a time, but by using an array, we can store more than
one value in a single variable.

› Figure below shows the difference between an array and a variable.

› Figure below shows arrays Salary,Name and Staff ID

› Arrays can be one-dimensional and multidimensional.
› The one-dimensional array is the simplest form of an array. It is a collection of elements or

components that have similar data types and names.
› A multidimensional array is really an array of array(s). We will focus on the two-dimensional

(2D) array, which is a collection of elements with the same data type or components arranged
in rows and columns.
› The figure below has four elements stored in the array.
97 | P a g e


Click to View FlipBook Version