Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
Course: Object Oriented Programming System With C++
Department of Computer Science & Engineering
MODULE -2
C++ control statements and Functions
Loops
while loop
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
for loop
Execute a sequence of statements multiple times and abbreviates the code that manages the
loop variable.
do...while loop
Like a ‘while’ statement, except that it tests the condition at the end of the loop body.
Object oriented programming system with C++
While loop
The syntax of a while loop in C++ is
while(condition)
{
statement(s);
}
i=1;
while (i<=10)
{
cout<<i;
i++;
}
Do -while
The syntax of a while loop in C++ is
do
{
statement(s);
}
while(condition)
i=1;
do
{
cout<<i;
i++;
}
While(i>=10)
For loops
The syntax of a while loop in C++ is
for ( init; condition; increment )
{
statement(s);
}
int main ()
{
// for loop execution
for( int i = 10; i < 20; i++ )
{
cout << "value of a: " << a << endl;
}
return 0;
}
DECISION MAKING STATMENTS
conditional statements
•if-else: An if-else statement operates on an either/or basis. One statement is executed if
the condition is true; another is executed if the condition is false.
•if-else if-else: This statement chooses one of the statements available depending on the
condition. If no conditions are true, the else statement at the end is executed.
•while: While repeats a statement as long as a given statement is true.
•do while: A do while statement is similar to a while statement with the addition that the
condition is checked at the end.
•for: A for statement repeats a statement as long as the condition is satisfied.
Assignment-if else
Write Program to Calculate Grade According to marks
1.If marks 40 to 50 then Grade is F
2.if marks >=50 <60 then Grade is D
3.if marks >=60 <70 then Grade is C
4.if marks >=70 <80 then Grade is B
5.if marks >=80 <90 then Grade is A
6.if marks >=90 then Grade is A+
Otherwise print “fail”
Unconditional Control Statements
•goto: A goto statement directs control to another part of the
program.
•break: A break statement terminates a loop (a repeated
structure)
•continue: A continue statement is used in loops to repeat the
loop for the next value by transferring control back to the
beginning of the loop and ignoring the statements that come
after it.
C++ Switch Statements
Use the switch statement to select one of many code blocks to be executed
Syntax
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example
int day = 3;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
}
goto Statement
# include <iostream>
using namespace std;
int main()
{ int I, num ,average, ,sum;
for(i = 1; i <= 10; ++i)
{ if( i==8)
{ goto a;
}
sum =sum + i;
}
cout << "nsum = " << sum;
a:cout<<“sum 1 to 7”<<sum;
return 0
;
}
for(i = 1; i <= n; ++i) { cout << "Enter n" << i << ": "; cin >> num; if(num < 0.0) { // Control of the program move to jump: goto jump; } sum += num; } jump: average = sum / (i - 1); cout << "nAverage = " << average; return
Output
Sum 1 to 7 = 28
break Statement
# include <iostream>
using namespace std;
int main()
{ int I, num ,average, ,sum;
for(i = 1; i <= 10; ++i)
{ if( i==8)
{ break;
}
sum =sum+i;
}
cout << "nsum = " << sum;
return 0
;
}
for(i = 1; i <= n; ++i) { cout << "Enter n" << i << ": "; cin >> num; if(num < 0.0) { // Control of the program move to jump: goto jump; } sum += num; } jump: average = sum / (i - 1); cout << "nAverage = " << average; return
Output
sum = 28
Continue Statement
# include <iostream>
using namespace std;
int main()
{ int I, num ,average, ,sum;
for(i = 1; i <= 10; ++i)
{ if( i==8)
{ continue;
}
sum =sum+i;
}
a: cout << "nsum = " << sum;
return 0
;
}
Output
sum = 47
Array and Strings
ARRAY
Introduction to array
types of array
syntax of Array declaration
example
c program to Martrix (single,double dimenension) operations
STRING
Introduction
String operation
String header file
Functions
C++ Functions
A Function is a sub-program that acts on data and often returns a value. Large programs are
generally avoiding because it is difficult to manage a single list of instructions. Thus, a large
program is broken down into smaller units known as functions. A functions is a named unit of
a group of program statements. This unit can be invoked from other parts of the program.
Why to use Functions ?
The most important reason to use functions is to make program handling easier as only a
small part of the program is dealt with at a time, thereby avoiding ambiguity. Another reason
to use functions is to reduce program size. Functions make a program more readable and
understandable to a programmer thereby making program management much easier.
C++ Function Types
There are two types of functions: library functions and user-defined functions
*Refer your class notes
C++ Standard Library Functions
•C++ Header Files -
•C++ Character String Functions -
•C++ Mathematical Functions -
Recursion
Recursion
Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems
which are easier to solve.
The function which calls the same function, is known as recursive function.
//program for factorial using recursion
#include<iostream>
using namespace std;
int main()
{
int factorial(int);
int fact,value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl
int factorial(int n)
{
if(n<0)
return(-1); /*Wrong value*/
if(n==0)
return(1); /*Terminating condition*/
else
{
return(n * factorial(n-1));
Write a program to print fibonaci series using recursion
Write a program to solve towers of Hanoi using recursion
The program which related to Tree concepts in data structures is based on recursion
Inline functions
The main use of the inline function in C++ is to save memory space. Whenever the function is called, then it takes a lot of time to
execute the tasks, such as moving to the calling function.
It will be greater than the time taken required to execute that function. use inline function if fuction called many times
Advantages of inline function
In the inline function, we do not need to call a function, so it does not cause any overhead.
It also saves the overhead of the return statement from a function.
It does not require any stack on which we can push or pop the variables as it does not perform any function calling.
An inline function is mainly beneficial for the embedded systems as it yields less code than a normal function.
We cannot provide the inline to the functions in the following circumstances:
If a function is recursive.
If a function contains a loop like for, while, do-while loop.
If a function contains static variables.
If a function contains a switch or go to statement
syntax
inline return_type function_name(parameters)
{
// function code
}
#include<iostream>
using namespace std;
inline int add(int a,int b)
{
int c;
return(a+b);}
int main()
{
cout<<"Addition:"<<add(2,3);
cout<<"Addition:"<<add(3,5);
cout<<"Addition:"<<add(21,31);
return 0;
}
Storage class
1. Storage class is used to define the lifetime and visibility of a variable
2. Lifetime refers to the period during which the variable remains active
3. visibility refers to the module of a program in which the variable is accessible.
There are five types of storage classes, which can be used in a C++ program
1.Automatic
2.Register
3.Static
4.External
5.Mutable
Automatic Storage Class
It is the default storage class for all local variables. The auto keyword is applied to all
local variables automatically.
 The variables defined using auto storage class are called as
local variables.
 Auto stands for automatic storage class.
 A variable is in auto storage class by default if it is not
explicitly specified.
 The scope of an auto variable is limited with the particular
block only.
 Once the control goes out of the block, the access is
destroyed. This means only the block in which the auto
variable is declared can access it.
#include <stdio.h>
int main( )
{
auto int j = 1;
{
auto int j= 2;
{
auto int j = 3;
printf ( " %d ", j);
}
printf ( "t %d ",j);
}
printf( "%dn", j);
}
Output 3 2 1
Register Storage Class
The register variable allocates memory in register than RAM. Its size is same of register
size. It has a faster access than other variables.
It is recommended to use register variable only for quick access such as in counter.
Example
register int counter=0;
Static Storage Class
The static variable is initialized only once and exists till the end of a program.
It retains its value between multiple functions call.
The static variable has the default value 0 which is provided by compiler.
#include <iostream>
using namespace std;
void func()
{
static int i=0; //static variable
int j=0; //local variable
i++;
j++;
cout<<"i=" << i<<" and j=" <<j<<endl;
}
int main()
{
func();
func();
func();
}
External Storage Class
The extern variable is visible to all the programs. It is used if two or more files are sharing
same variable or function.
The extern storage class is required when the variables need to be shared across multiple
files. Extern variables have global scope and these variables are visible outside the file in
which they are declared. The extern variable is visible to all the programs. It is used if two or
more files are sharing the same variable or function.
The lifetime of the extern variables is as long as the program in which it is declared is
terminated
extern int counter=0;
extern
Extern stands for external storage class.
Extern storage class is used when we
have global functions or variables which
are shared between two or more files.
Keyword extern is used to declaring a
global variable or function in another file
to provide the reference of variable or
function which have been already
defined in the original file.
Object oriented programming system with C++
Mutable Storage Class
Mutable specifier applies only to class objects, which allows a member of an object to override const member function.
A mutable member can be modified by a const member function.
modifiable even the member is part of an object declared as const.
#include<iostream>
using namespace std;
class test
{
mutable int a;
int b;
public:
test(int x,int y)
{
a=x;
b=y;
}
void square_a() const
{
a=a*a;
}
void display() const
{
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
}
int main()
{
const test x(2,3);
cout<<"Initial value"<<endl;
x.display();
x.square_a();
cout<<"Final value"<<endl;
x.display();
return 0;
}
Storage Class Keyword Lifetime
Automatic auto Function Block
External extern Whole Program
Static static Whole Program
Register register Function Block
Mutable mutable Class

More Related Content

Object oriented programming system with C++

  • 1. Course: Object Oriented Programming System With C++ Department of Computer Science & Engineering
  • 2. MODULE -2 C++ control statements and Functions
  • 3. Loops while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. for loop Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable. do...while loop Like a ‘while’ statement, except that it tests the condition at the end of the loop body.
  • 5. While loop The syntax of a while loop in C++ is while(condition) { statement(s); } i=1; while (i<=10) { cout<<i; i++; }
  • 6. Do -while The syntax of a while loop in C++ is do { statement(s); } while(condition) i=1; do { cout<<i; i++; } While(i>=10)
  • 7. For loops The syntax of a while loop in C++ is for ( init; condition; increment ) { statement(s); } int main () { // for loop execution for( int i = 10; i < 20; i++ ) { cout << "value of a: " << a << endl; } return 0; }
  • 9. conditional statements •if-else: An if-else statement operates on an either/or basis. One statement is executed if the condition is true; another is executed if the condition is false. •if-else if-else: This statement chooses one of the statements available depending on the condition. If no conditions are true, the else statement at the end is executed. •while: While repeats a statement as long as a given statement is true. •do while: A do while statement is similar to a while statement with the addition that the condition is checked at the end. •for: A for statement repeats a statement as long as the condition is satisfied.
  • 10. Assignment-if else Write Program to Calculate Grade According to marks 1.If marks 40 to 50 then Grade is F 2.if marks >=50 <60 then Grade is D 3.if marks >=60 <70 then Grade is C 4.if marks >=70 <80 then Grade is B 5.if marks >=80 <90 then Grade is A 6.if marks >=90 then Grade is A+ Otherwise print “fail”
  • 11. Unconditional Control Statements •goto: A goto statement directs control to another part of the program. •break: A break statement terminates a loop (a repeated structure) •continue: A continue statement is used in loops to repeat the loop for the next value by transferring control back to the beginning of the loop and ignoring the statements that come after it.
  • 12. C++ Switch Statements Use the switch statement to select one of many code blocks to be executed Syntax switch(expression) { case x: // code block break; case y: // code block break; default: // code block } Example int day = 3; switch (day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; case 3: cout << "Wednesday"; break; }
  • 13. goto Statement # include <iostream> using namespace std; int main() { int I, num ,average, ,sum; for(i = 1; i <= 10; ++i) { if( i==8) { goto a; } sum =sum + i; } cout << "nsum = " << sum; a:cout<<“sum 1 to 7”<<sum; return 0 ; } for(i = 1; i <= n; ++i) { cout << "Enter n" << i << ": "; cin >> num; if(num < 0.0) { // Control of the program move to jump: goto jump; } sum += num; } jump: average = sum / (i - 1); cout << "nAverage = " << average; return Output Sum 1 to 7 = 28
  • 14. break Statement # include <iostream> using namespace std; int main() { int I, num ,average, ,sum; for(i = 1; i <= 10; ++i) { if( i==8) { break; } sum =sum+i; } cout << "nsum = " << sum; return 0 ; } for(i = 1; i <= n; ++i) { cout << "Enter n" << i << ": "; cin >> num; if(num < 0.0) { // Control of the program move to jump: goto jump; } sum += num; } jump: average = sum / (i - 1); cout << "nAverage = " << average; return Output sum = 28
  • 15. Continue Statement # include <iostream> using namespace std; int main() { int I, num ,average, ,sum; for(i = 1; i <= 10; ++i) { if( i==8) { continue; } sum =sum+i; } a: cout << "nsum = " << sum; return 0 ; } Output sum = 47
  • 16. Array and Strings ARRAY Introduction to array types of array syntax of Array declaration example c program to Martrix (single,double dimenension) operations STRING Introduction String operation String header file
  • 17. Functions C++ Functions A Function is a sub-program that acts on data and often returns a value. Large programs are generally avoiding because it is difficult to manage a single list of instructions. Thus, a large program is broken down into smaller units known as functions. A functions is a named unit of a group of program statements. This unit can be invoked from other parts of the program. Why to use Functions ? The most important reason to use functions is to make program handling easier as only a small part of the program is dealt with at a time, thereby avoiding ambiguity. Another reason to use functions is to reduce program size. Functions make a program more readable and understandable to a programmer thereby making program management much easier. C++ Function Types There are two types of functions: library functions and user-defined functions *Refer your class notes
  • 18. C++ Standard Library Functions •C++ Header Files - •C++ Character String Functions - •C++ Mathematical Functions -
  • 19. Recursion Recursion Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve. The function which calls the same function, is known as recursive function. //program for factorial using recursion #include<iostream> using namespace std; int main() { int factorial(int); int fact,value; cout<<"Enter any number: "; cin>>value; fact=factorial(value); cout<<"Factorial of a number is: "<<fact<<endl int factorial(int n) { if(n<0) return(-1); /*Wrong value*/ if(n==0) return(1); /*Terminating condition*/ else { return(n * factorial(n-1));
  • 20. Write a program to print fibonaci series using recursion Write a program to solve towers of Hanoi using recursion The program which related to Tree concepts in data structures is based on recursion
  • 21. Inline functions The main use of the inline function in C++ is to save memory space. Whenever the function is called, then it takes a lot of time to execute the tasks, such as moving to the calling function. It will be greater than the time taken required to execute that function. use inline function if fuction called many times Advantages of inline function In the inline function, we do not need to call a function, so it does not cause any overhead. It also saves the overhead of the return statement from a function. It does not require any stack on which we can push or pop the variables as it does not perform any function calling. An inline function is mainly beneficial for the embedded systems as it yields less code than a normal function. We cannot provide the inline to the functions in the following circumstances: If a function is recursive. If a function contains a loop like for, while, do-while loop. If a function contains static variables. If a function contains a switch or go to statement
  • 22. syntax inline return_type function_name(parameters) { // function code } #include<iostream> using namespace std; inline int add(int a,int b) { int c; return(a+b);} int main() { cout<<"Addition:"<<add(2,3); cout<<"Addition:"<<add(3,5); cout<<"Addition:"<<add(21,31); return 0; }
  • 23. Storage class 1. Storage class is used to define the lifetime and visibility of a variable 2. Lifetime refers to the period during which the variable remains active 3. visibility refers to the module of a program in which the variable is accessible. There are five types of storage classes, which can be used in a C++ program 1.Automatic 2.Register 3.Static 4.External 5.Mutable
  • 24. Automatic Storage Class It is the default storage class for all local variables. The auto keyword is applied to all local variables automatically.  The variables defined using auto storage class are called as local variables.  Auto stands for automatic storage class.  A variable is in auto storage class by default if it is not explicitly specified.  The scope of an auto variable is limited with the particular block only.  Once the control goes out of the block, the access is destroyed. This means only the block in which the auto variable is declared can access it. #include <stdio.h> int main( ) { auto int j = 1; { auto int j= 2; { auto int j = 3; printf ( " %d ", j); } printf ( "t %d ",j); } printf( "%dn", j); } Output 3 2 1
  • 25. Register Storage Class The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables. It is recommended to use register variable only for quick access such as in counter. Example register int counter=0;
  • 26. Static Storage Class The static variable is initialized only once and exists till the end of a program. It retains its value between multiple functions call. The static variable has the default value 0 which is provided by compiler. #include <iostream> using namespace std; void func() { static int i=0; //static variable int j=0; //local variable i++; j++; cout<<"i=" << i<<" and j=" <<j<<endl; } int main() { func(); func(); func(); }
  • 27. External Storage Class The extern variable is visible to all the programs. It is used if two or more files are sharing same variable or function. The extern storage class is required when the variables need to be shared across multiple files. Extern variables have global scope and these variables are visible outside the file in which they are declared. The extern variable is visible to all the programs. It is used if two or more files are sharing the same variable or function. The lifetime of the extern variables is as long as the program in which it is declared is terminated extern int counter=0;
  • 28. extern Extern stands for external storage class. Extern storage class is used when we have global functions or variables which are shared between two or more files. Keyword extern is used to declaring a global variable or function in another file to provide the reference of variable or function which have been already defined in the original file.
  • 30. Mutable Storage Class Mutable specifier applies only to class objects, which allows a member of an object to override const member function. A mutable member can be modified by a const member function. modifiable even the member is part of an object declared as const. #include<iostream> using namespace std; class test { mutable int a; int b; public: test(int x,int y) { a=x; b=y; } void square_a() const { a=a*a; } void display() const { cout<<"a = "<<a<<endl; cout<<"b = "<<b<<endl; } int main() { const test x(2,3); cout<<"Initial value"<<endl; x.display(); x.square_a(); cout<<"Final value"<<endl; x.display(); return 0; }
  • 31. Storage Class Keyword Lifetime Automatic auto Function Block External extern Whole Program Static static Whole Program Register register Function Block Mutable mutable Class