3. Introduction: Computer
To make a computer do anything (i.e. solve a problem),
we have to write a computer program. In a computer
program we tell a computer, step by step, exactly what
want to do.
3
4. Introduction: Program vs Software
Program is simply a collection of instructions or ordered operations for
computer to perform specific function or particular task and achieve a
specific result
Software is a collection of programs and data files that are designed to
perform some specific set of operations
The process of software development is called programming
4
5. SDLC: Software development life cycle
SDLC is a series of steps a
programmer should follow before
s/he starts coding the program in
a specific language
How do we write a program?
It is a two phase process
5
6. SDLC: Software development life cycle
1. Problem solving phase
a. Problem Identification
b. Specify Requirements
c. Analyze the problem
d. Design algorithm and draw flowchart
2. Implementation phase
a. Write the program (Coding)
b. Testing and Debug the program
c. Program deployment
d. Maintain and Update the program
e. Document the program
6
7. SDLC: Problem identification
At this stage the problem being solved is observed carefully
Major area of concern are identified
Irrelevant information is filter out.
7
8. SDLC: Specify requirements
This stage demands to make clear the user’s requirements so that a proper
solution could be suggested.
Requirements are documented here.
8
9. SDLC: Analyze the problem
Problem is decomposed into sub-problems
This lead to simple solution
The technique is known as top down design (also called divide and conquer
rule).
9
10. SDLC: Design algorithm and draw Flowchart
Develop a finite list of steps to solve a problem.
Once algorithm has been designed it should be verified
After designing the algorithm, the next step is to draw a flowchart
Flowchart maps the algorithm to a pictorial presentation which helps in
understanding the flow of control and data in algorithm
10
11. SDLC: Write the program (coding)
Coding involves the conversion of an algorithm to a program, written in any
programming language.
The programmer must know the syntax of the programming language chosen.
The grammatical rules of a programming language to write programs are
referred to as syntax of that programming language.
11
12. SDLC: Test and debug the program
Testing is the process of evaluating a program to verify that it works as desired.
Debugging is the process of finding and removing errors in the program.
There are 3 types of errors
1. Syntax errors : occurs when one or more grammatical rules are violated. Are
usually detected by compilers
2. Logical errors: occurs when program follows wrong logic
3. Runtime errors: occurs when the program directs the computer to perform an
illegal operation such as dividing a number by zero
12
13. SDLC: Program deployment
Once the program has been tested thoroughly, it must be installed or
put into operation at the site where it will be used.
13
14. SDLC: Maintain & update the program
Program maintenance is ongoing process of upgrading the program to
accommodate new hardware and software.
Regular maintenance is essential to the continued usefulness of a program.
14
15. SDLC: Document the program
Documentation is a detailed description of a program’s algorithm, design, coding
method, testing and proper usage. A comprehensive documentation consists of the
following:
1. A description of what the program is supposed to do.
2. A description of the problem solution (the algorithm).
3. A description of the program design including any aids used (flowcharts,
algorithms etc.).
4. A description of the program’s testing process, including test data used and
result obtained.
5. A user manual (user guide).
15
16. Algorithm
The sequence of steps to be performed in order to solve a problem by the
computer is known as an algorithm
It is a recipe for solving problems!
Methods of specifying an algorithm
- Pseudocode - text based
- Flowchart - using drawings
16
17. Algorithm
Pseudo code
Is a plain language description of the
steps in an algorithm or another
system.
Its independent of any programming
language
Flow charts
Is a graphical or symbolic
representation of an algorithm
It is the diagrammatic representation
of the step-by-step solution to a given
problem.
17
18. Pseudocode and flowchart
A pseudocode and flowchart include following three types of control structures
1. Sequence: here, statements are placed one after the other and the execution
takes place starting from up to down
2. Branching (Selection): there is a condition and according to a condition, a
decision of either TRUE or FALSE is achieved. In the case of TRUE, one of the two
branches is explored; but in the case of FALSE condition, the other alternative is
taken. Generally, the ‘IF-THEN’ is used to represent branch control
3. Loop (Repetition): The Loop or repetition allows a statement(s) to be executed
repeatedly based on certain loop condition
18
23. Pseudocode and Flowchart exercise
Produce pseudocode and flowchart for the following problems
1. Calculate the sum of two input numbers and display the result
2. Calculate the area of a rectangle, given length and width from the user and
display the result
3. Compute the average of three input numbers, and then display the result
4. Convert an input Fahrenheit degree into its Celsius degree equivalent. Use the
formula: C= (5/9)*F-32.
5. Prints the largest of two given numbers
6. Prints the numbers from 0 - 100 23
25. What is a programming language?
A programming language is a vocabulary and set of grammatical rules for instructing a
computer or computing device to perform specific tasks.
Like natural languages, programming languages have their own syntax and semantics
Syntax is a collection of rules to specify the structure or form of code. Statements in a
program should obey the the grammar of the language
It answers the question: how do I construct a valid sentence
Semantics is about the meaning of the sentence. It answers the questions: is this sentence
valid? If so, what does the sentence mean?
25
26. Programming languages
High level programming languages
● It can be considered as a
programmer-friendly language.
● It is easy to understand.
● It is easy to debug.
● It can be run on different platforms.
● It is less memory efficient, i.e it
consumes more memory in
comparison to low-level languages
● Examples: C, C++, Java, Python...
Low level programming languages
● It is considered as a machine-friendly
language.
● It can be understood easily by the machine.
● It is difficult to understand.
● It is difficult to debug.
● It is not portable, it depends on the machine
● It is not used widely in today's times
● Examples: Assembly language and machine
language
There are two major types of programming languages, Low Level Languages and High
Level Languages
26
27. C++: Background
C++ is a programming language created by
Bjarne Stroustrup and his team at Bell
Laboratories in 1979. Forty years later, it is one of
the most widely used languages in the world; we
can find C++ applications everywhere
As the name implies, C++ was derived from the C
language; Bjarne’s goal was to add
object-oriented programming into C, a language
well-respected for its portability and low-level
functionality 27
28. C++: Why?
Software built with C++ is known for its performance and efficiency.
1. C++ is used to in the development of games, desktop apps, operating systems, robotics,
browsers, and so on because of its performance.
- Popular applications such as Microsoft Office, Adobe Photoshop, MySQL, google
chrome and even operating systems such as Windows are developed using C++
2. After learning C++, it will be much easier to learn other programming languages like
Java, Python, etc.
3. C++ helps you to understand the internal architecture of a computer, how computer
stores and retrieves information.
28
29. C++: Facts
C++ is case sensitive language
Statements should end with
semicolon(‘;’)
Every opened brace should be closed
Whitespaces are ignored by compilers.
So they are used for code readability.
Use indentations to increase code
readability
29
31. Getting started: Tools required
To write a C++ program we need
Text editor
● To write in our code, edit and save. For this we can use any text editor starting
with notepad. But using text editors especially developed for writing codes make
the writing process easy.
Compiler
● To run our program and see the result. See next slide for more on compilers
31
32. Getting started: Compiler
In order to run our program on the computer and see the output, first we need to convert our
program into an equivalent machine code, so that the computer can process/understand it. This can
be done by a program called Compiler.
Compiler is a program translator that translates the instruction of a higher level language to machine
language
The programs written by the programmer in higher level language is called source program(code).
After this program is converted to machine languages by the compiler it is called object program
There are different C++ compilers such as GCC for linux based systems, clang for macOS, MinGW
for windows, ...
32
33. Getting started: IDE
An IDE (integrated development environment) is a software used for building other applications
(software)
IDEs provide common developer tools into a single graphical user interface (GUI). An IDE typically
consists of:
1. Source code editor: a text editor that can assist in writing software code with features such
as syntax highlighting, auto- completion …
2. Compiler: compiling computer source code into binary code
3. Debugger: a program for testing other program that can graphically display the location of a
bug in the original code
There are a number of C++ IDEs like Visual studio, Code blocks, Dev C++ , Net beans, Eclipse ...
33
34. helloworld.cpp
A "Hello, World!" is a simple
program that outputs Hello,
World! on the screen. Since it's a
very simple program, it's often
used to introduce a new
programming language to a
newbie.
34
35. helloworld.cpp
#include<iostream>
The #include is a preprocessor
directive used to include files in our
program. The above code is including
the contents of the iostream
file/library to our program
This allows us to use cout in our
program to print output on the screen.
35
36. helloworld.cpp
using namespace std;
A namespace is like a region, where we have
functions, variables etc and their scope is limited to
that particular region. Here std is a namespace
name, this tells the compiler to look into that
particular region for all the variables, functions, etc.
In this case we are importing the std namespace
because we are using cout, which belongs in this
namespace.
36
37. helloworld.cpp
int main() {
....
}
As the name suggests this is the main function of our
program, where code execution begins. Every program
needs to define the main function
The int is the return type, which indicates to the compiler
that this function will return an integer value. That is the
main reason we have a return 0 statement at the end of
main function.
The curly braces indicate the start and the end of the
function. 37
38. helloworld.cpp
cout << "Hello World";
The cout object belongs to the
iostream file and the purpose of this
object is to display the content between
double quotes as it is, on the screen.
Note: ; is used to indicate the end of a
statement.
38
39. helloworld.cpp
return 0;
The return 0; statement is the "Exit
status" of the program. In simple terms,
the program ends with this statement.
This statement returns value 0 from the
main() function which indicates that the
execution of main function is successful.
The value 1 represents failed execution.
39
40. Compiling and executing program
Step 1 - Compiling
Turns source code(.cpp) into machine equivalent code (.obj or .o) files
Checks for any errors
Command for compiling g++ -c filename.cpp
Step 2 - Linking
Links object code (.obj or .o) files to external libraries and produces the final executable file (.exe)
Command for linking g++ filename.obj -o executable_filename
Step 3 - Executing
Runs the executable file and shows the program outputs
Command for executing executable_filename.exe 40
45. C++ Variables
While writing program in any language, you need to use various variables to
store various information.
Variables are nothing but reserved memory locations to store values. This
means that when you create a variable you reserve some space in memory.
Before using a variable you must create it first, such step is called variable
declaration
45
46. C++ Variables: Variable declaration
Syntax
type variable_name = value;
where ,
type is one of C++ data types (such as int)
variable_name is the name of the variable (such as x or myName).
Variable names should be valid identifiers
the equal sign is used to assign values to the variable
46
47. C++ Variables: Identifiers
Identifiers are unique names given to variables or functions to uniquely identify one from the others
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The later one is recommended to use since it creates understandable and maintainable code
The general rules for constructing names for variables (unique identifiers) are:
○ Names can contain letters, digits and underscores
○ Names must begin with a letter or an underscore (_)
○ Names are case sensitive (myVar and myvar are different variables)
○ Names cannot contain whitespaces or special characters like !, #, %, etc.
○ Reserved(keywords) words, words that have special functionality in C++ such as int,
cannot be used as names
47
48. C++ Variables: Identifiers example
Valid identifiers example
- num
- myVar
- mark1
- total_sale
- fullName
- num3
- _sum
Invalid identifiers example
● Using number at the beginning
○ 1num
● Using special chars
○ myVar$
○ total-sale
● Using only nums
○ 3
● Using space
○ full name
● Using reserved/keywords
○ main
○ int
○ Return
48
49. C++ Data types
Datatypes determine the type and size of data associated with variables. The
following are the basic data types in C++
49
50. C++ Data types : Examples
Note: a char variable value should be surrounded by single quotes and a string
variable value should be surrounded by double quotes. This are called character
literals and string literals respectively
50
51. C++ Data types: Type casting
Converting one data type into another is known as type casting or,
type-conversion. There are two types of casting:
Impliciting casting
It is automatically done by the compiler by converting smaller data
type into a larger data type
cout<<5/6; // prints 0
cout<<5/6.0; // prints 0.833333
Explicit casting
Explicit type conversion is done by the user by using (type) operator.
cout<< (double) 5/6; //prints 0.833333
char x = (int)65; 51
52. C++ Variables: Exercise
1. Create an integer variable and put an initial value of 16
2. Create 2 integer variables
3. Create a character variable and put an initial value of your choice
4. Create a variable that can hold real numbers
5. Create a variable that holds your name
52
54. C++ Output: print text
The cout object, together with the <<
operator, is used to output values/print
text on the console
In order to use the cout object, you have
to include the iostream library and also
import the std namespace
Values you want to be printed has to be
put inside double quotes
54
55. C++ Output: escape characters
Escape sequences are used to represent
certain special characters within string
literals (double quotes)
Some of the escape characters include:
n - new line
t - tab space
” - double quotes
Another way to insert a new line, is
with the endl manipulator 55
58. C++ Inputs: reading from keyboard
The cin object, together with the >> stream extraction operator, is used to
accept input from the input device, which is usually a keyboard
Like the cout object, in order to use the cin object, you have to include the
iostream library and also import the std namespace
Syntax
cin >> variable; // the variable is used to hold users input
Note: expected input type and the type of variable should match
58
60. 1. A program that accepts a character and echos back the character on
screen
2. A program that accepts two numbers and display back them on screen
as shown here
C++ Input/output: exercises
60
61. 1. A program that accepts users name and display it back on the screen
as follows
C++ Input/output: exercises
61
63. C++ Operators
Operators are used to perform operations on variables and values
C++ divides the operators into the following groups
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Bitwise operators
63
66. C++ Operators: Comparison operators
Comparison
operators are used
to compare two
values
The return value of
a comparison is
either true (1) or
false (0)
66
67. C++ Operators: Logical operators
Logical operators are used to determine the logic between variables or values
67
68. C++ Operators: Precedence rules
int x = 2 + 3 * 4;
What is the value of x after the
execution of the above
statement?
To be safe, use ( ) to expressions
that need to be evaluated first
68
69. C++ Operators: Implicit result casting
cout<< 5/9;
int x;
float y= 49.723;
x=y;
cout<< x;
What is the output of the
cout statements?
When constant values and
variables of different types
are mixed in an expression,
they are converted into the
same type.
The compiler will convert all
operands of lower order data
type into higher order data
type.
69
70. C++ Operators: Exercise
int x = 10;
int y = 3;
cout<<x/y;
cout<<(float)x/y;
cout<<x%y;
cout<<++x;
cout<<x++;
cout<<x++ + y;
int z = x++ + y;
cout<<z;
70
cout<<x == y;
cout<<x <= ++y;
cout<<!y;
cout<<y < 10 && y > 0;
char ch = ‘A’;
cout<<++ch;
cout<<ch;
Determine the
output of the
following cout
statements
71. C++ Operators: Exercise
71
Write C++ programs for the following problems
1. Calculate the sum of two input numbers and display the result
2. Accept two input numbers and display their sum, difference, product
and quotient
3. Calculate the area of a rectangle, given length and width from the user
and display the result
4. Compute the average of three input numbers, and then display the
result
5. Convert an input Fahrenheit degree into its Celsius degree equivalent.
Use the formula: C= (5/9)*F-32.
73. C++ conditional statements
Conditional statements, also known as
branch statements, are used to make
decisions based on a given condition. If the
condition evaluates to True, a set of
statements is executed, otherwise another
set of statements is executed
C++ offers if, else, else-if and switch
conditional statements
73
74. C++ conditional statements: if statement
Use the if statement to specify a block of code to be executed if a condition is true
74
75. C++ conditional statements: else statement
Use the else statement to specify a block of code to be executed if the condition is
false
75
76. C++ conditional statements: else if statement
Use the else if statement to specify a new condition if the first condition is false
76
78. C++ conditional statements: switch statements
Use the switch statement to select one of many code
blocks to be executed.
● The switch expression is evaluated once
● The value of the expression is compared with the
values of each case
● If there is a match, the associated block of code is
executed
● When C++ reaches a break keyword, it breaks out
of the switch block
● The default keyword specifies some code to run if
there is no case match 78
80. C++ conditional statements: Exercise
Write C++ programs for the following problems
1. A program that prints the largest of two given numbers on the screen
2. A program that prints the largest of three given numbers on the screen
3. A program that accepts a mark value from user and displays associated grade
‘A’, if mark is above 80,’B’ if mark is above 60, ‘C’ if mark is 50 else prints ‘F’
80
81. C++ conditional statements: Exercise
1. A program that accepts a grade and displays the following
Excellent, if grade is A,
V. good if grade is B,
Good if grade is C
else prints Failed
2. A program that checks if a user given number is even or odd and displays so on the
screen
81
83. C++ Loops
A loop statement allows us to
execute a statement or group of
statements repeatedly as long as a
certain condition is met.
C++ provides 3 types of loop
statements: while, do-while and for
loop
83
84. C++ Loops: while loop
The while loop loops through a block of code as long as a specified condition is
true:
84
85. C++ Loops: do/while loop
The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop as
long as the condition is true.
85
86. C++ Loops: for loop
When you know exactly
how many times you want
to loop through a block of
code, use the for loop
instead of a while loop:
Statement 1 is executed (one time) before
the execution of the code block.
Statement 2 defines the condition for
executing the code block.
Statement 3 is executed (every time) after
the code block has been executed.
86
87. C++ loop control statements: break and continue
The break statement can also be used
to jump out of a loop.
The continue statement breaks one
iteration (in the loop), if a specified
condition occurs, and continues
with the next iteration in the loop.
87
89. C++ Loops: Exercise
Write a program for the following problems
1. A program that displays the numbers from 1 - 100
2. A program that displays the even numbers between 1 - 100
3. A program that displays multiples of 5 upto 100
4. A program that displays
89
90. C++ Loops: Exercise
Write a program to print
multiplication table of a number
entered by a user upto a given
range
90
93. C++ Arrays
Arrays are used to store multiple
values in a single variable,
instead of declaring separate
variables for each value.
A specific element in an array is
accessed by an index. In C++
index starts from 0.
93
94. C++ Arrays : Array declaration
Like any other variable we have to declare an array before using them
Syntax for single-dimension array
type arrayName [ arraySize ];
where,
arrayName is a name given to the array. Just like a variable names
arraySize must be an integer constant greater than zero
type can be any valid C++ data type
94
95. C++ Arrays : Initializing arrays
You can initialize C++ array elements either one by one or using a single statement as follows
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than size of the array
If you omit the size of the array, an array just big enough to hold the initialization is created
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You can also initialize array elements after declaration by accessing each index
double balance[5];
balance[0] = 1000.0;
Balance[1] = 2.0;
95
96. C++ Arrays : 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
double salary = balance[3]; //copies 4th element, 7.0, to salary variable
cout<<balance[1]; // displays 2.0 on the screen
cout<<balance[2] + balance[4]; //displays 53.4 on the screen
double b = balance[5]; // throws an error, since we are accessing the size of the array
96
98. C++ Arrays: Exercise
1. Create an array variable that can hold 10 integers
2. Create an array variable that can hold 5 characters
3. Create an integer array and store 5 integers in it
a. Write a program that displays the array elements on the screen
b. write a program that displays the sum of numbers in the array
c. Write a program that displays the max element in the array
d. Write a program that displays the min element in the array
e. Write a program that accepts an input number from the user searches if the input exists in the
array and displays ‘Found’ if found else ‘Not found’
4. Write a program that accepts 5 integers from user and store them in an array
98
100. C++ Functions
● A function is a block of code which only runs when it is called.
● They are used to perform certain actions, and are important for reusing code: Define the
code once, and use it many times.
● Every C++ program has at least one function, which is main()
● A function is known with various names like a method or a sub-routine or a procedure etc.
● There are two types of functions
○ Built in functions
○ User defined functions
100
101. C++ Functions : Built in functions
● Built in functions are functions that are already part of the C++ library that you
can call in your programs
● Example:
○ The math.h library offers a lot of mathematical functions
○ The string.h library offers a lot of functions that allow you to operate on
strings
101
104. Built in
functions
example
cin can’t accept input strings that
include space in them since, cin
considers the space character as
a terminator. So to accept such
strings we can call the getline
function from string library
104
105. C++ Functions : User defined functions
● User defined functions are functions programmers define in their programs
besides the main() function
● Defining such functions includes the following steps
○ Declaring a function
○ Defining body of a function
○ Calling a function
105
106. C++ Functions : Function Declarations
A function declaration aka function signature, tells the compiler about a function to be defined
later in our program.
A function declaration has the following parts −
return_type function_name( parameter list );
where,
return_type: a function may return a value. The return_type is the data type of the value
the function returns. Some functions perform the desired operations without returning a
value. In this case, the return_type is the keyword void.
parameters list: a parameter is like a placeholder. When a function is invoked, you pass
a value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
106
107. C++ Functions : Function Declarations
Examples:
int getMax(int num1, int num2);
double area(double width, double height);
void displayText(string txt);
int[] acceptNumbers(int count);
Parameter names are not important in function declaration only their type is required, so
following is also valid declaration
int getMax(int, int);
Function declarations should be put before the definition of the main function
107
108. C++ Functions : Defining functions
The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) {
body of the function
}
, which is function signature + function body
Function signature: return_type function_name( parameter list )
Function body: contains a collection of statements that define what the
function does. 108
110. C++ Functions : Calling functions
To use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called
function. A called function performs defined task and when it’s return
statement is executed or when its function-ending closing brace is reached, it
returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with
function name, and if function returns a value, then you can store returned
value.
110
113. C++ Functions: Exercise
1. Write a function that accepts two numbers and return the sum
2. Write a function that accepts two numbers and returns the average of the
numbers
3. Write a function that calculates area of a rectangle given length and width
4. Write a function that accepts an array and returns the sum of the
elements
5. Write a function that finds the minimum element of an array
113