IT 102 Computer Programming: Instructor Rodel C. Yebes

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 121

IT 102

COMPUTER PROGRAMMING
Instructor
RODEL C. YEBES
Overview
• Computer programming is the act of writing computer programs, which
are a sequence of instructions written using a Computer Programming
Language to perform a specified task by the computer.

• Computer Programming is fun and easy to learn provided you adopt a


proper approach. 
Introduction to Computer Program
Before getting into computer programming, let us first understand computer
programs and what they do.

A computer program is a sequence of instructions written using a Computer Programming


Language to perform a specified task by the computer.

The two important terms that we have used in the above definition are −
• Sequence of instructions
• Computer Programming Language
To understand these terms, consider a situation when someone asks you about
how to go to a nearby KFC. What exactly do you do to tell him the way to go to
KFC?
You will use Human Language to tell the way to go to KFC, something as follows −
First go straight, after half kilometer, take left from the red light and then drive around one
kilometer and you will find KFC at the right.
Here, you have used the English Language to give several steps to be taken.
1. Go Straight
2. Drive half kilometer
3. Take left
4. Drive around 1 kilometer
5. Search for KFC at your right side

The above sequence of instructions is actually a Human Program written in English Language, which
instructs on how to reach KFC from a given starting point
Now, let's go back and try to understand a computer program, which is a
sequence of instructions written in a Computer Language to perform a
specified task by the computer. Following is a simple program written
in Python programming Language −

The above computer program instructs the computer to print "Hello, World!" on the
computer screen.
• A computer program is also called a computer software, which can range from two
lines to millions of lines of instructions.
• Computer program instructions are also called program source code and computer
programming is also called program coding.
• A computer without a computer program is just a dump box; it is programs that make
computers active.
As we have developed so many languages to communicate among ourselves,
computer scientists have developed several computer-programming languages
to provide instructions to the computer (i.e., to write computer programs).
These are some of the programming languages, which can be used to write
computer programs and following are a few of them −

• Java
• C
• C++
• C#
• Python
• PHP
• Perl
• Ruby
• Visual basic Net
Uses of Computer Programs
• Today computer programs are being used in almost every field, Household,
Agriculture, Medical, Entertainment, Military defense, Communication, Business
,Banking, Insurance, Education, Marketing, Healthcare, Engineering Design and
Government

Listed below are a few applications of computer programs −


• MS Word, MS Excel, Adobe Photoshop, Internet Explorer, Chrome, etc., are
examples of computer programs.
• Computer programs are being used to develop graphics and special effects in movie
making.
• Computer programs are being used to perform Ultrasounds, X-Rays, and other
medical examinations.
• Computer programs are being used in our mobile phones for SMS, Chat, and voice
communication.
What is C++
• C++ is a general purpose, case-sensitive, free-form programming language that
supports object-oriented, procedural and generic programming.
• C++ is a middle-level language, as it encapsulates both high and low level language
features.
C++ supports the object-oriented programming, the four major pillar of object oriented programming
used in C++ are:

• Encapsulation-is an Object Oriented Programming concept that binds together the data and
functions that manipulate the data, and that keeps both safe from outside interference and misuse. 
• Data hiding-is a software development technique specifically used in object-oriented programming
(OOP) to hide internal object details (data members).
• Inheritance-allows us to define a class in terms of another class, which makes it easier to create and
maintain an application. 
• Polymorphism- having many forms and it means that a call to a member function will cause a
different function to be executed depending on the type of object that invokes the function.
C++ history
C++ programming language was developed in 1980 by Bjarne Stroustrup at bell
laboratories of AT&T (American Telephone & Telegraph), located in U.S.A.

Bjarne Stroustrup is known as the founder of C++ language.

It was develop for adding a feature of OOP (Object Oriented


Programming) in C without significantly changing the C component.

C++ programming is "relative" (called a superset) of C, it means any valid


C program is also a valid C++ program.
C++ Features
1. Simple language in the sense that it provides structured approach (to break the problem into parts), rich set of
library functions, data types etc.

2. Machine Independent or Portable - Unlike assembly language, c programs can be executed in many machines with little
bit or no change. But it is not platform-independent.

3. Mid-level programming language - C++ is also used to do low level programming. It is used to develop system applications
such as kernel, driver etc. It also supports the feature of high-level language. That is why it is known as mid-level language.

4.  Structured programming language - C++ is a structured programming language in the sense that we can break the
program into parts using functions. So, it is easy to understand and modify.

5. Rich Library - C++ provides a lot of inbuilt functions that makes the development fast.
f
6. Memory Management -It supports the feature of dynamic memory allocation. In C++ language, we can free the
allocated memory at any time by calling the free() function.
• C++ Features
7. Speed-The compilation and execution time of C++ language is fast.

8.  Pointer - C++ provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array etc.

9. Recursion - In C++, we can call the function within the function. It provides code reusability for every
function.

10. Extensible - C++ language is extensible because it can easily adopt new features.

11. Object Oriented -C++ is object oriented programming language. OOPs makes development and
maintenance easier where as in Procedure-oriented programming language it is not easy to manage if code
grows as project size grows.

12. Compiler based - C++ is a compiler based programming language, it means without compilation no C++
program can be executed. First we need to compile our program using compiler and then we can execute our
program.
Where we use C++ Language

• Design Operating system


• Design Language Compiler
• Design Database
• Utilities and drivers
• Application Software/Desktop application
• Embedded systems
• Develop games
• Design web browsers etc…
Programming Concepts
Traditional Procedural Programming

• In traditional, procedural programming, data and functions (subroutines, procedures)


are kept separate from the data they process. This has a significant effect on the way a
program handles data:

■ the programmer must ensure that data are initialized with suitable values before use
and that suitable data are passed to a function when it is called
■ if the data representation is changed, e.g. if a record is extended, the corresponding
functions must also be modified.

• Both of these points can lead to errors and neither support low program maintenance
requirements.
Objects

• Object-oriented programming shifts the focus of attention to the objects, that is, to the
aspects on which the problem is centered.

• A program designed to maintain bank accounts would work with data such as balances,
credit limits, transfers, interest calculations, and so on. An object representing an
account in a program will have properties and capacities that are important for account
management. OOP objects combine data (properties) and functions (capacities).

• A class defines a certain object type by defining both the properties and the capacities
of the objects of that type. Objects communicate by sending each other “messages,”
which in turn activate another object’s capacities.
Advantages of OOP

• Object-oriented programming offers several major advantages to software


development:

■ reduced susceptibility to errors: an object controls access to its own data. More
specifically, an object can reject erroneous access attempts
■ easy re-use: objects maintain themselves and can therefore be used as building blocks
for other programs
■ low maintenance requirement: an object type can modify its own internal data
representation without requiring changes to the application..
Developing a C++ Program
The following three steps are required to create and translate a C++ program:

1. First, a text editor is used to save the C++ program in a text file. In other words, the
source code is saved to a source file. In larger projects the programmer will normally use
modular programming. This means that the source code will be stored in several source
files that are edited and translated separately.

2. The source file is put through a compiler for translation. If everything works as planned,
an object file made up of machine code is created. The object file is also referred to as a
module.

3. Finally, the linker combines the object file with other modules to form an executable
file. These further modules contain functions from standard libraries or parts of the
program that have been compiled previously.
A Beginner’s C++ Program
# - indicates the line is intended for the preprocessor.

<iostream> - comprise of convention for input/output .

Stream – an information that involves the flow of the data.

Int main() – main function


{} – open/close braces denotes the start or end of the function.

<< - indicates that characters are being pushed to the output stream

endl – end of line


Return 0 – terminates the program
Compiler in C++

A compiler is system software which converts programming language


code into binary format in single steps. In other words Compiler is a
system software which can take input from other any programming
language and convert it into lower level machine dependent language.
Interpreter

• It is system software which is used to convert programming language


code into binary format in step by step process.

Assembler
• An assembler is system software which is used to convert the assembly language
instruction into binary format in step by step process.
Difference Between Compiler Interpreter
How to Download, Install and Start with Dev-C++ IDE

• Bloodshed Dev-C++ is a full-featured Integrated Development


Environment (IDE) for the C/C++ programming language. It uses Mingw
port of GCC (GNU Compiler Collection) as it's compiler.

PART1: Download Dev-C++ IDE


PART 2: Install Dev-C++ IDE
PART 3: Configure Dev-C++ IDE
PART 4: Start with Dev-C++
Comments in C++

• Generally Comments are used to provide the description about the Logic written in


program. Comments are not display on output screen.
When we are used the comments, then that specific part will be ignored by compiler.
In 'C++' language two types of comments are possible
• Single line comments
• Multiple line comments

Single line comments


• Single line comments can be provided by using / /....................
Multiple line comments
• Multiple line comments can be provided by using /*......................*/
Rules for Writing Comments
Rules for Writing Comments
Keywords in C++
• Keyword is a predefined or reserved word in C++ library with a fixed meaning and used
to perform an internal operation. C++ Language supports more than 64 keywords.
• Every Keyword exists in lower case latter like auto, break, case, const, continue, int etc.
Constant in C++

• It is an identifier whose value can not be changed at the execution time of program. In
general constant can be used to represent as fixed values in a C++ program. Constants
are classified into following types.

If any single character (alphabet or numeric or special symbol) is enclosed between single cotes ' 'known as single character
constant.
If set of characters are enclosed between double cotes " " known as string character constant.
Variable in C++

• Variable is an identifier which holds data or another one variable is an identifier


whose value can be changed at the execution time of program. Variable is an
identifier which can be used to identify input data in a program.
Variable declarations

• This is the process of allocating sufficient memory space for the data in term of
variable.

If no input values are assigned by the user than system will gives a default value called
garbage value.

Garbage value can be any value given by system and that is no way related to correct
programs.
It is a disadvantage and it can overcome using variable initialization.
Variable initialization

•  is the process of allocating sufficient memory space with user defined
values.

Variable assignment

It is a process of assigning a value to a variable.


Test II: Programming and Debugging
Test II: Programming and Debugging
What does Algorithm mean?

• An algorithm is a step by step method of solving a problem. It is commonly


used for data processing, calculation and other related computer and
mathematical operations.

• An algorithm is also used to manipulate data in various ways, such as


inserting a new data item, searching for a particular item or sorting an item.
Program Development Life Cycle

• When we want to develop a program using any programming language,


we follow a sequence of steps. These steps are called phases in program
development. The program development life cycle is a set of steps or
phases that are used to develop a program in any programming
language.
Generally, program development life cycle contains 6 phases, they are as follow..

1. Problem Definition
2. Problem Analysis
3. Algorithm Development
4. Coding & Documentation
5. Testing & Debugging
6. Maintenance
Figure 1.1
Problem Definition

• In this phase, we define the problem statement and we decide the boundaries of
the problem. In this phase we need to understand the problem statement, what is
our requirement, what should be the output of the problem solution. These are
defined in this first phase of the program development life cycle.

• “What task is to be done?” the most important thing to consider is before solving
the problem is to identify and define the exact problem to be solved. A
programmer is charged with providing solution to a problem must have a complete
understanding about the needs and wants of the user.
Problem Analysis

• In phase 2, we determine the requirements like variables, functions, etc. to solve the
problem. That means we gather the required resources to solve the problem defined in
the problem definition phase. We also determine the bounds of the solution.

• The problem itself is first broken into a few larger parts and each part into smaller
segments and further into smallest segments if necessary, until it makes you feel
comfortable solving them piece by piece. Always remember the key to providing a good
solution to a problem is to fully understand the entire task and surrounding details that
come with absolute clarity.
Algorithm Development

• During this phase, we develop a step by step procedure to solve the


problem using the specification given in the previous phase. This phase
is very important for program development. That means we write the
solution in step by step statements.
Coding & Documentation

• This phase uses a programming language to write or implement actual


programming instructions for the steps defined in the previous phase. In
this phase, we construct actual program. That means we write the
program to solve the given problem using programming languages like
C, C++, Java etc.,
Testing & Debugging

• During this phase, we check whether the code written in previous step
is solving the specified problem or not. That means we test the program
whether it is solving the problem for various input data values or not.
We also test that whether it is providing the desired output or not.
Maintenance

• During this phase, the program is actively used by the users. If any
enhancements found in this phase, all the phases are to be repeated
again to make the enhancements. That means in this phase, the
solution (program) is used by the end user. If the user encounters any
problem or wants any enhancement, then we need to repeat all the
phases from the starting, so that the encountered problem is solved or
enhancement is added.
Operators in C++

• Operator -is a special symbol that tells the compiler to perform specific


mathematical or logical Operation.
Arithmetic Operators
Given table shows all the Arithmetic operator supported by C Language. Lets suppose
variable Ahold 8 and B hold 3.
Relational Operators

• Which can be used to check the Condition, it always return true or false.
Lets suppose variable A hold 8 and B hold 3.
Logical Operator

• Which can be used to combine more than one Condition?. Suppose you
want to combined two conditions A<B and B>C, then you need to
use Logical Operator like (A<B) && (B>C). Here && is Logical Operator.
Assignment operators

• Which can be used to assign a value to a variable. Lets suppose


variable A hold 8 and B hold 3.

A-=3 or A=A-3
Increment and Decrement Operator in C++
• Increment operators are used to increase the value of the variable by one
and decrement operators are used to decrease the value of the variable by
one.
• Both increment and decrement operator are used on single operand or
variable, so it is called as unary operator. Unary operators are having higher
priority than the other operators it means unary operators are execute
before other operators.
Type of Increment Operator

• pre-increment
• post-increment

pre-increment (++ variable)

In pre-increment first increment the


value of variable and then used inside
the expression (initialize into another
variable).

In above program first increase the value of i and then used value of i into expression
post-increment (variable ++)
In post-increment first value
of variable is use in the
expression (initialize into
another variable) and then
increment the value of
variable.

In above program first used the value of i into expression then increase value of i by
Type of Decrement Operator

•pre-decrement
•post-decrement

Pre-decrement (-- variable)


In pre-decrement first
decrement the value of
variable and then used inside
the expression (initialize into
another variable).

In above program first decrease the value of i and then value of i used in
post-decrement (variable --)

In Post-decrement first value of variable is


use in the expression (initialize into
another variable) and then decrement the
value of variable.

In above program first used the value of x in expression then decrease value of i by
1.
Sample - Algorithm in Calculating the Average Grade
1. Declaration of the header files
2. Initialize a variables that can holds a non-numeric characters/values
3. Declare a variables that can holds a numeric characters/values
4. Call the variable that holds for student name 1 and display the values.
5. Input student 1 Grades in Math, Filipino, English, Science and Physics
6. Calculate Student 1 Average Grade
7. Call the variable that holds for student name 2 and display the values
8. Input student 2 Grades in Math, Filipino, English, Science and Physics
9. Calculate Student 2 Average Grade
10. Display student Names and Average Grade
Decision Making Statement

Decision making statement is depending on the condition block need to be


executed or not which is decided by condition.

If the condition is "true" statement block will be executed, if condition is "false"


then statement block will not be executed.

These are the following types of decision making statement.


•if
•if-else
•if –else if
•Nested if
•Switch
•Nested switch
if Statement
if-then is most basic statement of Decision making statement. It tells to
program to execute a certain part of code only if particular condition is true.

//Boolean expression 

//code to be executed  

•Constructing the body of "if" statement is always optional,


Create the body when we are having multiple statements.
•For a single statement, it is not required to specify the
body.
•If the body is not specified, then automatically condition
part will be terminated with next semicolon ( ; ).
If Statement Examples
#include <iostream>
using namespace std;

int main ()
{
int grade = 85;
if (grade >= 75)
{
cout<<"Remarks: Passed";
}
return 0;
}
When the above code is compiled and executed, it Result:
produces the following result − Remarks: Passed
else
It is a keyword, by using this keyword we can create a alternative block for "if" part. Using else is
always optional i.e, it is recommended to use when we are having alternate block of condition.

In any program among if and else only one block will be executed. When if condition is false then
else part will be executed, if part is executed then automatically else part will be ignored.
If-else statement
An ‘if’ statement can be followed by an optional ‘else’
statement, which executes when the Boolean expression
is false. It executes if block if condition is true otherwise else
block is executed.
Syntax
if else statement examples
if...else if...else Statement

An if statement can be followed by an optional else if...else statement,


which is very useful to test various conditions using single if...else if
statement.

Syntax
Examples
Nested if statements

It is always legal to nest if-else statements, which means you can use


one if or else if statement inside another if or else if statement(s).
Example
switch statement

A switch statement allows a variable to be tested for equality against a


list of values. Each value is called a case, and the variable being switched
on is checked for each case.
Syntax
The following rules apply to a switch statement −

•You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.

•The constant-expression for a case must be the same data type as the variable in


the switch, and it must be a constant or a literal.

•When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.

•When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.

•Not every case needs to contain a break. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.

•A switch statement can have an optional default case, which must appear at the end


of the switch. The default case can be used for performing a task when none of the
cases is true. No break is needed in the default case.
Example 1
Example 2
OUTPUT
Example 3

OUTPUT
Nested switch statements

It is possible to have a switch as part of the statement sequence of an


outer switch. Even if the case constants of the inner and outer switch
contain common values, no conflicts will arise.
Example
Looping Structure

• Looping structure allows to execute a statement or group of statements


multiple times.

• It provides the following types of loops to handle the looping requirements:

1. While Loop
2. For Loop
3. Do . . . While Loop
C++ while loop

• A while loop statement repeatedly executes a target statement as long


as a given condition is true.

Here, statement(s) may be a single statement or a block of statements.


The condition may be any expression, and true is any non-zero value. The loop
iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately
following the loop.
Flow Diagram

Here, key point of the while loop is that the loop might not ever run.
When the condition is tested and the result is false, the loop body will
be skipped and the first statement after the while loop will be executed.
Example When the code is compiled and executed, it
produces the following result −
Example

Output:
Nested While Loop Example

• In C++, we can use while loop inside another while loop, it is known as
nested while loop. The nested while loop is executed fully when outer
loop is executed once.
Output:
C++ for loop
• 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.
Here is the flow of control in a for loop −

• Initialization: step is execute first and this is execute only once when we are
entering into the loop first time. This step is allow to declare and initialize
any loop control variables.

• Condition: is next step after initialization step, if it is true, the body of the
loop is executed. If it is false, the body of the loop does not execute and
flow of control goes outside the for loop.

• Increment or Decrements: After completion of Initialization and Condition


steps loop body code is executed and then Increment or Decrements steps
is execute. This statement allows to update any loop control variables.
Flow Diagram
For Loop Example
For Loop Example

Output:
Example
C++ Nested For Loop
• In C++, we can use for loop inside another for loop, it is known as
nested for loop. The inner loop is executed fully when outer loop is
executed one time. So if outer loop and inner loop are executed 4 times,
inner loop will be executed 4 times for each outer loop i.e. total 16
times.
C++ do...while loop

• Unlike for and while loops, which test the loop condition at the top of


the loop, the do...while loop checks its condition at the bottom of the
loop.
• A do...while loop is similar to a while loop, except that a do...while loop
is guaranteed to execute at least one time. Notice that the conditional
expression appears at the end of the
loop, so the statement(s) in the loop
execute once before the condition is
tested.
If the condition is true, the flow of
control jumps back up to do, and
the statement(s) in the loop execute
again. This process repeats until the
given condition becomes false.
Flow Diagram
Example of do - while loop
Example of do - while loop
C++ Nested do-while Loop

• In C++, if you use do-while loop inside another do-while loop, it is


known as nested do-while loop. The nested do-while loop is executed
fully for each outer do-while loop.
Example
Loop Control Statements

• Loop control statements change execution from its normal sequence.


When execution leaves a scope, all automatic objects that were created
in that scope are destroyed.
C++ break statement

• The break statement has the following two usages in C++ −


• When the break statement is encountered inside a loop, the loop is immediately terminated
and program control resumes at the next statement following the loop.

• It can be used to terminate a case in the switch statement (covered in the next chapter).

• If you are using nested loops (i.e., one loop inside another loop), the break statement will stop
the execution of the innermost loop and start executing the next line of code after the block.
Flow Diagram
Example
C++ continue statement

• The continue statement works somewhat like the break statement.


Instead of forcing termination, however, continue forces the next
iteration of the loop to take place, skipping any code in between.
• For the for loop, continue causes the conditional test and increment
portions of the loop to execute. For the while and do...while loops,
program control passes to the conditional tests.
Flow Diagram
Example
The Infinite Loop

• A loop becomes infinite loop if a condition never becomes false.


The for loop is traditionally used for this purpose. Since none of the
three expressions that form the ‘for’ loop are required, you can make an
endless loop by leaving the conditional expression empty.
C++ Arrays
Arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last
element.

Stores a fixed-size sequential collection of elements of the same type.


An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Declaring Arrays

• To declare an array in C++, the programmer specifies the type


of the elements and the number of elements required by an
array as follows −

This is called a single-dimension array. The arraySize must be an


integer constant greater than zero and type can be any valid C++
data type. For example, to declare a 10-element array called balance
of type double, use this statement −
Initializing Arrays

• You can initialize C++ array elements either one by one or using a single
statement as follows −

The number of values between braces { } can not be larger than the
number of elements that we declare for the array between square
brackets [ ]. Following is an example to assign a single element of the
array −
If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write −
If you omit the size of the array, an array just big enough to hold
the initialization is created. Therefore, if you write −

You will create exactly the same array as you did in the previous
example.

The above statement assigns element number 5th in the array a value of 50.0. Array with
4th index will be 5th, i.e., last element because all arrays have 0 as the index of their first
element which is also called base index. Following is the pictorial representation of the same
array we discussed above −
Accessing Array Elements

An element is accessed by indexing the array name. This is done by


placing the index of the element within square brackets after the name of
the array. For example −

The above statement will take 10th element from the array and assign the value to
salary variable. Following is an example, which will use all the above-mentioned three
concepts viz. declaration, assignment and accessing arrays −
Example A
Example B
Example C

This program makes use of setw() function to format the


output. When the above code is compiled and executed, it
produces the following result −
Example D
Key Notes

• You can access elements of an array by using indices.


• Suppose you declared an array mark as above. The first element
is arrayname[0], second element is arrayname[1] and so on.

You might also like