Module in CC102 Computer Programming 1
Module in CC102 Computer Programming 1
TECHNOLOGY,
INCORPORATED
MODULE
iN
COMPUTER
PROGRAMMING 1
MODULE I
LESSON 1: Orientation
Objectives: At the end of the lesson, the students will be able to:
1) Internalize the vision and mission of the institution;
2) Determine the subject policies and guidelines, topics, and course
Contents;
3) Analyze and apply the department protocol during the pandemic; and
4) Reflect on the importance of the orientation activity.
VISION
MISSION
This course will use varied teaching strategies such as lecture, discussion,
laboratory works and others. The lectures are designed to reinforce and augment the
Computer Programming 1 |2
material presented in the readings. Laboratory works will include discussion and actual
exercises. Students must participate actively in all the activities in order to experience
how the strategies and techniques are applied in their learning process.
Academic Integrity
Exceptional Circumstances
Class Attendance
Computer Programming 1 |3
Attendance must be highly observed for all students who are enrolled in this
course. Avoid absences as much as possible. Each session is very important on
student learning. Three tardiness is equal to one absence. The maximum number of
allowable absences of a student whether excuse or not is equivalent to twenty percent
of the total number of class hours in a given semester as per CHED recognition. Based
on that premise, the total allowable absences for MTW and TFS schedule are only ten
(10). If the students accumulated more than the allowable absences, he/she will be
dropped from the subject and will get a failing grade or NCA. Fifteen minutes late is
equal to one absence. Lastly, early dismissal or early out of a student before the allotted
time is also considered as absence.
Classroom Management
Students should have an official seating and grouping assignment that should be
observed from the before and after the class. Using electronic gadgets or any gaming
material which are not related to the subject are prohibited if there is an ongoing
classroom discussion.
Course Requirements
The following are the vital requirements for the completion of this course:
Class attendance
Class participation
Quizzes and assignments
Laboratory Works
Project
Examinations (Prelim, Midterm, Final)
Grading System
This subject will use the following grading system in evaluating the students’
performance in this course:
Quizzes 20%
Assignment 10%
Computer Programming 1 |4
to the “new normal classroom and mode of teaching and learning”. One of the foreseen
problems were the new classroom setting for the teachers and learners, safety
protocols during the pandemic, and the overall health safety measures of the school for
their employees and students. The new classroom setting is a classroom scenario
wherein strict social distancing between teacher and learner will be enforced and
blended learning system will be adopted. Blended learning is a style of education in
which students learn via electronic and online media as well as traditional face-to-face
teaching.
In line with this, in order for the MCTI Information Technology Department to
contribute for the overall safety of the teachers and students during the COVID-19
Pandemic, the following guidelines are set to be observed both by the teachers and
students in this department:
The teachers/students are also encourage to bring with them their personal
70% hand sanitizers and alcohol for them to disinfect their hands when
unconsciously in contact with unclean or unsanitized surfaces.
If any of the teacher/student is not “feeling well” during a class, he/she will be
advised not to continue the session and will be assisted at the MCTI Clinic to
be evaluated by the school nurse for further checking of health condition.
Activity. After the lesson, you may answer the following questions substantially. Take
note that you must observe neatness and cleanliness in answering this part of your
module.
1. What do you think about the vision and mission of the school? Discuss your answer
substantially.
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
Computer Programming 1 |7
2. Reflect on the policies of the course. What are the course policies that you like and
don’t like? Explain why you don’t like or like it the policy and justify your answer.
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
REFLECTIONS:
NOW: Try to reflect on the following statements and answer it. Write you answer in the
space provided.
Question #1. Health Protocols are important in the school.
Question #2. People should never over react on the policies or protocols during this
pandemic.
1.____________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
Computer Programming 1 |8
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
2.____________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
Computer Programming 1 |9
What are your expectations about this subject lesson? Write it in the space
provided.
History of C++
There are many text editors and compilers to choose from. In this tutorial, we will use an
IDE (see below).
An IDE (Integrated Development Environment) is used to edit AND compile the code.
Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free, and
they can be used to both edit and debug C++ code.
C++ Quickstart
Write the following C++ code and save the file as myfirstprogram.cpp (File > Save File
as):
myfirstprogram.cpp
this guide we will write and understand the first program in C++ programming. We are
writing a simple C++ program that prints “Hello World!” message. Lets see the program
first and then we will discuss each and every part of it in detail.
C o m p u t e r P r o g r a m m i n g 1 | 12
/*
* Multiple line
* comment
*/
#include<iostream>
return 0;
}
Output:
Hello World!
Let’s discuss each and every part of the above program.
1. Comments – You can see two types of comments in the above program
For example:
C o m p u t e r P r o g r a m m i n g 1 | 13
4. int main() – As the name suggests this is the main function of our program and the
execution of program begins with this function, the int here is the return type which
indicates to the compiler that this function will return a integer value. That is the main
reason we have a return 0 statement at the end of main function.
5. cin>> - is an object of the input stream and is used to take input from input streams
like files, console, etc.
6. cout << “Hello World!”; – The cout object belongs to the iostream file and the
purpose of this object is to display the content between double quotes as it is on the
screen. This object can also display the value of variables on screen(don’t worry, we will
see that in the coming tutorials).
7. return 0; – This statement returns value 0 from the main() function which indicates
that the execution of main function is successful. The value 1 represents failed
execution.
Activity
Program writing
Write a simple program that will print your full name, write it in a one whole sheet of
yellow pad paper.
Duration: 1 hour
int num1,num2;
num1=20;
num2=100;
Types of variables
Variables can be categorised based on their data type. For example, in the above
example we have seen integer types variables. Following are the types of variables
available in C++.
char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc.
Before going further lets discuss what is scope first. When we discussed the Hello
World Program, we have seen the curly braces in the program like this:
int main {
//Some code
}
Any variable declared inside these curly braces have scope limited within these curly
braces, if you declare a variable in main() function and try to use that variable outside
main() function then you will get compilation error.
Now that we have understood what is scope. Lets move on to the types of variables
based on the scope.
C o m p u t e r P r o g r a m m i n g 1 | 16
1. Global variable
2. Local variable
Global Variable
A variable declared outside of any function (including main as well) is called global
variable. Global variables have their scope throughout the program, they can be
accessed anywhere in the program, in the main, in the user defined function, anywhere.
Local variable
Local variables are declared inside the braces of any user defined function, main
function, loops or any control statements(if, if-else etc) and have their scope limited
inside those braces.
#include <iostream>
using namespace std;
C o m p u t e r P r o g r a m m i n g 1 | 17
char myFuncn() {
// This is a local variable
char myVar = 'A';
}
int main()
{
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Value of myVar: "<< myVar;
return 0;
}
Output:
Compile time error, because we are trying to access the variable myVar outside of its
scope. The scope of myVar is limited to the body of function myFuncn(), inside those
braces.
Lets see an example having same name global and local variable.
#include <iostream>
using namespace std;
// This is a global variable
har myVar = 'A';
char myFuncn() {
// This is a local variable
char myVar = 'B';
return myVar;
}
int main()
{
cout <<"Funcn call: "<< myFuncn()<<endl;
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Funcn call: "<< myFuncn()<<endl;
cout <<"Value of myVar: "<< myVar<<endl;
return 0;
}
C o m p u t e r P r o g r a m m i n g 1 | 18
Output:
Funcn call: B
Value of myVar: A
Funcn call: B
Value of myVar: Z
As you can see that when I changed the value of myVar in the main function, it only
changed the value of global variable myVar because local variable myVar scope is
limited to the function myFuncn().
Activity 1
Activity 2
Program writing
Write a simple program that will print your name vertically using char variable. Write it in
a one whole sheet of yellow pad paper.
Duration: 1 hour
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 = 40;
cout<<"num1 + num2: "<<(num1 + num2)<<endl;
cout<<"num1 - num2: "<<(num1 - num2)<<endl;
cout<<"num1 * num2: "<<(num1 * num2)<<endl;
cout<<"num1 / num2: "<<(num1 / num2)<<endl;
cout<<"num1 % num2: "<<(num1 % num2)<<endl;
return 0;
}
Output:
2) Assignment Operators
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 = 40;
num2 = num1;
cout<<"= Output: "<<num2<<endl;
num2 += num1;
cout<<"+= Output: "<<num2<<endl;
num2 -= num1;
cout<<"-= Output: "<<num2<<endl;
num2 *= num1;
cout<<"*= Output: "<<num2<<endl;
num2 /= num1;
cout<<"/= Output: "<<num2<<endl;
num2 %= num1;
cout<<"%= Output: "<<num2<<endl;
return 0;}
Output:
= Output: 240
C o m p u t e r P r o g r a m m i n g 1 | 22
+= Output: 480
-= Output: 240
*= Output: 57600
/= Output: 240
%= Output: 0
++ and —
num++ is equivalent to num=num+1;
#include <iostream>
using namespace std;
int main(){
int num1 = 240;
int num2 = 40;
num1++; num2--;
cout<<"num1++ is: "<<num1<<endl;
cout<<"num2-- is: "<<num2;
return 0;
}
Output:
num1++ is: 241
num2-- is: 39
4) Logical Operators
Logical Operators are used with binary variables. They are mainly used in conditional
statements and loops for evaluating a condition.
Logical operators in C++ are: &&, ||, !
Let’s say we have two boolean variables b1 and b2.
b1&&b2 will return true if both b1 and b2 are true else it would return false.
b1||b2 will return false if both b1 and b2 are false else it would return true.
!b1 would return the opposite of b1, that means it would be true if b1 is false and it
would return false if b1 is true.
C o m p u t e r P r o g r a m m i n g 1 | 23
5) Relational operators
We have six relational operators in C++: ==, !=, >, <, >=, <=
== returns true if both the left side and right side are equal
!= returns true if left side is not equal to the right side of operator.
5) Bitwise Operators
num1 | num2 compares corresponding bits of num1 and num2 and generates 1 if either
bit is 1, else it returns 0. In our case it would return 31 which is 00011111
num1 ^ num2 compares corresponding bits of num1 and num2 and generates 1 if they
are not equal, else it returns 0. In our example it would return 29 which is equivalent to
00011101
~num1 is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In our
example it would return -12 which is signed 8 bit equivalent to 11110100
num1 << 2 is left shift operator that moves the bits to the left, discards the far left bit,
and assigns the rightmost bit a value of 0. In our case output is 44 which is equivalent to
00101100
Note: In the example below we are providing 2 at the right side of this shift operator that
is the reason bits are moving two places to the left side. We can change this number
and bits would be moved by the number of bits specified on the right side of the
operator. Same applies to the right side operator.
num1 >> 2 is right shift operator that moves the bits to the right, discards the far right
bit, and assigns the leftmost bit a value of 0. In our case output is 2 which is equivalent
to 00000010
#include <iostream>
using namespace std;
int main(){
int num1 = 11; /* 11 = 00001011 */
int num2 = 22; /* 22 = 00010110 */
int result = 0;
result = num1 & num2;
cout<<"num1 & num2: "<<result<<endl;
result = num1 | num2;
C o m p u t e r P r o g r a m m i n g 1 | 25
6) Ternary Operator
This operator evaluates a boolean expression and assign the value based on the result.
Syntax:
#include <iostream>
using namespace std;
int main(){
int num1, num2; num1 = 99;
/* num1 is not equal to 10 that's why
* the second value after colon is assigned
* to the variable num2
C o m p u t e r P r o g r a m m i n g 1 | 26
*/
num2 = (num1 == 10) ? 100: 200;
cout<<"num2: "<<num2<<endl;
/* num1 is equal to 99 that's why
* the first value is assigned
* to the variable num2
*/
num2 = (num1 == 99) ? 100: 200;
cout<<"num2: "<<num2;
return 0;
}
Output:
num2: 200
num2: 100
.Operator Precedence in C++
This determines which operator needs to be evaluated first if an expression has more
than one operator. Operator with higher precedence at the top and lower precedence at
the bottom.
Unary_Operators
Logical AND
++ – – ! ~ &&
Multiplicative
Logical OR
*/% ||
Additive
Ternary
+–
?:
Shift
<< >> >>> Assignment
= += -= *= /= %= > >= < <= &= ^= |=
Relational
> >= < <=
Equality
==
C o m p u t e r P r o g r a m m i n g 1 | 27
Bitwise_AND
&
Bitwise_XOR
^
Bitwise_OR
|
Activity 1
Where does the logical operators mainly used? Write it in the space provided.
Activity 2
Program writing
Write a program that will print this series of number 0 1 2 3 4 5 6 7 8 9 using int variable.
Write it in a one whole sheet of yellow pad paper.
Duration: 1 hour
What is a Flowchart?
A flowchart is a graphical representations of steps. It was originated from computer
science as a tool for representing algorithms and programming logic but had extended
to use in all other kinds of processes. Nowadays, flowcharts play an extremely
important role in displaying information and assisting reasoning. They help us
visualize complex processes, or make explicit the structure of problems and tasks. A
flowchart can also be used to define a process or project to be implemented.
Flowchart Symbols
Different flowchart shapes have different conventional meanings. The meanings of
some of the more common shapes are as follows:
C o m p u t e r P r o g r a m m i n g 1 | 29
Activity 1
Why flow chart is important in c++ programming language? Write it in the space
provided.
C o m p u t e r P r o g r a m m i n g 1 | 31
Activity 2
Create a flow chart that will add, subtract, multiply and divide number 46 and number
47. Write it in a 1 whole sheet of yellow pad paper.
Duration: 1 hour
Introduction: Switch case statement is used when we have multiple conditions and we
need to perform different action based on the condition. When we have multiple
conditions and we need to execute a block of statements when a particular condition is
satisfied. In such case either we
;
default:
//C++ code
;
}
Switch Case statement is mostly used with break statement even though the break
statement is optional. We will first see an example without break statement and then we
will discuss switch case with break
#include <iostream>
using namespace std;
int main(){
int num=5;
switch(num+2) {
case 1:
cout<<"Case1: Value is: "<<num<<endl;
case 2:
cout<<"Case2: Value is: "<<num<<endl;
case 3:
cout<<"Case3: Value is: "<<num<<endl;
default:
cout<<"Default: Value is: "<<num<<endl;
}
return 0;
}
Output:
Before we discuss about break statement, Let’s see what happens when we don’t use
break statement in switch case. See the example below:
#include <iostream>
using namespace std;
int main(){
int i=2;
switch(i) {
case 1: cout<<"Case1 "<<endl;
case 2: cout<<"Case2 "<<endl;
case 3: cout<<"Case3 "<<endl;
case 4: cout<<"Case4 "<<endl;
default: cout<<"Default "<<endl;
}
return 0;
}
Output:
Case2
Case3
Case4
C o m p u t e r P r o g r a m m i n g 1 | 34
Default
In the above program, we have the variable i inside switch braces, which means
whatever the value of variable i is, the corresponding case block gets executed. We
have passed integer value 2 to the switch, so the control switched to the case 2,
however we don’t have break statement after the case 2 that caused the flow to
continue to the subsequent cases till the end. However this is not what we wanted, we
wanted to execute the right case block and ignore rest blocks. The solution to this issue
is to use the break statement in after every case block.
Break statements are used when you want your program-flow to come out of the switch
body. Whenever a break statement is encountered in the switch body, the execution
flow would directly come out of the switch, ignoring rest of the cases. This is why you
must end each case block with the break statement.
Let’s take the same example but this time with break statement.
#include <iostream>
using namespace std;
int main(){
int i=2;
switch(i) {
case 1:
cout<<"Case1 "<<endl;
break;
case 2:
cout<<"Case2 "<<endl;
break;
case 3:
cout<<"Case3 "<<endl;
break;
case 4:
cout<<"Case4 "<<endl;
break;
default:
cout<<"Default "<<endl;
}
return 0;
}
C o m p u t e r P r o g r a m m i n g 1 | 35
Output:
Case2
Now you can see that only case 2 got executed, rest of the subsequent cases were
ignored.
Why didn’t I use break statement after default?
The control would itself come out of the switch after default so I didn’t use break
statement after it, however if you want you can use it, there is no harm in doing that.
1) Case doesn’t always need to have order 1, 2, 3 and so on. It can have any integer
value after case keyword. Also, case doesn’t need to be in an ascending order always,
you can specify them in any order based on the requirement.
#include <iostream>
using namespace std;
int main(){
char ch='b';
switch(ch) {
case 'd': cout<<"Case1 ";
break;
case 'b': cout<<"Case2 ";
break;
case 'x': cout<<"Case3 ";
break;
case 'y': cout<<"Case4 ";
break;
default: cout<<"Default ";
}
return 0;
}
3) Nesting of switch statements are allowed, which means you can have switch
statements inside another switch. However nested switch statements should be avoided
as it makes program more complex and less readable.
C o m p u t e r P r o g r a m m i n g 1 | 36
Activity 1
What is switch case statement purpose in c++? Write your answer in the space
provided.
Activity 2
Program Analysis
Identify the output of each program shown. Write your answer in a ½ sheet of yellow
pad paper.
1.
#include <iostream>
using namespace std;
int main(){
int num=1;
switch(num+2) {
C o m p u t e r P r o g r a m m i n g 1 | 37
case 1:
cout<<"Case1: Value is: "<<num<<endl;
case 2:
cout<<"Case2: Value is: "<<num<<endl;
case 3:
cout<<"Case3: Value is: "<<num<<endl;
default:
cout<<"Default: Value is: "<<num<<endl;
Output:
2.
#include <iostream>
using namespace std;
int main(){
int i=2;
switch(i) {
case 1: cout<<"Case1 "<<endl;
case 2: cout<<"Case2 "<<endl;
case 3: cout<<"Case3 "<<endl;
case 4: cout<<"Case4 "<<endl;
default: cout<<"Default "<<endl;
}
return 0;
}
Ouput:
3.
#include <iostream>
using namespace std;
int main(){
int i=3;
switch(i) {
case 1: cout<<"Case1 "<<endl;
case 2: cout<<"Case2 "<<endl;
C o m p u t e r P r o g r a m m i n g 1 | 38
4.
#include <iostream>
using namespace std;
int main(){
int i=4;
switch(i) {
case 1: cout<<"Case1 "<<endl;
case 2: cout<<"Case2 "<<endl;
case 3: cout<<"Case3 "<<endl;
case 4: cout<<"Case4 "<<endl;
default: cout<<"Default "<<endl;
}
return 0;
Output:
Case doesn’t always need to have order 1, 2, 3 and so on. It can have any
integer value after case keyword. Also, case doesn’t need to be in an ascending
order always, you can specify them in any order based on the requirement.
C o m p u t e r P r o g r a m m i n g 1 | 39
Duration: 1 hour
decision in the program logic. For decision making in C++, we have four types of control
statements (or control structures), which are as follows:
a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement
If statement in C++
if(condition){
Statement(s);
}
The statements inside if parenthesis (usually referred as if body) gets executed only
when the given condition is true. If the condition is false then the statements inside if
body are completely ignored.
Example of if statement
#include <iostream>
using namespace std;
int main(){
int num=70;
if( num < 100 ){
/* This cout statement will only execute,
* if the above condition is true
*/
cout<<"number is less than 100";
}
if(condition_1) {
Statement1(s);
if(condition_2) {
Statement2(s);
}
}
C o m p u t e r P r o g r a m m i n g 1 | 41
Statement1 would execute if the condition_1 is true. Statement2 would only execute if
both the conditions( condition_1 and condition_2) are true.
#include <iostream>
using namespace std;
int main(){
int num=90;
/* Nested if statement. An if statement
* inside another if body
*/
if( num < 100 ){
cout<<"number is less than 100"<<endl;
if(num > 50){
cout<<"number is greater than 50";
}
}
return 0;
}
Output:
number is less than 100
number is greater than 50
Sometimes you have a condition and you want to execute a block of code if condition is
true and execute another piece of code if the same condition is false. This can be
achieved in C++ using if-else statement.
if(condition) {
Statement(s);
}
else {
Statement(s);
}
C o m p u t e r P r o g r a m m i n g 1 | 42
The statements inside “if” would execute if the condition is true, and the statements
inside “else” would execute if the condition is false.
#include <iostream>
using namespace std;
int main(){
int num=66;
if( num < 50 ){
//This would run if above condition is true
cout<<"num is less than 50";
}
else {
//This would run if above condition is false
C o m p u t e r P r o g r a m m i n g 1 | 43
if-else-if statement is used when we need to check multiple conditions. In this control
structure we have only one “if” and one “else”, however we can have multiple “else if”
blocks. This is how it looks:
if(condition_1) {
/*if condition_1 is true execute this*/
statement(s);
}
else if(condition_2) {
/* execute this if condition_1 is not met and
* condition_2 is met
*/
statement(s);
}
else if(condition_3) {
/* execute this if condition_1 & condition_2 are
* not met and condition_3 is met
*/
statement(s);
}
.
.
.
else {
/* if none of the condition is true
* then these statements gets executed
*/
statement(s);
}
C o m p u t e r P r o g r a m m i n g 1 | 44
Note: The most important point to note here is that in if-else-if, as soon as the condition
is met, the corresponding set of statements get executed, rest gets ignored. If none of
the condition is met then the statements inside “else” gets executed.
Example of if-else-if
#include <iostream>
using namespace std;
int main(){
int num;
cout<<"Enter an integer number between 1 & 99999: ";
cin>>num;
if(num <100 && num>=1) {
cout<<"Its a two digit number";
}
else if(num <1000 && num>=100) {
cout<<"Its a three digit number";
}
else if(num <10000 && num>=1000) {
cout<<"Its a four digit number";
}
else if(num <100000 && num>=10000) {
cout<<"Its a five digit number";
}
else {
cout<<"number is not between 1 & 99999";
}
return 0;
}
Output:
Activity 1
Activity 2
Program writing
Write a program that will print “Output is more than 75” using If statement. Write it
in a 1 whole sheet of yellow pad paper.
www.cplusplus.com
www.w3schools.com
C o m p u t e r P r o g r a m m i n g 1 | 46
www.visual-paradigm.com/tutorials/flowchart-tutorial
https://www.researchgate.net/publication/221045770_Real-
world_programming
MODULE II
Duration: 1 hour
Objectives: At the end of the lesson, the students will be able to:
There may be a situation, when you need to execute a block of code several A loop is
used for executing a block of statements repeatedly until a particular condition is
satisfied. For example, when you are displaying number from 1 to 100 you may want
set the value of a variable to 1 and display it 100 times, increasing its value by 1 on
each loop iteration.
while(condition)
{
statement(s);
}
C o m p u t e r P r o g r a m m i n g 1 | 47
In while loop, condition is evaluated first and if it returns true then the statements inside
while loop execute, this happens repeatedly until the condition returns false. When
condition returns false, the control comes out of loop and jumps to the next statement in
the program after while loop.
Note: The important point to note when using while loop is that we need to use
increment or decrement statement inside while loop so that the loop variable gets
changed on each iteration, and at some point condition returns false. This way we can
end the execution of while loop otherwise the loop would execute indefinitely.
#include <iostream>
using namespace std;
int main(){
int i=1;
/* The loop would continue to print
* the value of i until the given condition
* i<=6 returns false.
*/
while(i<=6){
C o m p u t e r P r o g r a m m i n g 1 | 48
A while loop that never stops is said to be the infinite while loop, when we give the
condition in such a way so that it never returns false, then the loops becomes infinite
and repeats itself indefinitely.
An example of infinite while loop:
This loop would never end as I’m decrementing the value of i which is 1 so the condition
i<=6 would never return false.
#include <iostream>
using namespace std;
int main(){
int i=1; while(i<=6) {
cout<<"Value of variable i is: "<<i<<endl; i--;
}
}
Example: Displaying the elements of array using while loop
#include <iostream>
using namespace std;
int main(){
int arr[]={21,87,15,99, -12};
/* The array index starts with 0, the
* first element of array has 0 index
* and represented as arr[0]
*/
int i=0;
while(i<5){
cout<<arr[i]<<endl;
C o m p u t e r P r o g r a m m i n g 1 | 49
i++;
}
}
Output:
21
87
15
99
-12
Activity 1
Activity 2
Using While Loop statement, write it in a 1 whole sheet of yellow pad paper.
In 99% of loops, the first counter you use is usually the letter i… as you nest
loops (more on that later), the letters are j, k, …
Loops are used to repeat a block of code.
Being able to have your program repeatedly execute a block of code is one of the
most basic but useful tasks in programming.
a loop lets you write a very simple statement to produce a significantly greater
result simply by repetition.
A while loop that never stops is said to be the infinite while loop
Duration: 1 hour
Objectives: At the end of the lesson, the students will be able to:
Introduction: Computers and applications help perform routine tasks very quickly.
They are great at counting and don't mind having to repeat a task a million times. And
programs are all about repetition. Think of something as simple as shuffling a deck of
cards. How great would it be if you could tell a computer to flip through six decks of
cards (virtually) and move cards around to random positions?
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
program.
First step: In for loop, initialization happens first and only once, which means that the
initialization part of for loop only executes once.
Second step: Condition in for loop is evaluated on each loop iteration, if the condition is
true then the statements inside for for loop body gets executed. Once the condition
returns false, the statements in for loop does not execute and the control gets
transferred to the next statement in the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for
loop executes that updates the loop counter.
Fourth step: After third step, the control jumps to second step and condition is re-
evaluated.
The steps from second to fourth repeats until the loop condition returns false.
C o m p u t e r P r o g r a m m i n g 1 | 52
A loop is said to be infinite when it executes repeatedly and never stops. This usually
happens by mistake. When you set the condition in for loop in such a way that it never
return false, it becomes infinite loop.
For example:
#include <iostream>
using namespace std;
int main(){
for(int i=1; i>=1; i++){
cout<<"Value of variable i is: "<<i<<endl;
}
return 0;
}
C o m p u t e r P r o g r a m m i n g 1 | 53
This is an infinite loop as we are incrementing the value of i so it would always satisfy
the condition i>=1, the condition would never return false.
// infinite loop
for ( ; ; ) {
// statement(s)
}
#include <iostream>
using namespace std;
int main(){
int arr[]={21,9,56,99, 202};
/* We have set the value of variable i
* to 0 as the array index starts with 0
* which means the first element of array
* starts with zero index.
*/
for(int i=0; i<5; i++){
cout<<arr[i]<<endl;
}
return 0;
}
Output:
21
9
56
99
202
C o m p u t e r P r o g r a m m i n g 1 | 54
C o m p u t e r P r o g r a m m i n g 1 | 55
Activity 1
What is the difference between For Loop and While Loop ? Write your answer in
the space provided.
Activity 2
using For Loop statement. Write it in a 1 whole sheet of yellow pad paper.
A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.
When you set the condition in for loop in such a way that it never return false, it
becomes infinite loop.
In for loop, initialization happens first and only once, which means that the
initialization part of for loop only executes once.
the interpreter always keeps track of which statement is about to be executed.
We call this the control flow, or the flow of execution of the program.
C o m p u t e r P r o g r a m m i n g 1 | 56
Duration: 1 hour
Objectives: At the end of the lesson, the students will be able to:
Introduction: In this lesson we will see do-while loop. do-while loop is similar to while
loop, however there is a difference between them: In while loop, condition is evaluated
first and then the statements inside loop body gets executed, on the other hand in do-
while loop, statements inside do-while gets executed first and then the condition is
evaluated.
do
{
statement(s);
} while(condition);
How do-while loop works?
First, the statements inside loop execute and then the condition gets evaluated, if the
condition returns true then the control jumps to the “do” for further repeated execution of
it, this happens repeatedly until the condition returns false. Once condition returns false
control jumps to the next statement in the program after do-while.
C o m p u t e r P r o g r a m m i n g 1 | 57
#include <iostream>
using namespace std;
int main(){
int num=1;
do{
cout<<"Value of num: "<<num<<endl;
num++;
}while(num<=6);
return 0;
}
Output:
Value of num: 1
Value of num: 2
Value of num: 3
Value of num: 4
Value of num: 5
Value of num: 6
#include <iostream>
using namespace std;
int main(){
int num=1;
do{
cout<<"Value of num: "<<num<<endl;
num++;
}while(num<=6);
return 0;
}
Output:
Value of num: 1
Value of num: 2
Value of num: 3
Value of num: 4
Value of num: 5
C o m p u t e r P r o g r a m m i n g 1 | 58
Value of num: 6
Activity 1
What are the similarities of For Loop, While Loop and Do-while Loop? Write your
answer in the space provided.
Activity 2
using Do-while Loop statement. Write it in a 1 whole sheet of yellow pad paper.
In do-while loop, statements inside do-while gets executed first and then the
condition is evaluated.
DO..WHILE loops are useful for things that want to loop at least once.
Keep in mind that you must include a trailing semi-colon in coding do-while loop.
A common error is to forget that a do..while loop must be terminated with a
semicolon (the other loops should not be terminated with a semicolon, adding to
the confusion).
C o m p u t e r P r o g r a m m i n g 1 | 59
Duration: 1 hour
Objectives: At the end of the lesson, the students will be able to:
continue;
Example: continue statement inside for loop
As you can see that the output is missing the value 3, however the for loop iterate
though the num value 0 to 6. This is because we have set a condition inside loop in
such a way, that the continue statement is encountered when the num value is equal to
3. So for this iteration the loop skipped the cout statement and started the next iteration
of loop.
#include <iostream>
using namespace std;
int main(){
for (int num=0; num<=6; num++) {
/* This means that when the value of
* num is equal to 3 this continue statement
* would be encountered, which would make the
* control to jump to the beginning of loop for
* next iteration, skipping the current iteration
*/
if (num==3) {
continue;
}
C o m p u t e r P r o g r a m m i n g 1 | 60
cout<<num<<" ";
}
return 0;
}
Output:
012456
Flow Diagram of Continue Statement
#include <iostream>
using namespace std;
int main(){
int j=6;
while (j >=0) {
if (j==4) {
j--;
continue;
}
cout<<"Value of j: "<<j<<endl;
j--;
}
C o m p u t e r P r o g r a m m i n g 1 | 61
return 0;
}
Output:
Value of j: 6
Value of j: 5
Value of j: 3
Value of j: 2
Value of j: 1
Value of j: 0
Example of continue in do-While loop
#include <iostream>
using namespace std;
int main(){
int j=4;
do {
if (j==7) {
j++;
continue;
}
cout<<"j is: "<<j<<endl;
j++;
}while(j<10);
return 0;
}
Output:
j is: 4
j is: 5
j is: 6
j is: 8
j is: 9
C o m p u t e r P r o g r a m m i n g 1 | 62
Activity 1
What is the purpose of continue statement in Loops? Write your answer in the
space provided.
Activity 2
Duration: 1 hour
Objectives: At the end of the lesson, the students will be able to:
Introduction: The break in C++ is a loop control statement which is used to terminate
the loop. As soon as the break statement is encountered from within a loop, the loop
iterations stops there and control returns from the loop immediately to the first statement
after the loop.
a) Use break statement to come out of the loop instantly. Whenever a break statement
is encountered inside a loop, the control directly comes out of loop terminating it. It is
used along with if statement, whenever used inside loop(see the example below) so that
it occurs only for a particular condition.
b) It is used in switch case control structure after the case blocks. Generally all cases in
switch case are followed by a break statement to avoid the subsequent cases (see the
example below) execution. Whenever it is encountered in switch-case block, the control
comes out of the switch-case body.
Syntax of break statement
break;
break statement flow diagram
C o m p u t e r P r o g r a m m i n g 1 | 64
In the example below, we have a while loop running from 10 to 200 but since we have a
break statement that gets encountered when the loop counter variable value reaches
12, the loop gets terminated and the control jumps to the next statement in program
after the loop body.
#include <iostream>
using namespace std;
int main(){
int num =10;
while(num<=200) {
cout<<"Value of num is: "<<num<<endl;
if (num==12) {
break;
}
num++;
}
cout<<"Hey, I'm out of the loop";
return 0;
}
Output:
Case 2
Case 3
Default
Hey, I'm out of the switch case
C o m p u t e r P r o g r a m m i n g 1 | 66
Activity 1
What is the purpose of Break statement in Loops? Write your answer in the space
provided.
Activity 2
Duration: 1 hour
C o m p u t e r P r o g r a m m i n g 1 | 67
Objectives: At the end of the lesson, the students will be able to:
Introduction: In a program we have any number of go-to and label statements, the Go-
to statement is followed by a label name, whenever Go-to statement is encountered, the
control of the program jumps to the label specified in the Go-to statement.The Go-to
statement is used for transferring the control of a program to a given label. The syntax
of Go-to statement looks like this:
goto label_name;
Program structure:
label1:
...
...
goto label2;
...
label2:
...
goto statements are almost never used in any development as they are complex and
makes your program much less readable and more error prone. In place of goto, you
can use continue and break statement.
Example of Go-to statement in C++
#include <iostream>
using namespace std;
int main(){
int num; cout<<"Enter a number: "; cin>>num;
if (num % 2==0){
goto print;
print:
cout<<"Even Number";
}
else {
cout<<"Odd Number";
}
return 0;
C o m p u t e r P r o g r a m m i n g 1 | 68
}
Output:
Enter a number: 42
Even Number
Activity 1
In your own idea, what is the purpose of Go-to statement in Loops? Write your
answer in the space provided.
Activity 2
Enter number: 3
Not divisible by 5
The Go-to statement is used for transferring the control of a program to a given
label.
Goto label_name; - syntanx used in goto statement.
www.geeksforgeeks.org
www.cpp.sh
https://www.tutorialspoint.com/cplusplus/cpp_for_loop.htm
www.beginnersbook.com
MODULE III
Introduction: You already know that every program must have a function
named main (which is where the program starts execution when it is run). However, as
programs start to get longer and longer, putting all the code inside the main function
becomes increasingly hard to manage. Functions provide a way for us to split our
programs into small, modular chunks that are easier to organize, test, and use. Most
programs use many functions.
The C++ standard library comes with plenty of already-written functions for you to use --
however, it’s just as common to write your own. Functions that you write yourself are
called user-defined functions.
A function is a set of statements that take inputs, do some specific computation and
produces output.
The idea is to put some commonly or repeatedly done task together and make a
function so that instead of writing the same code again and again for different inputs, we
can call the function.
C++ programs can work the same way. A program will be executing statements
sequentially inside one function when it encounters a function call. A function call is an
expression that tells the CPU to interrupt the current function and execute another
function. The CPU “puts a bookmark” at the current point of execution, and
then calls (executes) the function named in the function call. When the called function
ends, the CPU returns back to the point it bookmarked, and resumes execution.
The function initiating the function call is called the caller, and the function being called
is the callee or called function.
Syntax of Function
return_type function_name (parameter_list)
{
C o m p u t e r P r o g r a m m i n g 1 | 71
//C++ Statements
}
int main(){
//Calling the function
cout<<sum(1,99);
return 0;
}
Output:
100
The same program can be written like this: Well, I am writing this program to let you
understand an important term regarding functions, which is function declaration. Lets
see the program first and then at the end of it we will discuss function declaration,
definition and calling of function.
#include <iostream>
using namespace std;
//Function declaration
int sum(int,int);
//Main function
int main(){
//Calling the function
cout<<sum(1,99);
C o m p u t e r P r o g r a m m i n g 1 | 72
return 0;
}
/* Function is defined after the main method
*/
int sum(int num1, int num2){
int num3 = num1+num2;
return num3;
}
Function Declaration: You have seen that I have written the same program in two
ways, in the first program I didn’t have any function declaration and in the second
program I have function declaration at the beginning of the program. The thing is that
when you define the function before the main() function in your program then you don’t
need to do function declaration but if you are writing your function after the main()
function like we did in the second program then you need to declare the function first,
else you will get compilation error.
return_type function_name(parameter_list);
Note: While providing parameter_list you can avoid the parameter names, just like I did
in the above example. I have given int sum(int,int); instead of int sum(int num1,int
num2);.
return_type function_name(parameter_list) {
//Statements inside function
}
Calling function: We can call the function like this:
function_name(parameters);
Now that we understood the working of function, lets see the types of function in C++
C o m p u t e r P r o g r a m m i n g 1 | 73
Types of function
1) Built-in functions
2) User-defined functions
1) Built-in functions
Built-in functions are also known as library functions. We need not to declare and define
these functions as they are already written in the C++ libraries such as iostream, cmath
etc. We can directly call them when we need.
Here we are using built-in function pow(x,y) which is x to the power y. This function is
declared in cmath header file so we have included the file in our program
using #include directive.
#include <iostream>
#include <cmath>
using namespace std;
int main(){
C o m p u t e r P r o g r a m m i n g 1 | 74
Output:
32
2) User-defined functions
We have already seen user-defined functions, the example we have given at the
beginning of this tutorial is an example of user-defined function. The functions that we
declare and write in our programs are user-defined functions. Lets see another example
of user-defined functions.
User-defined functions
#include <iostream>
#include <cmath>
using namespace std;
//Declaring the function sum
int sum(int,int);
int main(){
C o m p u t e r P r o g r a m m i n g 1 | 75
int x, y;
cout<<"enter first number: ";
cin>> x;
Activity 1
Activity 2
Program writing
Write a simple program that will input 3 numbers and will subtract them (10 pts). write it
in a 1 whole sheet of yellow pad paper.
Output:
Functions provide a way for us to split our programs into small, modular chunks
that are easier to organize, test, and use. Most programs use many functions.
Functions that you write yourself are called user-defined functions.
return_type function_name(parameter_list); - syntax used in function.
A function call is an expression that tells the CPU to interrupt the current
function and execute another function.
A function is a set of statements that take inputs, do some specific computation
and produces output.
Duration: 1 hour
Introduction: The default arguments are used when you provide no arguments or only
few arguments while calling a function. The default arguments are used during
compilation of program. For example, lets say you have a user-defined
C o m p u t e r P r o g r a m m i n g 1 | 77
function sum declared like this: int sum(int a=10, int b=20), now while calling this
function you do not provide any arguments, simply called sum(); then in this case the
result would be 30, compiler used the default values 10 and 20 declared in function
signature. If you pass only one argument like this: sum(80) then the result would be
100, using the passed argument 80 as first value and 20 taken from the default
argument.
23
6
Rules of default arguments
As you have seen in the above example that I have assigned the default values for only
two arguments b and c during function declaration. It is up to you to assign default
values to all arguments or only selected arguments but remember the following rule
while assigning default values to only some of the arguments:
If you assign default value to an argument, the subsequent arguments must have
default values assigned to them, else you will get compilation error.
Activity 1
What is the purpose of Default arguments in C++ Funtions? Write your answer in
the space provided.
Activity 2
Program writing
Identify the following Functions if it is valid or invalid.
Default arguments are overwritten when calling function provides values for
them. For example, calling of function sum(10, 15, 25, 30) overwrites the value of
z and w to 25 and 30 respectively.
During calling of function, arguments from calling function to called function are
copied from left to right. Therefore, sum(10, 15, 25) will assign 10, 15 and 25 to
x, y, and z. Therefore, the default value is used for w only.
Once default value is used for an argument in function definition, all subsequent
arguments to it must have default value. It can also be stated as default
arguments are assigned from right to left. For example, the following function
definition is invalid as subsequent argument of default variable z is not default.
Duration: 1 hour
Method 1:
int arr[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Method 2:
int arr[] = {10, 20, 30, 40, 50};
C o m p u t e r P r o g r a m m i n g 1 | 82
Method 3:
int arr[5] = {10, 20, 30, 40, 50};
int main(){
int arr[] = {11, 22, 33, 44, 55};
cout<<arr[0]<<endl;
cout<<arr[1]<<endl;
cout<<arr[2]<<endl;
cout<<arr[3]<<endl;
cout<<arr[4]<<endl;
return 0;
}
Output:
11
22
33
44
55
Although this code worked fine, displaying all the elements of array like this is not
recommended. When you want to access a particular array element then this is fine but
if you want to display all the elements then you should use a loop like this:
#include <iostream>
using namespace std;
int main(){
int arr[] = {11, 22, 33, 44, 55};
int n=0;
while(n<=4){
cout<<arr[n]<<endl;
C o m p u t e r P r o g r a m m i n g 1 | 83
n++;
}
return 0;
}
Activity 1
Activity 2
Program Analysis
Identify the output of each program shown. Write your answer in a ½ sheet of yellow
pad paper.
1.
#include <iostream>
using namespace std;
int main(){
int arr[] = {11, 22, 33, 44, 55};
int n=2;
while(n<=4){
cout<<arr[n]<<endl;
n++;
C o m p u t e r P r o g r a m m i n g 1 | 84
}
return 0;
}
2.
#include <iostream>
using namespace std;
int main(){
int arr[] = {112, 2222, 48, 29, 25};
int n=3;
while(n<=4){
cout<<arr[n]<<endl;
n++;
}
return 0;
}
3.
#include <iostream>
using namespace std;
int main(){
int arr[] = {32, 424, 232, 534, 53, 5123, 23};
int n=4;
while(n<=6){
cout<<arr[n]<<endl;
n++;
}
return 0;
}
4.
#include <iostream>
using namespace std;
C o m p u t e r P r o g r a m m i n g 1 | 85
int main(){
int arr[] = {32, 424, 232, 534, 53, 5123, 23};
int n=0;
while(n<=3){
cout<<arr[n]<<endl;
n++;
}
return 0;
}
5.
#include <iostream>
using namespace std;
int main(){
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int n=0;
while(n<=6){
cout<<arr[n]<<endl;
n++;
}
return 0;
}
Duration: 1 hour
Introduction: Multidimensional arrays are also known as array of arrays. The data in
multidimensional array is stored in a tabular form as shown in the diagram below:
Initialization:
We can initialize the array in many ways:
Method 1:
int arr[2][3] = {10, 11 ,12 ,20 ,21 , 22};
Method 2:
This way of initializing is preferred as you can visualize the rows and columns here.
C o m p u t e r P r o g r a m m i n g 1 | 87
int main(){
int arr[2][3] = {{11, 22, 33}, {44, 55, 66}};
for(int i=0; i<2;i++){
for(int j=0; j<3; j++){
cout<<"arr["<<i<<"]["<<j<<"]: "<<arr[i][j]<<endl;
}
}
return 0;
}
Output:
arr[0][0]: 11
arr[0][1]: 22
arr[0][2]: 33
arr[1][0]: 44
arr[1][1]: 55
arr[1][2]: 66
Initialization:
We can initialize the array in many ways:
Method 1:
int arr[2][3][2] = {1, -1 ,2 ,-2 , 3 , -3, 4, -4, 5, -5, 6, -6};
Method 2:
This way of initializing is preferred as you can visualize the rows and columns here.
int arr[2][3][2] = {
{ {1,-1}, {2, -2}, {3, -3}},
{ {4, -4}, {5, -5}, {6, -6}}
}
int main(){
// initializing the array
int arr[2][3][2] = {
{ {1,-1}, {2,-2}, {3,-3} },
{ {4,-4}, {5,-5}, {6,-6} }
};
// displaying array values
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 3; y++) {
for (int z = 0; z < 2; z++) {
cout<<arr[x][y][z]<<" ";
}4
}
}
return 0;
}
Output:
1 -1 2 -2 3 -3 4 -4 5 -5 6 -6
C o m p u t e r P r o g r a m m i n g 1 | 89
Activity 1
What is Multidimensional Array in C++? Write your answer in the space provided.
Activity 2
Program writing
Write a simple program that will
Output:
Array {0}{0}: 21
Array {0}{1}: 22
Array {0}{2}: 24
Array {1}{0}: 25
Array {1}{1}: 26
Array {1}{2}: 27
Using Two Dimensional Array. Write it in a 1 whole sheet of yellow pad paper
A single dimensional array can be declared as int a[10] or int a[] = {1, 2, 3, 4}. It
means specifying the number of elements is optional in 1-D array.
A two dimensional array can be declared as int a[2][4] or int a[][4] = {1, 2, 3, 4, 5,
6, 7, 8}. It means specifying the number of rows is optional but columns are
mandatory.
Int myarray[2][3][2] – declaring a three dimensional Array.
Introduction: You can pass array as an argument to a function just like you pass
variables as arguments. In order to pass array to the function you just need to mention
the array name during function call like this:
function_name(array_name);
}
int main(){
int a[5] = {10, 20, 30, 40 ,50};
int b[5] = {1, 2, 3, 4, 5};
//Passing arrays to function
sum(a, b);
return 0;
}
Output:
11
22
33
44
55
#include <iostream>
#include <cmath>
using namespace std;
/* This method prints the square of each
* of the elements of multidimensional array
*/
void square(int arr[2][3]){
int temp;
for(int i=0; i<2; i++){
for(int j=0; j<3; j++){
temp = arr[i][j];
cout<<pow(temp, 2)<<endl;
}
}
}
int main(){
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
C o m p u t e r P r o g r a m m i n g 1 | 92
};
square(arr);
return 0;
}
Output:
1
4
9
16
25
36
Activity 1
What is Passing an Array to function in C++? Write your answer in the space
provided.
Activity 2
Program Analysis
Identify the output of each program shown. Write your answer in a ½ sheet of yellow
pad paper.
1.
#include <iostream>
using namespace std;
/* This function adds the corresponding
* elements of both the arrays and
* displays it.
*/
C o m p u t e r P r o g r a m m i n g 1 | 93
#include <iostream>
using namespace std;
void sum(int arr1[], int arr2[]){
int temp[5];
for(int i=0; i<5; i++){
temp[i] = arr1[i]+arr2[i];
cout<<temp[i]<<endl;
}
}
int main(){
int a[5] = {10, 20, 30, 40 ,50};
int b[5] = {1, 2, 3, 4, 50};
sum(a, b);
return 0;
}
3.
#include <iostream>
using namespace std;
void sum(int arr1[], int arr2[]){
int temp[5];
for(int i=0; i<5; i++){
temp[i] = arr1[i]+arr2[i];
C o m p u t e r P r o g r a m m i n g 1 | 94
cout<<temp[i]<<endl;
}
}
int main(){
int a[5] = {10, 20, 30, 40 ,50};
int b[5] = {1, 20, 3, 4, 5};
sum(a, b);
return 0;}
4.
#include <iostream>
using namespace std;
void sum(int arr1[], int arr2[]){
int temp[5];
for(int i=0; i<5; i++){
temp[i] = arr1[i]+arr2[i];
cout<<temp[i]<<endl;
}
}
int main(){
int a[5] = {10, 20, 3, 40 ,50};
int b[5] = {1, 2, 30, 4, 5};
sum(a, b);
return 0;
}
5.
#include <iostream>
using namespace std;
void sum(int arr1[], int arr2[]){
int temp[5];
for(int i=0; i<5; i++){
temp[i] = arr1[i]+arr2[i];
cout<<temp[i];
}
}
int main(){
int a[5] = {10, 20, 30, 40 ,50};
int b[5] = {10, 2, 3, 40, 5};
C o m p u t e r P r o g r a m m i n g 1 | 95
sum(a, b);
return 0;}
In order to pass array to the function you just need to mention the array name
during like this: function call
function_name(array_name);
Introduction: One of the most useful data types supplied in the C++ libraries is the
string. A string is a variable that stores a sequence of letters or other characters, such
as "Hello" or "May 10th is my birthday!". Just like the other data types, to create a string
we first declare it, then we can store a value in it.
Strings are words that are made up of characters, hence they are known as sequence
of characters. In C++ we have two ways to create and use strings: 1) By creating char
arrays and treat them as string 2) By creating string object
Lets discuss these two ways of creating string first and then we will see which method is
better and why.
1) Array of Characters – Also known as C Strings
Example 1:
A simple example where we have initialized the char array during declaration.
#include <iostream>
C o m p u t e r P r o g r a m m i n g 1 | 96
2) In this method, you can only use the in-built functions created for array which don’t
help much in string manipulation.
cout<<str<<endl;
The advantage of using this method is that you need not to declare the size of the
string, the size is determined at run time, so this is better memory management method.
The memory is allocated dynamically at runtime so no memory is wasted.
Activity 1
What is Passing an Array to function in C++? Write your answer in the space
provided.
C o m p u t e r P r o g r a m m i n g 1 | 99
Activity 2
Program writing
Write a simple program that will print your full name, age, address using Strings in C++.
(10 pts) write it in 1 whole sheet of yellow pad paper.
Example output:
Bryan Cabrido
24
Koronadal City
One of the most useful data types supplied in the C++ libraries is the string.
Strings are words that are made up of characters, hence they are known as
sequence of characters.
Size of the char array is fixed, which means the size of the string created
through it is fixed in size, more memory cannot be allocated to it during runtime.
Array of Characters can also be called C strings.
Project
https://www.onlinegdb.com/online_c++_compiler
https://www.programiz.com
Cprogramming.com
Onlinegbd.com