Sei sulla pagina 1di 170

TECHNOLOGY

KOVAIPUDUR,COIMBATORE – 42

LINUX & PROGRAMMING IN


C++
MODULE II

Presented by,

Sangeetha T
Assistant Professor,
Dept of IT,
SKCET.
1
i ng
m m
gr a
P ro
Introduction

• Programming can be defined as the process of


taking an algorithm and encoding it into notation, so
that it can be executed by a computer.

• Basically, a creative process was done by


programmers to instruct a computer on how to do a
task.
Programming Basics

• Programmers give machines a set of instructions to


make it do a certain task. 

• Instructions are given through the editor which then


the programming language follows and does certain
tasks which affect the state of the computer.
Cont…

Smartphones,
home appliances,
commercial tools, etc.

• All of them have software programs which can only be made to do


certain tasks with the help of programming language.
Cont…

• Programming language can be applied for following programs.

Applications
Servers
System Programs
s
ig m
a d
a r
g P
in
m
a m
g r
ro
P
Definition

• Programming paradigms can be defined as various


systems of ideas that have been used to guide the
design and architecture of various programming
languages.
FOUR WAYS OF PROGRAMMING
PARADIGMS
• Monolithic Programming
• Procedural Programming
• Structured Programming
• Object Oriented Programming

9
Monolithic Programming
• The program is written with a single function

• A program is not divided into parts

• When the program size increase its leads to difficulty

• The data variables are declared as global & the statements are
written in sequence

• The program contains jump statements such as goto

10
CONTD…

• The global data can be accessed from any portion of the program

• Due to this reason the data is not fully protected

• The concepts of subprograms not exist

• It is useful for small programs

• Eg:FORTAN,BASIC,ASSEMBLY LANGUAGE

11
Procedural Programming
(Procedure oriented)
 Top down approach
 Procedures, also known as functions or methods simply contains a
series of computational(Algorithmic) steps to be carried out.
 procedural programming specify the syntax and procedure to write
a program.
 Big program is a divided into small pieces.
 Functions are more important than data.
 Input- arguments, output-return values.

12
Contd…
Contd…

•  A developer who uses Procedural Programming might plan out the


program without the idea of recycling code.
•  In the case of a grading system, a Procedural Programming
programmer may think in terms of how the program should execute
as the code is executed.
• Ex. are C, Algol etc.

14
Structured Programming Concept(Modular
Prog.)
Structured programming techniques assist the programmer in
writing effective error free programs.

Top down approach

Overall program structure divided into separate subsections

This technique help to make isolated small pieces of code easier


to understand without having to understand the whole program
at once.

15
Contd…
After a piece has been tested and studied in detail individually,
it is than integrated into the overall program structure.

It is possible to write any computer program by using only three


(3) basic control structures (logical concept’s) :
• Sequence instructions

• Decision Structure(if-else)

• Loop (While, Do While,…)

Ex. are Pascal , C, ADA.

16
17
Elements of OOP

Definition of OOP:
“Object oriented programming is a programming methodology that
associates data structures with a set of operators which act upon it.”
Basic Concepts of OOPS

• Objects
• Classes
• Data Abstraction and Encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message passing
Objects
• OOP uses objects as its fundamental building blocks.
• Objects are the basic run-time entities in an object-oriented
system.
• Every object is associated with data and functions which define
meaningful operations on that object.
• Object is a real world existing entity.
• Object is an Instance of a particular class.
Contd…

24
Object

Operation

Operation Attributes Operation

Operation
Example: StudentObject

Enroll()

st_name
st_id
Performa Displayinfo
branch
nce() ()
semester

Result()
Cont…
Class

• Class is a collection of similar objects.

• A class is a template definition of the methods


and variables for a particular kind of object.

• class is the blue print from which an individual


objects are created.
Cont…
Cont…

• Let's take an example of developing a pet


management system, specially meant for dogs.

• Various information about the dogs like different


- Breeds of the dogs,
-age
-size
Need to model real life beings, i.e., dogs into software entities.
Three different breeds of dogs below.
Contd…

•  Common behaviors
• sleep, sit, eat,run
Contd…
Abstraction

• Abstraction is a process where you show only


“relevant” data and “hide” unnecessary details of an
object from the user.

Data abstraction is a mechanism of exposing only


the interfaces and hiding the implementation details
from the user.
Cont…

• Consider your mobile phone


- what buttons are to be pressed to
send a message or make a call.

-How your calls are connected is all abstracted


away from the user.
Cont…
Cont…
Encapsulation

• It is the process of combining data and functions into a single unit.

• It binds together the data and functions that manipulate the data,
and that keeps both safe from outside interference and misuse. 
Cont…

•  You can think of encapsulation as "data-hiding",


• allowing certain parts of an object to be visible,
• while other parts remain hidden.
Inheritance

• “Inheritance is the mechanism to provides the power of reusability


and extendibility.”
• “Inheritance is the process by which one object can acquire the
properties of another
object.”
• The process of obtaining the data members and methods from one
class to another class is known as inheritance. 
Cont…

• In the inheritance the class which is give data


members and methods is known as base or super or
parent class.

• The class which is taking the data members and


methods is known as sub or derived or child class.
Inheritance
Contd…

Point

Line
Types of Inheritance

• Single inheritance
• Multiple inheritance
• Hierarchical inheritance
• Multilevel inheritance
• Hybrid inheritance
Polymorphism

• Polymorphism means that the same thing can exist in two forms.

• “Polymorphism is in short the ability to call different functions by just


using one type of function call.”
Message Passing
StudentObject FacultyObject

Performance

MgmtObject Performance
Result
Overview of c++

• C++ was developed by Bjarne Stroustrup in the 1980 at Bell Labs.


• The name C++ comes from the C increment operator ++, which adds
1 to the value of a variable.
• The C++ is an extensive version of language C.
• Every C program can be consider as C++ Program but reverse is not
true.
• C++ supports for the Structured programming and also it fully
supports OOP
• Encapsulation
• Data hiding
• Inheritance
• Polymorphism.
Contd…

• C++ is also called as “C with classes“.


• Free-form
• Multi-paradigm
• Compiled
• General-purpose programming language.
• Intermediate-level language,
• Most of the C++ concepts are considered as basic concepts for “Java
Programming“.
C++ Design Aims : Why C++ was designed ?

• C++ makes programming more enjoyable for serious programmers.


• C++ is a general-purpose programming language that
• is a better C
• supports data abstraction
• supports object-oriented programming
Difference between c and c++
C C++

C is the function or procedure programming language. C++ is the object oriented programming language.

Top down approach is used in C. Bottom up approach is used in C++.

C++ is secure, because oop's concept is available. Here Data is


C is less secure than C++
hidden and can't be accessed by external functions.

In C programming variable declaration is possible only top of


In C++ you can any where declare variable.
program.

In C, namespace feature is not available. In C++, namespace feature is present.

C is a middle level language. C++ is a high level language.

In this programming, programs are divided into modules and In this programming, programs are divided into classes and
functions. functions.

Here no exception handling concept is available It support exception handling concept.

C uses scanf() and printf() function for standard input and


C++ uses cin>> and cout<< for standard input and output.
output.

Features like function overloading and operator overloading is


C++ supports function overloading and operator overloading.
not present.

C program file is saved with .C extension. C++ program file is saved with .CPP extension.
67
Character Set

• C++ The characters in C++ are grouped into the following categories:

68
Types Character Set
Lower Case Letters a-z
Upper Case Letters A-Z
Digits 0-9
Special Characters !@#$%^&*
White Spaces Tab Or New line Or Space
C++ Character set

A – Z= 26 = 65 to 90
a – z = 26 = 97 to 122
0 – 9 = 10 = 48 to 57
Symbols = 34= other values ASCII Values
TOTAL = 96
Character Set
• Valid C++ Characters: Special Characters are listed below:
Symbol Meaning Sym Meaning Symbol Meaning
bol

 ~  Tilde  + Plus sign  ”  Quotation mark

70
 ! Exclamation mark  |  Vertical bar  ;  Semicolon

 Opening angle
 # Number sign  \  Backslash  <
bracket
 $ Dollar sign  `  Apostrophe  >  Closing angle bracket
% Percent sign  –  Minus sign  ?  Question mark
 ^ Caret  =  Equal to sign  ,  Comma
 & Ampersand  {  Left brace  . Period
 * Asterisk  }  Right brace  /  Slash
( Left parenthesis  [  Left bracket

 ) Right parenthesis ]  Right bracket

_ Underscore  :   Colon
Tokens

1. Keywords
int ,switch,class
2.Variables
marks,age,name
3.Constants
121,350.75,2e3
4.Special Characters
#,?,~
5.Operators
+,-,: ?

71
RESERVED KEYWORDS

• Has predefined functionality


• C++ has 48 keywords
• Written in only in lower case
RESERVED KEYWORDS

delete boolean break enum


case volatile catch char
const continue default do
else asm extern union
float for auto unsigned
if inline register class
int template long double
virtual operator signed goto
protected public sizeof return
static struct this new
friend throw typedef private
try switch while short
IDENTIFIERS

• Programmer-designed tokens
• Meaningful & short
• Long enough to understand
• C++ rules for Identifiers
- alphabets, digits, underscore
- should not start with digits.
- Case sensitive
- Unlimited length
- Declared anywhere
Variable in C++
Variable declarations
•This is the process of allocating sufficient memory space for the
data in term of variable.
Syntax
Datatype variable_name;
eg: int a;
Variable initialization
•It is the process of allocating sufficient memory space with user
defined values.
Syntax
Datatype variable_name=value;
eg: int b = 30;

75
CONTD…

Variable assignment
•It is a process of assigning a value to a variable.

Syntax
Variable_Name = value
Example
int a= 20;
int b;

76
C++ Constants/literals

Numeric Constants Non Numeric constants

Integer Constants Character Constants

Real Constants String Constants

Decimal, Octal, Hex


LITERALS

• Sequence of char. that represents constant values to be stored in


variables

• C++ literals are:


- Integer literals: 1,2,456,0xffff
- Floating_point literals: 4.67,3.14E-05
- Charater literals: ‘A’, ‘B’
- String literals: “ABC”, “TOTAL”
LITERALS (Symbolic Constants)

• Using #define preprocessor directive


#define Symbol Name ConstantValue
ex: #define Max_Var 100

• Using const qualifier


ex: const int size=10;

• Using enum keyword


ex: enum{X,Y,Z};
defines const X=0;
defines const Y=0;
defines const Z=0;
OPERATORS

• Is a symbol that takes more than one operands & operates on them
to produce a result.
- Arithmetic
- Relational
- Logical
- Assignment
- increment/Decrement
- conditional
- scope resolution(::)
- special operators: new, delete, endl, setw
S. No OPERATORS SYMBOLS

1. Arithmetic +,-,/,*,%
2. Logical &&,||,!
3. Relational <,>,>=,<=,==,!=
4. Assignment =
5. Increment ++
6. Decrement --
7. Comma ,
8. Conditional (Ternary) ?:
9. Bitwise &,|,^,!,>>,<<
10. Special Operator Sizeof
11. Extraction >>
12. Insertion <<
13. Dynamic Memory Allocator New
14. Dynamic memory De-allocator Delete
SEPARATORS

• Symbols used to indicate where groups of code are divided &


arranged
• C++ separators:
()parentheses .. Methods, precedence in exp
{} braces .. Arrays init., block of codes, scopes
; semicolon
,comma.. Separate multiple identifiers, chain more than one stmt
. Period.. Data members, methods
[]Brackets.. Array referencing/dereferencing
DATA TYPES

• Data type is a keyword used to identify type of data.


• In general every programming language is containing three categories
of data types. They are
Fundamental or primitive data types
Derived data types
User defined data types

83
C++ Data types
S. No DATA TYPE Size (in bytes) RANGE

1 Short int/int 2 -32768 to +32767

2 Unsigned short 2 0 to 65535


int
3 long int 4 -2147483648 to 2147483647

4 Float 4 3.4e-38 to 3.4e+38

5 Char 1 -128 to 127

6 Unsigned char 1 0 to 255

7 Unsigned long int 4 0 to 4294967295

8 Double 8 1.7e-308 to 1.7e+308

9 Long double 10 1.7e-308 to 1.7e+308


Structure of C++ Program : Layout of C++
Program
• C++ Programming language is most popular language after C
Programming language.
• C++ is first Object oriented programming language.
• We have summarize structure of C++ Program in the following Picture

Structure of C++ Program
Some streams in<iostream.h>

• cout
• cin
• Operator << (Insertion)
• Operator >> (Extraction)
• endl

87
C vs C++

C Program C++ Program


#include<stdio.h> #include<iostream.h>
void main() void main()
{
{
int a;
int a; cout<<“Enter the value”;
printf (“ Enter the value ”); cin>>a;
scanf(“%d”, &a); cout<<endl<<“a=”<<a;
printf(“\n a=%d”,a); }
}
C++ Program :simple basic program

#include <iostream>
using namespace std;
int main()
{
int a,b,c;
cout<<”enter the number”<<endl;
cin>>a>>b;
c=a+b;
cout <<“the sum is”<<c;
return 0;
}
Contd…

#include <iostream>
int main()
{
int a,b,c;
std::cout<<”enter the number”;
cin>>a>>b;
c=a+b;
std::cout <<“the sum is”<<c;
return 0;
}

90
In trubo c++
#include <iostream.h>
#include<conio.h>
int main()
{
int a,b,c;
clrscr();
cout<<”enter the number”<<endl;
cin>>a>>b;
c=a+b;
cout <<“the sum is”<<c;
getch();
return 0;
}

91
Control Structures in C++
 Control structures control the flow of execution in a program or
function.
• A combination of individual instructions into a single logical unit with one entry point
and one exit point

UNI
T
III /
DEP
T OF
IT /
SKC
ET
Control Structures in C++
A realistic C program may require that a logical test be carried out at
some particular point within the program.
One of several possible actions will then be carried out depending on
the outcome of the logical test. This is known as branching.

93
There is also a special kind of branching, called selection, in which one
group of statements is selected from several available groups.
In addition, the program may require that a group of instructions be
executed repeatedly, until some logical condition has been satisfied.
This is known as looping.

UNI
T
III /
DEP
T OF
IT /
SKC
ET
C++ STATEMENTS
C++ stmts

Exp Labelled Guarding


stmt stmt stmt

Control
stmt

Selection stmt Iteration stmt Jump stmt

If contin
If switch while do for break
ue
return
else
Three kinds of execution flow
◦ Sequence:
 The execution of the program is sequential.

◦ Selection / Branching
 A control structure which chooses alternative to execute/program chooses to follow one branch or
another

 Example: if, if/else, switch


◦ Repetition / Looping
 A control structure which repeats a group of statements.

 Example: while, do/while, for


UNI
T
III /
DEP
T OF
IT /
SKC
ET
 Various control statements are available in C++ which makes extensive use of logical expressions and
compound statements.
 Logical expressions are constructed using

 relational operators(<,<=,>,>=,= = ,! =) and


 logical operators (&& , || , ! )
Examples:
 count <= 100, sqrt(a+b+c) > 0.005
 answer == 0, balance >= cutoff
 (count <= 100) && (ch = =‘A’ )
 (balance < 1000.0) || (status == ' R ' )
 (answer < 0) || ((answer > 5 . 0 ) && (answer <= 10.0))
 if(3+2%5) , if(a=10) , if(-5)
UNI
T
III /
DEP
T OF
IT /
SKC
ET
BRANCHING
• Simple if
• if-else
• if-else if ladder
• Nested if-else
• Switch-Case

UNI
T
III /
DEP
T OF
IT /
SKC
ET
The simple if Statement
• The if statement has the following syntax:

Condition is an expression that is


either false (represented by 0) or
if is a C++ true (represented by 1/non-zero).
reserved word

if ( condition )
statement;

If the condition is true, the statement is executed.


If the condition is false, the statement is not executed ,control UNI
comes out T
III /
DEP
T OF
IT /
SKC
ET
The if Statement- Example
#include <iostream>
using namespace std;
int main()
{
int num;
cout<<"Enter a number less than 10\n";
cin>>num;
if(num<10) /*If test condition is true, statement above will be executed, otherwise it
will not be executed */
{
cout<<“U r obedient”;
}
return 0;
} UNI
OUTPUT OUTPUT T
Enter a number less than 10 Enter a number less than 10 III /
7 12 DEP
U r obedient T OF
IT /
SKC
ET
The simple if Statement-example
#include <iostream>
using namespace std;
int main()
{ OUTPUT 1
int m,n; m=40 n=40
cin>>m>>n; m and n are equal
Thank you
if (m == n)
{
cout<<"m and n are equal"; OUTPUT 2
} m=40 n=42
cout<<“Thank you”; Thank you
}
UNI
T
III /
DEP
T OF
IT /
SKC
ET
The if-else Statement
An if statement can be followed by an optional else statement, which
executes when the boolean expression is false.
Syntax:
if(boolean_expression) // eg: A>0
{
True statements; // A is positive
else
{
False statements; //B is negative
}

UNI
T
III /
DEP
T OF
IT /
SKC
ET
The if-else Statement- flow
#include <iostream>
using namespace std;
int main()
{
int age;
cin>>age;
if (age>= 18)
{
cout<<“Eligible";
}
else
cout<<“Not eligible”;
}
OUTPUT 1 OUTPUT 2 UNI
T
Age=30 Age=12 III /
Eligible Not Eligible DEP
T OF
IT /
SKC
ET
The if-else Statement-Program to find the largest of 2 numbers
#include <iostream>
using namespace std;
int main( )
{
int a,b ;
cout<<"Enter numbers a and b\n";
cin>>a>>b;
if(a>b)
cout<<“ largest is:“<<a;
else
cout<“largest is:“<<b;
UNI
return 0; T
III /
} DEP
T OF
IT /
SKC
ET
The if-else Statement-Program to find the given number is odd or even
int main( )
{
int num;
cout<<"Enter a number you want to check.\n“;
cin>>num;
if((num%2)==0) //checking whether remainder is 0 or not.
cout<<“ The even no is:”<<num;
else
cout<<“the odd no is:“<<num;
return 0;
}
OUTPUT
Enter a number you want to check. UNI
25 T
III /
25 is odd.
DEP
Enter a number you want to check. T OF
2 IT /
2 is even. SKC
ET
Sample programs
• In a company an employee is paid as under:
• If his basic salary is less than Rs. 1500,
then HRA = 10% of basic salary and
DA = 90% of basic salary.
• If his salary is either equal to or above Rs. 1500,
then HRA = Rs. 500 and DA = 98% of basic salary.
• If the employee's salary is input through the keyboard write a program
to find his gross salary.

UNI
T
III /
DEP
T OF
IT /
SKC
ET
(if...elseif....else / else-if ladder Statement)
The if...else if statement is used when program requires more than one test
expression

if (test expression1)
{
statement/s to be executed if test expression1 is true;
}
else if(test expression2)
{
statement/s to be executed if test expression1 is false and 2 is true;
}
.
.
.
else
{
UNI
statements to be executed if all test expressions are false; T
} III /
DEP
T OF
IT /
SKC
ET
To print given number is positive or negative or zero-
using elseif ladder
#include <iostream>
using namespace std; else if (num < 0)
int main() {
{ cout<<“The number is
int num; negative\n“<<num;
cout<<"Enter a number \n";
}
cin>>num;
if (num > 0)
else if (num = = 0)
{ {
cout<<“The number is cout<<“number is zero
positive\n“<<num; “;
}
} UNI
cout<<“Thank you”; IIIT /
} DEP
T OF
IT /
SKC
ET
Calculate the EB bill using if-else-if ladder

Get the no. of units (n)


Units 1 to 100 Amount: Rs. 3.00 per unit
Units 101 to 250 Amount: Rs. 4.50 per unit
Units 251 to 350 Amount: Rs. 5.00 per unit
More than 350 Amount: Rs. 7.00 per unit

UNI
T
III /
DEP
T OF
IT /
SKC
ET
e n t
t e m
h Sta
itc
Sw

109
Selection-Using Switch-CASE

• A multiple selection structure is useful when an algorithm contains


series of decisions in which a variable/ expression is tested separately for
one of the several possible integral values

• A switch statement allows a variable to be tested for equality against a


list of values. Each value is called a case, and the variable being
switched on is checked for each switch case.

UNI
T
III /
DEP
T OF
IT /
SKC
ET
Switch Statement Syntax
switch(expr/var)
{
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
} UNI
T
III /
DEP
T OF
IT /
SKC
ET
Flow of execution-switch

UNI
T
III /
DEP
T OF
IT /
SKC
ET
Rules in switch
• All case expressions must be different. Expression must evaluate to an integer.

• First the expression is evaluated. Then the value of expression is compared with the
case expressions. The execution begins at the case statement, whose case expression

113
matches. All the statements below are executed.
• If default is present and if no other case matches then default statement is executed

UNI
T
III /
DEP
T OF
IT /
SKC
ET
Rules-Contd….

 The expression used in a switch statement must have an integral.

 You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.

114
 The constant-expression for a case must be the same data type as the
variable in the switch, and it must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.

UNI
T
III /
DEP
T OF
IT /
SKC
ET
Rules-Contd…
 When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow
of control will fall through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must
appear at the end of the switch. The default case can be used for
performing a task when none of the cases is true. No break is needed
in the default case.
UNI
T
III /
DEP
T OF
IT /
SKC
ET
Example 1
#include <iostream>
case 4:
using namespace std; cout<<“Thursday\n”;
cin>>day; break ;
switch ( day ) case 5:
{
cout<<“Friday\n”;
case 0: break ;
cout<<“Sunday\n” ;
case 6:
break ;
cout<<“Saturday\n”;
case 1: break ;
cout<<“Monday\n” ;
default:
break ;
cout<<“Error -- invalid
case 2: day.\n”;
cout<<“Tuesday\n”; break ;
break ; }
case 3:
cout<<“Wednesday\n”;
break ;

116
Example 2
#include <iostream> case'e':
using namespace std; case‘I':
int main() case'i':
case'O':
{
case'o':
char a; case'U':
cout<<"Enter any Alphabet : "; case'u': cout<<"It is a Vowel";
cin>>a; break;
default: cout<<"It is a Consonent";
switch (a)
}
{ }
case'A':
case'a':
case'E':
117
Example 3
#include <iostream> cout<<"Well done\n" ;
using namespace std; break;
int main () case 'D' :
{ cout<<"You passed\n" ;
char grade; break;
cin>>grade; case 'F' :
switch(grade) cout<<"Better try again\n" ;
{ break;
case 'A' : default :
cout<<"Excellent!\n" ; cout<<"Invalid grade\n" ;
break; }
case 'B' : cout<<"Your grade is %c\n", grade ;
}
case 'C' :

118
Example 4 Menu driven Calculator
#include <iostream> case 2:c=a-b;
using namespace std; cout<<“Difference is :\n“<<c ;
int main () break;
{ case 3:c=a*b;
int a,b,c,choice; cout<<“Multiply is :\n“<<c ;
cin>>a>>b; break;
cout<<“Menu \n”<<“1.Add case 4:c=a/b;
“<<“2.Sub”<<“ 3.Mul cout<<“Division is :\n“<<c;
“<<“4.Div” <<“5.Mod\n”;
break;
cin>>choice;
case 5:c=a%b;
switch(choice)
cout<<“Remainder is :\n“<<c ;
{
break;
case 1 :c=a+b;
default :
cout<<“Sum is :\n“<<c );
cout<<"Invalid Choice\n" ; } }
break;
119
Switch vs if-else ladder
• Cannot do with switch:
1. A float expression cannot be tested .
2. Cases cannot have variable expressions(eg: case a+3)
3. Multiple cases cannot use same expressions
Eg: case 3: case 1+2:
• Switch is faster than if-else ladder when more conditions to be tested
(because switch matches the value but in if-else all conditions are
evaluated)

UNI
T
III /
DEP
T OF
IT /
SKC
ET
Switch vs if-else ladder
• A nested if-else structure is just as efficient as a switch
statement.

• However, a switch statement may be easier to read.

• Also, it is easier to add new cases to a switch statement


than to a nested if-else structure.
UNI
T
III /
DEP
T OF
IT /
SKC
ET
Why Repetition

• In most software, the statements in the program may need to repeat for
many times.
• e.g., calculate the Simple interest for 10 users.
• It’s not elegant to write the code 10 times.

• Drawback:
• Lines of code increases
• Memory space wasted
• Compilation time increases

UNI
T
III /
DEP
T OF
IT /
SKC
ET
Decision Making- LOOPING
Repetition / Looping
A control structure which repeats a group of statements.
Example:

UNI
T
III /
DEP
T OF
IT /
SKC
ET
While Loop
 It is pre tested loop. It is used when we have to execute a part of code for
‘n’ numbers of times until the condition is true.

124
 Syntax:

while (Expression/Condition)
{
Loop body/Statements;
}
UNI
T
III /
DEP
T OF
IT /
SKC
ET
Calculate Sum of digits in a Number -while
#include<iostream>
using namespace std;
int main()
{
   int n, digit, temp, sum=0;
   cout<<"Enter the Any Integer No: \n";
   cin>>n;
   temp=n;
   while(n!=0)
   {
     digit = n%10;
     sum=sum+ digit;
    n=n/10;
   }
   cout<<“Number is    :\n“<<temp;
   cout<<"Sum of digit is:\n“<<sum;
 }

UNI
T
III /
DEP
T OF
IT /
SKC
ET
Calculate reverse of a Number(palindrome)-
while loop
#include<iostream>
using namespace std;
int main()
{
int n, rev = 0, rem,temp;
cout<<"Enter an integer: ";
cin>>n;
temp=n;
while(n != 0)
{
rem = n%10;
rev = rev*10 + rem;
n =n/ 10; UNI
if(temp==rev) T
}
cout<< temp<<is a palindrome”,; III /
cout<<“Number is   :\n“<<temp; DEP
cout<<"Reversed Number = “<< rev; T OF
IT /
} SKC
ET
To check given number is armstrong or not
void main()
{
int n, temp, rem,result=0;
cout<<"Enter a three digit integer: ";
cin>>n;
temp= n;
while (n!= 0)
{
rem = n%10;
result =result+ rem*rem*rem;
n=n/10;
}
if(result == temp)
cout<<temp<<“ is an Armstrong number";
else
cout<<temp<<“is not an Armstrong number";
} UNI
T
III /
DEP
T OF
IT /
SKC
ET
To check given number is prime or not
void main( )
{
int num, i ;
cout<<"Enter a number " ;
cin>>num ;
i=2;
while ( i <= num - 1 )
{
if ( num % i == 0 )

128
{
cout<< "Not a prime number" ;
break ;
}
i++ ;
}
if ( i == num )
cout<<"Prime number" ;
}

UNI
T
III /
DEP
T OF
IT /
10/17/2016 PSTC SKC
ET
do...while loop

 A do...while loop is similar to a while loop, except that a do...while loop is


guaranteed to execute at least one time

 Syntax:

do
{
statement(s);
UNI
} T
III /
while( condition ); DEP
T OF
IT /
SKC
ET
Calculate factorial -while loop
#include<iostream>
using namespace std; Sample output:
int main() Enter a number: 5
{ Factorial of 5 is: 120
  int i=1,fact=1,num;
 cout<<"Enter a number: ";
  cin>>num;
   while(i<=num)
{
      fact=fact*i;
       i++;
  } UNI
T
  cout<<"Factorial is:“<<num<<fact; III /
DEP
} T OF
IT /
SKC
ET
For loop
• A for loop is a repetition control structure that allows you to efficiently
write a loop that needs to execute a specific number of times.

• SYNTAX:
for (initialization expression;
loop repetition condition;
update expression)
{
Statements;
}
UNI
T
III /
DEP
T OF
IT /
SKC
ET
To print Fibonacci series
#include<iostream>  
using namespace std;
int main()
{
int n, first = 0, second = 1, next, c;  
cout<<"Enter the number of terms\n";
cin>>n;  
cout<<"First terms of Fibonacci series are \n“<<n;
  for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
cout<<“\n“<<next); UNI
T

III /
return 0; DEP
} T OF
IT /
SKC
ET
•An Array is a collection of same data type. The elements of an
array are referred by a common name and are differentiate from
one another by their position with in an array. The elements of
an array can be of any data type but all elements in an array must
be of the same type.
The general form of declaring a array is
type array_name[size];
where type is a valid datatype, array_name is the name of the
array and size is the number of elements that array_name
contains.
Example:
int A[100];
 int  data type of elements that an array
A  name of array 100  size of an array
The individual elements of an array can be referenced by means of its subscript (or
index)
Suppose A is an array of 20 elements, we can reference each element as
 A[0]  1st element
A[1]  2nd element
A[2]  3rd element
:
:
A[19]  20th element
Note: Subscript enclosed within parenthesis.
In C subscript starts from 0. That is, if we declare an array of size n, then we can refer
the elements from 0 to (n-1)th element.
Arrays are of 3 types. They are
Single Dimensional Array
Two Dimensional Array
Multi Dimensional Array
•The general form of Single Dimensional array is:
data type variable[size];
Example:
int A[20];

Initialization of arrays during declaration


•Similar to other datatypes, the array also can be initialized at the
time of declaration.
int num[5] ={3,2,1,5,4};
char name[15] = {‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’,’s’};
float rate[] = {20.5,15.75,12.34};
Program illustrating Single Dimensional Array
#include<iostream>
using namespace std;
void main()
{
int a[5],i;
cout<<“Enter 5 elements into an array:”;
for(i=0;i<=4;i++)
cin>>a[i];
cout<<“The 5 elements are:”;
for(i=0;i<=4;i++)
cout<<a[i];
}
Program Illustrating Two Dimensional arrray
#include<iostream>
using namespace std;
int main()
{
int marks[10],i,n,sum=0;
cout<<“Enter no elements into array:”;
cin>>n;
for(i=0;i<=n;i++)
{
cout<<“enter the marks of the students \n”;
cin>>marks[i];
sum=sum+marks[i];
}
cout<<“sum”<<sum;
}
Max and Min elements of an array
#include<iostream.h> min=a[1];
#include<conio.h> for(i=0;i<n;i++){
void main() if(max<a[i])
{ {
int a[20],n,i,max=0,min; max=a[i];}
clrscr(); if(min>a[i])
cout<<"\n Enter the number of {
elements for 1-D array : "; min=a[i];
cin>>n; }}
for(i=0;i<n;i++){ cout<<"\n Greatest element from
cout<<"\n Enter element : "; above array inserted is :"<<max;
cin>>a[i]; cout<<"\n smallest element from
} above array is :"<<min;
getch();
}
138
Logic of Sorting and searching an
elements in an array
Sorting Searching

for (i = 0; i < n; ++i) for(i=0;i<n;i++)


{ if(key==a[i])
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{a = number[i];
number[i] = number[j];
number[j] = a;
}}}

139
Inserting an elements in an array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i,pos,item,n;
clrscr();
printf("Enter the no of elements in an array \n");
scanf("%d",&n);
printf("enter the array elements");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

140
printf("enter the item to be inserted");
scanf("%d",&item);
printf("enter the position to be inserted");
scanf("%d",&pos);
for(i=n-1;i>=pos;i--)
{
a[i+1]=a[i];
}
n++;
a[i+1]=item;
for(i=0;i<n;i++)
{
printf("%d \t",a[i]);
}
printf("\n");
getch();
}
141
Deleting an elements in an array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i,pos,item,n;
clrscr();
printf("Enter the no of elements in an array \n");
scanf("%d",&n);
printf("enter the array elements");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
142
printf("enter the item to be deleted");
scanf("%d",&item);
printf("enter the position to be deleted");
scanf("%d",&pos);
for(i=pos;i<n;i++)
{
a[i]=a[i+1];
}
n--;
for(i=0;i<n;i++)
{
printf("%d \t",a[i]);
}
printf("\n");
getch();
}
143
•The general form of Two-Dimensional Arrays is
type array name[row_size][column size];
Example:
int a[2][2];

Initializing Two-Dimensional Arrays


•Like the one-dimensional arrays, following their declaration with a list of
initial values enclosed in braces may initialize two-dimensional arrays. For
Example,
int a[2][2] ={1,2,5,4};
•Initializes the elements of the first row to zero and the second row to one.
The initialization is done row by row. The above statement can be
equivalently written as
int a[2][2]={{1,2},{5,4}};
Addition of two matrices
#include<iostream.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j;
clrscr();
cout<<"Enter the first matrix \n";
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cin>>a[i][j];
}
}
145
cout<<"Enter the second for(i=0;i<2;i++)
matrix \n"; {
for(i=0;i<2;i++) for(j=0;j<2;j++)
{ {
for(j=0;j<2;j++) cout<<c[i][j];
{ cout<<" ";
cin>>b[i][j]; }
}} cout<<endl;
cout<<“Addition of two matrix }
\n";
getch();
for(i=0;i<2;i++)
}
{
for(j=0;j<2;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
146
Logic of transpose and diagonal matrix

• Transpose
b[j][i]=a[i][j] or b[i][j]=a[j][i]
• Diagonal
if(i==j)
{
sum=sum+a[i][j];
}

147
Matrix Multiplication
#include<iostream.h>
#include<conio.h>
void main()
{
int row1,col1,row2,col2;
int i,j,k;
int mat1[5][5],mat2[5][5],multi[5][5];
clrscr();
cout<<"enter the row for first matrix\n";
cin>>row1;
cout<<"enter column for first matrix\n";
cin>>col1;
cout<<"enter elements of first matrix\n";
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
cin>>mat1[i][j];
}
}
cout<<"enter the row of second matrix\n";
cin>>row2;
cout<<"enter column for second matrix\n";
cin>>col2;
cout<<"enter elements of second matrix\n";
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
cin>>mat2[i][j];
}
}
if(col1==row2)
{
cout<<"multiplication of matrices is\n";
for(i=0;i<row1;i++){
for(j=0;j<col1;j++){
multi[i][j]=0;
for(k=0;k<col1;k++)
{
multi[i][j]+=mat1[i][k]*mat2[k][j];
}
cout<<multi[i][j];
}
cout<<endl;
}
}
else
cout<<"multiplication is not compatible";
getch();
}
Functions are building blocks of C. Function performs the
same set of instructions on different sets of data or at different
portions of a program.
C functions can be classified into two categories, namely
1.Library functions and
2.User-defined functions.
main is an example of user-defined functions.
printf and scanf belong to the category of library functions.
The main distinction between these two categories is that
library functions are not required to be written by us whereas a
user-defined function has to be developed by the user at the
time of writing a program.
It facilitates top-down modular programming. In this
programming style, the high level logic of the overall problem is
solved first while the details of each lower-level function are
addressed later.
The length of a source program can be reduced by using
functions at appropriate places. This factor is particularly
critical with microcomputers where memory space is limited.
Many other programs may use a function. This means that a
C programmer can build on what others have already done,
instead of starting over, from scratch.  
As mentioned earlier, it is easy to locate and isolate a faulty
function for further investigations.
Elements of user-defined
functions
1.Function/Prototype Declaration
2.Function Definition
3.Function Call
Function prototype(Declaration):
• Every function in C++ programming should be declared before
they are used. These type of declaration are also called function
prototype. Function prototype gives compiler information about
function name, type of arguments to be passed and return type.
Syntax of function prototype

return_type function_name(type(1) argument(1),....,type(n)


argument(n));
• The example,int add(int a, int b); is a function prototype which provides following information
to the compiler:
 name of the function is add()
 return type of the function is int.
 two arguments of type int are passed to function.
• Function prototype are not needed if user-definition function is written before main() function .
Function call
• Control of the program cannot be transferred to user-defined
function unless it is called invoked.
• Syntax of function call

function_name(argument(1),....argument(n));

• In the above example, function call is made using statement


add(num1,num2); from main(). This make the control of
program jump from that statement to function definition and
executes the codes inside that function.
Function definition

• Function definition contains programming codes to perform


specific task.
• Syntax of function definition
return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
//body of function
}
Return Statement

• Return statement is used for returning a value from function


definition to calling function.
• Syntax of return statement
return (expression);
For example:
return a; return (a+b);
• In above example, value of variable add in add() function is
returned and that value is stored in variable sum in main()
function. The data type of expression in return statement
should also match the return type of function.
User-defined functions can be categorized as:
1.Function with no arguments and no return value
2.Function with no arguments and return value
3.Function with arguments but no return value
4.Function with arguments and return value.
Program
#include<iostream.h>
using namespace std;
 void sum();   /*declaring prototype of function*/
 void main()
 {
    sum();      /* calling function,
   }

int sum ( )
 {
 int a,b, result;
  cout<<"\n Enter the two numbers : ";
  cin>>a>>b;    /* taking two numbers as input*/
  result = a + b ;   /*adding two numbers*/
  cout<<“the result is”<<result;
 }
Program
#include<iostream.h>
using namespace std;
 int sum();   /*declaring prototype of function*/
 void main()
 {
   int c;
c=sum( );      /* calling function,
cout<<“the result is “<<c;
   }
int sum ( )
 {
int a,b,result;
  cout<<"\n Enter the two numbers : ";
  cin>>a>>b;    /* taking two numbers as input*/
  result = a + b ;   /*adding two numbers*/
return(result);
  }
Program
#include<iostream.h>
using namespace std;
 void sum(int,int);   /*declaring prototype of function*/
 void main()
 {
  int a,b;
  cout<<"\n Enter the two numbers : ";
  cin>>a>>b;    /* taking two numbers as input*/
  sum(a,b);      /* calling function,
   }

int sum ( int num1,int num2)


 {
  int result;  /* defining variable, its scope lies within function */
  result = num1 + num2 ;   /*adding two numbers*/
  cout<<“the result is “<<result;
 }
Program
#include<iostream.h>
using namespace std;
 int sum(int,int);   /*declaring prototype of function*/
 void main()
 {
  int a,b,c;
  cout<<"\n Enter the two numbers : ";
  cin>>a>>b;    /* taking two numbers as input*/
  c = sum(a,b);      /* calling function,
                       *the value returned by the function is stored in c */
  cout<<"\n The sum of two numbers is : “<<c;
   }
 int sum ( int num1,int num2)
 {
  int result;  /* defining variable, its scope lies within function */
  result = num1 + num2 ;   /*adding two numbers*/
  return (result) ;     /* returning result */
 }
Passing arguments to a function

• There are two ways to pass the parameters into a function

• Call by Value
• Call by reference
• In call by value method, the #include <iostream.h>
value of the variable is passed to #include<conio.h>
void swap(int,int);
the function as parameter. void main() {
• The value of the actual int i=7, j=-3;
parameter can not be modified clrscr();
by formal parameter. cout <<"i = "<< i << endl
<<"j = "<< j << endl;
• Different Memory is allocated swap(i,j);
for both actual and formal getch();
parameters. Because, value of }
void swap(int a, int b)
actual parameter is copied to {
formal parameter. int t;
Note: t = a;
a = b;
• Actual parameter – This is the b = t;
argument which is used in cout<<<<“a = "<< a << endl
function call. <<“b = "<< b << endl;
}
• Formal parameter – This is the
argument which is used in
function definition
Program : Pointers as function Parameters
#include <iostream.h>
In functions we can pass the duplicate
#include<conio.h>
values for the actual parameters, but we
void swap(int *, int *);
can pass the address of a variable as an
void main() {
argument to a function in the normal int i=7, j=-3;
fashion. Clrscr();
When we pass addresses to a function, swap(&i,&j);
the parameters receiving the addresses cout <<"i = "<< i <<
should be pointers. The process of endl <<"j = "<< j << endl;
calling a function using pointers to pass getch();
the addresses of variable is known as }
call by address. void swap(int *a, int *b)
{
int t;
t = *a;
*a = *b;
*b = t;}
Difference

call by value call by reference

This method copy address of


This method copy original value into
arguments into function as a
function as a arguments.
arguments.
Changes made to the parameter
Changes made to the parameter
affect the argument. Because address
inside the function have no effect on
is used to access the actual
the argument.
argument.
Actual and formal arguments will be Actual and formal arguments will be
created in different memory location created in same memory location
Function Overloading
• Function refers to a segment that groups code to perform a specific
task.

• In C++ programming, two functions can have same name if number


and/or type of arguments passed are different.

or

Function Overloading is a concept that allows multiple function to


share the same name with different argument types.
Function Overloading
Draw()

Draw()

Draw()

Draw()
#include <iostream> void display(int var)
using namespace std; {
void display(int); cout << "Integer number: " << var ;
void display(float); }
void display(int, float);
void display(float var)
int main()
{
{ cout << "Float number: " << var ;
int a = 5; }
float b = 5.5;
display(a); void display(int var1, float var2)
display(b); {
display(a, b); cout << "Integer number: " << var1;
cout << " and float number:" << var2;
}
}
Eg
•Swapping of two numbers using function overloading
•Area of various shapes using function overloading

170

Potrebbero piacerti anche