SlideShare uma empresa Scribd logo
1 de 113
Baixar para ler offline
Fundamentals of Programming
with C++
By: Seble Nigussie
Introduction
to
Programming
Program vs software
Programming
Software development life cycle
Algorithm
Pseudocode & flowcharts
2
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Flowchart symbols
19
Finding area of a square
20
Greatest
of
two
numbers
21
Finding
the sum
of the
first five
natural
numbers
22
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
Introduction to C++
Programming languages
Background of C++
Why learn C++?
C++ facts
24
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
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
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
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
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
Getting started
Environment setup
The “Hello World!” program
Compiling and executing programs
30
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
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
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
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
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
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
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
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
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
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
Compiling and executing programs with CLI
41
Compiling
in IDE
If any errors are
encountered it
will be shown on
the bottom
console
42
Executing
in IDE
If anytime runtime
errors are not
occurred, the
output of the
program will be
shown on the
console
43
Variables
&
Data types
Data types
Declaring variables
Initializing variables
Naming variables (Identifiers)
Keywords
44
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
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
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
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
C++ Data types
Datatypes determine the type and size of data associated with variables. The
following are the basic data types in C++
49
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
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
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
C++ Input/Output
statements
cout statements
printing texts
escape characters
printing variable values
cin statements
53
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
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
C++ Output: exercise
Write C++ programs that
display each of the
outputs shown using
cout only
56
C++
Output:
Display
from
variables
57
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
C++ Inputs:
cin examples
59
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
1. A program that accepts users name and display it back on the screen
as follows
C++ Input/output: exercises
61
Operators
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Precedence rule
Implicit casting of results
62
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
C++ Operators: Arithmetic operators
64
C++ Operators: Assignment operators
Assignment
operators are
used to assign
values to
variables
65
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
C++ Operators: Logical operators
Logical operators are used to determine the logic between variables or values
67
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
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
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
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.
Conditional
Statements
Introduction
if statements
else statements
else-if statements
switch statements
72
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
C++ conditional statements: if statement
Use the if statement to specify a block of code to be executed if a condition is true
74
C++ conditional statements: else statement
Use the else statement to specify a block of code to be executed if the condition is
false
75
C++ conditional statements: else if statement
Use the else if statement to specify a new condition if the first condition is false
76
C++ conditional statements: else if statement example
77
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
C++ conditional statements:
Switch statements examples
79
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
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
C++ Loops
Introduction
Types of loops
While loop
Do-while loop
For loop
Break & continue statements
82
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
C++ Loops: while loop
The while loop loops through a block of code as long as a specified condition is
true:
84
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
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
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
C++ Loops: break and continue statements
88
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
C++ Loops: Exercise
Write a program to print
multiplication table of a number
entered by a user upto a given
range
90
C++ Loops: Exercise
Write a program that prints the
following stars shape
91
C++ Arrays
Introduction
Declaring an array
Initializing an array
Accessing array elements
Arrays with loops
92
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
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
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
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
C++ Arrays : Arrays with loops
97
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
C++ Functions
Introduction
Built in functions
Declaring a function
Defining a function
Calling a function
99
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
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
Built in
functions
example
cmath and math
libraries offer a
lot of built in
mathematical
functions
102
Built in
functions
example
strcmp function
from cstring
library is used to
compare strings
103
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
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
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
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
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
109
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
C++ Functions : Calling functions
111
C++
Functions
112
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

Mais conteúdo relacionado

Mais procurados

Compiler vs Interpreter-Compiler design ppt.
Compiler vs Interpreter-Compiler design ppt.Compiler vs Interpreter-Compiler design ppt.
Compiler vs Interpreter-Compiler design ppt.Md Hossen
 
The components of a computer
The components of a computerThe components of a computer
The components of a computertrisson255
 
Steps for c program execution
Steps for c program executionSteps for c program execution
Steps for c program executionRumman Ansari
 
1. over view and history of c
1. over view and history of c1. over view and history of c
1. over view and history of cHarish Kumawat
 
Language processing activity
Language processing activityLanguage processing activity
Language processing activityDhruv Sabalpara
 
Why programming is important
Why programming is importantWhy programming is important
Why programming is importantAman Kumar
 
Functioning of computer
Functioning of computerFunctioning of computer
Functioning of computerSunipa Bera
 
Introduction to Hardware and Software
Introduction to Hardware and SoftwareIntroduction to Hardware and Software
Introduction to Hardware and SoftwarePravinGhosekar
 
Application software
Application softwareApplication software
Application softwaremoazamali28
 
Introduction to Computer Softwares
Introduction to Computer SoftwaresIntroduction to Computer Softwares
Introduction to Computer SoftwaresNaresh Dubey
 
Programming Languages / Translators
Programming Languages / TranslatorsProgramming Languages / Translators
Programming Languages / TranslatorsProject Student
 
Network software n othr types of software
Network software n othr types of software Network software n othr types of software
Network software n othr types of software Dhani Ahmad
 
Software de aplicacion
Software de aplicacionSoftware de aplicacion
Software de aplicacionpudin108
 

Mais procurados (20)

Compiler vs Interpreter-Compiler design ppt.
Compiler vs Interpreter-Compiler design ppt.Compiler vs Interpreter-Compiler design ppt.
Compiler vs Interpreter-Compiler design ppt.
 
Computer software
Computer softwareComputer software
Computer software
 
The components of a computer
The components of a computerThe components of a computer
The components of a computer
 
System software vs application software
System software vs application softwareSystem software vs application software
System software vs application software
 
Steps for c program execution
Steps for c program executionSteps for c program execution
Steps for c program execution
 
Introduction to Computer Software
Introduction to Computer SoftwareIntroduction to Computer Software
Introduction to Computer Software
 
1. over view and history of c
1. over view and history of c1. over view and history of c
1. over view and history of c
 
Language processing activity
Language processing activityLanguage processing activity
Language processing activity
 
Why programming is important
Why programming is importantWhy programming is important
Why programming is important
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Functioning of computer
Functioning of computerFunctioning of computer
Functioning of computer
 
Introduction to Hardware and Software
Introduction to Hardware and SoftwareIntroduction to Hardware and Software
Introduction to Hardware and Software
 
Application software
Application softwareApplication software
Application software
 
Introduction to Computer Softwares
Introduction to Computer SoftwaresIntroduction to Computer Softwares
Introduction to Computer Softwares
 
Programming Languages / Translators
Programming Languages / TranslatorsProgramming Languages / Translators
Programming Languages / Translators
 
Network software n othr types of software
Network software n othr types of software Network software n othr types of software
Network software n othr types of software
 
Computer software
Computer softwareComputer software
Computer software
 
Software de aplicacion
Software de aplicacionSoftware de aplicacion
Software de aplicacion
 
Presentation 1
Presentation 1Presentation 1
Presentation 1
 
Translators(Compiler, Assembler) and interpreter
Translators(Compiler, Assembler) and interpreterTranslators(Compiler, Assembler) and interpreter
Translators(Compiler, Assembler) and interpreter
 

Semelhante a Fundamentals of programming with C++

Software programming and development
Software programming and developmentSoftware programming and development
Software programming and developmentAli Raza
 
Introduction to programming language (basic)
Introduction to programming language (basic)Introduction to programming language (basic)
Introduction to programming language (basic)nharsh2308
 
L1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfL1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfMMRF2
 
Introduction to Computer
Introduction to ComputerIntroduction to Computer
Introduction to Computerzaheeriqbal41
 
PCCF UNIT 1.pptx
PCCF UNIT 1.pptxPCCF UNIT 1.pptx
PCCF UNIT 1.pptxDivyaKS12
 
Stnotes doc 5
Stnotes doc 5Stnotes doc 5
Stnotes doc 5Alok Jain
 
structured programming Introduction to c fundamentals
structured programming Introduction to c fundamentalsstructured programming Introduction to c fundamentals
structured programming Introduction to c fundamentalsOMWOMA JACKSON
 
Introduction_to_Programming.pptx
Introduction_to_Programming.pptxIntroduction_to_Programming.pptx
Introduction_to_Programming.pptxPmarkNorcio
 
Programming_Fundamentals_Chapter_1_INTRO.pdf
Programming_Fundamentals_Chapter_1_INTRO.pdfProgramming_Fundamentals_Chapter_1_INTRO.pdf
Programming_Fundamentals_Chapter_1_INTRO.pdfBernardVelasco1
 
Computer and programing basics.pptx
Computer and programing basics.pptxComputer and programing basics.pptx
Computer and programing basics.pptxgaafergoda
 
Diploma ii cfpc u-1 introduction to c language
Diploma ii  cfpc u-1 introduction to c languageDiploma ii  cfpc u-1 introduction to c language
Diploma ii cfpc u-1 introduction to c languageRai University
 

Semelhante a Fundamentals of programming with C++ (20)

Software programming and development
Software programming and developmentSoftware programming and development
Software programming and development
 
Introduction to programming language (basic)
Introduction to programming language (basic)Introduction to programming language (basic)
Introduction to programming language (basic)
 
L1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfL1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdf
 
Week10 final
Week10 finalWeek10 final
Week10 final
 
Introduction to Computer
Introduction to ComputerIntroduction to Computer
Introduction to Computer
 
Introduction to c language
Introduction to c language Introduction to c language
Introduction to c language
 
PCCF UNIT 1.pptx
PCCF UNIT 1.pptxPCCF UNIT 1.pptx
PCCF UNIT 1.pptx
 
Stnotes doc 5
Stnotes doc 5Stnotes doc 5
Stnotes doc 5
 
Lecture 1-3.ppt
Lecture 1-3.pptLecture 1-3.ppt
Lecture 1-3.ppt
 
structured programming Introduction to c fundamentals
structured programming Introduction to c fundamentalsstructured programming Introduction to c fundamentals
structured programming Introduction to c fundamentals
 
Introduction_to_Programming.pptx
Introduction_to_Programming.pptxIntroduction_to_Programming.pptx
Introduction_to_Programming.pptx
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Programming_Fundamentals_Chapter_1_INTRO.pdf
Programming_Fundamentals_Chapter_1_INTRO.pdfProgramming_Fundamentals_Chapter_1_INTRO.pdf
Programming_Fundamentals_Chapter_1_INTRO.pdf
 
Computer and programing basics.pptx
Computer and programing basics.pptxComputer and programing basics.pptx
Computer and programing basics.pptx
 
C.pdf
C.pdfC.pdf
C.pdf
 
PROBLEM SOLVING
PROBLEM SOLVINGPROBLEM SOLVING
PROBLEM SOLVING
 
Lesson 1
Lesson 1Lesson 1
Lesson 1
 
Fundamentals of Programming Chapter 2
Fundamentals of Programming Chapter 2Fundamentals of Programming Chapter 2
Fundamentals of Programming Chapter 2
 
Diploma ii cfpc u-1 introduction to c language
Diploma ii  cfpc u-1 introduction to c languageDiploma ii  cfpc u-1 introduction to c language
Diploma ii cfpc u-1 introduction to c language
 
Introduction to programming c
Introduction to programming cIntroduction to programming c
Introduction to programming c
 

Mais de Seble Nigussie

Introduction to JSON & Ajax
Introduction to JSON & AjaxIntroduction to JSON & Ajax
Introduction to JSON & AjaxSeble Nigussie
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuerySeble Nigussie
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptSeble Nigussie
 
Introduction to Bootstrap
Introduction to BootstrapIntroduction to Bootstrap
Introduction to BootstrapSeble Nigussie
 
Flexbox, Grid and Sass
Flexbox, Grid and SassFlexbox, Grid and Sass
Flexbox, Grid and SassSeble Nigussie
 
Introduction to Microprocessors
Introduction to MicroprocessorsIntroduction to Microprocessors
Introduction to MicroprocessorsSeble Nigussie
 

Mais de Seble Nigussie (9)

Introduction to JSON & Ajax
Introduction to JSON & AjaxIntroduction to JSON & Ajax
Introduction to JSON & Ajax
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Introduction to Bootstrap
Introduction to BootstrapIntroduction to Bootstrap
Introduction to Bootstrap
 
Flexbox, Grid and Sass
Flexbox, Grid and SassFlexbox, Grid and Sass
Flexbox, Grid and Sass
 
Introduction to CSS3
Introduction to CSS3Introduction to CSS3
Introduction to CSS3
 
Introduction to HTML
Introduction to HTMLIntroduction to HTML
Introduction to HTML
 
Introduction to HTTP
Introduction to HTTPIntroduction to HTTP
Introduction to HTTP
 
Introduction to Microprocessors
Introduction to MicroprocessorsIntroduction to Microprocessors
Introduction to Microprocessors
 

Último

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 

Último (20)

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 

Fundamentals of programming with C++

  • 1. Fundamentals of Programming with C++ By: Seble Nigussie
  • 2. Introduction to Programming Program vs software Programming Software development life cycle Algorithm Pseudocode & flowcharts 2
  • 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
  • 20. Finding area of a square 20
  • 22. Finding the sum of the first five natural numbers 22
  • 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
  • 24. Introduction to C++ Programming languages Background of C++ Why learn C++? C++ facts 24
  • 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
  • 30. Getting started Environment setup The “Hello World!” program Compiling and executing programs 30
  • 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
  • 41. Compiling and executing programs with CLI 41
  • 42. Compiling in IDE If any errors are encountered it will be shown on the bottom console 42
  • 43. Executing in IDE If anytime runtime errors are not occurred, the output of the program will be shown on the console 43
  • 44. Variables & Data types Data types Declaring variables Initializing variables Naming variables (Identifiers) Keywords 44
  • 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
  • 53. C++ Input/Output statements cout statements printing texts escape characters printing variable values cin statements 53
  • 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
  • 56. C++ Output: exercise Write C++ programs that display each of the outputs shown using cout only 56
  • 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
  • 62. Operators Arithmetic operators Assignment operators Comparison operators Logical operators Precedence rule Implicit casting of results 62
  • 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
  • 65. C++ Operators: Assignment operators Assignment operators are used to assign values to variables 65
  • 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
  • 77. C++ conditional statements: else if statement example 77
  • 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
  • 79. C++ conditional statements: Switch statements examples 79
  • 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
  • 82. C++ Loops Introduction Types of loops While loop Do-while loop For loop Break & continue statements 82
  • 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
  • 88. C++ Loops: break and continue statements 88
  • 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
  • 91. C++ Loops: Exercise Write a program that prints the following stars shape 91
  • 92. C++ Arrays Introduction Declaring an array Initializing an array Accessing array elements Arrays with loops 92
  • 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
  • 97. C++ Arrays : Arrays with loops 97
  • 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
  • 99. C++ Functions Introduction Built in functions Declaring a function Defining a function Calling a function 99
  • 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
  • 102. Built in functions example cmath and math libraries offer a lot of built in mathematical functions 102
  • 103. Built in functions example strcmp function from cstring library is used to compare strings 103
  • 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
  • 109. 109
  • 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
  • 111. C++ Functions : Calling functions 111
  • 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