0% found this document useful (0 votes)
301 views

Module in CC102 Computer Programming 1

This document provides an orientation module for a Computer Programming 1 course at Marvelous College of Technology. It outlines the course policies, guidelines, requirements and grading system. The key points are: 1) The vision of the college is to provide quality education and develop students' intellectual and occupational skills. The course will use lectures, discussions, labs and projects. 2) Students must practice academic integrity and late assignments are not accepted. Class attendance is highly observed with allowable absences being 10. 3) Due to COVID-19, safety protocols include thermal scanning, social distancing, mandatory masks, hand sanitizing and assigned computers for students.

Uploaded by

Bryan Cabrido
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
301 views

Module in CC102 Computer Programming 1

This document provides an orientation module for a Computer Programming 1 course at Marvelous College of Technology. It outlines the course policies, guidelines, requirements and grading system. The key points are: 1) The vision of the college is to provide quality education and develop students' intellectual and occupational skills. The course will use lectures, discussions, labs and projects. 2) Students must practice academic integrity and late assignments are not accepted. Class attendance is highly observed with allowable absences being 10. 3) Due to COVID-19, safety protocols include thermal scanning, social distancing, mandatory masks, hand sanitizing and assigned computers for students.

Uploaded by

Bryan Cabrido
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 100

MARVELOUS COLLEGE OF

TECHNOLOGY,
INCORPORATED

MODULE
iN

COMPUTER
PROGRAMMING 1

For BSIT- I Students Of MCTI

Prepared By: Bryan L. Cabrido


Computer Programming 1 |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.

The Vision and Mission of Marvelous College of Technology, Inc.

VISION

The Marvelous College of Technology, Incorporated envisions its students to be


technically skilled, intellectually proficient, socially aware, and endeavouring to
transform the society in response to the signs of times.

MISSION

The institution commits to:

 Provide quality education through continuous upgrading of


programs and services,
 Develop and equip students with sufficient intellectual and
occupational skills to meet the demands of a globally changing
environment,
 Respect the dignity of the person especially the poor,
 Design and enhance curricular offerings with lifelong learning skills
essential in responding to industry needs and better quality of life
for our graduates, and
 Promote and strengthen our Filipino culture and values.

COURSE POLICIES AND GUIDELINES

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

Practice of Academic Integrity is expected in all students. Cheating is a major


offense. On all assignments, copying answers from classmates, allowing others to copy
his/her answers, and all other forms of plagiarism and cheating as given in the MCTI
Students’ Handbook will result in a failing grade for the assignment, and the incident
may be reported to the Dean of Students for disciplinary action. Students who are guilty
of cheating, plagiarism, intentional or without prior acknowledgement of the source in
any way violates the academic integrity policy of Marvelous College of Technology, Inc.,
and will received a failing mark (F) or Zero (0) points on the test or assignment in
question. On the other hand, students are welcome to discuss their homework
assignments and work together with their colleagues, but they must write each
assignment on themselves. If the students work together with their colleagues, make
sure that the student can also solve all the problems on his/her own when his/her
colleagues are not there to help. The students are not allowed to collaborate with
anyone on any exams.

Missed or Late Work

Late assignments are not accepted, except in exceptional circumstances and, if


possible, the student must have a permission from the instructor in advance. If a student
misses an assignment, then he/she will get a zero point for that assignment.

Exceptional Circumstances

Exceptional circumstances include religious obligations, serious personal illness


or injury, sudden hospitalization or death of an immediate family member, and illness
requiring home-stay of a dependent. If the absence or late assignment can be
anticipated, the student must notify the instructor at least one week prior. Unanticipated
absences may be excused only within 2 weeks following the date of the absence and
upon presentation of verifiable written documentation.

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

Class Participation/attendance 10%


Project 20%
Examination 50%
Total 100%
------------------------------------------------------------------------------------------------------------

THE MCTI INFORMATION TECHNOLOGY DEPARTMENT PROTOCOL

The "New Normal" is about to be experienced by the teachers and learners in


this institution that will be involved in the new mode of teaching and learning
environment. It is inevitable that this situation will trigger a paradigm shift - from the
accustomed classroom setting that are usually practice during classes by the teachers
and students

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:

 Good personal hygiene must be practiced by the teachers/students before


reporting to the school. These include proper personal grooming, hygienic
bath, and taking healthy meals and vitamins that will boost their immune
system. These may sound unusual but everyone is encourage to practice the
aforementioned since the virus is unseen and having a strong immune
system is the strongest fortress or defense of the teachers/students to combat
this disease. The proverb “A sound mind is in a sound body”, which is of
Greek origin, insists that the mind and body should be both healthy and
sound. Furthermore, a sound mind means a mind capable of good, positive
Computer Programming 1 |5

and free thinking mind. Thus, a healthy body is obtained by maintaining a


good diet and good exercise to keep the body going.

 Upon entering the classroom, the teachers/students must undergo thermal


scanning in Security Guard at the gate to check their body temperature. If the
body temperature exceeds the normal temperature (37˚C), then the
teachers/students are not allowed to enter any classrooms or school
premises and will be advised to rest or seek medical attention. After the
thermal scanning, they are instructed to wash their hands properly in the hand
washing area then step on the feet disinfectant to disinfect their footwear.

 The teachers/students are strictly advised that wearing a face mask is a


“MUST” when they are entering the school campus, and especially the
classroom. Primarily, one should bring or secure this item in their belongings.

 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.

 The teacher will assign a computer to the students to be used, 1 computer


per student. Once the student already has a computer assigned by his/her
teacher, he/she is not allowed to transfer or used other computers unless
unwanted circumstances occurred.

 In accordance with the mandate of the national government and local


government, the MCTI Information Technology Department is advocating that
“Social Distancing” must be practice by the teachers/students before,
during, and after the class. Therefore, unnecessary conversations,
gossiping, or gatherings of the students with their classmates are prohibited
to ensure that physical distancing is maintained.

 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.

 The teacher/student is prohibited to report to the class if he/she is has a flu,


cough, fever, or sick in order for him not to infect his/her fellows. He/she will
be advised to take a rest until his/her condition is getting better.
Computer Programming 1 |6

Based on the above-mentioned protocol, the MCTI Information Technology


Department is directing all the teachers and students in the concerned department to
strictly abide it during this COVID-19 Pandemic. Although there were many challenges
posed by this pandemic in this educational institution, this situation emphasizes that the
learner will be more responsible in their independent learning guided by their
modules and responsible teacher facilitators. Changes will be disseminated immediately
until further notice from the authorities will be issued. One department, one school, one
goal: "BEAT COVID". Let us heal as one.

Name: _______________________________ Year Level: ___________


Course: ______________________________ Date: ________________
Instructor: ____________________________ Room: _______________
Time/Schedule: ________________________ Remarks: ____________

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

Lesson 2: History of C++ and Hello World


Duration: 1 hour

What are your expectations about this subject lesson? Write it in the space
provided.

Objectives: At the end of the lesson, you will be able to:

 Define what is C++ Programming.


 Know the parts of the program.
 Learn how to install and write a program.

Procedures: Lecture and demonstration.


Introduction: C++ language is a direct descendant of C programming language with
additional features such as type checking, object oriented programming, exception
handling etc. You can call it a “better C”. It was developed by Bjarne Stroustrup.
C++ is a general purpose language, when I say general purpose it simply means that it
is designed to be used for developing applications in a wide variety of domains.

History of C++

The C++ programming language has a history going back to 1979,


when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the
languages Stroustrup had the opportunity to work with was a language called
Simula, which as the name implies is a language primarily designed for
simulations. The Simula 67 language - which was the variant that Stroustrup
C o m p u t e r P r o g r a m m i n g 1 | 10

worked with - is regarded as the first language to support the object-oriented


programming paradigm. Stroustrup found that this paradigm was very useful for
software development, however the Simula language was far too slow for
practical use.

In 1985, Stroustrup's reference to the language entitled The C++


Programming Language was published. That same year, C++ was implemented
as a commercial product. The language was not officially standardized yet,
making the book a very important reference. The language was updated again in
1989 to include protected and static members, as well as inheritance from
several classes.

In 1990, The Annotated C++ Reference Manual was released. The same


year, Borland's Turbo C++ compiler would be released as a commercial product.
Turbo C++ added a plethora of additional libraries which would have a
considerable impact on C++'s development. Although Turbo C++'s last stable
release was in 2006, the compiler is still widely used.

In 1998, the C++ standards committee published the first international


standard for C++ ISO/IEC 14882:1998, which would be informally known as C+
+98. The Annotated C++ Reference Manual was said to be a large influence in
the development of the standard. The Standard Template Library, which began
its conceptual development in 1979, was also included. In 2003, the committee
responded to multiple problems that were reported with their 1998 standard, and
revised it accordingly. The changed language was dubbed C++03.

In 2005, the C++ standards committee released a technical report (dubbed


TR1) detailing various features they were planning to add to the latest C++
standard. The new standard was informally dubbed C++0x as it was expected to
be released sometime before the end of the first decade. Ironically, however, the
new standard would not be released until mid-2011.

In mid-2011, the new C++ standard (dubbed C++11) was finished.


The Boost library project made a considerable impact on the new standard, and
some of the new modules were derived directly from the corresponding Boost
libraries.
Written by Albatross.
C o m p u t e r P r o g r a m m i n g 1 | 11

C++ Get Started

To start using C++, you need two things:

 A text editor, like Notepad, to write C++ code


 A compiler, like GCC, to translate the C++ code into a language that the
computer will understand

There are many text editors and compilers to choose from. In this tutorial, we will use an
IDE (see below).

C++ Install IDE

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.

Note: Web-based IDE's can work as well, but functionality is limited.

We will use Code::Blocks in our tutorial, which we believe is a good place to start.

You can find the latest version of Codeblocks


at http://www.codeblocks.org/downloads/26. Download the mingw-setup.exe file, which
will install the text editor with a compiler.

C++ Quickstart

Let's create our first C++ file.

Open Codeblocks and go to File > New > Empty File.

Write the following C++ code and save the file as myfirstprogram.cpp (File > Save File
as):

myfirstprogram.cpp

Hello World – First C++ Program

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

Hello World Program in C++

/*
* Multiple line
* comment
*/
#include<iostream>

//Single line comment


using namespace std;

//This is where the execution of program begins


int main()
{
// displays Hello World! on screen
cout<<"Hello World!";

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

// This is a single line comment


/* This is a multiple line comment
* suitable for long comments
*/
Comments as the names suggests are just a text written by programmer during code
development. Comment doesn’t affect your program logic in any way, you can write
whatever you want in comments but it should be related to the code and have some
meaning so that when someone else look into your code, the person should understand
what you did in the code by just reading your comment.

For example:
C o m p u t e r P r o g r a m m i n g 1 | 13

/* This function adds two integer numbers


* and returns the result as an integer value
*/int sum(int num1, int num2) {
return num1+num2;
}
Now if someone reads my comment he or she can understand what I did there just by
reading my comment. This improves readability of your code and when you are working
on a project with your team mates, this becomes essential aspect.

2. #include<iostream> – This statements tells the compiler to include iostream file.


This file contains pre defined input/output functions that we can use in our program.

3. using namespace std; – A namespace is like a region, where we have functions,


variables etc and their scope is limited to that particular region. Here std is a
namespace name, this tells the compiler to look into that particular region for all the
variables, functions, etc. I will not discuss this in detail here as it may confuse you. I
have covered this topic in a separate tutorial with examples. Just follow the tutorial in
the given sequence and you would be fine.

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.

Key points for Lesson 2

 Hello World – is the first program written by the learner in programming.


C o m p u t e r P r o g r a m m i n g 1 | 14

 IDE (Integrated Development Environment) - is used to edit AND compile the


code.
 Bjarne Stroustrup - is the one who developed the C++.
 C Language – is the older version of C++.
 1990 - The Annotated C++ Reference Manual was released.

Activity

Program writing
Write a simple program that will print your full name, write it in a one whole sheet of
yellow pad paper.

Lesson 3: Variables in C++

Duration: 1 hour

Objectives: At the end of the lesson, you will be able to:

 Define what is Variables in C++ Programming.


 know the types of variables.
 Learn how to program using variables in c++.

Procedures: Lecture and demonstration.

Introduction: A variable is a name which is associated with a value that can be


changed. For example when I write int num=20; here variable name is num which is
associated with value 20, int is a data type that represents that this variable can hold
integer values. We will cover the data types in the next tutorial. In this tutorial, we will
discuss about variables.

Syntax of declaring a variable in C++

data_type variable1_name = value1, variable2_name = value2;


For example:

int num1=20, num2=100;


C o m p u t e r P r o g r a m m i n g 1 | 15

We can also write it like this:

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++.

int: These type of of variables holds integer value.

char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc.

bool: holds boolean value true or false.

double: double-precision floating point value.

float: Single-precision floating point value.

Types of variables based on their scope

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.

Lets take an example to understand it:

Global variable example


Here we have a global variable myVar, that is declared outside of main. We have
accessed the variable twice in the main() function without any issues.
#include <iostream>
using namespace std;
// This is a global variable
char myVar = 'A';
int main()
{
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Value of myVar: "<< myVar;
return 0;
}
Output:
Value of myVar: A
Value of myVar: Z

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.

Local variable example

#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.

Can global and local variable have same name in C++?

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

How important variables in C++? Write it in the space provided.

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.

Key points for Lesson 3

 Variable – is a name which is associated with a value that can be changed.


C o m p u t e r P r o g r a m m i n g 1 | 19

 Global Variable - A variable declared outside of any function


 Local Variable - are declared inside the braces of any user defined function.
 Scope – is any codes that declared inside the braces.
 Data Types – Categorized Variables.

Lesson 4: Operators in C++

Duration: 1 hour

Objectives: At the end of the lesson, you will be able to:

 Know the types of operators in c++.


 Determine the types of operators in c++.
 Learn how to program using operators in c++.

Procedures: Lecture and demonstration.

Introduction: Operator represents an action. For example + is an operator that


represents addition. An operator works on two or more operands and produce an
output. For example 3+4+5 here + operator works on three operands and produce 12
as output.

Types of Operators in C++

1) Basic Arithmetic Operators


2) Assignment Operators
3) Auto-increment and Auto-decrement Operators
4) Logical Operators
5) Comparison (relational) operators
6) Bitwise Operators
7) Ternary Operator
C o m p u t e r P r o g r a m m i n g 1 | 20

1) Basic Arithmetic Operators

Basic arithmetic operators are: +, -, *, /, %

+ is for addition.


– is for subtraction.
* is for multiplication.
/ is for division.
% is for modulo.

Note: Modulo operator returns remainder, for example 20 % 5 would return 0

Example of Arithmetic Operators

#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:

num1 + num2: 280


num1 - num2: 200
num1 * num2: 9600
num1 / num2: 6
num1 % num2: 0
C o m p u t e r P r o g r a m m i n g 1 | 21

2) Assignment Operators

Assignments operators in C++ are: =, +=, -=, *=, /=, %=

num2 = num1 would assign value of variable num1 to the variable.

num2+=num1 is equal to num2 = num2+num1

num2-=num1 is equal to num2 = num2-num1

num2*=num1 is equal to num2 = num2*num1

num2/=num1 is equal to num2 = num2/num1

num2%=num1 is equal to num2 = num2%num1

Example of 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

3) Auto-increment and Auto-decrement Operators

++ and —
num++ is equivalent to num=num+1;

num–- is equivalent to num=num-1;

Example of Auto-increment and Auto-decrement Operators

#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

Example of Logical Operators


#include <iostream>
using namespace std;
int main(){
bool b1 = true;
   bool b2 = false;
cout<<"b1 && b2: "<<(b1&&b2)<<endl;
  cout<<"b1 || b2: "<<(b1||b2)<<endl;
   cout<<"!(b1 && b2): "<<!(b1&&b2);
return 0;
}
Output:
b1 && b2: 0
b1 || b2: 1
!(b1 && b2): 1

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.

> returns true if left side is greater than right.

< returns true if left side is less than right side.

>= returns true if left side is greater than or equal to right side.

<= returns true if left side is less than or equal to right side.

5) Bitwise Operators

There are six bitwise Operators: &, |, ^, ~, <<, >>

num1 = 11; /* equal to 00001011*/


num2 = 22; /* equal to 00010110 */
C o m p u t e r P r o g r a m m i n g 1 | 24

Bitwise operator performs bit by bit processing.


num1 & num2 compares corresponding bits of num1 and num2 and generates 1 if both
bits are equal, else it returns 0. In our case it would return: 2 which is 00000010
because in the binary form of num1 and num2 only second last bits are matching.

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

Example of Bitwise Operators

#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

 cout<<"num1 | num2: "<<result<<endl;


result = num1 ^ num2;
  cout<<"num1 ^ num2: "<<result<<endl;
result = ~num1;
 cout<<"~num1: "<<result<<endl;
result = num1 << 2;
 cout<<"num1 << 2: "<<result<<endl;
result = num1 >> 2;
  cout<<"num1 >> 2: "<<result;
return 0;
}
Output:

num1 & num2: 2


num1 | num2: 31
num1 ^ num2: 29
~num1: -12
num1 << 2: 44 num1 >> 2: 2

6) Ternary Operator

This operator evaluates a boolean expression and assign the value based on the result.
Syntax:

variable num1 = (expression) ? value if true : value if false


If the expression results true then the first value before the colon (:) is assigned to the
variable num1 else the second value is assigned to the num1.

Example of Ternary Operator

#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.

Key points for Lesson 4:

 Operator – represents an action.


 Logical operators - are used with binary variables.
 Bitwise operators - performs bit by bit processing.
 Ternary operators - this operator evaluates a boolean expression and assign
the value based on the result.
 Operator Precedence – This determines which operator needs to be evaluated
first if an expression has more than one operator.

Lesson 5: Flow chart


C o m p u t e r P r o g r a m m i n g 1 | 28

Duration: 1 hour

Objectives: At the end of the lesson, you will be able to:

 Know the importance of flow chart.


 Define the different kinds of a flow chart.
 Learn how to create a flow chart.

Procedures: Lecture and understanding.

Introduction: A flowchart is simply a graphical representation of steps. It shows steps


in sequential order and is widely used in presenting the flow of algorithms, workflow or
processes. Typically, a flowchart shows the steps as boxes of various kinds, and their
order by connecting them with arrows.

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

When to Draw Flowchart?


Using a flowchart has a variety of benefits:
 It helps to clarify complex processes.
 It identifies steps that do not add value to the internal or external customer,
including delays; needless storage and transportation; unnecessary work,
duplication, and added expense; breakdowns in communication.
 It helps team members gain a shared understanding of the process and use this
knowledge to collect data, identify problems, focus discussions, and identify
resources.
 It serves as a basis for designing new processes.
C o m p u t e r P r o g r a m m i n g 1 | 30

Flowchart Example – Simple Algorithms

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.

Key points for Lesson 5:

 Ellipse – is used to indicate the start and end of the program.


 Parallelogram - is used with binary variables.
 Rectangle – is used to show the processing thath takes place in the flow chart.
 Diamond – is used to make decisions in the flowchart.
 Flow Chart – is a graphical representations of step.

Lesson 6: Switch Case statement in C++

Duration: 1 hour

Objectives: At the end of the lesson, you will be able to:

 Know the purpose of switch case statement in c++.


 Determine the types of operators in c++.
 Learn how to program using switch case statement in c++.

Procedures: Lecture and demonstration.

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

The syntax of Switch case statement:

switch (variable or an integer expression)


{
case constant:
//C++ code
;
case constant:
//C++ code
C o m p u t e r P r o g r a m m i n g 1 | 32

;
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

Example of Switch Case

#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:

Default: Value is: 5


Explanation: In switch I gave an expression, you can give variable as well. I gave the
expression num+2, where num value is 5 and after addition the expression resulted 7.
Since there is no case defined with value 4 the default case got executed.

Switch Case Flow Diagram

It evaluates the value of expression or variable (based on whatever is given inside


switch braces), then based on the outcome it executes the corresponding case.
C o m p u t e r P r o g r a m m i n g 1 | 33

Break statement in Switch Case

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.

2) You can also use characters in switch case. for example –

#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

case 3: cout<<"Case3 "<<endl;


case 4: cout<<"Case4 "<<endl;
default: cout<<"Default "<<endl;
}
return 0;
Output:

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:

Key points for Lesson 6

 Switch case Statement – is used when we have multiple conditions and we


need to perform different action based on the condition.
 Break Statements - are used when you want your program-flow to come out of
the switch body.
 Nested Switch Case Statement – is a switch case statement inside a switch.

 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

Lesson 7: Conditional Statements in C++

Duration: 1 hour

Objectives: At the end of the lesson, you will be able to:

 Know the importance of if else statement in c++.


 Identify the types of If-else statement in c++.
 Learn how to program using If-else case statement in c++.

Procedures: Lecture and demonstration.

Introduction: Sometimes we need to execute a block of statements only when a


particular condition is met or not met. This is called decision making, as we are
executing a certain code after making a

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 statement consists a condition, followed by statement or a set of statements as shown


below:

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.

Flow diagram of If statement


C o m p u t e r P r o g r a m m i n g 1 | 40

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(num > 100){


/* This cout statement will only execute,
* if the above condition is true
*/
cout<<"number is greater than 100";
}
return 0;
}
Output:
number is less than 100

Nested if statement in C++

When there is an if statement inside another if statement then it is called the nested if


statement.
The structure of nested if looks like this:

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.

Example of Nested if statement

#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

If else statement in C++

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.

This is how an if-else statement looks:

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.

Flow diagram of if-else

Example of if-else statement

#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

cout<<"num is greater than or equal 50";


}
return 0;
}
Output:

num is greater than or equal 50


if-else-if Statement in C++

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:

Enter an integer number between 1 & 99999: 8976


Its a four digit number

Activity 1

Give at least 2 reasons why decision making is important in writing a program.


C o m p u t e r P r o g r a m m i n g 1 | 45

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.

Key points for Lesson 7:

 If statement– allows you to control if a program enters a section of code or not


based on whether a given condition is true or false.
 If-else statement -  is also used to control the program flow based on
some condition, only the difference is: it's used to execute
some statement code block if the expression is evaluated to true, otherwise
executes else statement code block.
 If-else-if statement
C++ has the following conditional statements: Use if to specify a block of code
to be executed, if a specified condition is true. Use else to specify a block of
code to be executed, if the same condition is false. Use else if to specify a new
condition to test, if the first condition is false.
 Nested if statement – which means you can use one if or else if
statement inside another if or else if statement(s).
 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.

References for Module 1:

 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

2. Iterative or Looping statement in C++

Lesson 8: While loop in C++

Duration: 1 hour

Objectives: At the end of the lesson, the students will be able to:

 Understand the flow of While loop.


 Know the features of the While loop statements.
 Write a simple program using While loop.

Procedures: Lecture (Read and Understand) and demonstration.

Introduction: A loop statement allows us to execute a statement or group of


statements multiple times and following is the general from of a loop statement in most
of the programming languages.

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.

In C++ we have three types of basic loops: While, For and Do-while.

Syntax of while loop

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

How while Loop works?

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.

Flow Diagram of While loop

While Loop example in C++

#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

cout<<"Value of variable i is: "<<i<<endl; i++;


}
}
Output:
Value of variable i is: 1
Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6
Infinite While loop

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

What is the importance of While loops. Write it in the space provided.

Activity 2

Program writing (10 pts)


 Write a program that will
Output:
Value of i: 6
Value of i: 7
Value of i: 8
Value of i: 9
Value of i: 10
C o m p u t e r P r o g r a m m i n g 1 | 50

Using While Loop statement, write it in a 1 whole sheet of yellow pad paper.

Key points for Lesson 8

 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

Lesson 9: For loop in C++

Duration: 1 hour

Objectives: At the end of the lesson, the students will be able to:

 Understand the flow of For loop.


 Know the features of the Forloop statements.
 Write a simple program using For loop.

Procedures: Lecture (Read and Understand) and demonstration.

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.

Syntax of for loop

for(initialization; condition ; increment/decrement)


{
C++ statement(s);
}
Flow of Execution in for loop, 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
C o m p u t e r P r o g r a m m i n g 1 | 51

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

Example of a Simple For loop in C++


Here in the loop initialization part I have set the value of variable i to 1, condition is i<=6
and on each loop iteration the value of i increments by 1.
#include <iostream>
using namespace std;
int main(){
for(int i=1; i<=6; i++){
/* This statement would be executed
* repeatedly until the condition
* i<=6 returns false.
*/
cout<<"Value of variable i is: "<<i<<endl;
}
return 0;
}
Output:

Value of variable i is: 1


Value of variable i is: 2
Value of variable i is: 3
Value of variable i is: 4
Value of variable i is: 5
Value of variable i is: 6
Infinite for loop in C++

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.

Here is another example of infinite for loop:

// infinite loop
for ( ; ; ) {
// statement(s)
}

Example: display elements of array using for loop

#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

Program writing (10 pts)


 Write a program that will
Output:
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5

using For Loop statement. Write it in a 1 whole sheet of yellow pad paper.

Key points in Lesson 9

 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

Lesson 10: Do-while loop in C++

Duration: 1 hour

Objectives: At the end of the lesson, the students will be able to:

 Understand the flow of Do-while loop.


 Know the features of the Do-while statements.
 Write a simple program using For loop.

Procedures: Lecture (Read and Understand) and demonstration.

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.

Syntax of do-while loop

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

Do-while loop example in C++

#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

Another example: using char variables

#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

Program writing (10 pts)


 Write a program that will
Output:
Number 1
Number 2
Number 3
Number 4
Number 5

using Do-while Loop statement. Write it in a 1 whole sheet of yellow pad paper.

Key points for Lesson 10

 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

Lesson 11: Continue Statement in C++

Duration: 1 hour

Objectives: At the end of the lesson, the students will be able to:

 Understand the flow of Continue Statement.


 Know the features of Continue statements.
 Write a simple program using Continue Statement.

Procedures: Lecture (Read and Understand) and demonstration.

Introduction: Continue statement is used inside loops. Whenever a continue statement


is encountered inside a loop, control directly jumps to the beginning of the loop for next
iteration, skipping the execution of statements inside loop’s body for the current
iteration.

Syntax of continue statement

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

Example: Use of continue in While loop

#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

Program writing (10 pts)


 Write a program that will
Output:
Ages who passed the board exam are:
30
29
27
26
25

using Continue statement. Write it in a 1 whole sheet of yellow pad paper.

Key points for Lesson 11

 For the for loop, continue statement causes the conditional test and increment


portions of the loop to execute.
 For the while and do...while loops, continue statement causes the program
control to pass to the conditional tests.
 The continue statement forces the next iteration of the loop to take place,
skipping any code in between.
C o m p u t e r P r o g r a m m i n g 1 | 63

Lesson 12: Break statement in C++

Duration: 1 hour

Objectives: At the end of the lesson, the students will be able to:

 Understand the flow of Break statement.


 Know the features of Break statements.
 Write a simple program using Break Statement.

Procedures: Lecture (Read and Understand) and demonstration.

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

Example – Use of break statement in a while loop

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:

Value of num is: 10


Value of num is: 11
Value of num is: 12
Hey, I'm out of the loop

Example: break statement in for loop


#include <iostream>
using namespace std;
int main(){
int var;
for (var =200; var>=10; var --) {
cout<<"var: "<<var<<endl;
if (var==197) {
break;
}
}
C o m p u t e r P r o g r a m m i n g 1 | 65

cout<<"Hey, I'm out of the loop";


return 0;
}
Output:
var: 200
var: 199
var: 198
var: 197
Hey, I'm out of the loop

Example: break statement in Switch Case


#include <iostream>
using namespace std;
int main(){
int num=2;
switch (num) {
case 1: cout<<"Case 1 "<<endl;
break;
case 2: cout<<"Case 2 "<<endl;
break;
case 3: cout<<"Case 3 "<<endl;
break;
default: cout<<"Default "<<endl;
}
cout<<"Hey, I'm out of the switch case";
return 0;
}
Output:
Case 2
Hey, I'm out of the switch case
In this example, we have break statement after each Case block, this is because if we
don’t have it then the subsequent case block would also execute. The output of the
same program without break would be:

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

Program writing (10 pts)


 Write a program that will
Output:
I’am your chosen number:
1
2
3
4
5

using Continue statement. Write it in a 1 whole sheet of yellow pad paper.

Key points for Lesson 12

 Break; - syntax used in break statement.


 Generally all cases in switch case are followed by a break statement to avoid the
subsequent cases.
 The break in C++ is a loop control statement which is used to terminate the loop.

Lesson 13: Go-to statement in C++

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:

 Understand the flow of Go-to statement.


 Know the features of Go-to statements.
 Write a simple program using Go-to Statement.

Procedures: Lecture (Read and Understand) and demonstration.

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

Program writing (10 pts)


 Write a program that will identify if the number is divisible by 5. Write it in a 1
whole sheet of yellow pad paper.
Example Output:
Enter number: 10
Divisible by 5

Enter number: 3
Not divisible by 5

using Go-to statement. Write it in a 1 whole sheet of yellow pad paper.

Key points for Lesson 13

 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.

References for Module 2:


C o m p u t e r P r o g r a m m i n g 1 | 69

 www.geeksforgeeks.org
 www.cpp.sh
 https://www.tutorialspoint.com/cplusplus/cpp_for_loop.htm
 www.beginnersbook.com

MODULE III

3. Functions, Arrays and Strings in C++


C o m p u t e r P r o g r a m m i n g 1 | 70

Lesson 14: Functions in C++


Duration: 1 hour

Objectives: At the end of the lesson, you will be able to:

 Learn the basics in Functions in c++.


 Write a program that uses a Functions.

Procedures: Lecture (Read and Understand) and demonstration.

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
}

Let’s take a simple example to understand this concept.


A simple function example
#include <iostream>
using namespace std;
/* This function adds two integer values
* and returns the result
*/int
sum(int num1, int num2){
int num3 = num1+num2; return num3;
}

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.

syntax of function declaration:

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);.

Function definition: Writing the full body of function is known as defining a function.


syntax of function definition:

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

We have two types of function in C++:

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.

Example: C++ built-in function example

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

/* Calling the built-in function


* pow(x, y) which is x to the power y
* We are directly calling this function
*/
cout<<pow(2,5);
return 0;
}

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;

cout<<"enter second number: ";


cin>>y;

cout<<"Sum of these two :"<<sum(x,y);


return 0;
}
//Defining the function sum
int sum(int a, int b) {
int c = a+b;
return c;
}
Output:
enter first number: 22
enter second number: 19
Sum of these two :41

Activity 1

What are the importance of Functions in programming. 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 | 76

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:

Enter First number: 5

Enter Second number: 4

Enter Third number: 1

Difference of these three are: 0

Key points for Lesson 14

 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.

Lesson 15: Default Arguments in C++ Functions

Duration: 1 hour

Objectives: At the end of the lesson, you will be able to:

 Learn the basics in Default Arguments in C++ Functions.


 Write a program that uses a Default Arguments in C++ Functions.

Procedures: Lecture (Read and Understand) and demonstration.

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.

Example: Default arguments in C++


#include <iostream>
using namespace std;
int sum(int a, int b=10, int c=20);
int main(){
/* In this case a value is passed as
* 1 and b and c values are taken from
* default arguments.
*/
cout<<sum(1)<<endl;

/* In this case a value is passed as


* 1 and b value as 2, value of c values is
* taken from default arguments.
*/
cout<<sum(1, 2)<<endl;

/* In this case all the three values are


* passed during function call, hence no
* default arguments have been used.
*/
cout<<sum(1, 2, 3)<<endl;
return 0;
}
int sum(int a, int b, int c){
int z;
z = a+b+c;
return z;
}
Output:
31
C o m p u t e r P r o g r a m m i n g 1 | 78

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.

For example: Lets see some valid and invalid cases.

Valid: Following function declarations are valid –


int sum(int a=10, int b=20, int c=30);
int sum(int a, int b=20, int c=30);
int sum(int a, int b, int c=30);

Invalid: Following function declarations are invalid –


/* Since a has default value assigned, all the
* arguments after a (in this case b and c) must have
* default values assigned
*/
int sum(int a=10, int b, int c=30);

/* Since b has default value assigned, all the


* arguments after b (in this case c) must have
* default values assigned
*/
int sum(int a, int b=20, int c);

/* Since a has default value assigned, all the


* arguments after a (in this case b and c) must have
* default values assigned, b has default value but
* c doesn't have, thats why this is also invalid
*/
int sum(int a=10, int b=20, int c);
C o m p u t e r P r o g r a m m i n g 1 | 79

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.

Write your answer in ½ sheet of yellow pad paper.

1. int sum(int a, int b=2, int c=3);


C o m p u t e r P r o g r a m m i n g 1 | 80

2. int sum(int a=1, int b, int c=30);

3. int sum(int a, int b=2, int c=30);

4. int sum(int a, int b,=1 int c);

5. int sum(int a=1, int b, int c=30);

6. int sum(int a, int b=2, int c);

7. int sum(int a=1, int b=2, int c=3);

8. int sum(int a, int b, int c=1);

9. int sum(int a, int b, int c=4);

10. int sum(int a, int b=20, int c=30);

Key points in Lesson 15

 A default argument is a value provided in a function declaration that is


automatically assigned by the compiler if the caller of the function doesn't provide
a value for the argument with a default value.

 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.

Lesson 16: Arrays in C++

Duration: 1 hour

Objectives: At the end of the lesson, you will be able to:

 Learn the basics of Arrays in C++.


 Write a program that uses Arrays in C++ program.

Procedures: Lecture (Read and Understand) and demonstration.


C o m p u t e r P r o g r a m m i n g 1 | 81

Introduction: An array is collection of items stored at contiguous memory locations.


The idea is to store multiple items of same type together. This makes it easier to
calculate the position of each element by simply adding an offset to a base value, i.e.,
the memory location of the first element of the array (generally denoted by the name of
the array).

An array is a collection of similar items stored in contiguous memory locations. In


programming, sometimes a simple variable is not enough to hold all the data. For
example, lets say we want to store the marks of 500 students, having 500 different
variables for this task is not feasible, we can define an array with size 500 that can hold
the marks of all students.

Declaring an array in C++

There are couple of ways to declare an array.

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

Accessing Array Elements


Array index starts with 0, which means the first array element is at index 0, second is at
index 1 and so on. We can use this information to display the array elements. See the
code below:
#include <iostream>
using namespace std;

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

What is an Array 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 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;
}

Lesson 17: Multidimensional Arrays in C++

Duration: 1 hour

Objectives: At the end of the lesson, you will be able to:

 Learn the basics of Multidimensional Arrays in C++.


 Write a program that uses Multidimensional Arrays in C++ program.

Procedures: Lecture (Read and Understand) and demonstration.


C o m p u t e r P r o g r a m m i n g 1 | 86

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:

A two dimensional array:


int arr[2][3];
This array has total 2*3 = 6 elements.

A three dimensional array:


int arr[2][2][2];
This array has total 2*2*2 = 8 elements.

Two dimensional array


Lets see how to declare, initialize and access Two Dimensional Array elements.

How to declare a two dimensional array?


int myarray[2][3];

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 arr[2][3] = {{10, 11 ,12} , {20 ,21 , 22}};

Accessing array elements:


arr[0][0] – first element
arr[0][1] – second element
arr[0][2] – third element
arr[1][0] – fourth element
arr[1][1] – fifth element
arr[1][2] – sixth element

Example: Two dimensional array in C++


#include <iostream>
using namespace std;

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

Three dimensional array


Lets see how to declare, initialize and access Three Dimensional Array elements.

Declaring a three dimensional array:


int myarray[2][3][2];
C o m p u t e r P r o g r a m m i n g 1 | 88

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

Three dimensional array example


#include <iostream>
using namespace std;

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

Key points for Lesson 17


C o m p u t e r P r o g r a m m i n g 1 | 90

 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.

Lesson 18: Passing Array to Function in C++


Duration: 1 hour

Objectives: At the end of the lesson, you will be able to:

 Learn the basics of Passing an Arrays to functions in C++.


 Write a program that uses Passing of Arrays in C++ program.

Procedures: Lecture (Read and Understand) and demonstration.

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

Example: Passing arrays to a function


In this example, we are passing two arrays a & b to the function sum(). This function
adds the corresponding elements of both the arrays and display them.
#include <iostream>
using namespace std;
/* This function adds the corresponding
 * elements of both the arrays and
 * displays it.
 */
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;
}
C o m p u t e r P r o g r a m m i n g 1 | 91

}
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

Example 2: Passing multidimensional array to function


In this example we are passing a multidimensional array to the function square which
displays the square of each element.

#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

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] = {1, 2, 3, 4, 5};
//Passing arrays to function
sum(a, b);
return 0;
}
2.

#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;}

Key points for Lesson 18

 C++ does not allow to pass an entire array as an argument to a function.


However, You can pass a pointer to an array by specifying the array's name
without an index.
 When an array is passed as an argument to a function, only the name of an
array is used as argument.

 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);

Lesson 19: Strings in C++


Duration: 1 hour

Objectives: At the end of the lesson, you will be able to:

 Learn the basics of Strings in C++.


 Write a program that uses Strings in C++ program.

Procedures: Lecture (Read and Understand) and demonstration.

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

using namespace std;


int main(){
char book[50] = "A Song of Ice and Fire";
  cout<<book;
return 0;
}
Output:
A Song of Ice and Fire

Example 2: Getting user input as string


This can be considered as inefficient method of reading user input, why? Because when
we read the user input string using cin then only the first word of the string is stored in
char array and rest get ignored. The cin function considers the space in the string as
delimiter and ignore the part after it.
#include <iostream>
using namespace std;
int main(){
char book[50];
cout<<"Enter your favorite book name:";
//reading user input
cin>>book;
cout<<"You entered: "<<book;
return 0;
}
Output:
Enter your favorite book name:The Murder of Roger Ackroyd
You entered: The
You can see that only the “The” got captured in the book and remaining part after space
got ignored. How to deal with this then? Well, for this we can use cin.get function, which
reads the complete line entered by user.

Example 3: Correct way of capturing user input string using cin.get


#include <iostream>
using namespace std;
int main(){
char book[50];
cout<<"Enter your favorite book name:";
C o m p u t e r P r o g r a m m i n g 1 | 97

//reading user input


cin.get(book, 50);
cout<<"You entered: "<<book;
return 0;
}
Output:
Enter your favorite book name:The Murder of Roger Ackroyd
You entered: The Murder of Roger Ackroyd

Drawback of this method


1) 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. For example, lets
say you have created an array of character with the size 10 and user enters the string of
size 15 then the last five characters would be truncated from the string.
On the other hand if you create a larger array to accommodate user input then the
memory is wasted if the user input is small and array is much larger then what is
needed.

2) In this method, you can only use the in-built functions created for array which don’t
help much in string manipulation.

What is the solution of these problems?


We can create string using string object. Lets see how we can do it.

String object in C++


Till now we have seen how to handle strings in C++ using char arrays. Lets see another
and better way of handling strings in C++ – string objects.
#include<iostream>
using namespace std;
int main(){
// This is how we create string object
string str;
cout<<"Enter a String:";
/* This is used to get the user input
* and store it into str
*/
getline(cin,str);
cout<<"You entered: ";
C o m p u t e r P r o g r a m m i n g 1 | 98

cout<<str<<endl;

/* This function adds a character at


* the end of the string
*/ str.push_back('A');
cout<<"The string after push_back: "<<str<<endl;
/* This function deletes a character from
* the end of the string
*/
str.pop_back();
cout << "The string after pop_back: "<<str<<endl;
return 0;
}
Output:
Enter a String:XYZ
You entered: XYZ
The string after push_back: XYZA
The string after pop_back: XYZ

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

Key points for Lesson 19

 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

Compile all the activities we created. Put it in a Yellow Clear book

References for Module 3:

 https://www.onlinegdb.com/online_c++_compiler
 https://www.programiz.com
 Cprogramming.com
 Onlinegbd.com

You might also like