Download as pdf or txt
Download as pdf or txt
You are on page 1of 157

UNIT 2

C++ Basics

IT 103 Computer Programming 1


Lesson 1
Overview of C++ Language

IT 103 Computer Programming 1


UNIT 2
LESSON 1 Overview of C++ Language
C++ is a statically typed, compiled, general-purpose, case-
sensitive, free-form programming language that supports
procedural, object-oriented, and generic programming.

C++ is regarded as a middle-level language, as it comprises a


combination of both high-level and low-level language features.

Note:
A language is a set of valid sentences. What makes a sentence
valid? You can break validity down into two things: syntax and
semantics. The term syntax refers to grammatical structure
whereas the term semantics refers to the meaning of the
vocabulary symbols arranged with that structure.

IT 103 Computer Programming 1


UNIT 2
LESSON 1 Overview of C++ Language
Processing a C++ Program
1 Writing and Editing a Program Editor

2 Processing preprocessor or directives


Preprocessor
Syntax Error

3 Compiling a C++ Program Compiler


Library
4 Linking a C++ Program
Linker

5 Loading a Program into Memory


Loader

6 Executing a Program Execution


IT 103 Computer Programming 1
UNIT 2
LESSON 1 Overview of C++ Language
Processing a C++ Program
1 Writing and Editing a Program
You use a text editor to create a C++ program following the
rules or syntax of the high-level language. This program is
called the source code, or source program. The program
must be saved in a text file that has the extension .cpp.
An integrated development environment (IDE) is a
programming environment that has been packaged as an
application program, typically consisting of a code editor, a
compiler, a debugger, and a graphical user interface (GUI)
builder. The IDE may be a standalone application or may be
included as part of one or more existing and compatible
applications.
IT 103 Computer Programming 1
UNIT 2
LESSON 1 Overview of C++ Language
Processing a C++ Program

2 Processing preprocessor or directives


C++ statements are processed by a program called
preprocessor.

IT 103 Computer Programming 1


UNIT 2
LESSON 1 Overview of C++ Language
Processing a C++ Program

3 Compiling a C++ Program


. After processing preprocessor directives, the next step
is to verify that the program obeys the rule of the
programming language – that is, the program is
syntactically correct – and translate the program into the
equivalent machine language. The compiler checks
source program for syntax errors and, if no error is
found, translates the program into the equivalent
machine program. The equivalent machine language
program is called an object program.

IT 103 Computer Programming 1


UNIT 2
LESSON 1 Overview of C++ Language
Processing a C++ Program
4 Linking a C++ Program

Once the program is developed and successfully


compiled, you must still bring the code for the resources
used from IDE into your program to produce a final
program that the computer can execute. This prewritten
code(program) resides in a place called the library. A
program called a linker combines the object program
with the programs from libraries.
Linker is a program that combines the object program
with other programs in the library and is used in the
program to create the executable code.

IT 103 Computer Programming 1


UNIT 2
LESSON 1 Overview of C++ Language
Processing a C++ Program

5 Loading a Program into Memory


You must next load the executable program into main
memory for execution. A program called a loader
accomplishes this task.
Loader is a program that loads an executable program
into main memory.

IT 103 Computer Programming 1


UNIT 2
C++ Basics

IT 103 Computer Programming 1


Lesson 2
Basic Elements of a Program

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Symbols

, Commas are used to separate items in a list


; Semicolons are used to end statement

+ - * / mathematical symbols
<= != == >= relational operators

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Symbols
Comment symbols
// single-line comment symbol

For example,
// This is my first program
// C++ Language

/* */ multiple-line comment symbol


For example;
/*This is my first program
C++ Language
*/

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Reserved Words
Reserved words are also called keywords that cannot be redefined
within any program; that is, they cannot be used for anything
other than their intended use.
Some of the important reserved words are :
char float int void
break if else switch
case return for do
while main

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Identifier
Identifier refers to the names of variables, constants, functions
and other objects defined in a C++ program. It allows us to name
data and other objects in the program.

Rules for identifiers are:


•The only valid name symbols are the capital letters A
through Z, the lowercase letters a through z.
•the digits 0 through 9, and the underscore.
•The first character of the identifier cannot be a digit or an
underscore.

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Identifier
Rules for identifiers are:
•An identifier cannot contain punctuation marks, math
symbols or other special symbols.
•ANSI guarantees only the first 32 characters to be
significant.
•C++ identifier is case-sensitive
•The last rule is that the name we create cannot be
keywords.

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Identifier
Examples of Valid and Invalid identifiers
Valid Identifiers Invalid Identifiers
grade grade+3
area1 1area
area_of_triangle area of triangle

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Data Type
A data type defines a set of values that a variable can hold.
Based on the data type of a variable; the operating system
allocates memory and decides what can be stored in the
reserved memory.
Type Keyword Data type Examples
Boolean boolean
Character char boolean true, false
Integer int
Floating point float char ‘A’ , ‘b’ ,’+’
Double floating double
point int 10,200,550
Valueless void
float /double 10.54, 2.56

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Variable

A variable can hold a number or data of other types. The


number or other type of data held in a variable is called its
value. In programming languages, variables are implemented
as memory location. The compiler assigns a memory location
to each variable name (identifier) in the program. Each
variable in a program must be declared. When you declare a
variable you are telling the compiler what kind of data you
will be storing in the variable

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Variable
Variable Declaration

A syntax rule to declare a variable is:

datatype identifier;

For example:
int x;

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Operator

An operator is a symbol that tells the compiler to perform


specific mathematical or logical manipulations.

Types of operators:
•Assignment Operator
•Arithmetic Operators
•Relational Operators
•Logical Operators

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Operator

•Assignment Operator

The assignment operator (=) is used in the assignment


statement which takes the following form:

variable = expression;

Example:
y = 5;

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Operator
•Arithmetic Operators
Operator Meaning Example
* Multiplication x*y
/ Division x/y
% Modulus x%y
+ Addition x+y
- Subtraction x–y
++ Increment x++
-- Decrement x--
+ (unary) Positive sign +x
- (unary) Negative sign -x

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Operator
Order of Precedence

It is possible to build mathematical expressions with several operators. When


more than one arithmetic operator is used in an expression, C++ uses the
operator precedence rules to evaluate the expression. According to the order
of precedence rules for arithmetic operators,

* , / ,% are at higher level of precedence than + , -

However, when operators have the same level, the operations are performed
from left to right.

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Operator
•Relational Operators

Two expressions can be compared using relational and equality operators.


The result of such an operation is either true or false
The relational operators in C++ are:

< > <= >= == !=


•Logical Operators

&& (AND) || (OR) ! (NOT)

IT 103 Computer Programming 1


UNIT 2
LESSON 2 Basic Elements of a Program

• Expression
Arithmetic Expression

An Arithmetic expression is any expression that is used for


computations/mathematical manipulations.

Boolean Expression (Conditional Expression)

A Boolean expression is any expression that is either true


or false.

IT 103 Computer Programming 1


UNIT 2
C++ Basics

IT 103 Computer Programming 1


Lesson 3
CodeBlocks Environment

IT 103 Computer Programming 1


UNIT 2
LESSON 3 CodeBlocks Environment

▪ Code::Blocks (or C::B) is a cross-platform IDE that supports


compiling and running multiple programming languages. It is
a free C, C++ and Fortran IDE built to meet the most
demanding needs of its users. It is created and developed to
be very extensible and fully configurable.
An Integrated Development Environment (IDE) is a software
application that gives comprehensive facilities to a computer
programmer for software development. An IDE normally includes
a source code editor, build automation tools, and a debugger.

IT 103 Computer Programming 1


UNIT 2
LESSON 3 CodeBlocks Environment

M W Start page
a i
n n
a d
g o
e w
m
e
n
t
Logs window

IT 103 Computer Programming 1


UNIT 2
LESSON 3 CodeBlocks Environment

Creating a File
1. Select File>New>File

IT 103 Computer Programming 1


UNIT 2
LESSON 3 CodeBlocks Environment

Creating a File
2. Select C/C++ source

IT 103 Computer Programming 1


UNIT 2
LESSON 3 CodeBlocks Environment

3. Click Next.

IT 103 Computer Programming 1


UNIT 2
LESSON 3 CodeBlocks Environment

4. Select C++

IT 103 Computer Programming 1


UNIT 2
LESSON 3 CodeBlocks Environment

5. Click the ellipsis (…) to select the file


location. Once location(folder) is selected
(e.g. Documents\SamplePrograms),
specify the file name.
Click Save, then Finish.

IT 103 Computer Programming 1


UNIT 2
C++ Basics

IT 103 Computer Programming 1


Lesson 4
Basic Input/Output Statement

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Structure of a C++ Program
#include <preprocessor directive> -Lines beginning with a hash
sign (#) are directives read
using namespace std;
and interpreted by what is
known as the preprocessor.
int main()
-special lines interpreted
{
statement 1;
before the compilation of
statement 2;
the program itself begins.
.
.
.
statement n;
return 0;
}

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Structure of a C++ Program
#include <iostream>
#include <preprocessor directive>

using namespace std;


iostream is the name of the
library that contains the
int main()
definitions of the routines
{
statement 1;
that handle basic
statement 2;
input/output operation.
.
.
.
statement n;
return 0;
}

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Structure of a C++ Program
#include <preprocessor directive>

using namespace std;


The line int main()simply means
that the main body of the
int main() program starts here. It is
{ referred to as the main()
statement 1; function, it is the function called
statement 2; when the program is run. The
. execution of all C++ programs
. begins with the main function,
. regardless of where the function
statement n; is actually located within the
return 0; code.
}

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Structure of a C++ Program
#include <preprocessor directive>

using namespace std;

{ }
The braces and mark the beginning
int main() and end of the main body of the
{ program.
statement 1; Everything between these braces is the
statement 2; function's body that defines what
. happens when main is called. The
.
statements inside the braces are called
as executable statements. Statements
.
are executed in the same order that
statement n;
they appear within a function’s body.
return 0;
}

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Structure of a C++ Program
#include <preprocessor directive>

using namespace std;

int main()
{
statement 1;
statement 2;
.
. The line return 0; terminates
. main()function and causes it to
statement n; return the value 0 to the calling
return 0; process.
}

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Structure of a C++ Program
#include <preprocessor directive>
All the elements in the standard C++
library are declared within what is
using namespace std;
called a namespace:
the namespace std.
int main()
{
statement 1; In order to refer to the elements in the
statement 2; std namespace a program shall either
qualify each and every use of elements
.
of the library or introduce visibility of
.
its components.
.
statement n;
return 0;
}

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Basic Output Statement

The Standard Output Stream (cout)

The predefined object cout is an instance of ostream class. The cout


object is said to be "connected to" the standard output device, which
usually is the display screen. The cout is used in conjunction with the
stream insertion operator, which is written as << which are two less than
signs:

cout<< expression or manipulator;


-expression is evaluated, its value is printed, and manipulator is used to
format the output.

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Basic Output Statement

The Standard Output Stream (cout)

cout<< expression or manipulator;


Examples:
cout<<"Hello"; // prints Hello
cout<<120; // prints 120
cout<<“x”; // prints x
cout<<x; // prints the value of x

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Basic Output Statement

The Standard Output Stream (cout)

cout<< expression or manipulator;


Multiple insertion operations (<<) may be written in a single statement:
Example:

age = 18;

cout<<“I am ”<<age<<“ years old ”;

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Basic Output Statement

Escape Sequence
The backslash (\) is known as the escape character in the ASCII character set. The
escape character is used in the C++ language to tell the computer that a special
character follows.

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Basic Output Statement

Escape Sequence
Example:
To insert a line break in the output, a newline character (\n) is inserted in the exact position,
the line should be broken. Output

Hello!
cout<< "Hello!\n"; Have a nice day!
cout<< "Have a nice day!";

To insert a tab in the output, use \t Output

Hello! Have a nice day!


cout<< "Hello!\tHave a nice day!";

The endl manipulator can also be used to break lines.


Output

cout<< "Hello!”<<endl; Hello!


cout<< "Have a nice day!"; Have a nice day!

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Basic Output Statement

cout is part of the standard C++ library, and


all elements in the standard C++ library are
declared within what is called a namespace:
the namespace std. Accessing the elements
in the std namespace is by means of using
declarations:

using namespace std;

This will allow all elements in the std


namespace to be accessed without the std::
prefix).

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Basic Output Statement

cout is part of the standard C++ library, and


all elements in the standard C++ library are
declared within what is called a namespace:
the namespace std. Accessing the elements
in the std namespace is by means of using
declarations:

using namespace std;

This will allow all elements in the std


namespace to be accessed without the std::
prefix).

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Basic Input Statement

The Standard Input Stream (cin)

The predefined object cin is an instance of istream class. The cin


object is said to be attached to the standard input device, which
usually is the keyboard. The cin is used in conjunction with the
stream extraction operator, which is written as >> which are two
greater than signs as shown in the following example.

cin>> variable;

IT 103 Computer Programming 1


UNIT 2
LESSON 4 Basic Output Statement

The Standard Input Stream (cin)

cin>> variable;
Example:

int age;
cout<<"Please enter your age: ";
cin>>age;
cout<<"You are "<<age<<“ years old”;

IT 103 Computer Programming 1


UNIT 3
Program Control Structures
Selection Structure

IT 103 Computer Programming 1


Lesson 1
Selection Structure:
The if/if–else Statement

IT 103 Computer Programming 1


Selection Structure : if /if-else Statement

if statement if -else statement


(one option) (two options)

if (conditional expression) if (conditional expression)


{ {
statement 1;
. statement;
.
.
. }
statement N; else {
statement;
}
}

IT 103 Computer Programming 1


Selection Structure : if /if-else Statement

if statement

if (conditional expression) if (number>0)


{ {
statement 1; cout<<“Positive”;
.
. }
.
.
statement N;

IT 103 Computer Programming 1


Selection Structure : if /if-else Statement

if -else statement
if (conditional expression) if (number>0)
{ {
cout<<“Positive”;
statement;
}

} else {
else { cout <<“Not a positive number”;
statement;
}
}

IT 103 Computer Programming 1


Selection Structure : if /if-else Statement

Ladderized if - else statement


(three or more options)

if (conditional expression1)
{
statement;

}
else if (conditional expression2)
{
statement;

}
else {
statement;

IT 103 Computer Programming 1


Selection Structure : if /if-else Statement
Example: Test if the number is positive , negative or zero

if (number>0)
{
cout<<“Positive”;
}
else if (number<0)
{
cout<<“Negative”;
}
else {
cout<<“Zero ”;
}

IT 103 Computer Programming 1


Selection Structure : if /if-else Statement
Nested if/ if - else statement
if (conditional expression1) if (conditional expression1)
{ {
if (conditional expression 1.1)
if (conditional expression 1.1) {
{ statement;
statement;
}
} else {
else { statement;
statement; }
}
}
} else
{
if (conditional expression 2.1)
{
statement;

}
else {
statement;
}
} IT 103 Computer Programming 1
Selection Structure : if /if-else Statement
Example: Test if the number is positive , negative or zero. In case the number
is positive, test if it is even or odd.
if (number>0)
{
cout<<“Positive”;
if (number%2==0)
{
cout<<“Even ”;

}
else {
cout<<“Odd ”;
}
}

else if (number<0)
{
cout<<“Negative”;
}
else {
cout<<“Zero ”;
}
IT 103 Computer Programming 1
UNIT

4 STRUCTURES

IT 105 Computer Programming 2


LESSON 1
Introduction to Structures

IT 105 Computer Programming 2


Structures
A structure is a collection of related elements, possibly of
different types, having a single name.
It allows you to wrap one or more variables with different
data types under a single name.

In other programming languages, structures are called


records, and members are known as fields.

IT 105 Computer Programming 2


Structures
For example, you want to refer to student with multiple data like
name,course, age, grade :

Student structure name


(group name)
Name Course Age Grade field names
(members)
Ana BSIT 18 90
John BIT 19 92
Cathy BSM 18 89

string string int int

IT 105 Computer Programming 2


Structure Definition

Structure definition consists of the reserved word struct, the name


of the structure (tag) ,and the symbol {,field list, the symbol }.

struct structure name


{
field list
(structure members)
};

IT 105 Computer Programming 2


Structure Definition

Example :
struct student structure name
{
char name[20];
field list
char course[5];
(structure members)
int age;
int grade;

};

IT 105 Computer Programming 2


Structure Variable

A structure variable is variable declared with struct as the


data type capable of holding multiple data.

A struct is a data type with a number of components (or


fields), can contain any valid data types like int, char, float even
arrays or even other structures.

IT 105 Computer Programming 2


Structure Variable Declaration
To declare a variable of type struct:

struct structure name identifier;

struct student stud;


* stud is the name of the variable of type struct which means that this
variable can hold values of all members of structure student, as illustrated
below:

stud name course age grade

IT 105 Computer Programming 2


Structure Variable Initialization
To initialize a variable of type struct:

struct student stud ={ “Ana”, ”BSIT”,18,90};


Ana BSIT 18 90

name course age grade

members of structure student

IT 105 Computer Programming 2


Accessing Members of Structure

Input name cin.getline(stud.name,20);


Display age cout <<stud.age;
Test if grade is if (stud.grade>=75)
passed or failed
cout<<“passed”;

struct student stud;

IT 105 Computer Programming 2


Sample Program

IT 105 Computer Programming 2


Sample Program

IT 105 Computer Programming 2


Sample Program
A program that computes the salary of employee based on
hours worked and rate per hour.

//Structure Definition
struct employee
{
double hours;
double rate; // or can be written as double hours,rate, salary;
double salary;
};
//Structure Variable Declaration

struct employee emp;

IT 105 Computer Programming 2


Sample Program

IT 105 Computer Programming 2


UNIT 3
Program Control Structures
Selection Structure

IT 103 Computer Programming 1


Program Control Structures
Selection Structure
Conditional statements are features of programming language to
construct a selection structure. These are statements used to
perform a certain task which depend on whether the conditional
expression specified evaluates to true or false.

C++ supports two types of conditional statements:


if and switch statements

IT 103 Computer Programming 1


Lesson 1
Selection Structure:
The if/if–else Statement

IT 103 Computer Programming 1


Selection Structure : if Statement

if Statement (one-way selection)


The if statement is used when the program is made to choose one
statement.

True

The general form of if statement is: Condition

Statement 1
if (conditional expression) False

statement;
Statement 2

IT 103 Computer Programming 1


Selection Structure : if Statement

if Statement (one-way selection)


Example 1 :

x=5; Output

if(x>=5)
hello good day
cout<<“hello ”;
cout<<“good day”;

IT 103 Computer Programming 1


Selection Structure : if Statement

if Statement (one-way selection)


Example 2 :

x=4; Output

if(x>=5)
good day
cout<<“hello”;
cout<<“good day”;

IT 103 Computer Programming 1


Selection Structure : if Statement

if Statement (one-way selection)


Example 3 :

x=5;
Output

if (x>=5)
12
x*=2;
x+=2;
cout<< x;

IT 103 Computer Programming 1


Selection Structure : if Statement

if Statement (one-way selection)


Example 4 :

x=4;
Output

if (x>=5)
x*=2; 6
x+=2;
cout<< x;

IT 103 Computer Programming 1


Selection Structure : if Statement

if Statement with block of statements


The use of braces in an if statement with a single statement is optional but
required when code contains a block of statements. Writing braces, whether
single or block of statements, is recommended as it makes the code more
readable and helps avoid errors when modifying a program.
True

if (conditional expression) Condition

{
Statement 1
Statement1;
False
.
Statement n
.
.
Statement n;
Statement
}
IT 103 Computer Programming 1
Selection Structure : if Statement

if Statement with block of statements


Example 5 :

x=5; Output

if(x>=5)
hello good day
{
cout<<“hello ”;
cout<<“good day”;
}

IT 103 Computer Programming 1


Selection Structure : if Statement

if Statement with block of statements


Example 6 :

x=4; Output

if(x>=5)
God Bless
{
cout<<“hello ”;
cout<<“good day”;
}
cout<< “God Bless”;
IT 103 Computer Programming 1
Selection Structure : if Statement

if Statement with block of statements


Example 7 :

x=5; Output

if (x>=5)
12
{
x*=2;
x+=2;
}
cout<< x ;
IT 103 Computer Programming 1
Selection Structure : if Statement

if Statement with block of statements


Example 8 :

x=4; Output

if (x>=5)
4
{
x*=2;
x+=2;
}
cout<< x ;
IT 103 Computer Programming 1
Selection Structure : if-else Statement

if-else Statement (two-way selection)


The if- else statement is used when the program is made to choose one of the
two paths or statements.
True
The general form of if-else statement is:
Condition

Statement 1
if (conditional expression)
False

statement 1;
else
statement 2; Statement 2

IT 103 Computer Programming 1


Selection Structure : if-else Statement

If-else Statement with block of statements


The general form of if-else statement is:

if (conditional expression)
{
statement(s);
}
else {
statement(s);
}

IT 103 Computer Programming 1


Selection Structure : if-else Statement

if-else Statement (two-way selection)


Example 9 :

x=5; Output

if(x>=5)
hello
cout<<“hello ”;
else
cout<<“good day”;

IT 103 Computer Programming 1


Selection Structure : if-else Statement

if-else Statement (two-way selection)


Example 10 :

x=4; Output

if(x>=5)
good day
cout<<“hello ”;
else
cout<<“good day”;

IT 103 Computer Programming 1


Selection Structure : if-else Statement

if-else Statement (two-way selection)


Example 11 :

x=4; Output

if (x>=5)
6
x*=2;
else
x+=2;
cout<< x ;

IT 103 Computer Programming 1


Selection Structure : if-else Statement

if-else Statement (two-way selection)


Example 12 :

x=5; Output

if (x>=5)
10
x*=2;
else
x+=2;
cout<< x ;

IT 103 Computer Programming 1


Selection Structure : if-else Statement

if-else Statement (two-way selection)


Example 13:

x=6; Output

if (x<=5)
{
x+=2; 13
}
else
{
x*=2;
x++;
}
cout<< x ;

IT 103 Computer Programming 1


Selection Structure : Ladderized if-else Statement

Ladderized if-else Statement (multiple selection)


The ladderized if-else statement used to is used if there are three or more
possible outcomes are expected in a program
The general form of ladderized if-else statement is:

if (conditional expression_1)
statement_1;
else if (conditional expression _2)
statement_2;
else if (conditional expression _n)
statement_n;
:
:
else
statement_else;

IT 103 Computer Programming 1


Selection Structure : Nested if/if-else Statement

The nested if/ if-else statement is known as nested when there is another if/if-else
statement inside it. This is considered a sub-condition of a parent condition.

if ( conditional expression_1)
{
if ( conditional expression_1.1)
{
statement_1.1;
}
else
{
statement_1.2;
}
}
else
{
statement_2;
}

IT 103 Computer Programming 1


UNIT 3
Program Control Structures
Selection Structure

IT 103 Computer Programming 1


Program Control Structures
Selection Structure
Conditional statements are features of programming language to
construct a selection structure. These are statements used to
perform a certain task which depend on whether the conditional
expression specified evaluates to true or false.

C++ supports two types of conditional statements:


if and switch statements

IT 103 Computer Programming 1


Lesson 2
Selection Structure:
The switch Statement

IT 103 Computer Programming 1


Selection Structure : switch Statement

The switch statement is a multi-way decision and used when there are
multiple conditions. It is an alternative statement for an if-else ladder
with a limitation that switch can only test for equality.

IT 103 Computer Programming 1


Selection Structure : switch Statement
The general form of the switch statement is:
switch (variable_expression) It evaluates the variable (with integer or
{ character data type) whether it matches
case constant1:{ one of the case constants (integer or
character values), then based on the
statement sequence_1;
outcome, it executes the corresponding
break;
case.
}
case constant2:{ The break statement is used to
statement sequence _2; terminate/exit, the statement sequence
associated with each case constant.
break;
Whenever this statement is encountered,
}
the execution directly comes out of the
default: { switch and ignoring the rest of the given
statement sequence _3; cases.
break;
The default segment of the switch is
}
executed if no matches are found.
}
IT 103 Computer Programming 1
Selection Structure : switch Statement

Example :

A program that determines the color


code of Junior High School students
based on the grade level

IT 103 Computer Programming 1


UNIT 3
Program Control Structures
Repetition Structure

IT 103 Computer Programming 1


Program Control Structures
Repetition Structure
Repetitive /Iterative statements (loops) allow a set of instructions to be
repeated or carried out several times until certain conditions have been
met.
Iterative statements (loops) allow a set of instructions to be repeated or
carried out several times until certain conditions have been met. It can
be predefined(count controlled) as in in the for loop, or open
ended(condition controlled) as in while and do while.

IT 103 Computer Programming 1


Lesson 3
Repetition Structure:
The for Statement

IT 103 Computer Programming 1


Repetition Structure : for Statement

This statement performs the following actions :

Initialization of 1. The initial statement executes.


counter (control
variable)

2. The loop condition is evaluated.


False

Condition 3. If the loop condition evaluates to true, execute the


END

True
body of the loop.

body of the loop


4. Execute the increment/decrement statement

Increment/
Decrement
5. Repeat Step 2 until the loop condition evaluates to
false.

IT 103 Computer Programming 1


Repetition Structure : for Statement

The general form of the for statement is:

1 2 4
for (initialization; condition; increment)
{
3
statement(s);
}

IT 103 Computer Programming 1


Repetition Structure : for Statement

Example 1 :

Output

for (x=1;x<=5;x=x+1)
cout<<x<<“ ”; 1 2 3 4 5

IT 103 Computer Programming 1


Repetition Structure : for Statement

Example 2 :

Output

for (x=1;x<=5;x=x+1)
cout<<x<<“ ”; 1 2 3 4 5 6
cout<<x<<“ ”;

IT 103 Computer Programming 1


Repetition Structure : for Statement

Example 3 :

Output

1
for (x=1;x<=5;x=x+1) 1
2
{
2
cout<<x<<endl; 3
3
cout<<x<<endl; 4
} 4
5
5

IT 103 Computer Programming 1


Repetition Structure : for Statement

Example 4 : print “HELLO” 5 times

Let x be the control variable(counter)

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

for (x=5;x>=1;x=x-1)

IT 103 Computer Programming 1


Repetition Structure : for Statement

Example 4 : print “HELLO” 5 times

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


{ {
cout<<“HELLO”; cout<<“HELLO”;
} }

for ( x=5 ;x>=1 ;x=x-1 ) for ( x=5;x>=1;x--)


{ {
cout<<“HELLO”; cout<<“HELLO”;
} }

IT 103 Computer Programming 1


Repetition Structure : for Statement

Example 5 : get the sum of all integers from 1 to 10

for(num=1; num<=10; num++)


{
sum=sum + num;
}

cout<< “The Sum of 1 to 10 is ”<<sum;

IT 103 Computer Programming 1


Repetition Structure : for Statement

Nested for Loop

The general form of the nested for statement is:

for (initialization; condition; increment)


{
for (initialization; condition; increment)
{

statement(s);
}
}

IT 103 Computer Programming 1


Repetition Structure : for Statement

Example 6 :

Output

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


{ 1 2
for (y=1; y<=3; y++)
1 3
{
2 1
cout<<x<<“\t”<<y<<endl;
2 2
}
} 2 3

IT 103 Computer Programming 1


UNIT 3
Program Control Structures
Repetition Structure

IT 103 Computer Programming 1


Program Control Structures
Repetition Structure
Repetitive /Iterative statements (loops) allow a set of instructions to be
repeated or carried out several times until certain conditions have been
met.
Iterative statements (loops) allow a set of instructions to be repeated or
carried out several times until certain conditions have been met. It can
be predefined(count controlled) as in in the for loop, or open
ended(condition controlled) as in while and do while.

IT 103 Computer Programming 1


Lesson 4
Repetition Structure:
The while/do-while Statement

IT 103 Computer Programming 1


Repetition Structure : while Statement

Condition-controlled loop

The general form of the while and do-while statement :

while (condition) do
{ {
statement;
} statement;

}while (condition);

IT 103 Computer Programming 1


Repetition Structure : while Statement

Example 1 :

ans = 'Y';
while (ans =='Y')
{
cout<<"Hello\n";
cout <<"Try again?(Y/N) ";
cin>>ans;
}

IT 103 Computer Programming 1


Repetition Structure : while Statement

Example 2 :

ans = 'Y';

do
{
cout<<"Hello\n";
cout <<"Try again?(Y/N) ";
cin>>ans;

} while (ans =='Y')

IT 103 Computer Programming 1


Repetition Structure : while Statement

Example 3 :

x=1;
while (x<=5)
{
cout<<"Hello ";
x++;
}

IT 103 Computer Programming 1


UNIT 4
Modular Programming

IT 103
Computer Programming 1
Lesson 1
Introduction to Modular Programming

IT 103
Computer Programming 1
Modular Programming
Breaking a complex problem into smaller parts, each of these parts of a
program is referred to as a module.

A complex problem divided into more sub-problems

IT 103
Computer Programming 1
Modular Programming

In programming, the smaller programs are known as sub-programs


with other names such as macro, sub-routine, procedure, module, and
function.

Each module represents a function that contains series of statements that


carry out a task.

IT 103
Computer Programming 1
Functions in C++

In programming, the smaller programs are known as sub-programs


with other names such as macro, sub-routine, procedure, module, and
function.

Each module represents a function that contains series of statements that


carry out a task.

IT 103
Computer Programming 1
Functions in C++

C++ program consists of functions , categorized as built-in functions


and user- defined functions.
• Built-in Functions known as library functions are provided and
already defined in C++. These are included in the header files like,
for instance, <iostream> in which data types and other
input/output functions are defined.

IT 103
Computer Programming 1
Functions in C++

C++ program consists of functions , categorized as built-in functions


and user- defined functions.
• User- Defined Functions are functions defined and created by the
programmer that performs a specific task. These must be declared
and defined before being used the same as variables.

IT 103
Computer Programming 1
Functions in C++

C++ program consists of one or more functions, the most important of


which is the function main() where execution starts and ends but main()
can call other functions to do special tasks.

A function can also call other functions; when the function call statement
is encountered even not in the main() function, the control is transferred
to the called function, and all its statements are executed.

With the execution of the return statement, the control returns to the
statement immediately following the function call statement.

IT 103
Computer Programming 1
Functions in C++

As illustrated, when main() calls


function A, the program control is
transferred to the called function A.
This called function performs the
defined task, which in this case, is
another function call. This time the
control transfers to function B. When
all the statements of function B are
executed, the control returns to the
calling function (function A). The
control then returns back to the
main() after the execution of
function A as indicated by the return
statement.

IT 103
Computer Programming 1
UNIT 4
Modular Programming

IT 103
Computer Programming 1
Lesson 2
Components of a Function

IT 103
Computer Programming 1
Function Definition
The function definition contains the code for a function. It is made up of two
parts: the function header and the function body, which is a compound
statement.

Function Header
A function header is made up of three parts: the return type, the
function name, and the formal parameter list. A semicolon is not used
at the end of the function definition header.

return_type function_name (formal parameter list)

IT 103
Computer Programming 1
Function Definition
The function definition contains the code for a function. It is made up of two
parts: the function header and the function body, which is a compound
statement.
Function Body
The function body contains the local {
declarations and the function statements. local declarations
The body starts with local definitions that
specify the variables needed by the function. statements;
After the local definitions, the function return;
statements, terminating with a return }
statement, are coded recommend that every
function, even void functions, have a return
statement.
IT 103
Computer Programming 1
Function Definition
The function definition contains the code for a function. It is made up of two
parts: the function header and the function body, which is a compound
statement.
return_type function_name (formal parameter list)
{
local declarations
function header
statements;
return; function body
}
Note:
Variables that are declared inside a function are called local
variables while global variables are created by declaring them
outside of any function.
IT 103
Computer Programming 1
Function Declaration
Any identifier or user-defined word can only be used once they have
been declared. The same applies to functions that functions need to be
declared before being called.
The function declaration consists of the name, return type, and types
of parameters of the functions. With these prototype declarations,
they can be called before they are entirely defined, allowing, for
example, to place the function from where they are called (main)
before the actual definition of these functions.
The basic function declaration is as follows:
return_type function_name (parameter list);

IT 103
Computer Programming 1
Function Call
While creating a C function, you give a definition of what the function
has to do. To use a function, you will have to call that function to
perform the defined task.

A called function performs a defined task, and when its return


statement is executed or when its function-ending closing brace is
reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters
along with the function name, and if the function returns a value, then
you can store the returned value.

IT 103
Computer Programming 1
C++ Program Structure with User-Defined Functions

Structure 1: A user-defined function can be defined below the main ()


function provided the program has a function declaration above it.

IT 103
Computer Programming 1
C++ Program Structure with User-Defined Functions
C++ programs can be written where the function definition is above
Structure 2:
main(). In this case, a function declaration is not required. This will
make the structure of the code more organized and easier to read.

IT 103
Computer Programming 1
UNIT 4
Modular Programming

IT 103
Computer Programming 1
Lesson 3
Variables ,Return Type and Parameters
of a Function

IT 103
Computer Programming 1
Variables
A function can have variables that are local to its scope only, or it can
use variables that can be accessed throughout the program, referred
to as local variables and global variables, respectively.
Variables that are declared inside a function
are called local, while global variables are
created by declaring them outside of any
function.

IT 103
Computer Programming 1
Return Type

A function may return a value. The return type of the function is the
data type of the value the function returns.

The return statement returns the flow of the execution to the


function from where it is called. As soon as the statement is
executed, the flow of the program stops immediately and return the
control from where it was called. The return statement may or may
not return anything for a void function, but for a non-void function, a
return value is must be returned

IT 103
Computer Programming 1
Return Type
User-defined functions in C++ are classified into two categories based
on the return type of the function, namely:

Void Function
These functions do not return a value to the calling function. Thus,
they are not used (called) in an expression. A call to a void function is a
stand–alone statement.

Value- returning Function


These functions return the value of a specific data type using the
return statement. It is used (called) in either expression or an output
statement or as a parameter in a function call.

IT 103
Computer Programming 1
Return Type

Void Function

IT 103
Computer Programming 1
Return Type

Value- returning Function

IT 103
Computer Programming 1
Function Parameters

Parameters refer to the type and identifier, and arguments are the
values passed to the function.

Parameters are of two kinds:

•Actual parameters. These are variables found in the function call whose
values will be passed to the formal parameters of the called function.

•Formal parameters. These are the variables found in the function


header that will receive values from the actual parameters.

IT 103
Computer Programming 1
Function Parameters

formal parameters

actual parameters

IT 103
Computer Programming 1
UNIT 4
Modular Programming

IT 103
Computer Programming 1
Lesson 4
Basic Function Designs

IT 103
Computer Programming 1
The Four Basic Function Designs

The four basic functions designs based on the return


types and parameter are as follows:

1. void functions with no parameters


2. void functions with parameters
3. non-void functions with no parameters
4. non-void functions with parameters

IT 103
Computer Programming 1
void functions with no parameters

IT 103
Computer Programming 1
void functions with parameters

IT 103
Computer Programming 1
non-void functions with no parameters

IT 103
Computer Programming 1
non-void functions with parameters

IT 103
Computer Programming 1

You might also like