I prepared these slides for the student of FSC BSC BS Computer science.these slides are very easily understanding the concept of programming in C++.All topics are clear with the help of examples easy in reading the topic and understanding the logic.
1. PROGRAMMING USING
C++
A U T H O R : A B D U L L A H J A N
M S C S
L E C T U R E R : G O V T P O S T G R A D U AT E C O L L E G E N O W S H E R A
2. COMPUTER PROGRAM
⢠A computer program is a set instruction written in computer language to perform a
specified task for a computer. A computer program tell the computer that what to do
and in which order to do. Different types of programming language are used to
develop programs. Some commonly used programming languages are C++ , java ,SQL,
HTMLetc.
3. STRUCTURE OF A C++ PROGRAM
⢠Each C++ program has three main components:
1)preprocessor directive
2)main function
3)body of main function
⢠General syntax of a C++ program is given below
preprocessor directives <header file>
Int main() {
body of the program
}
4. STRUCTURE OF A C++ PROGRAM
⢠Program to display âhello worldâ
#include <iostream.h>
#include <conio.h>
Int main(){
Cout<<âhello world!â;
getch();
Return 0;
}
Output:
Hello world!
5. STRUCTURE OF A C++ PROGRAM
⢠Preprocessor directives:
The instruction that are given to the compiler before the beginning of the actual
program are called preprocessor Directives.
a preprocessor is a collection of special statement which are executed before the
compilation process.
Almost ever C++ program contains a preprocessor directive. The #include preprocessor
directives is commonly used to insert header files with extension.h. these header file are
already stored in computer in include directory.
Example:
#include <iostream.h>
6. STRUCTURE OF A C++ PROGRAM
⢠Header file:
header file is a C++ source file that contain definition of library function/objects.
The preprocessor directive âincludeâ is used to add a header file into the progam.
Thename of file is written in angle brackets (<>) after â#includeâ directive.
For example the header file iostream.h has definitions of different built-in input and
output objects and function. It is include in the above program. Because its object âcout â
is used in the program.
Syntax:
#include <name of the header file>
7. STRUCTURE OF A C++ PROGRAM
⢠Main function :
the main() function indicates the beginning of a C++ program
Or
The main function is the point by where all C++ programs start their execution.
When a C++ program is executed the control goes directly to the main() function.
Syntax :
Int main(){
program statementâŚ
}
8. STRUCTURE OF A C++ PROGRAM
⢠C++ statement
The statement of the program are written under the main() function between the curly
braces {}. These statement are the body of the program . Each statement in C++ ends
with a semicolon(;).
C++ is a case sensitive language.
9. STRUCTURE OF A C++ PROGRAM
⢠Reserved words :
Reserved words or keywords are those words which have their special meaning within
the C++ language and are reserved for some specific purpose . Reserved cannot be used
as a variable and cannot be for any other purpose in a C++ program.
Reserved words table.
if goto Int Float do
double Char class New else
Short Private public protected for
switch long const catch break
namespace void throw try this
10. STRUCTURE OF A C++ PROGRAM
⢠getch():
this is a standard library function defined in the header file <conio.h> and is used to
wait for the user to input a character from the keyboard.
Return 0:
the return statement return the control to the operating system. The code 0 returned by
the return statement tells the operating system that program terminates normally
Syntax :
Return 0;
11. STRUCTURE OF A C++ PROGRAM
⢠Single line comment:
it is represented by double slash symbol // for single
Example :
// Int is used for integer
⢠Multi line comment:
for multi lines it is represented by /*âŚ.. */ compiler ignore every thing in these symbols.
Example :
/* this program is written for to add two integers and subtract two integers
and output the average of the two integer */
12. CONSTANT
⢠A quality that cannot change its value during execution of the program is called
constant
⢠There are four types of constant in C++ these are:
⢠Integer constant
⢠Floating point constant
⢠Character constant
⢠String constant
⢠Hexadecimal constant
⢠Octal constant
13. CONSTANT
⢠integer constant: A numerical value without a decimal part is called integer constant (+) and (-)
can also be used with an integer constant
⢠Example:
⢠#include <iostream>
⢠#include<conio.h>
using namespace std;
⢠Int main () {
⢠Cout<< 526;
⢠Cout<< 555;
⢠Return 0;
⢠}
14. CONSTANT
⢠Floating point constant: Numeric value thatâs have an integer as well as a decimal part are called
floating point values.
⢠Example:
⢠#include <iostream>
⢠#include<conio.h>
using namespace std;
⢠Int main () {
⢠Cout<< 52.6;
⢠Cout<< 55.5;
⢠Return 0;
⢠}
15. CONSTANT
⢠Character constant: A single character enclosed in single quotation marks is called character
constant .
⢠Example:
⢠#include <iostream>
⢠#include<conio.h>
using namespace std;
⢠Int main () {
⢠Cout<< âaâ;
⢠Cout<< âbâ;
⢠Return 0;
⢠}
16. CONSTANT
⢠string constant:
⢠A sequence of characters consisting of alphabets, digits and or special character
double quotation marks is called string constant
⢠Example:
⢠#include <iostream>
⢠#include<conio.h>
using namespace std;
⢠Int main () {
⢠Cout<< âPakistanâ;
⢠Cout<< âatifâ;
⢠Return 0;
⢠}
17. CONSTANT
⢠hexadecimal constant: The constant represented in hexadecimal number system are called
hexadecimal constants
⢠Example:
⢠#include <iostream>
⢠#include<conio.h>
using namespace std;
⢠Int main () {
⢠Cout<< 0*3fff;
⢠Cout<<0*3FFF;
⢠Return 0;
⢠}
18. CONSTANT
⢠Octal constant: The representation of constants in octal number system is called octal constant.
â˘
⢠Example:
⢠#include <iostream>
⢠#include<conio.h>
using namespace std;
⢠Int main () {
⢠Cout<< 03777;
⢠Cout<< 0397;
⢠Return 0;
⢠}
19. VARIABLE:
⢠A variable in C++ is a name for a piece of memory that can be used to store information .Variable can be
change its value
⢠Example:
⢠#include <iostream>
⢠#include<conio.h>
using namespace std;
⢠Int main () {
⢠int a;
⢠a=10;
⢠Cout<< a;
⢠Return 0;
⢠}
20. ⢠Declaration of variable: Assigning the name and data type that a variable can hold is called declaration of the
variable. All variable that are used in a program are declared using variable declaration statement.
⢠Syntax:
⢠Type list of variable;
⢠Type::specifies datatype of variable. For example it may be int , float.
⢠List variable:: specifies a list of variable separated by commas.
⢠Example:
⢠Int abc, xyz, zzz;
⢠Sample program // subtract two number
⢠#include <iostream>
⢠#include<conio.h>
using namespace std;
⢠Int main () {
⢠int a, b;
⢠int result;
⢠a=55;
⢠b=22;
⢠result = a-b;
⢠cout<< âthe result is=â<<result;
⢠Return 0;
⢠}
21. ⢠Sample program input number from keyboard:
⢠#include <iostream>
⢠#include<conio.h>
using namespace std;
⢠int main () {
⢠cout<<âEnter a numberâ;
⢠int x;
⢠cin>>x;
⢠cout<<âenter another numberâ;
⢠int y;
⢠cin>>y;
⢠cout<<âthe sum isâ<<x+y<<endl;
⢠getch ();
⢠return 0;
⢠}
22. ⢠Initialization variable: When a variable is declared a memory location is assigned to it.
Assigning a known value to a variable at the time of its declaration is called initialization
the variable.
⢠Syntax:
⢠int a = 110;
⢠int b = 60;
â˘
⢠#include <iostream>
⢠#include<conio.h>
using namespace std;
⢠int main () {
⢠int a = 55;
⢠int b = 22;
⢠int result;
⢠result = a-b;
⢠cout<< âthe result isâ<<result;
⢠getch ();
⢠return 0;
23. FUNDAMENTAL DATA TYPE IN C++
⢠While programming we store the variable in computers memory but the computers have to
know that what kind of data we want to store in them
⢠Data type tells the compiler that what type of data mean integer character or floating point
etc. the variable will store and what will be range of the values.
⢠The most commonly used data type in C++ are:
⢠Character
⢠Integer
⢠Floating point
⢠Boolean
⢠Unsigned
24.
25. FUNDAMENTAL DATA TYPE IN C++
⢠The char keyword represent the character data type in C++
⢠Example:
char x;
Or
Char gender;
Gender = âMâ;
26. FUNDAMENTAL DATA TYPE IN C++
⢠Integer data types which store only integer numbers such as 100 -200 etc are called
integer data types.
⢠Int
⢠Short int
⢠Long
27. FUNDAMENTAL DATA TYPE IN C++
1) Int data type:
the keyword int stand for the integer data type in C++ and normally has two bytes
of memory (16 bits). A
2) Short int data type:
short int is used to declare the short integer data type in C++. The maximum size of
the short int data type is 2 bytes(16 bits)
3) Long int data type:
long int stands for long integer data type and is used in C++ to store larger integer
values.
its size is 4 bytes (32 bits)
28. FLOATING POINT DATA TYPE
⢠Sometimes we need to store very large numbers, or numbers with a decimal point. The
data types which are used to store such type of data are called floating point data
types.
⢠Such as 4.0, 2.5, 3.33 or 0.1226
⢠Three different type of floating point
⢠Float
⢠Double
⢠Long double
29. FUNDAMENTAL DATA TYPE IN C++
⢠Float data type:
it needs 4 bytes (32 bits) of memory to store values.
⢠Double data type:
double data type occupies 8 bytes(64 bits) of memory.
⢠Long double data type:
it needs 10 bytes (80 bits) memory space in the RAM.
30. FUNDAMENTAL DATA TYPE IN C++
⢠Boolean data type:
it is capable of holding one of the two values true(1) or false (0). It occupies 1 byte of
memory
⢠Unsigned data type:
the unsigned numbers are whole numbers and always hold positive values starting form 0
till is maximum size. Here the sign bit also used for the value which means no bit is reserved
for holding a sign(+/-). The unsigned numbers may be classified into four types.
Unsigned char
Unsigned integer
Unsigned short integer
Unsigned long integer
31. FUNDAMENTAL DATA TYPE IN C++
⢠Constant Qualifier:
Const keyword is used to define constant identifier whose values remain constant
during the whole life of the program.
Const identifier must be assigned with a value when declared and then that value cannot
be changed.
Example:
const int DollarRate = 86;
DollarRate = 123; //compiler error
32. FUNDAMENTAL DATA TYPE IN C++
⢠Type Casting operator:
the conversion of data from one type to another is called type casting. It has two types
1) Implicit type casting
2) Explicit type casting
33. FUNDAMENTAL DATA TYPE IN C++
⢠Implicit(complete) type casting:
the compiler automatically converts data from one type to another when they are
used in expressions. When a value of one type is assigned to another type, the compiler
implicitly converts that value into the value of the new type. For example :
Double a = 3; // implicit casting to double value 3.0
Int b= 3.14156 //implicit casting to integer value 3
34. FUNDAMENTAL DATA TYPE IN C++
⢠Explicit(fully or clear or state) Casting:
explicit casting is performed by programmer. It is performed by using cast operator.
The cast operator tells the computer to convert the data type value.
Syntax:
Type(experssion);
Type: it indicate the data type to which operand is to be converted
Expression: it indicates the constant variable or expression whose data type is to be
converted
35. FUNDAMENTAL DATA TYPE IN C++
⢠Example:
#include<iostream>
#include<conio.h>
Using namespace std;
Int main(){
Float a,b;
Int c;
a = 10.3;
b = 5.2;
c = (int)a%(int)b;
Cout<<âresult isâ<<c;
Getch();
Return 0;
}
36. FUNDAMENTAL DATA TYPE IN C++
⢠Example 2:
⢠Int x;
⢠Float pi = 3.14;
⢠X = (int)pi;
37. INPUT / OUTPUT HANDLING
⢠Standard output:
the default standard output of a C++ program is the screen and cout is the C++ stream object
which defines it. cout is used in conjuction with the insertion operator . Which as <<.
Example:
Cout << âOutputâ;
⢠Standard input (cin):
the standard input device used for entering input to the computer is keyboard. In C++ the stream
extraction operator >> and object cin are used to handle the standard input.
Example:
Int marks;
Cin >> marks;
38. INPUT / OUTPUT HANDLING
#include<iostream>
#include<conioh>
Using namespace std;
Int main(){
Float age;
Cout<<âplease enter your ageâ;
Cin>>age;
Cout<<âthe age you entered is â<<age<<âyearâ;
Getch();
Return 0;
}
39. INPUT / OUTPUT HANDLING
⢠Cin and strings
cin can also be used to get string with extraction operator >> in the same way as it is used to get values for
variable.
Example:
Int main(){
Char teststr[50];
Cout<<âenter your name nâ;
Cin>>teststr;
Cout<<ân your name is â <<teststr;
Getch();
Return 0;
}
40. INPUT / OUTPUT HANDLING
⢠Gets() , puts() , getch() function:
Gets :
Is a standard library function defined in stdio.h header file which is used to get a string
from the keyboard . Its general syntax is :
Gets(string variable name);
It reads characters from stdin and store them as a string into string variable until a
newline character.
41. INPUT / OUTPUT HANDLING
⢠#include<stdio.h>
⢠#include<conio.h>
⢠#include<iostream>
⢠Using namespace std;
⢠Int main(){
⢠Char test str[150];
⢠Cout<<âinsert your full addressâ;
⢠Gets(test str);
⢠Cout<<ân your address is :â<<teststr;
⢠Getch();
⢠Return 0;
}
42. INPUT / OUTPUT HANDLING
⢠Puts() function:
puts() function writes a string to the screen and appends(added at the end of a book) a
newline character automatically at the string.
Syntax:
Puts(string variable);
44. INPUT / OUTPUT HANDLING
⢠Getch() function:
⢠Getch() function is a function that obtain the next available character from the console.
As a result of this function nothing is echoed on the screen. When no keystroke is
available the function waits until a key is pressed. The value of keystroke is returned by
the function when the key is pressed.
⢠Syntax:
⢠Getch();
46. INPUT / OUTPUT HANDLING
FUNCTION
⢠Most commonly used
⢠Getchar ():
stands for get character and is used to get a single character from standard
input device(keyboard)
Syntax:
Int getchar();
47. INPUT / OUTPUT HANDLING
FUNCTION
⢠Putchar():
is a standard output function in stdio.h header file and is used to display a single
character received as an argument on the screen
Syntax:
Putchar(ch);
49. INPUT / OUTPUT HANDLING
FUNCTION
⢠Endl and setw manipulator:
⢠Manipulators are used for formatting output.
1) Endl manipulator:
this manipulator is used for new line .
Example :
Int main(){
Cout<<âwelcomeâ<<endl;
Cout<<âto â<<endl;
Cout<<âcollegeâ;
Getch();
Return 0;
}
50. INPUT / OUTPUT HANDLING
FUNCTION
⢠Setw manipulator:
this manipulator sets minimum field width on output
Syntax:
Setw(x);
Example:
#include<iostream>
#include<conio.h>
#include<iomanip.h>
52. OPERATOR IN C++
⢠C++ is rich in operator and supports a wide range of these operators that range from
the simplest unary to the complex ternary. Operator are very important because
without their, expressions cannot be evaluated.
⢠Types of operator are :
⢠Assignment operator :
⢠The assignment operator assigns a value to a variable.
⢠Syntax:
A = 10;
53. OPERATOR IN C++
⢠Example :
⢠Int main(){
⢠Int a ,b;
⢠A=10;
⢠B=12;
⢠Cout<<a;
⢠Cout<<b;
⢠Getch();
⢠Return 0;
⢠}
54. OPERATOR IN C++
⢠Arithmetic operator:
⢠Five types of arithmetic operator:
⢠+
⢠-
⢠*
⢠/
⢠%
55. OPERATOR IN C++
⢠Example:
⢠Int main(){
⢠Int a , b,sum,sub,division,modulus;
⢠A=20;
⢠B= 10;
⢠Sum = a+b;
⢠Cout<<sum;
⢠Sub = a-b;
⢠Cout<<sub;
⢠Division = a/b;
⢠Cout<<division;
⢠Modulus = a%b;
⢠Cout<<modulus;
⢠Getch();
⢠Return 0;
⢠}
56. OPERATOR IN C++
⢠Arithmetic assignment operator:
⢠+=
⢠-=
⢠*=
⢠/=
⢠%=
57. OPERATOR IN C++
⢠Example:
⢠Int main(){
⢠Int a , b;
⢠B=20;
⢠A=b;
⢠A += 200; // equivalent to a = a+200
⢠Cout<<âvalue after addition â<<a;
⢠Getch();
⢠Return 0;
⢠}
58. OPERATOR IN C++
⢠Increment and decrement operator:
⢠These operators are also called unary arithmetic operators. These operators are used
to make expression short. The increment operator ++ and the decrement operator â
increase or decrease the value stored in a variable by 1 . For example :
⢠Int A++;
⢠Int A +=1
⢠Int A = A + 1;
59. OPERATOR IN C++
⢠Two version of these increment and decrement operators. These are prefix version and
a postfix version
⢠Prefix:
⢠In prefix form of the increment and decrement operators the operators precede(come
before ) their operands, e.g ++x, --z
60. OPERATOR IN C++
⢠Example:
⢠Int x = 5;
⢠Cout<<âincrement in prefix form = â<<++x;
⢠Cout<<âdecrement in prefix form = â<<--x;
61. OPERATOR IN C++
⢠Postfix:
⢠In postfix form of the increment and decrement operators the operands precede(come
before ) their operator e.g x++, zâ
⢠Example:
⢠The following program to demonstrate the use of increment and decrement operators
62. OPERATOR IN C++
⢠Int main(){
⢠Int x = 25 , y = 25;
⢠Cout<<x<ââ<<y<<endl;
⢠Cout<<++x<<ââ<<++y<<endl;
⢠Cout<<x<<ââ<<y<<endl;
⢠Cout<<x++<<ââ<<y--<<endl;
⢠Cout<<x<<ââ<<y<<endl;
⢠Getch();
⢠Return 0;
⢠}
63. OPERATOR IN C++
⢠Relational operator:
⢠Relational operator are used for the comparsion between two expersion.
⢠These operator are :
⢠==
⢠!=
⢠>
⢠<
⢠>=
⢠<=
65. OPERATOR IN C++
⢠Logical operator:
⢠Logical not !
⢠Logical AND &&
⢠Logical OR ||
66. OPERATOR IN C++
⢠Logical NOT:
⢠The ! Operator is the C++ unary operator that is used to perform the Boolean NOT
operation.
x !x
True False
False True
67. OPERATOR IN C++
⢠Example :
⢠!(5 == 5) //evaluates to false because the experssion (5 == 5) is true
⢠!(6<=4) //evaluates to true because (6 <= 4) would false
68. OPERATOR IN C++
⢠Logical AND
⢠Logical && operator is a binary operator that needs two operands.it is used to test
whether both conditions are true or not. If both the condition are true the logical &&
return true, otherwise it returns false.
⢠Truth table
⢠X Y X && Y
False False False
False True False
True False False
True True True
69. OPERATOR IN C++
⢠Logical OR:
⢠The logical || operator is used to test whether either of two conditions is true.
⢠Truth table:
X Y X || Y
False False False
False True True
True False True
True True True
70. OPERATOR IN C++
⢠Ternary (or conditional) operator (? :)
⢠The conditional operator takes three operands and is therefore also called ternary
operator.
⢠Syntax:
⢠Condition ? Result1:result2;
⢠Here if condition is true the expression will return result1 and if condition is false it will
return result2. consider the following lines of code to demonstrate the use of
conditional operator.
⢠7 == 5 ?4 :3 //return 3, since 7 is not equal to 5
⢠7 ==5+2 ?4 :3 //return 4 since 7 is equal to 5+2
71. OPERATOR IN C++
⢠Int main(){
⢠Int x , y , z;
⢠X=22;
⢠Y = 77;
⢠Z = (x>y)? X:y;
⢠Cout<<âthe greater value isâ<<z;
⢠Getch();
⢠Return 0;
⢠}
72. OPERATOR IN C++
⢠Expression :
⢠An expression consists of operator and operands or it may be the combination of
variable and / or constant linked with operator. For example :
⢠Arithmetic expressions :
⢠X = y+2;
⢠Sum = x+y;
⢠Relational operator:
⢠X>y;
⢠Z>=10;
75. (CONDITIONAL){DECISION}
STATEMENT
⢠The statement of a computer program are executed one after the other in the order in
which they are written . This is known as sequential execution of the program.
⢠The order of execution of the statement in a program can be changed. This is done
with the help of conditional statements. The conditional statements are used to
execute (or ignore) a set of statements after testing a condition. The conditional
statements are also called selection statements.
76. USE OF DECISION OR CONDITIONAL
STATEMENT
⢠IF STATEMENT:
the âif statementâ is used to execute (or ignore) a set of statement after
testing a condition
the âif statementâ evaluates a condition. If the given condition is true, the statement (or a
set of statement) following the âif statementâ is executed. If the given condition is false, the
statement (or a set of statement) following the âif statementâ condition is ignored and the
control transfer to the next statement.
Syntax:
If(condition)
Statement 1;
Statement 2;
77. ⢠In the above syntax only statement1 will be executed if the given condition is true therwise
the control shifts to statement 2 that comes after the statement1
⢠The curly statement in curly braces { } are known as compound statement
⢠Syntax : for execution set of statement
If(condition){
Statement 1;
Statement 2;
Statement 3;
}
Statement n;
78. if the given condition is true the compound statement given in curl braces are executed .
If the condition is false the control shift to the statement n and the set of statement that
follows the âif statementâ is ignored.
79. ⢠The flowchart for the âif statementâ
Condition
Statement ( s)
Statement after if
structure
True
False
80. ⢠Example of if:
⢠Int main(){
⢠Int x;
⢠Cout<<âenter a numberâ;
⢠Cin>>x;
⢠If(x%2==0)
⢠Cout<<x<<âis even numberâ;
⢠Getch();
⢠Return 0;
⢠}
81. ⢠Example 2:
⢠Int main(){
⢠Int a,b;
⢠A=100;
⢠B=50;
⢠If(a>b)
⢠Cout<<âislamabadâ;
⢠Cout<<âokâ<<endl;
⢠}
82. ⢠Example :
⢠Int main(){
int c;
Cin>>c;
If(c>10)
{
Cout<<âislamabadâ<<endl;
Cout<<âokâ<<endl;
}
}
83. ⢠Int main(){
⢠Int a,b;
⢠Cout<<âenter first valueâ;
⢠Cin>>a;
⢠Cout<<âenter second valueâ;
⢠Cin>>b;
⢠If(a>b)
⢠Cout<<âfirst value is greaterâ;
⢠If(b>a)
⢠Cout<<âsecond value is greaterâ;
⢠}
84. ⢠If-else statement:
the âif-elseâ statement tests the given relational conditional. If the condition
is true then the first block of statement is executed. If the condition is false block of
statement is ignored and the second block following the else is executed.
Syntax:
If(conditiona)
Statement 1;
Else
Statement 2;
85. ⢠The flowchart for the âif-else statementâ
Condition
Statement (1)
Statement after if
structure
TrueFalse
Statement ( 2)
86. ⢠Example:
⢠Int main(){
⢠Int x;
⢠Cout<<âenter a numberâ;
⢠Cin>>x;
⢠If(x%2==0)
⢠Cout<<x<<âx is even numberâ;
⢠Else
⢠cout<<x<<âx is odd numberâ;
⢠getch();
⢠Return 0;
⢠}
87. ⢠Example 2:
⢠Int main(){
⢠Int a , b;
⢠Cout<<âenter first numberâ;
⢠Cin>>a;
⢠Cout<<âenter second numberâ;
⢠Cin>>b;
⢠If(a>b)
⢠Cout<<âfirst is greatorâ;
⢠Else
⢠Cout<<âsecond is greatorâ;
⢠}
88. ⢠Example 3:{
⢠Int main(){
⢠Int a , b;
⢠Cout<<âenter first valueâ;
⢠Cin>>a;
⢠Cout<<âenter second valueâ;
⢠Cin>>b;
⢠If(a%2 == b%2)
⢠Cout<<âboth values are equalâ;
⢠Else
⢠Cout<<âvalues are differentâ;
⢠Getch();
⢠Return 0;
⢠}
89. ⢠Nested if statement:
when an âif statementâ is used within another âif statementâ it is called the
nested if statement. The ânested if statementâ is used for multi-way decision-making
Syntax:
If(condition-1){
if(condition-2){
statement-2;
}
Statement-3;
}
90. ⢠Example :
⢠Int a , b , c;
⢠Cout<<âenter first valueâ;
⢠Cin>>a;
⢠Cout<<âenter second valueâ;
⢠Cin>>b;
⢠Cout<<âenter third valueâ;
⢠Cin>>c;
⢠If(a==b)
⢠{
⢠if(a==c)
⢠Cout<<âall values are equalâ;
⢠}else
⢠Cout<<âthese values are differentâ;
91. ⢠Example 2:
⢠Int n;
⢠Cout<<âenter a numberâ;
⢠Cin>>n;
⢠If(n%2 == 0)
⢠Cout<<n<<âis multiple of 2â;
⢠Else
⢠If(n%3 == 0)
⢠Cout<<n<<âis multiple of 3â;
⢠Else
⢠Cout<<n<<âis neither multiple of 2 nor 3â;
⢠Getch();
⢠Return 0;
⢠}
93. ⢠Switch statement:
switch statement is a better alternative of the nested if-else structure. The nested if-
else structure is sometimes more difficult to understand to find that which if clause is
associated with which else clause. It is used when multiple choices are given and one choice is
to be selected.
Syntax:
Switch (expression)
{
Case const-1;
Statements;
Break;
Case const-2;
Statements;
Break;
Case const-n;
Statements;
Break;
Default;
Statements;
}
94. ⢠Switch evaluates the expression and if the value of the expression equal to constant-1 ,
it executes group of statement1 until it encounters the break statement. When it
reaches the break statement the program jumps to the end of the switch. If the value
of the expression is not equal to constant1. it is matched with constant-2 if it is equal
to this constant-2 this group of statements2 is executed until break keyword is reached
and then a jump will occur to the end of the switch. Finally if the value of expression
does not match with any of the constant then program execute the statements after
the default keyword. The default clause is optional.
95. ⢠Int main(){
⢠Int x;
⢠Cout<<âenter value of xâ;
⢠Cin>>x;
⢠Switch(x){
⢠Case 1:
⢠cout<<âx is 1â;
⢠Break;
⢠Case 2:
⢠Cout<<âx is 2â;
⢠Break;
⢠Default:
⢠Cout<<âvalue of x is neither 1 nor 2â;
⢠}
⢠Getch();
⢠Return 0;
⢠}
96. ⢠Int main(){
⢠Int a,b;
⢠Char op;
⢠Cout<<âenter ist # ,operator $2nd #â<<endl;
⢠Cout<<âpress enter keyâ<<endl;
⢠Cin>>a>>op>>b;
⢠Switch (op){
⢠Case â+â:
⢠Cout<<âaddition =â<<(a+b);
⢠Break;
⢠Case â-â:
⢠Cout<<âsubtraction = â<<(a-b);
⢠Break;
⢠Case â*â:
⢠Cout<<âmultiplication =â<<(a*b);
⢠Break;
⢠Case â/â:
⢠Cout<<âdivision = â<<(a/b);
⢠Break;
⢠Default:
⢠Cout<<âinvalid inputâ;
⢠}
⢠}
97. ⢠Break :
⢠The break statement is used to exist from the body of the switch structure .
98. LOOPS
⢠Loops are used to repeat a statement or group of statement a certain number of times
until the condition is true. These are also called repetitive or iterative statement.
⢠Types of loops:
⢠For
⢠While
⢠Do-while
99. ⢠For loop:
⢠The most commonly used looping structure in C++ is for loop. For loop is ideal in
situation when we know in advance the exact number of iteration.
⢠Syntax:
⢠It has following parts:
⢠Initialization
⢠Condition
⢠Increment or decrement
⢠Body of loop
100. ⢠Syntax:
⢠For(initialization; condition; increment/decrement)
⢠For (a=1; a<=10; a++)
⢠Example :
⢠Int main(){
⢠For (int i=1; i<6; i++)
⢠Cout<<âPAKISTANâ<<endl;
⢠Getch();
⢠Return 0;
⢠}
102. ⢠Example 3:
⢠Int tab, c, r;
⢠Cout<<âEnter any valueâ;
⢠Cin>>tab;
⢠For(c=1; c<=10; c++){
⢠R=tab * c;
⢠Cout<<tab<<âxâ<<c<<â=â<<r<<endl;
⢠}
⢠}
103. Example 4:
Int n, sum;
Sum = 0;
For(n=1; n<=10; n+=2)
{
Sum = sum + n;
Cout<<n<<endl;
}
Cout<<âsum = â<<sum<<endl;
104. ⢠Example 5:
⢠Int main(){
⢠For (int a=1,b=10; a<=10; a++,b--)
⢠Cout<<âaâ<<a<<âtb=â<<b<<endl;
⢠}
105. ⢠The initialization and increment/decrement fields are optional. They can remain empty
but in all cases the semicolon signs between them must be written. For example we
could write : for(;n<10;) if we want to specify no initialization and no increase.
⢠Int n=0;
⢠For(;n<10;)
⢠{
⢠Cout<<n<<â,â;
⢠N++;
⢠}
106. ⢠While loop:
⢠While loop is another structure that is used in computer programs to repeat a
statement or a group of statements until the condition is true.
⢠Syntax:
⢠While(condition){
⢠Statement 1;
⢠Statement 2;
⢠}
107. ⢠Example :
⢠Int n;
⢠Cout<<âenter the starting numberâ;
⢠Cin>>n;
⢠While(n>0){
⢠Cout<<n<<â,â;
⢠--n;
⢠}
⢠Getch();
⢠Return 0;
109. ⢠Do while loop:
⢠Sometime a programmer want to execute the loop at least once for some problems. To do
this ,C++ offers the facility of do while loop.
⢠Syntax:
⢠Do{
⢠Statement;
⢠.
⢠Statement n;
⢠}
⢠While(condition)
110. ⢠Example :
⢠Int main(){
⢠Int I =0;
⢠do{
⢠Cout<<âPAKISTANâ<<endl;
⢠++I;
⢠}while(i<6);
⢠Getch();
⢠Return 0;
⢠}
111. ⢠Example 2:
⢠Int n;
⢠N = 1;
⢠Do
⢠{
⢠Cout<<n<<endl;
⢠N++;
⢠}
⢠While(n<=10);
⢠}
112. ⢠Example 3:
⢠Int main(){
⢠Int x;
⢠Do{
⢠Cout<<âenter number (0 is for ending)â;
⢠Cin>>x;
⢠Cout<<âyou entered:â<<x<<endl;
⢠}while(x!=0);
⢠Getch();
⢠Return 0;
⢠}
113. ⢠Example 4:
⢠int main(){
⢠Int marks;
⢠Char name[25], address[15],op;
⢠Do{
⢠Cout<<âenter name of studentâ;
⢠Cin>>name;
⢠Cout<<âenter address of studentâ;
⢠Cin>>address;
⢠Cout<<âenter marks obtainedâ;
⢠Cin>>marks;
⢠Cout<<endl<<âstudent record is:â<<endl;
⢠Cout<<name<<âtâ<<address<<âtâ<<marks<<endl;
⢠Cout<<âmore record [Y/N]â;
⢠Cin>>op;
⢠}
⢠While(op == âyâ || op == âYâ);
⢠Cout<<âokâ;
⢠}
114. ⢠Example 4: // write a program to convert the given decimal number into octal number
using the do-while loop
⢠Int main(){
⢠Int n, r;
⢠Cout<<âenter any integer no.â;
⢠Cin>>n;
⢠Do{
⢠R = n % 8;
⢠Cout<<r<<endl;
⢠N = n/8;
⢠}
⢠While( n >= 1);
⢠Cout<<endl<<âokâ;
⢠}
115. FACTORIAL OF A GIVEN NUMBER
⢠Example 5: write a program to compute and print the factorial of a given number using the do-while
loop
⢠Int main(){
⢠Long int f,m,n;
⢠Cout<<âenter any noâ;
⢠Cin>>n;
⢠M = n;
⢠F = 1;
⢠Do
⢠{
⢠F = f*n;
⢠N--;
⢠}
⢠While(n >= 1);
⢠Cout<<âfactorial of â<<m<<â=â<<f;
⢠}
116. CONTINUE STATEMENT
⢠The âcontinueâ statement shifts the control back to the beginning of the loop. It is
used inside the body of the loop. When this statement is executed inside the body of
the loop, the control shifts to the first statement of the body of the loop
⢠Syntax:
⢠Continue;
117. ⢠Int main(){
⢠Int c;
⢠C = 1;
⢠While (c <=5){
⢠Cout<<âPAKISTANâ<<endl;
⢠C++;
⢠Continue;
⢠Cout<<âislamabadâ;
⢠Cout<<âpeshawarâ;
⢠}
⢠}
118. NESTED LOOP
⢠A loop structure completely inside the body of another loop structure is called nested loop.
⢠Int main(){
⢠Int u, I;
⢠U = 1;
⢠While (u <= 2){
⢠i=1;
⢠Cout<<u<<endl;
⢠While(i<=3){
⢠Cout<<âPAKISTANâ<<endl;
⢠i++;
⢠}
⢠U++;
⢠}
⢠}
121. ARRAY AND
STRINGS
U N I T 5
A U T H O R : : A B D U L L A H J A N
L E C T U R E R I N : : PA K I S TA N D E G R E E C O L L E G E
122. CONCEPT OF ARRAYS
⢠An array is a sequence of objects of same data type. The objects in an array are also
called elements of array.
⢠An array is represented in the computer memory by a consecutive(following one after
the other in regular order) group of storage location. These location are referenced by
a single variable called array name. each element of an array is referenced by its
position in the array
⢠The position of an element in an array is represented by an index value or subscript. In
an array with ânâ elements the index value are 0,1,âŚ..n-1, where â0â represents the index
value of first element and ân-1â represent the index value of last elements.
⢠Arrays are used to process a large amount of data of same type. The data is stored in
an array. The array is accessed by a single variable name
123. CONCEPT OF ARRAYS
⢠Consider the example for storing 10 values of type int in an array without having to
declare 10 different variables each one with a different variable name. instead of that
using an array we can store 10 different values of the same data type with a unique
variable name .
⢠Consider an array X that contains 10 integer values of type int.
⢠Represented as
0 1 2 3 4 5 6 7 98
X
Array X of ten location
124. CONCEPT OF ARRAYS
⢠These elements are numbered from 0 to 9 since arrays the first index is always 0.
125. REPRESENTATION OF ARRAY
⢠Array elements are stored in consecutive memory locations inside the computer
memory.
⢠For example :
if in the above array X we store the marks of seven students and the first
element X[0] is stored at address 100 inside the computer memory then
X[1],X[2],X[3],X[4],X[5],X[6]
Will be stored at memory address 102,104,106,108,110 and 112 respectively, here the
difference in the values of the memory addresses is two numbers because an int data
type occupies 2 bytes of memory space. It is shown in figure
10 02 24 06 13 11 04 08 11 0
0 1 3 4 9
X
2 765 8
108 110 112 114 116 118102
10
4
10610
0
Memory
address
indices
Data item
126. REPRESENTATION OF ARRAY
⢠Consider another example shown in figure of one dimensional array named SUB for
storing the title of a subject whose length is 7 character, such as PHYSICS
p H Y S I C S
0 1 3 4
SUB
2 65
104 105 106101
10
2
10310
0
127. TERMINOLOGY USED IN ARRAYS
⢠Terminologies are name , size and index
⢠Name of array:
The name of the array can be any valid identifier
Example :
x[0],x[2]
Size of array:
The number of elements that can be stored in an array is called the size or length of that
array
Example :
Float z[10];
128. TERMINOLOGY USED IN ARRAYS
⢠Index::
⢠The location number of an item in an array is called index or subscript of that element.
⢠Example:
0 to 6 int x[7]
129. DEFINITION AND INITIALIZATION OF
AN ARRAY⢠One Dimensional Array::
One dimensional array is also known as a list or a linear array. It consists of
only one column or one row.
Like a regular variable an array must be declared before it is used. A typical declaration for a
one dimensional array in C++ is :
Data type name [size];
Here data type is a valid data type (such as int , float ,âŚ.) name is a valid identifier and
enclosed in square brackets [] is the size of the array which means that how many elements
this array can accommodate.
For example ::
Int x[7];
Char vowel [5];
Float temp [7];
130. ONE DIMENSIONAL ARRAY
⢠One dimensional array of vowel : : char vowel [5];
A E I O U
0 1 3 4
Vowel
2
104101
10
2
10310
0
131. INITIALIZING ONE DIMENSIONAL
ARRAY⢠Like other variable the values in the elements of an array can also be assigned when
the array is declared. The assigning of values to the elements of the array at the time of
its declaration is called initializing of the array.
⢠For example to declare an array âtempâ of type double with 5 elements. With values
66.3, 77.7, 99.2, 63.9, and 59.3 in elements temp[0], temp[1],temp[2],temp[3],temp[4]
respectively the statement is written as :
⢠Double temp[5] = {66.3, 77.7, 99.2, 63.9, 59.3 };
⢠The values on the right-hand-side enclosed in curly brackets are assigned to the
elements of the array in the order in which they are written.
⢠If the number of elements in an array is greater than values in the list, then the
remaining last elements are initialized.
132. ⢠// initializing array using initializer list method
⢠#include <iostream>
⢠#include<conio.h>
⢠Using namespace std;
⢠Int main(){
⢠Int a[5] ={3,2,7,5,8};
⢠Cout<<a[0]<<endl;
⢠Cout<<a[1]<<endl;
⢠Cout<<a[2]<<endl;
⢠Cout<<a[3]<<endl;
⢠Cout<<a[4]<<endl;
⢠Getch();
⢠Return 0;
⢠}
133. ⢠Exampel 2:
⢠Int main(){
⢠Int temp[5] = {1,2,3,4,5};
⢠Int I;
⢠For(i=0; i<=4; i++)
⢠Cout<<temp [i] <<endl;
⢠Getch();
⢠Return 0;
⢠}
134. ⢠Example 3:
⢠Int main(){
⢠Char first[7] = {âMâ,âAâ,âRâ,âRâ,âIâ,âAâ,âMâ};
⢠Second [7];
⢠Int c;
⢠//copy value from âfirstâ to âsecondâ;
⢠For (c=0 ; c<=6; c++)
⢠Second [c] = first [c];
⢠//print value from âsecondâ array on screen
⢠For(c=0;c<=6;c++)
⢠Cout<<second [c];
⢠Getch();
⢠Return 0;
⢠}
135. ACCESS AND WRITING AT AN INDEX
IN AN ARRAY
⢠Each element of an array is referenced by its index. In an array of n elements each
element has an index value. The index of the first elements its 0 and of the last element
is n-1.
⢠The index value is written within square brackets after the array name.
⢠Thus the first element of an array temp is referenced as temp[0] similarly the last
elements of an array temp of n elements is referenced as temp[n-1]
⢠To access all elements of an array we use loops instead of individual reference to each
element,
136. ⢠#include <iostream>
⢠#include<conio.h>
⢠Using namespace std;
⢠Int main(){
⢠Int a[5];
⢠a[0] = 9;
⢠a[1] = 7;
⢠a[2] = 6;
⢠a[3] = 5;
⢠a[4] = 4;
⢠For ( int I = 0; i<=4; i++)
⢠Cout<<âvalue in a[â<<i<<â] = â<<a[i]<<endl;
⢠Getch();
⢠Return 0;
⢠}
137. ⢠// example having an array temperature that accepts the values of weekly temperature
from the users at run time and write them into their respective indexes.
⢠Example 2:
⢠Int main(){
⢠Float temp[7];
⢠Cout<<âenter 7 days temperature:â<<endl;
⢠For(int I = 0; i<7; ++i)
⢠Cin>>temp[i];
⢠Cout<<âthe last week temperature was:â<<endl;
⢠For(int i=0; i<7; ++i)
⢠Cout<<temp[i]<<â,â;
⢠Getch();
⢠Return 0;
⢠}
138. TRAVERSING AN ARRAY
⢠Accessing the elements of an array is called traversing of array
⢠//reading numbers into an array and then searching for an item
⢠Int main(){
⢠Int a[10]; //declare an array of 10 integers
⢠Int n=0;
⢠Cout<<âenter 10 integer valuesâ<<endl;
⢠While(n<10)
⢠{
⢠Cin>>a[n];
⢠N++;
⢠}
⢠Int item; //declare an item to search
⢠Cout<<âenter an item to searchâ<<endl;
⢠Cin>>item;
140. ⢠//consider another program of array traversal using for loop to display those values
from the array which are odd
⢠Int main(){
⢠Int a[] = {3,2,7,5,8};
⢠For(int i=0; i<5; i++)
⢠{
⢠If(a[i]%2!=0)
⢠Cout<<a[i]<<endl;
⢠}
⢠Getch();
⢠Return 0;
⢠}
141. SIZEOF() OPERATOR
⢠The sizeof() operator can be used with arrays to return the size allocated for the entire
array.
⢠Consider the following program
⢠//size of an array example
⢠Int main(){
⢠Int a[] = {0,1,2,3,4};
⢠Cout<<âsize of the array A is:â<<sizeof(A);
⢠Getch();
⢠Return 0;
⢠}
142. ⢠Example 2:
⢠// to find the number of elements in array using
⢠Int main(){
⢠Int a[] = {0,1,2,3,4};
⢠Cout<<âsize of the array =â<<sizeof(a)<<âbytesâ;
⢠Int total_element = sizeof(a);
⢠Cout<<âtotal number of elements in the array A are :â<<total_element;
⢠Getch();
⢠Return 0;
⢠}
143. TWO DIMENSIONAL
⢠Two-dimensional array can be considered as a table that consists of rows and column.
Each element in 2-D array is referred with the help of two indexes. One index is used to
indicate the row and the second index indicates the column of the element.
⢠Syntax:
⢠Int a[3][5];
145. ⢠//writing in a two dimensional array using loop
⢠Int main(){
⢠Int a[2][4];
⢠For (int I =0 ; i<2 i++)
⢠For(int j = 0 ; j<4 ; j++){
⢠Cout<<âenter an integer : â;
⢠Cin>>a[i][j];
⢠}
⢠For(int I = 0 ; i<2;i++){
⢠For (int j = 0; j<4;j++)
⢠Cout<<a[i][j]<<âtâ;
⢠Cout<<endl;
⢠}
⢠Getch();
⢠Return 0;
⢠}
146. WHAT IS STRING
⢠The sequence of character enclosed in quotation marks and is used to handle non-
numeric data i.e names , address, etc. are called strings.
⢠Define a C string
⢠Data type name_of_string [size of string];
⢠Example:
⢠Char str[20];
147. INITIALIZING STRING
⢠Char greeting[6] = {âHâ,âeâ,âIâ,âIâ,âoâ,â0â};
⢠Example :
⢠Int main(){
⢠Char question[] = âplease enter your first name:â;
⢠Char greeting[] = âHelloâ;
⢠Char yourname[80];
⢠Cout<<question;
⢠Cin>>yourname;
⢠Cout<<greeting<<yourname<<â!â;
⢠Getch();
⢠Return 0;
⢠}
148. ⢠Example 2:
⢠Int main(){
⢠String str1(âcall meâ);
⢠String str2 = âsend SMSâ;
⢠String str3(âokayâ);
⢠Cout<<âfirst string str1 is :â<<str1<<endl;
⢠Cout<<âsecond string str2 is :â<<str2<<endl;
⢠Cout<<âthird string str3 is :â<<str3<<endl;
⢠Getch();
⢠Return 0;
⢠}
150. COMMONLY USED STRING FUNCTION
⢠The header file string provides many string manipulation function. These are discussed
with help of program as follows
⢠Concatenation function:
⢠Strcat() function:
⢠Combining two strings into a single string is called string concatenation. strcat()
function is used for this purpose.
152. COPYING STRING
⢠Copy() function is used to copy one string to another string.
⢠Syntax:
⢠Str.copy (string_name,number_of_character,string_pointer)
153. ⢠Example :
⢠Int main(){
⢠String str = âwelcome to c++ stringâ;
⢠Char x[55];
⢠Cout<<âstr is â<<str<<endl;
⢠Str.copy(x,7,0); //copy 7 character of string str into string x starting from position zero
⢠Cout<<âthe copied string is :â<<x<<endl;
⢠Getch();
⢠Return 0;
⢠}
⢠Output ::
⢠Welcome to c++ string
⢠The copied string is : welcome
154. STRCPY() FUNCTION
⢠For copying string another string function strcpy() can also be used. Consider the
following program to demonstrate the use of strcpy()
⢠Example ::
⢠Int main(){
⢠String SS;
⢠Char CC[17];
⢠SS = âthis is a stringâ;
⢠Strcpy(CC,âthis is a stringâ);
⢠Cout<<SS<<endl; cout<<CC<<endl;
⢠Getch();
⢠Return 0;
⢠}
155. FINDING A CHARACTER OR WORD IN
A STRING
⢠Find() function:
⢠To find a particular word or a character in a string, find() function is used. Find function
takes only one argument which is the desired character or word within the string.
⢠Example ::
⢠Int main(){
⢠String str(âC++ is a very interesting programming languageâ);
⢠Int loc1,loc2;
⢠Loc1 = str.find(âinterestingâ);
⢠Cout<<âword interesting is found on position :â<<loc1+1;
156. ⢠Loc2 = str.find(âgâ);
⢠Cout<<ân first character âgâ found position :â<<loc2;
⢠getch();
⢠Return 0;
⢠}
⢠Output ::
⢠Word interesting is found on position : 15
⢠First character âgâ found on position : 24
157. FINDING LENGTH OF A STRING
⢠To find the length of a string length() function is used. Consider the following program to
demonstrate working of the length() function
⢠Int main(){
⢠String str(âc++ is a very interesting programming languageâ);
⢠Cout<<âlength of the given string is :â<<str.length();
⢠Getch();
⢠Return 0;
⢠}
⢠Ouptut ::
⢠Length of the given sting is : 46
158. SWAPPING STRINGS
⢠To swap (or interchange) values of two strings , swap() function is used. Consider the
following program to demonstrate working of swap() function
⢠Example ::
⢠Int main(){
⢠String str1 = âF.SC Part 1â;
⢠String str2 = âF.SC Part 2â;
⢠Cout<<âstr1 is :â<<str1<<endl;
⢠Cout<<âstr2 is :â<<str2<<endl;
⢠Str1.swap(str2);
⢠Cout<<âstr1 is:â<<str1<<endl;
159. SWAP STRING
⢠Cout<<âstr2 is:â<<str2<<endl;
⢠getch();
⢠Return 0;
⢠}
⢠Output ::
⢠Str1 is : F.SC Part 1
⢠Str2 is : F.SC Part 2
⢠Str1 is : F.SC Part 2
⢠Str2 is : F.SC Part 1
161. FUNCTIONSU N I T 6
A U T H O R : : A B D U L L A H J A N
P A K I S T A N D E G R E E C O L L E G E N O W S H E R A
162. FUNCTIONS
⢠A function is a set of instruction that are designed to perform a specific task. A function is a
complete and independent program. It is executed by the main function or any other
function of the program to perform its task.
⢠The function are written to write the code of a large program by dividing it into smaller
units. When a program is more than a few hundred lines, it become difficult to follow. In
this situation the program is divided into smaller independent units. These smaller units are
coded as function.
⢠The function are also written to avoid replication of a code in the program. In large
programs one often has to execute a piece of code several time. Instead of writing the code
several times, the code is written only once as a function and this function is called to
execute its code.
163. CONCEPT OF FUNCTION
⢠Whenever we want to perform a task again and again in a program such as calculating
the square or cube for multiple integer values then it is too difficult to write the same
code multiple times, say 5 times for different integer values in the same program.
165. BUILT IN FUNCTIONS
⢠C++ language provide a number of pre-complied function for some commonly used
operation.
⢠These function are called built-in function. Built-in function are part of the c++
language and are highly valuable, pre-tested and completely reliable. The c++ built-in
function are made for various assignment ranging from algebra, geometry.
Trigonometry,finance,text and graphics to some complex operation.
⢠Or
⢠The function that have already been defined as a part of the language and can be used
in any program are called built-in function.
166. ⢠Consider the following example that request the value of angle and calculate its sine and
display it on the screen
⢠//built-in function (sin() program)
⢠#include<math.h>
⢠Int main(){
⢠Flaot angle;
⢠Cout<<âenter value for angleâ<<endl;
⢠Cin>>angle;
⢠Cout<<âthe sine ofâ<<angle<<âdegree is â<<sin(angle);
⢠Getch();
⢠Return 0;
⢠}
⢠Output ::
⢠Enter value of angle :
⢠45.0
⢠The sine of 45.0 degree is = 0.850904
⢠You can calculate cos(x) , tan(x) , cot(x) built-in function
167. ⢠Consider another example
⢠#include<math.>
⢠Int main(){
⢠Int x;
⢠Cout<<âenter value of xâ<<endl;
⢠Cin>>x;
⢠Cout<<âabsolute value ofâ<<x<<âis :â<<abs(x);
⢠Getch();
⢠Return 0;
⢠}
⢠Output ::
⢠Enter value of x
⢠-12
⢠Absolute value of -12 is : 12
168. USER DEFINED FUNCTION
⢠The function defined by the users, according to their needs, to perform their own tasks
are called user-defined functions. These functions are used to overcome the limitations
of build-in function
169. DEFINING USER DEFINED FUNCTION
⢠A function must be defined first to use it in the program. The general syntax for
defining a user-defined function is given below
⢠Type name(parameter1 , parameter2, âŚ)
⢠{
⢠Statement;
⢠}
170. ⢠//consider a function named addition to take two integer values add them together and
return the result to calling program. The following code segment defined this function
⢠//user defined function(addition) program
⢠Int addition(int a, int b)
⢠{
⢠Int sum;
⢠Sum = a+b;
⢠Return (sum);
⢠}
⢠Int main()
⢠{
⢠Int z;
⢠Z = addition(55,33);
⢠Cout<<âthe sum of a and b is =â<<z;
⢠Getch();
⢠Return 0;
⢠}
⢠Output ::
⢠The sum of a and b is = 88
171. ADVANTAGES OF USING FUNCTIONS
⢠Code reusability :
The code inside the function can be reused by calling it again and
again in the program.
⢠Updating code:
It is much easier to change or update the code in a function which
needs to be done once.
⢠Readability and understandability :
It makes the code easier to read and understand
172. FUNCTION SIGNATURE
⢠Name of the function
⢠The number order and data types of the arguments
⢠Return type of function
lets us consider the add function to demonstrate function signature
double add(int x, double y)
{
Return x+y;
}
174. FUNCTION PROTOTYPE /
DECLARATION
⢠In function declaration the following information about the function is provided to the
compiler
⢠The name of function
⢠The type of data returned by the function
⢠The number and types of arguments or parameter used in the function
⢠Semicolon is used at the end of function declaration to indicate the end of function
declaration.
⢠The function declaration is similar to a variable declaration. The rules for naming function
are same as those for naming variables
⢠Syntax of function declaration I s
175. FUNCTION PROTOTYPE /
DECLARATION
⢠Type function-name (arguments)
⢠Example :
⢠Void display (void)
⢠Example :
⢠Int sum (int, int)
⢠Example :
⢠Float temp (void);
176. FUNCTION DEFINITION
⢠A function definition specifies what a function does. It has two parts : a declaration /
header and function body enclosed in {}. Function declarator is similar to function
prototype with only difference that it has the variables name for the parameters and
without semicolon(;).
⢠Consider the following function declaratory.
⢠syntax:
⢠Type function_name (list of parameter) // declaratory
⢠{
⢠set of statements // body of function
⢠}
177. ⢠Example :
⢠int maximum (int x , int y , int z) // function declaratory
⢠{
⢠Int max = x;
⢠If(y > max)
⢠Max = y;
⢠If (z > max)
⢠Max = z;
⢠Return max;
⢠}
178. FUNCTION CALLING
⢠A function call is a statement in the calling function (e.g main() function) to execute the
code of the function. Consider the following statement:
⢠Maximum (a,b,c);
⢠The function call has the list of argument that are passed to the function declaratory.
The arguments in this call are a , b and c . The following program shows different parts
of the function i.e prototype definition and call.
179. SIMPLE EXAMPLE
⢠//write a program to print a message on the screen using function
⢠Int main(){
⢠Void display (void);
⢠Display();
⢠Cout<<âokâ:
⢠}
⢠Void display (void){
⢠Cout<<âit is my first function programâ<<endl;
⢠}
180. ⢠// finding maximum out of three integers using function
⢠Int main(){
⢠Int a,b,c;
⢠Cout<<âenter three integerâ;
⢠Cin>>a>>b>>c;
⢠Cout<<âmaximum is :â<<maximum (a,b,c)<<endl; //function call
⢠Getch();
⢠Return 0;
⢠}
⢠Int maximum (int x, int y, int z) //function definition
⢠{
⢠Int max = x;
⢠If(y > max)
⢠Max = y;
⢠If(z > max)
⢠Max = z;
⢠Return max;
⢠}
⢠Output ::
⢠Enter three integer : 4 -2 6
⢠Maximum Is :6
181. SCOPE OF VARIABLES
⢠By the scope of a variable we mean that if a variable is defined in a program then in
which parts of the same program this variable can be accessed. There are three scope
of variables
⢠Local scope
⢠Global scope
⢠Static variable
182. LOCAL VARIABLE
⢠A variable declared inside a function is known as local variable. Local variable are also
called a automatic variables. The syntax of declaring a local variable is as follow.
⢠Auto data_type identifier;
⢠Auto it is a keyword that indicates that variable is automatic
⢠Data_type it indicates the data type of variable
⢠Identifier it indicates the name of variable
183. SCOPE OF LOCAL VARIABLE
⢠The area where a variable can be accessed is known as scope of variable. Local variable
can be used only in the function in which it is declared. If a statement access a local
variable that is not in scope, the compiler generates a syntax error.
184. LIFE TIME OF LOCAL VARIABLE
⢠The time period for which a variable exists in the memory is known as the lifetime of
variable.
⢠Different types of variable have different lifetime
⢠The life time of local variable starts when the control enters the function in which it is
declared local variable
⢠The life time of local variable starts when the control enters the function in which it is
declared. Local variable is automatically destroyed when the control exists from the
function and its life time ends. When the control exits from the function and its lifetime
ends. When the life time of a local variable ends, the value stored in this variable also
becomes inaccessible.
185. ⢠Example:
⢠Int main(){
⢠Int I;
⢠For(I = 1 ; i<=5;i++)
⢠Fun();
⢠Getch();
⢠}
⢠Void fun()
⢠{
⢠Int n=0; //local variable
⢠N++;
⢠Cout<<âthe value of n = â<<n<<endl;
⢠}
186. ⢠How above program works?
⢠The above program declare a function fun(). The function declares a local variable n
and initializes it to 0. the main() function calls it five times using for loop. The control
moves to the function in each function call. The local variable n is created in the
memory and is initialized with 0. finally the value of n is displayed on screen. The
variable n is destroyed from the memory when the control exits the function.
187. GLOBAL VARIABLE
⢠A variable declared outside any function is known as global variable. Global variables
can be used by all function in the program. The values of these variable are shared
among different functions. If one function changes the value of a global variable, this
change is also available to other functions
188. SCOPE OF GLOBAL VARIABLE
⢠Global variable can be used by all functions in the program. It means that these
variable are globally accessed from any part of the program. Normally global variables
are declared before main function
189. LIFE TIME OF GLOBAL VARIABLE
⢠Global variable exits in the memory as long as the program is running. These variables
are destroyed from the memory when the program terminates. These variables occupy
memory longer than local variables. So global variables should be used only when
these are very necessary.
190. ⢠Write a program that inputs a number in a global variable. The program calls a function
that multiplies the value of global variable by 2. the main function then displays the value
of global variable.
⢠#include<iostream>
⢠Int g;
⢠Void fun();
⢠Int main(){
⢠Cout<<âenter a numberâ;
⢠Cin>>g;
⢠Cout<<âvalue of g before function call:â<<g<<endl;
⢠Fun();
⢠Cout<<âvalue of g after function call:â<<g<<endl;
⢠Getch();
⢠}
⢠Void fun(){
⢠g = g*2;
⢠}
191. ⢠How above program works?
⢠The above program declare a global variable g. the variable is accessible to all function
in the program. The function fun() doubles the value of g when main() function calls it.
Finally main() function displays the increased value of g.
192. STATIC VARIABLE
⢠A local variable declared with keyword static is called static variable. The keyword static
is used to increase the lifetime of local variable.
193. SCOPE OF STATIC VARIABLE
⢠The scope of static variable is similar to the scope of local variable. Static variable can
be used only in the function in which it is declared.
194. LIFE TIME OF STATIC VARIABLE
⢠The life static variable is similar to global variable. Static variable exist in the memory as
long as the program is running. These variables are destroyed from the memory when
the program terminates.
195. ⢠#include<iostream>
⢠Void demo(){
⢠Auto int auto_var = 0; // automatic variable
⢠Static int static_var = 0 // static variable
⢠Cout<<âauto =â<<auto_var<<â,â<<âstatic=â<<static_var<endl;
⢠++auto_var; ++static_var;
⢠}
⢠Int main(){
⢠Int i=0;
⢠While(I < 3)
⢠{
⢠Demo(); i++;}
⢠Getch();
⢠Return 0;
⢠}
⢠Ouptut ::
⢠Auto = 0, static = 0
⢠Auto = 0 static = 1
⢠Auto = 0 static = 2
196. Here the automatic variable Auto_var iosses its values when the control goes out of the
function body but static variable static_var keeps its last value even if the controls goes
out of the function
197. FORMAL PARAMETERS AND ACTUAL
PARAMETERS
⢠In function prototype and function calls variable and values are written in the
parenthesis of the functions. These are divided into two categories; formal parameters
and actual parameters.
198. FORMAL PARAMETER
⢠Formal parameter are those parameter which appear in function declarator/header and also
in function prototype. These are also called formal arguments and are used to receive
values for function
⢠For example :
⢠Void foo(int x); // prototype âx is a formal parameter
⢠Void foo(int x) //declarator âx is a formal parameter
⢠{
⢠Body
⢠}
199. ACTUAL PARAMETER
⢠Actual parameter are those parameter which appear in function called are used to send
data to formal parameter. These are also called actual arguments. Consider the following
function call:
⢠Foo(6); // 6 is the argument passed to parameter x
⢠Foo(y+1) //the value of (y+1) is the argument passed to parameter x
⢠The actual parameter can be fixed values or variables holding values or expressions
resulting in some values
⢠In function main, in the following example, rice , chicken and fruit are actual parameters
when used to call calculate_bill. On the other hand the corresponding variable in
calculate_bill (namely diner1, diner2 and diner3, respectively) are formal parameters
because they appear in the function definition and receive values passed in the function
call.
200. ⢠Lets look at calculate_bill function in the following program
⢠#include<stdio.h>
⢠Int calculate_bill(int , int ,int);
⢠Int main(){
⢠Int bill;
⢠Int rice = 25;
⢠Int chiken = 32;
⢠Int fruit = 27; Bill = calculate_bill (rice,chiken,fruite);
⢠Cout<<âthe total bill comes to â<<bill<<âRSâ;
⢠getch();
⢠Return 0;
⢠}
⢠Int calculate_bill (int diner1,int diner 2, int diner 3) {
⢠Int total;
⢠Total = diner + diner2 + diner3;
⢠Return total;
⢠}
Actual parameter
Formal
parameter
201. ⢠Output:
⢠The total bill comes to 84 Rs.
⢠Although formal parameter are always variable but actual parameter may not be
variables. Number expression or even function calls can also be used as actual
parameters. Here are some example of valid actual parameter in the function call to
calculate_bill
⢠Bill = calculate_bill (25, 32, 27);
⢠Bill = calculate_bill(50+60,25*2,100-75)
⢠Bill = calculate_bill(rice,chicken,(int)sqrt(27));
202. LOCAL AND GLOBAL FUNCTION
Local function :
⢠Those function which are defined inside the body of another function are called local
function.
Global function :
⢠A function declared outside any function is called global function.
203. INLINE FUNCTION
⢠The function declared with keyword inline is known as inline function. The inline
function is declared before main function. Only very small function are declared as
inline functions. When a program is complied the compiler generates special code at
each function call to move the control to the called function. It also generates special
code at the end of function definition to move the control back to the calling function.
The shifting of control from calling function to called function and back to calling
function takes time during program execution. This time can be eliminated by using
inline function.
⢠The code of function body is inserted at each function call if the function is declared as
inline function. It allows the program to execute the function statements without
shifting the control from calling function. It saves time and increases program
efficiency
204. INLINE FUNCTION
⢠The code of function body is repeated at each function call. It takes more memory than
normal function call. That is why the inline functions must only be used if the function
body contains a small number of statements.
205. INLINE FUNCTION EXAMPLE
⢠#include<iostream>
⢠Inline int cube(int n)
⢠{
⢠Return n*n*n;
⢠}
⢠Int main(){
⢠Cout<<cube(3)<<endl;
⢠Cout<<cube(5)<<endl;
⢠Cout<<cube(9)<<endl;
⢠Getch();
⢠Return 0;
⢠}
206. ⢠#include<iostream>
⢠Inline int min(int a, int b)
⢠{
⢠Return a>b ? b:a;
⢠}
⢠Int main(){
⢠Cout<<âminimum out of 25 and 26 is :â<<min(25,26);
⢠Cout<<âminimum out of 23 and 22 is :â<<min(23,22);
⢠Getch();
⢠Return 0;
⢠}
⢠Ouput :
⢠Minimum out of 25 and 26 is :25
⢠Minimum out of 23 and 22 is : 22
207. PASSING ARGUMENTS AND
RETURNING VALUES
⢠When we want to execute functions we need to pass arguments (values) to a function.
The result (values) produced within the function body is then returned back to the
calling program. The following section describe different methods used for passing
arguments (values) to functions.
208. PASSING ARGUMENTS
⢠The following are the most commonly used methods of passing arguments to
functions.
⢠Passing arguments by constant
⢠Passing arguments by values
⢠Passing argument by reference
209. PASSING ARGUMENTS BY CONSTANT
⢠While calling a function arguments are passed to the calling function. In passing
constant as arguments the actual constant values are passed instead of passing the
variables.
211. PASSING ARGUMENTS BY CONSTANT
⢠In above program the function call display (5) passes the constant argument (5) to the
function
212. PASSING ARGUMENTS BY CONSTANT
⢠Consider another program defining a function display gender() that takes a character
constant âfâ or âmâ as argument from the calling function
⢠//passing character constant as argument
⢠Void displayGender(char ch){
⢠Cout<<âthe gender marker you passed is :â<<ch<<endl;
⢠}
⢠Int main(){
⢠displayGender(âfâ); //function call
⢠Getch();
⢠Return 0;
⢠}
⢠Ouput :
⢠The gender marker you passed is : f
213. PASSING ARGUMENTS BY VALUE
⢠A parameter passing mechanism in which the value of the actual parameter is copied
to formal parameter of called function is known as pass by value. If the function makes
any change in formal parameter, it does not affect the values of actual parameter. It is
the default mechanism for passing parameter to function.
⢠Consider the following program to demonstrate the use of passing argument by value.
214. Int main(){
Int n;
Cout<<âenter numberâ;
Cin>>n;
Show(n);
Cout<<âend of programâ;
}
Void show(int num)
{
Cout<<âthe number is â<<num;
}
Void show(int);
Variable
Variable num
Actual
parameter
Formal parameter
Function
definition
215. ⢠Passing parameter y value
⢠Void foo(int y){
⢠Cout<<ây in foo() = â<<y<<endl;
⢠Y = 6;
⢠Cout<<ây in foo() =â<<y<<endl;
⢠} //y is destroyed here
⢠Int main(){
⢠Int x = 5;
⢠Cout<<âx in main() before call = â<<x<<endl;
⢠Foo(x); // argument passed by value
⢠Cout<<âx in main() after call = â<<x<<endl;
⢠Getch();
⢠Return 0;
⢠}
216. ⢠Ouptut of the program
⢠X In main() before call = 5
⢠Y in foo() = 5
⢠Y in foo() = 6
⢠X in main() after call = 5
⢠In this program the original value of x is not changed before and after calling the
function foo().
217. ⢠Consider another example that uses a function addition that gets argument by values
⢠Int addition (int a , int b)
⢠{
⢠Int result;
⢠result = a+b;
⢠Rerurn (result);
⢠}
⢠Int main(){
⢠Int z, x = 5 , y = 3;
⢠Z = addition (x,y); // arguments passed by value
⢠Cout<<âthe sum of both the value is = â <<z;
⢠Getch();
⢠Return 0 ;
⢠}
⢠Ouptut :
⢠The sum of both the value is = 8
218. PASSING ARGUMENTS BY REFERENCE
⢠A parameter passing mechanism in which the address of actual parameter is passed to
the called function is known as pass by reference. The formal parameter is not created
separately in the memory. Formal parameter becomes a second name of actual
parameter. It means that single memory location is shared between actual parameter
and formal parameter. If the called function makes any changed in formal parameter,
the change is also available in calling function.
219. Int main(){
Int n;
Cout<<âenter numberâ;
Cin>>n;
Show(n);
Cout<<âend of programâ;
}
Void show(int &num)
{
Cout<<âthe number is â<<num;
}
Void show(int&);
Actual
parameter
Formal parameter
Function
definition
220. ⢠Void addone(int&y){
⢠Y++; //changing values in function
⢠}
⢠Int main(){
⢠Int x = 55;
⢠Cout<<âx in main() before call = â<<x<<endl;
⢠Addone(x); //passing arguments by reference
⢠Cout<<âx in main() after call =â<<x<<endl;
⢠Getch();
⢠Return 0;
⢠}
⢠Output :
⢠X in main() before call = 55
⢠X in main() after call = 56
221. ⢠In the above example the value of x is passed by reference and changed inside the
function addone(). This change affects the value of x in main() because the formal
argument & y in the function declarator is a reference to x and any change to y results in
change in x
222. ⢠Consider another example having a function named duplicate that receive arguments
by reference:
⢠Void duplicate(int&a, int &b , int&c){
⢠A = a*2;
⢠B = b*2l
⢠C = c*2;
⢠}
⢠Int main(){
⢠Int x = 1, y= 3, z = 7;
⢠Cout<<âx=â<<x<<â,y=â<<y<<â,z=â<<z<<endl;
⢠Duplicate(x,y,z);
⢠Cout<<âx=â<<x<<â,y=â<<y<<â,z=â<<z<<endl;
⢠Getch();
⢠Return 0;
⢠}
223. OUTPUT
⢠Values of x,y and z in main() before calling function
⢠X = 1, y= 3, z =7
⢠Values of x , y and z in main() after calling function
⢠X = 2, y = 6, z = 14
224. ⢠Sometimes we need a function to return multiple values. However function can only
return one value. One way to return multiple values is the use of method of passing
arguments by reference.
⢠Passing arguments by this method allow programmers to change the value of the
arguments which is sometimes useful. Similarly it is a fast approach to passing and
processing values in a function and also has the facility of returning multiple values
from a function.
225. DEFAULT ARGUMENTS
⢠The arguments in which data is initialized during the function declaration are called
default arguments .
226. ⢠Int divide(int a, int b = 2)
⢠{
⢠Int r;
⢠R = a/b;
⢠Return (r);
⢠}
⢠Int main(){
⢠Cout<<âresult by providing one argument =â<<divide(12); // function call with one
argument
⢠Cout<<endl;
⢠Cout<<âresult by providing both the arguments =â<<divide(20,4);
⢠Getch();
⢠Rerurn 0;
⢠}
⢠Output :
⢠Result by providing one argument = 6
⢠Result by providing both the arguments = 5
227. DEFAULT ARGUMENTS
⢠As we can see in the body of the program there are two calls to function divide(). In
the first one we have only passed one argument but the function divide() gets the
second value from the default argument int b = 2 in the function prototype and thus
result is 6. in the second call there are two parameter passed so the default value for b
is ignored and b takes the value passed as argument that is 4 making the result
returned equal to 5.
228. RETURN STATEMENT
⢠If the return type of a function is any valid data type such as int , long , float , double ,
long double or char then return statement should be used in the function body to
return the result to the calling program.
⢠The general syntax of the use of return statement is given below
⢠Return (expression or variable holding results or constant)
229. ⢠//use of return statement in the cube() function
⢠Int cube(int x)
⢠{
⢠Int c;
⢠C = x*x*x;
⢠Return c; // or return (c);
⢠}
⢠In a function returns a value by the use of return statement then the call to the
function should be form statement or an expression that utilize it.
⢠Fro example:
⢠Cout<<cube (x);
⢠Int y = cube (x);
231. ⢠Int mul(int a , int b)
⢠{
⢠If(b%a == 0)
⢠Return 1;
⢠Else
⢠Return 0;
⢠}
⢠Int main(){
⢠Int I,x,y,r;
⢠For(i=1; i<=5; i++)
⢠{
⢠Cout<<âenter a pair of integerâ;
⢠Cin>>x>>y;
⢠R = mul(x,y);
⢠If(r == 1)
⢠Cout<<y<<âis multiple of â<<x<<endl;
⢠Else
⢠Cout<<y<<âis not multiple ofâ<<x<<endl;
⢠}
⢠Getch();
⢠}
Enter a pair of integer : 2 10
10 is multiple of 2
Enter a pair of integer : 5 13
13 is not multiple of 5
Enter a pair of integer : 3 27
27 is a multiple of 3
232. FUNCTION OVERLOADING
⢠In programming language two or more variable or functions with the same name
cannot be used in a single program or block of code. Function overloading is a feature
of C++ that allows us to create multiple functions with the same name. so long as they
have different number or types of parameters.
⢠Consider the following example having two function with the same name display used
to perform slightly different tasks in over loaded form.
234. NUMBER OF ARGUMENTS
⢠Functions can be overloaded if they have different numbers of parameters. More than
one functions with the same name but different number of parameter can be used in a
single program. In the calls to these functions the compiler disambiguates the calls by
looking at the number of arguments and formal parameters in the function
decelerator. Consider the following example:
235. ⢠Overloaded functions with different number of parameter
⢠Int addition(int x , int y){
⢠Return (x+y);
⢠}
⢠Int addition (int x, int y, int z){
⢠Return (x+y+z);
⢠}
⢠Int main(){
⢠Int a = 55 , b = 22 , c = 100;
⢠Cout<<âoutput of 2 integer = â<<addition(a,b);
⢠Cout<<endl;
⢠Cout<<âoutput of 3 integer = â<<addition(a,b,c);
⢠Cout<<endl;
⢠Getch();
⢠Return 0 ;
⢠}
236. ⢠Output of the program
⢠Output of 2 integers = 77
⢠Output of 3 integers = 177
237. DATA TYPES OF ARGUMENTS
⢠One way to archive function overloading is to define multiple function with the same
name but different types of parameters. Consider the following example
⢠Overloading function print() with different types of parameter
238. ⢠#include<iostream>
⢠#include<conio.h>
⢠Void print(int x){
⢠Cout<<âx=â<<s<<endl;
⢠}
⢠Void print(float y)
⢠{
⢠Cout<<ây = â<<y<<endl;
⢠}
⢠Int main(){
⢠Print(55);
⢠Print(33.66);
⢠Getch();
⢠Return 0;
⢠}
⢠Output of the program
⢠X = 55
⢠Y = 33.66
239. RETURN TYPE
⢠The return type of function is not considered when functions are overloaded. It means
that if two or more functions with the same name have same functions signatures but
different return types then they are not considered as overloaded and the compiler will
generate error message.
⢠Considered the following case
⢠Int display();
⢠Double display(); //this prototype generates error message
⢠Consider another example :
240. RETURN TYPE
⢠Int randomnumber();
⢠Double randomnumber(); // this prototype generates error message
Here the compiler generates an error message of re-declaration for the second
declaration at line number 2. It is because that both the declaration have same number
of parameter (zero in this case) but only the return types are different which do not play
any role in the overloading. If we want to do it, for then these function will need to be
given different names.