SlideShare a Scribd company logo
1 of 241
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
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.
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
}
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!
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>
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>
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…
}
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.
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
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;
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 */
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
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;
• }
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;
• }
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;
• }
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;
• }
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;
• }
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;
• }
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;
• }
• 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;
• }
• 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;
• }
• 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;
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
FUNDAMENTAL DATA TYPE IN C++
• The char keyword represent the character data type in C++
• Example:
char x;
Or
Char gender;
Gender = ‘M’;
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
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)
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
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.
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
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
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
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
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
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;
}
FUNDAMENTAL DATA TYPE IN C++
• Example 2:
• Int x;
• Float pi = 3.14;
• X = (int)pi;
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;
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;
}
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;
}
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.
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;
}
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);
INPUT / OUTPUT HANDLING
• Int main(){
• Char teststr[100];
• Cout<<“enter a string”;
• Gets(teststr);
• Cout<<“you entered”;
• Puts(teststr);
• Getch();
• Return 0;
}
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();
INPUT / OUTPUT HANDLING
• Int main(){
• Char ch;
• Cout<<“press any keyn”;
• Ch = getch();
• Cout<<“you passed:”<<ch<<endl;
• Getch();
• Return 0;
}
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();
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);
INPUT / OUTPUT HANDLING
FUNCTION• #include<iostream>
• #include<stdio.h>
• #include<conio.h>
• Uisng namespace std;
• Int main(){
• Char ch;
• Cout<<“enter character for gender”;
• Ch = getchar();
• Cout<<“you have entered”;
• Putchar(ch);
• Getch();
• Return 0;
• }
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;
}
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>
INPUT / OUTPUT HANDLING
FUNCTION
• Int main(){
• Int x1=2 , x2=4 , x3=6;
• Cout<<setw(8)<<“Number”<<setw(20)<<“Square”<<endl
• <<setw(8)<<“2”<<setw(20)<<x1*x1<<endl
• <<setw(8)<<“4”<<setw(20)<<x2*x2<<endl
• <<setw(8)<<“6”<<setw(20)<<x3*x3<<endl;
• Getch();
• Return 0;
• }
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;
OPERATOR IN C++
• Example :
• Int main(){
• Int a ,b;
• A=10;
• B=12;
• Cout<<a;
• Cout<<b;
• Getch();
• Return 0;
• }
OPERATOR IN C++
• Arithmetic operator:
• Five types of arithmetic operator:
• +
• -
• *
• /
• %
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;
• }
OPERATOR IN C++
• Arithmetic assignment operator:
• +=
• -=
• *=
• /=
• %=
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;
• }
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;
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
OPERATOR IN C++
• Example:
• Int x = 5;
• Cout<<“increment in prefix form = ”<<++x;
• Cout<<“decrement in prefix form = ”<<--x;
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
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;
• }
OPERATOR IN C++
• Relational operator:
• Relational operator are used for the comparsion between two expersion.
• These operator are :
• ==
• !=
• >
• <
• >=
• <=
OPERATOR IN C++
• Example:
• (7 == 5) //false
• (5>4) //true
• (3! = 2) //true
• (6>=6) //true
• (5<5) //false
OPERATOR IN C++
• Logical operator:
• Logical not !
• Logical AND &&
• Logical OR ||
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
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
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
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
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
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;
• }
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;
OPERATOR IN C++
• Logical expressions:
• (x>y)||(x=10)
CONTROL
STRUCTURE
A U T H O R : : A B D U L A H J A N
U N I T 4
(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.
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;
• 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;
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.
• The flowchart for the “if statement”
Condition
Statement ( s)
Statement after if
structure
True
False
• 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;
• }
• Example 2:
• Int main(){
• Int a,b;
• A=100;
• B=50;
• If(a>b)
• Cout<<“islamabad”;
• Cout<<“ok”<<endl;
• }
• Example :
• Int main(){
int c;
Cin>>c;
If(c>10)
{
Cout<<“islamabad”<<endl;
Cout<<“ok”<<endl;
}
}
• 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”;
• }
• 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;
• The flowchart for the “if-else statement”
Condition
Statement (1)
Statement after if
structure
TrueFalse
Statement ( 2)
• 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;
• }
• 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”;
• }
• 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;
• }
• 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;
}
• 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”;
• 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;
• }
• Float per;
• Cout<<“enter percentage marks”<<endl;
• Cin>>per;
• If(per >= 80){
• Cout<<“your grade is A+”<<endl;
• Cout<<“excellent”;
• }else{
• If(per <80 && per>=70){
• Cout<<“your grade is A”<<endl;
• Cout<<“very good”;
• }else {
• if(per<70 && per>=60){
• Cout<<“your grade is B”<<endl;
• Cout<<“Good”;
• }else
• Cout<<“you are failed, try again”;
• }
• }
• Getch();
• Return 0;
• 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;
}
• 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.
• 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;
• }
• 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”;
• }
• }
• Break :
• The break statement is used to exist from the body of the switch structure .
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
• 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
• 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;
• }
• Example 2:
• For(int n=10; n>0; n--)
• Cout<<n<<“,”;
• Getch();
• Return 0;
• 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;
• }
• }
Example 4:
Int n, sum;
Sum = 0;
For(n=1; n<=10; n+=2)
{
Sum = sum + n;
Cout<<n<<endl;
}
Cout<<“sum = ”<<sum<<endl;
• Example 5:
• Int main(){
• For (int a=1,b=10; a<=10; a++,b--)
• Cout<<“a”<<a<<“tb=”<<b<<endl;
• }
• 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++;
• }
• 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;
• }
• Example :
• Int n;
• Cout<<“enter the starting number”;
• Cin>>n;
• While(n>0){
• Cout<<n<<“,”;
• --n;
• }
• Getch();
• Return 0;
• Example 2:
• Int n=1;
• While(n<= 50)
• {
• Cout<<n<<“”;
• if(n%10 == 0)
• Cout<<endl;
• N++;
• }
• Getch();
• Return 0;
• 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)
• Example :
• Int main(){
• Int I =0;
• do{
• Cout<<“PAKISTAN”<<endl;
• ++I;
• }while(i<6);
• Getch();
• Return 0;
• }
• Example 2:
• Int n;
• N = 1;
• Do
• {
• Cout<<n<<endl;
• N++;
• }
• While(n<=10);
• }
• 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;
• }
• 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”;
• }
• 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”;
• }
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;
• }
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;
• Int main(){
• Int c;
• C = 1;
• While (c <=5){
• Cout<<“PAKISTAN”<<endl;
• C++;
• Continue;
• Cout<<“islamabad”;
• Cout<<“peshawar”;
• }
• }
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++;
• }
• }
• Example :
• Int main(){
• For(int i=1; i<=5; i++) //outer loop
• {
• For(int j=1; j<=I; j++) //inner loop
• Cout<<“$”;
• Cout<<endl;
• }
• Getch();
• Return 0;
• }
WORK SMART
NOT
HARD
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
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
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
CONCEPT OF ARRAYS
• These elements are numbered from 0 to 9 since arrays the first index is always 0.
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
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
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];
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]
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];
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
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.
• // 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;
• }
• 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;
• }
• 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;
• }
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,
• #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;
• }
• // 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;
• }
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;
• For(int i=0; i<10; i++) //traverse array
• {
• If(item!=a[i]) //comparsion
• Continue;
• Else{
• Cout<<“item”<<item<<“is found at location”<<i+1;
• Goto end;
• }
• }
• Cout<<“search unsuccessful:”<<item<<“is not found”;
• End:
• Getch();
• Return 0;
• }
• //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;
• }
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;
• }
• 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;
• }
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];
ACCESS TWO DIMENSIONAL ARRAYS
• Int main(){
• Int I , j, a[2][3] = {15,21,9,84,33,72};
• For(i = 0; I<2; i++)
• {
• For( j=0; j<3; j++)
• Cout<<“arr[“<<i<<”][“<<j<<”] = ”a[i][j]<<“t”;
• Cout<<endl;
• }
• Getch();
• Retrun 0;
• }
• //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;
• }
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];
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;
• }
• 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;
• }
• Example 3:
• Int main(){
• String str1 = “Hello”;
• String str2 = “world”;
• String str3 , str4;
• Int len;
• Str3 = str1; //string copying
• Str4 = str1 + str2;
• Len = str4.size(); // find the string size
• Cout<<“str3 = t”<<str3<<endl;
• Cout<<“str4 = t”<<str4<<endl;
• Cout<<“length of str4 = t”<<len<<endl;
• Getch();
• }
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.
• Example // string concatenation program
• Int main(){
• Char firstname[15] = “SSC”;
• Char lastname[15] = “computer”;
• Strcat(firstname,lastname);
• Cout<<firstname;
• Getch();
• Return 0;
}
Output::
SSC computer
COPYING STRING
• Copy() function is used to copy one string to another string.
• Syntax:
• Str.copy (string_name,number_of_character,string_pointer)
• 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
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;
• }
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;
• 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
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
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;
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
GOOD LUCK
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
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.
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.
TYPES OF FUNCTIONS
•Built in function
•User defined function
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.
• 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
• 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
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
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;
• }
• //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
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
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;
}
COMPONENTS OF FUNCTION
• Function prototype / declaration
• Function definition
• Function call
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
FUNCTION PROTOTYPE /
DECLARATION
• Type function-name (arguments)
• Example :
• Void display (void)
• Example :
• Int sum (int, int)
• Example :
• Float temp (void);
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
• }
• 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;
• }
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.
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;
• }
• // 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
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
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
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.
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.
• 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;
• }
• 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.
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
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
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.
• 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;
• }
• 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.
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.
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.
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.
• #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
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
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.
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
• }
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.
• 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
• 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));
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.
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
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.
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;
• }
• #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
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.
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
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.
• Example :
• #include<iostream>
• #include<conio.h>
• Void display(int x){
• Cout<<“x = “<<x<<endl;
• }
• Int main(){
• Display(25);
• Getch();
• Return 0;
• }
• Output :
• X = 25
PASSING ARGUMENTS BY CONSTANT
• In above program the function call display (5) passes the constant argument (5) to the
function
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
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.
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
• 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;
• }
• 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().
• 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
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.
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
• 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
• 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
• 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;
• }
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
• 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.
DEFAULT ARGUMENTS
• The arguments in which data is initialized during the function declaration are called
default arguments .
• 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
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.
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)
• //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);
• #include<iostream>
• Char grade(int m){
• If(m > 80)
• Return ‘A’;
• Else
• If(m > 60)
return ‘B’;
• Else
• If(m > 40)
• Return ‘C’;
• Else
• Return ‘F’;
• }
• Int main(){
• Int marks;
• Char g;
• Cout<<“enter marks”;
• Cin>>marks;
• G = grade(marks);
• Cout<<“your grade Is”<<g;
• Getch();
• }
• 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
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.
• Void display(int a){
• Cout<<a;
• }
• Void display(){
• Cout<<“welcome”<<endl;
• }
• Int main(){
• Display();
• Display(55);
• Getch();
• Return 0;
• }
• Ouput :
• Welcome
• 55
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:
• 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 ;
• }
• Output of the program
• Output of 2 integers = 77
• Output of 3 integers = 177
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
• #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
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 :
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.
WORK SMART
NOT
HARD
E N D

More Related Content

What's hot

C++ PROGRAMMING BASICS
C++ PROGRAMMING BASICSC++ PROGRAMMING BASICS
C++ PROGRAMMING BASICS
Aami Kakakhel
 

What's hot (20)

Intro to c++
Intro to c++Intro to c++
Intro to c++
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
Advanced c programming in Linux
Advanced c programming in Linux Advanced c programming in Linux
Advanced c programming in Linux
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Lecture01
Lecture01Lecture01
Lecture01
 
c++
 c++  c++
c++
 
C++ PROGRAMMING BASICS
C++ PROGRAMMING BASICSC++ PROGRAMMING BASICS
C++ PROGRAMMING BASICS
 
C++ Programming Language Training in Ambala ! Batra Computer Centre
C++ Programming Language Training in Ambala ! Batra Computer CentreC++ Programming Language Training in Ambala ! Batra Computer Centre
C++ Programming Language Training in Ambala ! Batra Computer Centre
 
45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala
 
Managing console input
Managing console inputManaging console input
Managing console input
 
Introduction to C++
Introduction to C++ Introduction to C++
Introduction to C++
 
basics of c++
basics of c++basics of c++
basics of c++
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)
 
basics of C and c++ by eteaching
basics of C and c++ by eteachingbasics of C and c++ by eteaching
basics of C and c++ by eteaching
 
Console Io Operations
Console Io OperationsConsole Io Operations
Console Io Operations
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programming
 
C++ io manipulation
C++ io manipulationC++ io manipulation
C++ io manipulation
 
Managing console
Managing consoleManaging console
Managing console
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
 

Similar to Programming using c++ tool

C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorial
SURBHI SAROHA
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
rohassanie
 
C tutorials
C tutorialsC tutorials
C tutorials
Amit Kapoor
 
67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf
Rajb54
 
Chap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptxChap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptx
Ronaldo Aditya
 

Similar to Programming using c++ tool (20)

OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorial
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
 
Prog1-L1.pdf
Prog1-L1.pdfProg1-L1.pdf
Prog1-L1.pdf
 
C
CC
C
 
C tutorials
C tutorialsC tutorials
C tutorials
 
67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf67404923-C-Programming-Tutorials-Doc.pdf
67404923-C-Programming-Tutorials-Doc.pdf
 
Chap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptxChap_________________1_Introduction.pptx
Chap_________________1_Introduction.pptx
 
Programming Fundamental Slide lecture no.2 (Section E)
Programming Fundamental Slide lecture no.2 (Section E)Programming Fundamental Slide lecture no.2 (Section E)
Programming Fundamental Slide lecture no.2 (Section E)
 
c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
C Programming
C ProgrammingC Programming
C Programming
 
C++ basics
C++ basicsC++ basics
C++ basics
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Introduction to C++,Computer Science
Introduction to C++,Computer ScienceIntroduction to C++,Computer Science
Introduction to C++,Computer Science
 
C programming language
C programming languageC programming language
C programming language
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
 
Basic c
Basic cBasic c
Basic c
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Recently uploaded (20)

FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 

Programming using c++ tool

  • 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);
  • 43. INPUT / OUTPUT HANDLING • Int main(){ • Char teststr[100]; • Cout<<“enter a string”; • Gets(teststr); • Cout<<“you entered”; • Puts(teststr); • Getch(); • Return 0; }
  • 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();
  • 45. INPUT / OUTPUT HANDLING • Int main(){ • Char ch; • Cout<<“press any keyn”; • Ch = getch(); • Cout<<“you passed:”<<ch<<endl; • Getch(); • Return 0; }
  • 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);
  • 48. INPUT / OUTPUT HANDLING FUNCTION• #include<iostream> • #include<stdio.h> • #include<conio.h> • Uisng namespace std; • Int main(){ • Char ch; • Cout<<“enter character for gender”; • Ch = getchar(); • Cout<<“you have entered”; • Putchar(ch); • Getch(); • Return 0; • }
  • 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>
  • 51. INPUT / OUTPUT HANDLING FUNCTION • Int main(){ • Int x1=2 , x2=4 , x3=6; • Cout<<setw(8)<<“Number”<<setw(20)<<“Square”<<endl • <<setw(8)<<“2”<<setw(20)<<x1*x1<<endl • <<setw(8)<<“4”<<setw(20)<<x2*x2<<endl • <<setw(8)<<“6”<<setw(20)<<x3*x3<<endl; • Getch(); • Return 0; • }
  • 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 : • == • != • > • < • >= • <=
  • 64. OPERATOR IN C++ • Example: • (7 == 5) //false • (5>4) //true • (3! = 2) //true • (6>=6) //true • (5<5) //false
  • 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;
  • 73. OPERATOR IN C++ • Logical expressions: • (x>y)||(x=10)
  • 74. CONTROL STRUCTURE A U T H O R : : A B D U L A H J A N U N I T 4
  • 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; • }
  • 92. • Float per; • Cout<<“enter percentage marks”<<endl; • Cin>>per; • If(per >= 80){ • Cout<<“your grade is A+”<<endl; • Cout<<“excellent”; • }else{ • If(per <80 && per>=70){ • Cout<<“your grade is A”<<endl; • Cout<<“very good”; • }else { • if(per<70 && per>=60){ • Cout<<“your grade is B”<<endl; • Cout<<“Good”; • }else • Cout<<“you are failed, try again”; • } • } • 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; • }
  • 101. • Example 2: • For(int n=10; n>0; n--) • Cout<<n<<“,”; • 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;
  • 108. • Example 2: • Int n=1; • While(n<= 50) • { • Cout<<n<<“”; • if(n%10 == 0) • Cout<<endl; • 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++; • } • }
  • 119. • Example : • Int main(){ • For(int i=1; i<=5; i++) //outer loop • { • For(int j=1; j<=I; j++) //inner loop • Cout<<“$”; • Cout<<endl; • } • Getch(); • Return 0; • }
  • 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;
  • 139. • For(int i=0; i<10; i++) //traverse array • { • If(item!=a[i]) //comparsion • Continue; • Else{ • Cout<<“item”<<item<<“is found at location”<<i+1; • Goto end; • } • } • Cout<<“search unsuccessful:”<<item<<“is not found”; • End: • Getch(); • Return 0; • }
  • 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];
  • 144. ACCESS TWO DIMENSIONAL ARRAYS • Int main(){ • Int I , j, a[2][3] = {15,21,9,84,33,72}; • For(i = 0; I<2; i++) • { • For( j=0; j<3; j++) • Cout<<“arr[“<<i<<”][“<<j<<”] = ”a[i][j]<<“t”; • Cout<<endl; • } • Getch(); • Retrun 0; • }
  • 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; • }
  • 149. • Example 3: • Int main(){ • String str1 = “Hello”; • String str2 = “world”; • String str3 , str4; • Int len; • Str3 = str1; //string copying • Str4 = str1 + str2; • Len = str4.size(); // find the string size • Cout<<“str3 = t”<<str3<<endl; • Cout<<“str4 = t”<<str4<<endl; • Cout<<“length of str4 = t”<<len<<endl; • Getch(); • }
  • 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.
  • 151. • Example // string concatenation program • Int main(){ • Char firstname[15] = “SSC”; • Char lastname[15] = “computer”; • Strcat(firstname,lastname); • Cout<<firstname; • Getch(); • Return 0; } Output:: SSC computer
  • 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.
  • 164. TYPES OF FUNCTIONS •Built in function •User defined function
  • 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; }
  • 173. COMPONENTS OF FUNCTION • Function prototype / declaration • Function definition • Function call
  • 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.
  • 210. • Example : • #include<iostream> • #include<conio.h> • Void display(int x){ • Cout<<“x = “<<x<<endl; • } • Int main(){ • Display(25); • Getch(); • Return 0; • } • Output : • X = 25
  • 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);
  • 230. • #include<iostream> • Char grade(int m){ • If(m > 80) • Return ‘A’; • Else • If(m > 60) return ‘B’; • Else • If(m > 40) • Return ‘C’; • Else • Return ‘F’; • } • Int main(){ • Int marks; • Char g; • Cout<<“enter marks”; • Cin>>marks; • G = grade(marks); • Cout<<“your grade Is”<<g; • Getch(); • }
  • 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.
  • 233. • Void display(int a){ • Cout<<a; • } • Void display(){ • Cout<<“welcome”<<endl; • } • Int main(){ • Display(); • Display(55); • Getch(); • Return 0; • } • Ouput : • Welcome • 55
  • 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.