Computer Programming
Computer Programming
Computer Programming
Computer programming
➢ Introduction to Computer
⚫ What is Computer?
⚫ Computer System
✓ Basic component / Basic organization of a
computer system.
⚫ Software
✓ System software
✓ Application software
➢ What is Computer?
A computer is a device capable of performing computations and
making logical decisions at speeds millions (even billions) of
times faster than human beings can.
System
Software
➢ What is software?
➢ A computer is an electronic machine that can process data, but it
needs to be told what to do in the form of a set of instructions.
➢ Software is a set of computer readable codes compiled to enable
computer to carry out specific functions.
➢ It is also designed to enable humans to communicate effectively
with their computer by passing simple instructions/commands
through user interface.
➢ Software allows the hardware to do something useful; without
software, the hardware wouldn't know what it was supposed to do.
➢ Software /programs are stored as files on a storage device such as the
hard disk, DVD, or Memory sticks.
⚫ When they need to run, they are loaded into the computer's memory(RAM).
9
Cont'd
➢ There are two main categories of software :
1. System software
2. Application software
Application
Software
System
Software
11
Cont'd
Operating system
Operating is a set of programs that manages computer hardware
and various resources.
It allows the parts of a computer to work together by performing
tasks like transferring data between memory and disks or sending
output onto a display device.
12
Cont'd
Main activities performed by the operating system include:
Provide a user interface and handle input/output
Manage system memory
Manage programs
execute and provide services for applications software.
Provide networking capability
Control access to system resources
Manage files
Manage computer’s resources – resource allocation
provides a platform to run high-level system software
13
Cont'd
Utility software
➢ It is a program that performs very specific tasks, usually related to
managing system resources. It is designed to do one or two specific,
but vital tasks.
Algorithm Development
• skill of coming up with sequence of simple and machine understandable set of
instructions showing the step of solving the problem.
• Those set of steps should not be dependent on any programming language or
machine.
Computer Language Translator
⚫ Language Translator:
➢ A translator is a computer program that translates a program
written in a given programming language into a functionally
equivalent program in a different computer language, without
losing the functional or logical structure of the original code.
2. Design
3. implementation or Coding
4. Testing
5. Deployment
6. Maintenance
7. Documentation
1. Requirement Gathering and Analysis
⚫ In this phases, all the relevant information is collected from the
customer to develop a product as per their expectation.
⚫ Any ambiguities must be resolved in this phase only.
⚫ Business analyst and Project Manager set up a meeting with the
customer to gather all the information like what the customer wants to
build, who will be the end-user, what is the purpose of the product.
⚫ Before building a product, a core understanding or knowledge of the
product is very important.
⚫ For Example, A customer wants to have an application which involves
money transactions. In this case, the requirement has to be clear like
what kind of transactions will be done, how it will be done, in which
currency it will be done, etc.
1. Requirement Gathering and Analysis (Cont’d)
⚫ Once the requirement gathering is completed, requirement analysis is done to
check the feasibility of the development of a product.
⚫ In case of any ambiguity, a call is set up for further discussion.
⚫ Once the requirement is clearly understood, the Software Requirement
Specification (SRS) document is created.
⚫ This document should be thoroughly understood by the developers and also
should be reviewed by the customer for future reference.
⚫ The requirement analysis specification will contain:
▬ The proposed system or solution, which has been agreed by the client and
developer.
▬ A list of existing tools, new tools, required facilities and people available
for developing the solution.
▬ A schedule for the next stages of the project, including the deliverables for
each stage.
2. System Design
⚫ The design phase comes after a good understanding of customer’s
requirements, this phase defines the elements of a system, the components,
the security level, modules, architecture and the different interfaces and
type of data that goes through the system.
⚫ A general system design can be done with a pen and a piece of paper to
determine how the system will look like and how it will function, and then a
detailed and expanded system design is produced, and it will meet all
functional and technical requirements, logically and physically.
✓ Testing: –done by testing team to making sure that the program does what
is intended for. The task of locating and identifying of bugs/errors.
✓ Debugging:- done by development team for finding and removing
errors/bugs from the program.
⚫ Errors in a program are called bug, and process of locating and removing
errors is called debugging.
⚫ When the program is completed and all separate modules have been tested, a
full test of the program is performed.
▬ Any errors in the program will be corrected and the test repeated.
⚫ Types of tests:
▬ Alpha test
▬ Beta test
▪ Tested externally.
5. Deployment
Once the product is tested, it is ready to deploy in the production
environment or first UAT (User Acceptance testing) is done depending
on the customer expectation.
⚫ Problem solving
⚫ Algorithm
√ Pseudocode
√ flowchart
➢ Problem Solving
⚫ Problem solving is the process of transforming the description of a
problem into the solution by using our knowledge of the problem
domain and by relying on our ability to select and use appropriate
problem-solving strategies, techniques, and tools.
2. Problem analysis:
⚫ To analysis how the problem affects the researcher & his or her
current situation & other people involved in the situation.
⚫ The gravity of the problem & all the factors that are contributing to
the problem are determined
Problem Solving process
3. Generating possible solutions
⚫ Focus must be on identifying & generating all possible solutions for a
problem.
⚫ It also helps to redefine the problem & revise the problem solving
process in case the initial solution fails to manage the problem
effectively.
Algorithm
What is an Algorithm?
⚫ The sequence of steps to be performed in order to solve a problem by the
computer is known as an algorithm.
⚫ Algorithm is a finite set of unambiguous steps for solving a particular
problem. It is a step-by-step analysis of the process.
⚫ To make a computer do anything (i.e. solve a problem), you have to write a
program: In a computer program, you have to tell a computer, step by step,
exactly what you want it to do. The computer then executes the program,
following each step mechanically, to accomplish the end goal.
⚫ Algorithm has the following attributes:
▬ Input: An algorithm may or may not require input
▬ Output: Each algorithm is expected to produce at least one result
▬ Definiteness: Each instruction must be clear and unambiguous.
▬ Finiteness: It should be terminate after finite number of steps.
Flow of Control Structures
⚫ Though instructions in an algorithm appears in sequence, they may not
execute in that order.
⚫ An instruction that alters the order of an algorithm is called flow of control
structure.
❖ Test the algorithm: choose data sets and verify that your
algorithm works.
➢ Example 1: Write an algorithm that should read any two integer
numbers from the input and compute the sum of the two numbers.
Solution:
Step-1: Start
Step-2: Define the algorithm as Sum
Step-3: Define any three Variables
step-4: input any two integer numbers
Step-5: Add the two numbers
Step-6: Store the result in the third Variable
Step-7: Display the result
step-8: Stop
➢ Example 2: Write an algorithm that should read any two
numbers from the input and return the greater one.
Solution:
step-1: Start
step-2: Define any two variables num1 and num2
step-3: input any two numbers
step-4: if num1>num2 Then
Display “ num1 is greater” ;
else
Display “ num2 is greater” ;
End if
step-5: Stop
What is Pseudocode?
Pseudocode is a method used to define an algorithm, written in a
form that can easily be converted into real programming
statements. But it cannot be compiled nor executed.
Algorithm vs Pseudocode
Both Algorithm and Pseudocode describe the logical sequence
how to solve a problem
⚫ There are some basic shape and boxes included in the flowchart
so as to explain the steps of the algorithm.
▬ It must start with a start box and end with a terminal box.
Symbols Used In Flowchart
➢ Example 1: Draw the flowchart for an algorithm that should read
any two integer numbers from the input and compute the sum of
the two numbers.
solution:
➢Example 2: Draw the flowchart for an algorithm that should read
any two numbers from the input and return the greater one.
Solution:
Activities:
1) Develop an algorithm which will read any number N from the
keyboard and compute the sum of numbers between 0 and the number
N. And also draw the corresponding flowchart.
3) Write an algorithm to find the sum of first 50 even numbers and also
draw the corresponding flowchart.
Individual Assignment:
Instruction: You must show important steps and flows.
1. Develop an algorithm which will read any number N from the
user and print all its divisors, and draw the corresponding
flowchart.
syntax:
#include<iostream.h> // Preprocessor directive
#include<conio.h>
Class declaration (optional)
Function definition variable (optional)
return_type main( )
{ // used to start the block of code in main( ) function
clrscr( ); //It clears the previous output screen.
Program code will be written here
getch(); //It holds the final output screen until any key is pressed
by user.
Structure of C++ program (cont’d)
➢ Simple C++ Program
♦ The size of the memory space allocated and types of value for a
variable depends on the data type.
Scope of Variables in C++
⚫ In C++, Scope of a variable refers to the visibility of the
variables.
⚫ i.e. Scope is a region of the program, and variables can be
defined:
1. Local variables:- declared inside a function or a block.
✓ Do not exist outside the block in which they are
declared, i.e. they can not be accessed or used outside
that block.
2. Global variables:- declared outside of all function.
✓ Declared at the top of the program outside all of the
functions or blocks, and can be accessed from any
portion of the program.
Example: Identify the Scope of Variables
Tokens in C++
➢ C++ Program is a collection of Tokens, Comments, and White
Space.
➢ A token is the smallest unit/element of a C++ program that is
meaningful to the compiler. In fact, every unit that makes a
sentence in C++ is a Token.
Name of functions
Name of classes
● Floating-constant: 4.67,3.14E-05
✓ ; semicolon.
● Arithmetic Operators
● Relational Operators
● Logical Operators
● Assignment Operators
➢ Relational Operators
▪ Relational/comparison operators such as >, <, >=, =<, ==, !=,
… etc are used to compare two operands, values or
expressions to evaluate the relationship.
Example: if(x % 2 != 0) then x is odd
or if(x % 2 = = 0) then x is even
➢ Logical operator
▪ Assignment operator such as =, +=, -=,*=, /=, %=, etc are used to
assign/initialize a value to a variable during the program
execution.
➢ Decrement Operators (- -)
➢ Data Type:
♦ Data type describes the property of the data and the size of
▪ Primitive/Built-in,
▪ Derived, and
▪ User-defined data types.
●Primitive data types: ● Derived data types: ● User defined data
❖ Integer ✓ Array types:
✓ Short int ✓ Pointer ✓ Struct
✓ Long int ✓ Class
❖ Floating types
✓ enum
✓ Float
✓ Double
❖ Char
❖ bool
Built-in data types:
► char: For characters. occupy 1 byte.
Example: char ch = 'A';
► int: For integers. Occupies (sizes) 2 bytes.
Example: int num = 100;
► Long int: For integers. Occupies (sizes) 4 bytes.
Example: int num = 200000;
► float: For single precision floating point. Occupies (sizes) 4 bytes.
Example: float num = 123.78987;
► double: For double precision floating point. Occupies (sizes) 8 bytes.
Example: double num = 10098.98899;
► bool: For booleans, true or false. Occupy 1 byte
Example: bool b = true;
► const: for fixed value through the program execution.
example: const int day=7;
BUILT IN DATA TYPES
➢ Character data type:
• Char ch ;
Ans:
#include<iostream.h>
void main( )
{
cout<< “Hello world, welcome to Ethiopia”;
}
Output:
Exercise:
write a C++ program that add given two numbers and display the
result.
➢ Comment in C++
▪ C++ comments start with /* and end with */ for multiple lines
Example: /* This is a my first “Hello World” program using C++
programming language */
1. Sequence structures
2. Selection structures
3. Iteration structures
Sequence structure
■ Sequence structure is the construct where statements are executed
one after the other in the order in which they are written.
Example: Write a program in C++ that will print the phrase shown below:
“Welcome to Bahir Dar University
Engineering Faculty, Department of Fashion Technology”
Ans:
#include<iostream.h>
void main( )
{
cout<< “Welcome to \n”;
cout<< “ Bahir Dar University Engineering Faculty \n”;
cout<< “EiTEX Department of Fashion ”;
} Output
Welcome to
Bahir Dar University Engineering Faculty
EiTEX Department of Fashion
Selection statement
The selection statements allow you to choose a set of statements
for execution depending on a condition.
Selection structure includes if…else, else if, nested if, and
switch.
If…else statement is a conditional branching statement used to
execute a set of code when the condition is true, otherwise executes
the code in the "else" part.
Flowchart
Syntax
SELECTION STATEMENT
Example: Write a program in C++ that read any two number from the
keyboard and then display the greater one using if…else statement.
Ans: #include <iostream.h>
void main()
{ int b,c;
cout<<“Enter any two numbers one by one:”;
cin>>b>>c;
if (b>c)
cout << "B is greater than C";
else
cout << "C is greater than B";
}
SELECTION STATEMENT
else if statement is an extension of the "if…else" conditional
branching statement.
When the expression in the "if" condition is "false" another "else
if " construct is used to execute a set statements based on an
expression.
Syntax
if(condition_1) flowchart
{ block statement_1; }
else if(condition_2)
{ block statement_2; }
else if(condition_n)
{ block statement_n; }
else
default statement;
SELECTION STATEMENT
Example: write a program which will ask the user to input the
student’s mark and then find the grade in letter.
Ans:
#include <iostream.h>
int main() {
float mark;
cout<<"Enter student's mark: ";
cin>>mark;
if (mark < 40)
cout<<“Grade = F";
else if (mark < 50)
cout<<“Grade = E";
else if (mark < 60)
cout<<“Grade = D";
SELECTION STATEMENT
else if (mark < 70)
cout<<“ Grade = C";
else if (mark < 85)
cout<<“ Grade = B";
else
cout<<“ Grade = A";
cout<<"\n";
return 0;
}
SELECTION STATEMENT
Nested if…else statement is if…else statement inside another if
statement.
Syntax and flowchart:
if(condition_1) {
if(condition_2)
{ block statement_1; }
else
{ block statement_2; }
}
else
{ block statement_3; }
Block statement_3;
SELECTION STATEMENT
Example: Write the program which will accept three numbers from
the user and return the greatest number among them.
Ans:
#include<iostream.h>
int main() {
int x, y, z;
cout<<"Enter values for x, y, and z\n";
cin >>x>>y>>z;
if(x>=y)
{ {
if(x>=z)
{
cout<<"The greatest number is:"<<x<<endl;
} else
SELECTION STATEMENT
{
cout<<"The greatest number is:"<<z<<endl;
}
}
else if(y>z)
{
cout<<"The greatest number is:”<<y<< endl;
} else
{
cout<<"The greatest number is:”<<z<< endl;
} Output
return 0; Enter values for x, y, and z
7
} 9
8
The greatest number is: 9
SWITCH STRUCTURE
Switch statement compares the value of an expression against a list
of integers or character constants.
The lists of constants are listed using the "case" statement along with a
"break" statement to end the execution. If no conditions match then the
code under the default statement will be executed.
break;
Case2 stmt
case constant2: Statements; .
break; .
.
.
Case n stmt
.
case statement n: statements;
default
break;
Default: Statements;
}
SWITCH STRUCTURE
Example: write a C++ program which will ask the user to input the grade
in letter (A,B,C,D, or F) as input and return the string ‘Excellent’, ‘Best
done’, ‘passed’, ‘Poor’, ‘Better try again’, ‘invalid grade’ for the input
‘and any other key respectively using switch statement.
Solution: #include <iostream.h>
int main () {
char grade ; // local variable declaration
cout<<" what is the grade in letter? ";
cin>>grade;
switch(grade)
{
case 'A' : cout << "Excellent!" << endl;
break;
SWITCH STRUCTURE
case 'B' : cout<< “Best done“<<endl;
break;
case 'C' : cout << “Passed" << endl;
break;
case 'D' : cout << “Better try " << endl;
break;
case 'F' : cout << “ Fail, do it again" << endl;
break;
default : cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
}
GOTO STATEMENT
The goto statement is used for unconditional branching or
transfer of the program execution to the labeled statement.
Syntax:
GOTO STATEMENT
Example: Write a program in C++ that read any number and check
whether the number is even or odd.
#include <iostream.h>>
int main(){
ineligible:
cout<<"You are not eligible to vote!\n";
cout<<"Enter your age:\n";
int age;
cin>>age;
if (age < 18)
goto ineligible;
else
cout<<"You are eligible to vote!";
}
ITERATION STATEMENTS
■ Iteration or loops statements help to accomplish repetitive
execution.
■ There are three loop structures, which are while, do-while
and for loop.
While Loop
While statement is iteration structure that executes a set of code only
when the condition is true.
It is also known as "Entry controlled loop" since it is executed only
inside the loop if the condition is satisfied. Start
Syntax:
While (condition)
While loop statement
{
flowchart
Statement1;
Statement 2;
}
Stop
■ The flow diagram indicates that a condition is first evaluated.
■ If the condition is true, the loop body is executed and the condition is
re-evaluated; otherwise it exit.
Example:
#include <iostream.h>
int main()
{
int i=1;
while(i<5)
{
cout<<"Value of variable i is: "<<i<<endl;
i++;
} Output:
Value of variable i is: 1
return 0; Value of variable i is: 2
} Value of variable i is: 3
Value of variable i is: 4
In the above example the “while" statement iterates starting with the
value of i=1 till i is less than 5 every time increasing the value of i by 1.
Do…While Loop
The Do…While statement is an iteration statement that executes a set of code
first, then it checks the condition. This statement is also known as "Exit
controlled loop" since the condition is checked only after executing the
loop at least once.
This statement is similar to while loop except that the test condition occurs at
the end of the loop.
Therefore, Do …while loop is guaranteed to execute the loop body at least
once before testing the condition. Start
Syntax:
do {
Statement 1;
Statement 2;
} While (test condition);
Stop
In the above example the “do…while" statement iterates starting with the
value of i=2 till i is less than 7 every time increasing the value of i by 1.
For loop
The For Loop Statement is an iteration statement that executes a
set of code (block of statements) repeatedly until a particular
condition is satisfied.
Syntax:
for (initial value; test condition; increment/decrement)
{
Statement;
}
2. Write a C++ program that should find the sum of the number between 1 and 99
using while loop.
3. Write a program in C++ that should read any number from the input and compute
the factorial of that number using for loop.
4. Write a program in C++ that should print English Alphabet from ‘A’ to ‘M’.
ABCDEFGHIJKLNM
5. Write a program that should ask the user to input his/her name and print 10 times
6. Write a program in C++ that print display the result shown below using for, do…while
or while loop.
FUNCTION
➢ In programming, a function is block of code/statements which is
used to perform a particular task.
parts Explanation
Return type the type of data that the function returns
Function definition:
● A function definition is done to tell the compiler what task the
function will perform.
▬ It provides the actual body of the function.
▬ Function definition consists of the function header and its
body.
● A function prototype and a function definition must agree
EXACTLY on the return type, the name, and the parameters.
FUNCTION CALLING
► A function is called (invoked) by providing the function name,
followed by the parameters being sent enclosed in parentheses.
► To call a function, you simply need to pass the required
parameters along with function name.
► If the function is without parameters, it can be called directly
using its name.
► But for functions with arguments, there are two ways to call a
function:
■ Call by Value:
…………………
…………………
int main ( ) {
………………….
………………..
}
FUNCTION
When a program begins running, the system calls
the main() function and then the system starts executing
codes from main() function.
2. Write a function, sum( ), in C++ that should get the number from the user and calculate
the sum from “0” to number given by the user.
3. Write a function, Sqr_toot( ), in C++ that should get value of a, b, and c from the user
and find the roots of the following quadratic equation.
F=ax2+bx+c
4. Write a function, find( ), in C++ that accept three numbers from the user and Find the
largest, and smallest, and average of the numbers.
5. Write a function, isEven( ), in C++ that should get the number from the user and
determine whether the number is even or not.
6. Develop a program in C++ that has function printTemp() which prints "Cold" on if the
temperature is below 10, "OK" if the temperature is in the range 20 -> 30,"Hot" if the
temperature is above 30.
ARRAYS
➢ Arrays: An array is a collection of data that holds fixed
number of values of same type.
dataType arrayName[arraySize];
- array size refers to number of element in the array.
Example: int m [5] ; - ‘int’ is the data type.
- ‘m’ is the array name.
- 5 is number of elements.
How to initialize an array in C++? We can initialize
an array during declaration:
example: int mark[5] = {19, 10, 8, 17, 9};
NOTE: Elements within brackets [ ] in an array must be
a constant value.
CONT…
▪ int a[5] means a[0], a[1], a[2], a[3], a[4] or
Int int int int int
a[0] a[1] a[2] a[3] a[4]