0% found this document useful (0 votes)
15 views132 pages

Programming Course Material

Chapter 1 introduces the fundamentals of computer programming, including definitions, programming paradigms, and the program development life cycle. It covers the distinction between low-level and high-level programming languages, as well as problem-solving techniques using algorithms, flowcharts, and pseudocode. The chapter also outlines the basic elements of programming, including variable declarations, data types, and control statements.

Uploaded by

Gedef Yirgalem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views132 pages

Programming Course Material

Chapter 1 introduces the fundamentals of computer programming, including definitions, programming paradigms, and the program development life cycle. It covers the distinction between low-level and high-level programming languages, as well as problem-solving techniques using algorithms, flowcharts, and pseudocode. The chapter also outlines the basic elements of programming, including variable declarations, data types, and control statements.

Uploaded by

Gedef Yirgalem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 1

Introduction and Basic Concepts

1
Outline

•Basics of Program Development


• What is computer programming?
• Reasons to study programming
• Programming paradigms
• Flow Chart, Pseudocode, Algorithm
• Program Development Life Cycle 2
What is computer programming

• A Computer is an electronic device that accepts data and makes logical


decisions according to instructions that have been given to it
• Based on the instruction it produces meaningful information in a form that is
useful to the user.
• They have been deployed to solve different real life problems such as
Engineering problems, Accountings, education, government operations ,
3
banking.
Cont. …

• In order to solve a given problem,


computers must be given the correct
instruction about how they can solve it,
programming comes it to picture.

4
Cont. …

• The terms computer programs,


software programs, or just
programs are the instructions that

tells the computer what to do.

5
Cont. …

• A programming language is an artificial language that can be used


to control the behavior of a machine, particularly a computer.
• Programming languages, like natural language (such as Amharic),
are defined by syntactic and semantic rules which describe their
structure and meaning respectively

6
Cont. …

• Writing computer programs means writing instructions that


will make the computer follow and run a program based on
those instructions

7
• Levels of Programming

There are two levels of programming.

Low –Level and High-level programming

8
Levels of Programming

• Low level language is a language


which operators based on 0s and 1s.
• Computers only understand one
language and that is binary language
or the language of 1s and 0s

9
Levels of Programming

• Although the computer easily understood these


programs, it proved too difficult for a normal
human being to remember all the instructions in the
form of 0s and 1s.
• Examples of low-level programming assembly
and machine code
10
High level programming

• High-level languages are more


English-like and, therefore, make
it easier for programmers to
"think" in the programming
language.

11
High level programming

• High-level languages also require


translation to machine language
before execution.
• This translation is accomplished by
either a compiler or an interpreter.
• Example, C++, Java, C#, Php

12
Programming paradigms

• Programming paradigms are a way to


classify programming languages based
on their features.
• There are two main programming
paradigms such as procedural and
Object-oriented

13
Procedural Programming Languages

• Procedural programming
specifies a list of operations that
the program must complete to
reach the desired state.

14
Procedural Programming Languages

• Procedural programming
specifies a list of operations that
the program must complete to
reach the desired state.

15
Procedural Programming Languages

Procedures, also known as functions,


subroutines, or methods, are small
sections of code that perform a
particular function.

16
Object-oriented Programming Languages

• Object-oriented programming
is one the newest and most
powerful paradigms.
• Every thing represents in the
form of class and object.

17
Object-oriented Programming Languages

• A program thus becomes a collection


of cooperating objects, rather than a
list of instructions.
• Objects can store state information
and interact with other objects

18
Object-oriented Programming Languages

OOP principles/concepts

19
Problem Solving

• Computer solves varieties of problems • A program is not needed only to


solve a problem but also it should
that can be expressed in a finite
be reliable, (maintainable)
number of steps leading to a precisely portable and efficient.
defined goal by writing different
programs.

20
Problem Solving

• The programmer uses programming • Before a program is written, the


language to communicate the logic programmer must clearly understand
of the solution to the computer. what data are to be used, the desired
result, and the procedure to be used to
produce the result

21
Problem Solving

• The programmer uses programming • Before a program is written, the


language to communicate the logic programmer must clearly understand
of the solution to the computer. what data are to be used, the desired
result, and the procedure to be used to
produce the result
• The procedure, or solution, selected is
referred to as an algorithm
22
Problem Solving

• An algorithm is defined as a step-by step sequence of instructions that


must terminate and describe how the data is to be processed to produce
the desired outputs.
• There are three commonly used tools to help to document program logic
such as flowcharts, structured chart, and Pseudocode.

23
Flowchart Cont. ….

• Flowchart is a schematic representation of an


algorithm or a process
• Flowchart doesn’t depend on any particular
programming language so that it can used, to
translate an algorithm to more than one
programming language.

24
Flowchart Cont. ….

• Flowchart uses different


symbols (geometrical
shapes) to represent
different processes

25
Flowchart Cont. ….

Algorithm description
Example 1: - Draw flow ▪ Read the rules of the two numbers (A and
chart of an algorithm to add B)
two numbers and display ▪ Add A and B
their result. ▪ Assign the sum of A and B to C
▪ Display the result ( c)

26
Flowchart Cont. ….

• The flow chart becomes

27
Example 2: Write an algorithm description and draw a flow chart to check a number is negative
or not.
Algorithm description.
1/ Read a number x
2/ If x is less than zero write a message negative
else write a message not negative

28
Write the algorithmic description and draw a flow chart to find the following sum.
Sum = 1+2+3+…. + 50
Algorithmic description
1. Initialize sum too and counter to 1
1.1. If the counter is less than or equal to 50

• Add counter to sum


• Increase counter by 1
• Repeat step 1.1
1.2. Else
• Exit

29
30
Flowchart Exercise
Home Work for next class
1. What is an algorithm?
2. Explain need of an algorithm?
3. Explain steps involve in drawing of a flowchart.
Draw a flowchart for the following
1. Write an algorithm to find average age of a group of 10 players?
2. Receive 3 numbers and display them in ascending order from smallest to largest
3. Add the numbers from 1 to 100 and display the sum
4. Add the even numbers between 0 and any positive integer number given by the user.
5. Find the average of two numbers given by the user. 31
1. Find the average, maximum, minimum, and sum of three numbers given by the user.
2. Find the area of a circle where the radius is provided by the user.
3. Swap the contents of two variables using a third variable.
4. Swap the content of two variables without using a third variable.
5. Read an integer value from the keyboard and display a message indicating if this number is odd or even.

6. determining prime number?


7. generates first 50 items of the Fibonacci series:
1, 1, 2, 3, 5, 8…?
8. Convert a decimal number, n, to binary format? 32
Pseudocode

• Pseudocode is a compact and informal • The purpose of using pseudocode is


high-level description of a computer that it may be easier for humans to
read than conventional programming
algorithm that uses the structural languages
conventions of programming languages.

• A program in pseudocode is not an executable program

33
Pseudocode Example

• For example: Write a program that obtains two integer numbers from the user. It will
print out the sum of those numbers.

Pseudocodes
• Prompt the user to enter the first integer
• Prompt the user to enter a second integer
• Compute the sum of the two user inputs
• Display an output prompt that explains the
answer as the sum
• Display the result
34
Program Development Life Cycle

• PDLC: is a serious of steps that we follow to develop a quality software


• It has five life cycles

1. Requirement Analysis
2. Design/Planning
3. Implementation or testing
4. Testing and debugging
5. Deploying and Maintaining the Program
35
36
Next Class

• Compilation Process and running


• Structure of C++ program
• Basic Elements
▪ Identifiers/ variable names
▪ Keywords (reserved words)
▪ Comments
• Data Types, Variables, and Constants
▪ Variables
37
▪ Basic Data Types
Cont..

• Character and Number


Operators

▪ Assignment Operators
▪ Arithmetic Operators
▪ Relational Operators
▪ Logical Operators
▪ Increment/decrement Operators

38
Structure of C++ Program

▪ [Comments]
▪ [Preprocessor directives]
▪ [Global variable declarations]
▪ [Prototypes of functions]
▪ [Definitions of functions]

39
Showing Sample program

• Any program written in //This my first cpp program (C++ Comment )


C++ has to contain a 1: #include <iostream.h> (C++ preprocess directive)
3: int main() (function definition)
number of components
4: {
such as: the main 5: cout << "Hello World!\n";
Function body
function; some variable 6: return 0;
7: }
declarations; and some
executable statements. 40
Structure of C++ Program

• If you want a string of characters written, be sure to enclose them in double


quotes (“”), as shown on line 5.
• The final two characters, \n, tell cout to put a new line after the words Hello
World
• C++ program file saved as .cpp
• Every C++ statement should ends with “;”
41
Basic Elements and Identifiers

• An identifier is name associated with a function or data object


and used to refer to that function or data object
• An identifier must be:
• Start with a letter or underscore
• Consist only of letters, the digits 0-9, or the underscore
symbol _
• Not be a reserved word
42
Basic Elements and Identifiers

• Examples of valid identifier, day_in_month, myAge, num1, Int


• Examples of invalid identifier, day-in_month, 1num, int,
myAGe; my age
• C++ identifier is case sensitive

43
Keywords (reserved words)

• Reserved/Key words have a unique meaning within a C++ program


• These symbols, the reserved words, must not be used for any other purposes.
• All reserved words are in lower-case letters
• The following are some of the reserved words of C++.
Auto, bool, int, if , break, case, do, delete, else, return, static, void, using

44
Comments

• A comment is a piece of descriptive text which explains some aspect of a program.


• Program comments are totally ignored by the compiler and are only intended for human
readers.
• C++ provides two types of comment delimiters:
• Anything after // (until the end of the line on which it appears) is considered a
comment.
• Anything enclosed by the pair /* and */ is considered a comment.

45
Data Types, Variables, and Constants

• A variable is a symbolic name for a memory location in which data can be stored and
subsequently recalled.

• All variables have two important attributes.


• A type, which is, established when the variable is defined (e.g., integer, float,
character).
• A value, which can be changed by assigning a new value to the variable. The kind of
values a variable can assume depends on its type.

46
Variable Declaration

• Declaring a variable means defining (creating) a variable.


• create or define a variable by stating its type, followed by one or more
spaces, followed by the variable name and a semicolon.
• Good variable names tell you what the variables are for; using good names
makes it easier to understand the flow of your program.

47
Variable Declaration

• Variables must be declared before used!


• C++ variable name is case sensitive
• We can create more than one variable of the same type in one statement by
writing the type and then the variable names, separated by commas.
• For example: int myAge, myWeight; // two int variables

48
Basic Data Types

• When you define a variable in C++, you must tell the compiler what kind of
variable it is.
• Basic C++ data types, int, float, double, short, long, char

49
Operators

• C++ provides operators for composing arithmetic, relational,


logical, and
conditional expressions.
• It also provides operators which produce useful side-effects,
such as assignment, increment, and decrement.
• C++ has different types of operator
50
Assignment Operators

• The assignment operator is used for storing a


value at some memory location (typically
denoted by a variable)
• Examples of assignment operators: =,+=,-=, *=,
%=

51
Arithmetic Operators

• C++ provides five basic arithmetic operators.


• Such as +,-,*,/,%
• Integer division always results in an integer
outcome (i.e., the result is always rounded down).

52
Relational Operators

• C++ provides six relational operators for


comparing numeric quantities.
• such as, ==, !=, <,>,<=,>=

53
Logical Operators

• C++ provides three logical operators for


combining logical expression.
• Like the relational operators, logical operators
evaluate to 1 or 0.
• Such as &&, ||

54
Increment/decrement Operators

❑ The auto increment (++) and auto decrement (-


-) operators provide a convenient way of,
respectively, adding and subtracting 1 from a
numeric variable.
❑ Both operators can be used in prefix and
postfix form.
55
Exercise Question

• Accept one number and find the square of that number


• Accept three number and find the average of those number
• Write a program that can accept your name and display as out put
• Accept characters from keyboard and display to the screen
• Accept two number and find the reminder of those number
• Accept one number from keyboard and display “this number is between
10 and 20” as a message if the number is between 10 and 20. 56
57
Chapter Two: Control Statements

• Introduction
• Conditional Statements
• If Statement
• If-else statement
• If-else-if statement
• Switch statement 58
Introduction

• The order in which statements are executed


is called flow control (or control flow).
• Flow control in a program is typically
sequential, from one statement
to the next, but may be diverted to other
paths by branch statements

59
Cont.… ..

• There are different types of C++ statements


• Declaration statements are used for defining There are four types
variables. of conditional
• Branching statements are used for specifying statement
alternate paths of execution, depending on the
outcome of a logical condition

60
If Statement

• Syntax

• if (expression)
statement;
• First expression is evaluated. If the outcome is nonzero (true) then
statement is executed. Otherwise, nothing happens.
• Example: Display the number if it is greater than 10

61
If-else statement

• This statement has two


Syntax
alternative statements: one which
if (expression)
is executed if a condition is statement1;
satisfied and one which is else
executed if the condition is not statement 2;

satisfied
62
If-else statement

• First expression is evaluated. If the outcome • For example: Write a C++

is nonzero (true) then statement1 is executed. program to check whether a given

Otherwise, statement2 is executed. number is positive or negative

• For example: check the number is odd or not


• If statements may be nested by having an if
statement appear inside another if statement.
63
If-else-if statement

• This is called multiple conditional statement


Syntax
if (expression 1)
statement1; • Example, Accept student total mark and
else if (expression 2) calculate the letter grade
statement 2;
.
Else
Statement n. 64
Switch Statement

• The switch statement Syntax

provides a way of choosing switch (expression) {


case constant 1:
between a set of
statements;
alternatives, based on the Case constant n:

value of an expression. The statements;


default:
general form of the switch
statement; }
statement is 65
Switch Statement

• The switch statement provides a way of choosing between a set of


alternatives, based on the value of an expression. The general form of
the switch statement is:
• First expression (called the switch tag) is evaluated, and the outcome
is compared to each of the numeric constants (called case labels), in
the order they appear, until a match is found
66
Switch Statement

• The statements following the matching case are then


• Write a
executed.
program in C++
• Execution continues until either a break statement is
to read any
encountered or all intervening statements until the end
digit, display in
of the switch statement are executed.
the word

67
Switch Statement

• The statements following the matching case are then


• Display the name
executed.
of digits
• Execution continues until either a break statement is
• Check the letter is
encountered or all intervening statements until the end
either Vowels or
of the switch statement are executed.
consonant

68
Questions

• Write a C++ program to check whether a given number is even or odd


• Write a C++ program to read the value of an integer m and display the value
of m is 1 when m is larger than 0, 0 when m is 0 and -1 when m is less than 0
• Write a C++ program to find the largest of two numbers
• Write a C program to check whether an alphabet is a vowel or consonant
• Write a C++ program to find the largest of three numbers
• Write a C++ program to calculate the root of a Quadratic Equation.
• Write a C++ program to read temperature in centigrade and display in
Fahrenheit
• Write a program in C++ to read any day number in integer and display day
name in the word 69
70
Chapter Three: Looping Statements

Content Outline
• For Loop
• While Loop
• Do-while Loop
• Jumping Statement

71
• For Loop

• The for statement (also called for loop)


is similar to the while statement, but Syntax

has two additional components. for (expression1; expression2;

• An expression which is evaluated only expression3)

once before everything else, and an {

expression which is evaluated once at statement;

the end of each iteration. }


72
• For Loop

• The most common use Example 1, print a number from 0 up to 100;


Example 2, print even number starting from 2 up to 100;
of for loops is for
Example 3, print the sum of numbers starting from 1 up to 10.
situations where a
Example 4, print the sum of odd number starting from 1 up to 15
variable is incremented
or decremented with
every iteration of the
loop.
73
While Loop

• While statement (also called while


loop) provides a way of repeating a Syntax
statement while a condition is meet. while(expression){
statement; }

74
While Loop

• If the expression outcome is nonzero


then statement (called the loop body)
is executed and the whole process is
repeated. Otherwise, the loop is
terminated.

75
Do…while Statement

• The do statement (also called do loop)


Syntax
is similar to the while statement, except
do
that its body is executed first and then
{
the loop condition is examined
statement;
}
while(expression);
76
Do…while Statement

• It is useful for situations


• First statement is executed and then
where we need the loop
expression is evaluated. If the outcome
body to be executed at least
of the latter is nonzero then the whole
once, regardless of the loop
process is repeated. Otherwise, the
condition
loop is terminated.

77
Continue Statement

• For example, a loop which


• The continue statement terminates the
repeatedly reads in a
current iteration of a loop and instead
number, processes it but
jumps to the next iteration.
ignores negative numbers,
• It applies to the loop immediately
and terminates when the
enclosing the continue statement. It is an
number is zero
error to use the continue statement outside
a loop. 78
Break Statement

• A break statement may appear inside a loop (while, do, or for) or a switch
statement. It causes a jump out of these constructs, and hence terminates them
• Like the continue statement, a break statement only applies to the loop or
switch immediately enclosing it. It is an error to use the break statement
outside a loop or a switch

79
Exercise Question (do it three types of loop)

• Write a program in C++ to find the first 10 natural numbers


• Write a program in C++ to display n terms of natural number and their sum
• Write a program in C++ to check whether a number is prime or not.
• Write a program in C++ to find prime number within a range between two number
• Write a program in C++ to find the factorial of a number
• Write a program in C++ to find the last prime number occur before the entered number.
• Write a program in C++ to find the Greatest Common Divisor (GCD) of two numbers
• Write a program in C++ to display the pattern like right angle triangle with number
• Write a program in C++ to make such a pattern like a pyramid with an asterisk
• Write a program in C++ to display the pattern using digits with right justified and the highest
columns appears in first row
• You can get more question here

80
81
Chapter Four: Array and String

▪ Introduction • Multidimensional arrays


▪ What is an arrays • Initializing Multidimensional

▪ One Dimensional Array Arrays

▪ Declaration of Arrays
▪ Accessing Array Elements
▪ Initialization of arrays 82
Cont. …

▪ C++ String
▪ String object and C-String
▪ String input and output

83
Introduction

• Variables in a program have values


associated with them.
• During program execution these values
are accessed by using the identifier
associated with the variable in
expressions
84
Introduction

• In none of the programs written so far have


very many variables been used to represent
the values that were required
• To get round this difficulty all high-level
programming languages use the concept of a
data structure called an Array.
85
What is an arrays

• An array is a data structure which • An individual element of an


allows a collective name to be array is identified by its own
given to a group of elements unique index (or subscript)
which all have the same type. • An array can be thought of as a
collection of numbered boxes
each containing one data item.

86
What is array

• To access a particular item the index of the


box associated with the item is used to access
the appropriate box. The index must be an
integer and indicates the position of the
element in the array.

87
Declaration of Arrays

• An array declaration is very similar to a


variable declaration Syntax

• First a type is given for the elements of the Data_type arrayName[Size]

array, then an identifier for the array and,


For example: float annualTemp[100];
within square brackets, the number of
elements in the array.
88
Declaration of Arrays

• The previous declaration will cause the compiler to


allocate space for 100 consecutive float variables in
memory.
• The number of elements in an array must be fixed at
compile time. It is best to make the array size a
constant
89
Accessing Array Elements

• The first element in an array in C++ always has


the index 0, and if the array has n elements the
last element will have the index n-1.
• For statements are the usual means of accessing
every element in an array.

90
Accessing Array Elements

• Using an index, or subscript, that is out of range is


called Subscript Overflow.
• Subscript overflow is one of the commonest
causes of erroneous results and can frequently
cause very strange and hard to spot errors in
programs.
91
Initialization of arrays

• An array can be initialized in a similar manner.


• In this case the initial values are given as a list enclosed in
curly brackets.
• For example initializing an array to hold the first few prime
numbers could be written as follows:

92
Initialization of arrays

• int primes[] = {1, 2, 3, 5, 7, 11, 13};

93
Multidimensional arrays

• An array may have more than one dimension.


• Each dimension is represented as a subscript
in the array. Therefore a two dimensional
array has two subscripts, a three dimensional
array has three subscripts, and so on
94
Multidimensional arrays

Syntax:
datatype arrayName[size][size];
For example
int num[3][2];
• Arrays can have any number of dimensions, although most of the arrays that you
create will likely be of one or two dimensions.
95
Array Exercise

• Create an array that can hold ten integers, and get input from user. Display those
values on the screen and count the result.
• Write a C++ program to find the next greater element of every element of a given
array of integers. Ignore those elements which have no greater element.
• Write a C++ program to find the most occurring element in an array of integers.
• Write a C++ program to find the largest element of a given array of integers.
• Write a C++ program to find the largest three elements in an array.
• Write a C++ program to find the second smallest elements in a given array of
integers.
• Write a C++ program to find a number which occurs odd number of times of a
given array of positive integers.

96
C++ String

• String is a collection of characters.


• There are two types of strings commonly used in C++ programming
language
• Strings that are objects of string class (The Standard C++ Library
string class)
• C-strings (C-style Strings) 97
C++ String

• In C programming, the collection of characters is stored in the form of


arrays.
• C-strings are arrays of type char terminated with null character, that is, \0
• How to define a C-string?
char str[] = "C++";
• In the above code, str is a string and it holds 4 characters

98
C++ String to read a line of text

char str[4] = "C++";


char str[] = {'C','+','+','\0'};
char str[4] = {'C','+','+','\0'};

• C++ String to read a word


• C++ String to read a line of text

99
C++ String to read a line of text

#include <iostream>
using namespace std;
int main() {
char str[100];
cout << "Enter a string: ";
[Link](str, 100);
cout << "You entered: " << str << endl; return
0;
}
100
C++ String to read a line of text

• To read the text containing blank space, [Link] function can be used. This function
takes two arguments.
• First argument is the name of the string (address of first element of string) and
second argument is the maximum size of the array.
• In the above program, str is the name of the string and 100 is the maximum size of
the array.

101
string Object

• Unlike using char arrays, string objects has no fixed length, and can be
extended as per your requirement.
• It needs to include string library
• C++ String to read a word
• C++ String to read a line of text

102
string Object

#include <iostream>
#include <string>
using namespace std;
int main() {
// Declaring a string object
string str;
cout << "Enter a string: ";
getline(cin, str);
cout << "You entered: " << str << endl; return 0;
} 103
104
Chapter Five: Function

Content Outline
• Introduction to Function
• Types of function
• Parts of function
• User Defined Function
• Standard Function

105
Chapter Five: Function

Content Outline
• Function declaration
• Function return type
• Function parameter
• Function calling
• Function Argument

106
Introduction to Function

• A function is a block of code that • You can divide up your code into separate
performs a specific task. functions
• Every C++ program has at least • How you divide up your code among
one function, which is main(), different functions is up to you,
• The most trivial programs can • Logically the division usually is such that
define additional functions. each function performs a specific task.

107
C++ User-defined Function

• C++ allows the programmer to define their own function.


• A user-defined function groups code to perform a specific task
• That group of code is given a name (identifier).
• When the function is invoked from any part of the program, it
all executes the codes defined in the body of the function.

108
Parts of function

• 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.

109
Parts of function

• Function Name − This is the actual name of the function.


The function name and the parameter list together constitute
the function signature.

110
Parts of function

• Function Body − The function body contains a collection of


statements that define what the function does.
• Parameters − 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.

111
Function Declaration

• A function declaration tells the compiler about a function


name and how to call the function.
• Syntax to declare a function
returnType functionName (parameter1, parameter2,...)
{
// function body

} 112
//

Function Declaration

• Example
function declaration
void greet() {
cout << "Hello World";
}

113
//

Function Declaration

• From the above example,


• greet() is the name of the function
• void is the return type of the function
• The empty parentheses mean it doesn't have any parameters
• The function body is written inside {}

114
//

Function Calling

• To execute a function, you will have to call or invoke that function.


• A called function performs defined task and when it’s return statement
is executed
• When its function-ending closing brace is reached, it returns program
control back to the main program.

115
//

Function Calling

• In the above program, we have declared a function named greet(). To


use the greet() function, we need to call it.
• Here's how we can call the above greet() function.
int main()
{
// calling a function
greet();
} 116
//

Function Calling

117
//

Function Calling

• To call a function, you simply need to pass the required parameters


along with function name
• If function returns a value, then you can store returned value

118
Function Arguments

• If a function is to use arguments, it must declare variables that accept


the values of the arguments.
• These variables are called the formal parameters of the function.
• The formal parameters behave like other local variables inside the
function and are created upon entry into the function and destroyed
upon exit.

119
Function Parameters

• A function can be declared with parameters (arguments). A parameter


is a value that is passed when declaring a function.
• For example, let us consider the function below:
void printNum(int num) {
cout << num;

}
• Here, the int variable num is the function parameter 120
Function Parameters

121
Function Parameters

• In the above program, we have used a function that has


one int parameter and one double parameter.
• We then pass num1 and num2 as arguments. These values are stored
by the function parameters n1 and n2 respectively.

122
Function Parameters

123
Return Statement

• In the above programs, we have used void in the function declaration.


For example,

• This means the function is not returning any value.

124
Return Statement

• It's also possible to return a value from a function. For this, we need to
specify the returnType of the function during function declaration.
• Then, the return statement can be used to return a value from a function.

125
Benefits of Using User-Defined Functions

• Functions make the code reusable. We can declare them once and use them
multiple times.
• Functions make the program easier as each small task is divided into a function.
• Functions increase readability.

126
C++ Library Functions

• Library functions are the built-in functions in C++ programming.


• Programmers can use library functions by invoking the functions directly; they
don't need to write the functions themselves.
• Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
• In order to use library functions, we usually need to include the header file in
which these library functions are defined.
127
C++ Library Functions

• For instance, in order to use mathematical functions such as sqrt() and abs(), we
need to include the header file cmath.

128
C++ Library Functions

C++ Program to Find the Square Root of a Number

129
Question

• Write a program that ask for two numbers, compare them and show the maximum. Declare a
function called max_two that compares the numbers and returns the maximum.
• Write a program that asks the user for an integer number and find the sum of all natural numbers
upto that number (create function sum).
• Write C++ program to check even or odd using functions
• Write C++ program to find cube of a number using function
• Write C++ program to find sum of natural numbers in given range using recursion
• Write C++ program to find power of a number using recursion
130
Question

• Write C++ program to print elements of array using recursion


• Write C++ program to find maximum and minimum elements in array using recursion
• Write C++ program to find prime numbers in given range using functions

131
132

You might also like