Docsity

C++ Programming notes, Study notes of Computer Science

Toggle sidebar
bg1
C++
UNIT I
Difference between C and C++
C C++
C is a Structure oriented programming language C++ is a Object Oriented Programming language
It is based on function It is based on data
Larger programs divided into function Larger programs are divided into different Objects
One or more function share the global data Each and every object can have data and function
and function can access the data within the object
only
The data can be move freely from one function to
another function
External function cannot access the data object
within the class
We cannot add the data on function easily We can add data and function into class easily
Top down approach is used to design a program Bottom up approach is used to design a program
It cannot contain inheritance, polymorphism, data
abstraction and data encapsulation
It contain inheritance, polymorphism, data
abstraction and data encapsulation
Scanf and Printf function can be used to input and
output function in program
Cin and Cout can be used to input and output
function in program
It cannot support overload and virtual function It support overload and virtual function
It cannot support inline and friend function It can support inline and friend function
The declaration can be used in first statement of
program
The declaration can be used anywhere in the
program
Evaluation of C++
C++ is an Object Oriented Programming Language.
In 1980, Bjarne Stroustrab was developed C++.
Initially it was named as C with Class.
It was developed by AT & T Bell Lab at murray hill, in USA
He was strong supporter of simula 67 and Algol 68.
In 1983, he was combined the best feature of Simula 67, Algol 68 to C with Classes and that it
was named as C++ in 1983.
C++ is the extended version of C
C++ is an superset of C
The C++ can contain the following additional features:
1. Inheritance
2. Polymorphism
3. Dynamic Binding
4. Message passing
5. Data abstraction and Encapsulation.
The features of C++
It is a freeform language. It is flexible.
It is OOP language. It can support many concepts of OOPs
It provides quick performance compare than any other Object Oriented Programming Language.
It can contain small size code.
It can be understood easier than any other programming language.
Basic concepts of OOPs
The important object oriented features are namely:
1. Object
2. Class
3. Methods
4. Data abstraction
5. Encapsulation
6. Inheritance
7. Polymorphism
8. Message passing
9. Dynamic binding
10. Reusability
11. Delegation
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50

Partial preview of the text

Download C++ Programming notes and more Study notes Computer Science in PDF only on Docsity!

C++

UNIT I

Difference between C and C++

C C++

C is a Structure oriented programming language C++ is a Object Oriented Programming language It is based on function It is based on data Larger programs divided into function Larger programs are divided into different Objects One or more function share the global data Each and every object can have data and function and function can access the data within the object only The data can be move freely from one function to another function External function cannot access the data object within the class We cannot add the data on function easily We can add data and function into class easily Top down approach is used to design a program Bottom up approach is used to design a program It cannot contain inheritance, polymorphism, data abstraction and data encapsulation It contain inheritance, polymorphism, data abstraction and data encapsulation Scanf and Printf function can be used to input and output function in program Cin and Cout can be used to input and output function in program It cannot support overload and virtual function It support overload and virtual function It cannot support inline and friend function It can support inline and friend function The declaration can be used in first statement of program The declaration can be used anywhere in the program

Evaluation of C++

 C++ is an Object Oriented Programming Language.  In 1980, Bjarne Stroustrab was developed C++.  Initially it was named as C with Class.  It was developed by AT & T Bell Lab at murray hill, in USA  He was strong supporter of simula 67 and Algol 68.  In 1983, he was combined the best feature of Simula 67, Algol 68 to C with Classes and that it was named as C++ in 1983.  C++ is the extended version of C  C++ is an superset of C  The C++ can contain the following additional features:

  1. Inheritance
  2. Polymorphism
  3. Dynamic Binding
  4. Message passing

5. Data abstraction and Encapsulation.

The features of C++

 It is a freeform language. It is flexible.  It is OOP language. It can support many concepts of OOPs  It provides quick performance compare than any other Object Oriented Programming Language.  It can contain small size code.  It can be understood easier than any other programming language.

Basic concepts of OOPs

 The important object oriented features are namely:

  1. Object
  2. Class
  3. Methods
  4. Data abstraction
  5. Encapsulation
  6. Inheritance
  7. Polymorphism
  8. Message passing
  9. Dynamic binding
  10. Reusability
  11. Delegation
  1. Genericity Object  This is the basic unit of object oriented programming.  That is both data and function that operate on data are bundled as a unit called as object.  It represents any person, place and etc.  Every object has its own properties and features that illustrate what the object can do.  An object is a specimen of class.  It can be singly recognized by its name. Class  A class is grouping of objects that have the identical properties, common behavior and shared relationship.  A class bins the data and its related functions together.  Objects are nothing but variables of type class.  Once a class has been declared, the programmer can create a number of objects associated with the class.  The syntax used to create an object is similar to the syntax used to create an integer variable in C.  The class defines the characteristics and action of objects. Method  An operation required for an object when coded in class is called a method.  All objects in a class carry out certain common actions or operations.  The operations that are required for an object are to be defined in the class. Class A { Private data member1; data member2; public: method1() { } method2() {} }; Data Abstraction  It refers to the procedure of representing essential features without including the background details.  A powerful method to achieve abstraction is through the manipulation of hierarchical classifications.  For example a computer is made of various parts such as CPU, Keyboard, and so on.  We think it as a single unit, but the single unit has several sub-units.  They together do the single task.  By assembling sub-parts we can built a single system.  It is used to define a data type available in the programming language, called as abstract data type  It consists of a set of values and a set of operations. Encapsulation  The packing up of data and functions into a single component is known as encapsulation.  The data is not reachable by the outside functions.  Only those functions that are able to access the data are defined within the class.  With encapsulation we accomplish data hiding.  Data hiding is an important feature using which an object can be used without the user knowing how it works internally.  Fundamental of encapsulation is class. Inheritance  It is the method by which objects of one class get the properties of another class.  It provides the thought of reusability.  The programmer can add new properties to the existing class without changing it.  This can be achieved by deriving a new class from the existing one.  The new class will possess features of both the classes.  For example, re, yellow, and blue are the main colors.  The orange is created from the combination of red and yellow, green is created from yellow and blue and violet is created from red and blue.  The orange has the attributes of both red and yellow, which produces a new effect. Polymorphism

Java  It was developed by Patrick Naughton, James Gosling, Chris Warth, Mike Sheridan and Ed Frank at Sun Microsystems.  It is an object oriented programming language and supports maximum OOP characteristics exist.  Its structure is like C and C++, but it easier than C++.  It excludes few confusing and unsafe features of C and C++ like pointers.  It allows client/server programming.  It is used for Internet programming.  The Java programs are downloaded by the client machines and executed on different types of hardware.  This portability is achieved by translation of java program to machine code using compiler and interpreter.  The Java compiler converts the source program to JVM.  The compiler Java program is called as byte code.  The Java interpreter translates byte code into the object code.

 Compiler and interpreter do the conversion of Java program to object code.

Application of OOP (or) Usages of OOP

 The OOP technology is changing the style of software engineers to think, analyze, plan and implement the software.  The software developed using OOP technology is more efficient and easy to update.  It have standard class library.  The users in their program can reuse the standard class library.  It saves lot of time and coding work.  The most popular application of object oriented programming is windows.  There are several windowing software based on OOP technology.  Following are the areas for which OOP is considered.

  1. Simulation
  2. Object oriented DBMS
  3. Office automation software
  4. Artificial Intelligence and expert systems
  5. CAD/CAM software
  6. Network programming & Internet applications

7. System software

Usage of C++

 It is a flexible language.  Lengthy programs can be easily controlled by the use of C++.  It permits us to create hierarchy associated objects and libraries that can be useful to other programmers.  C++ helps the programmer to write bug-free program, which are easy to maintain.

Stream in C++

 The C++ supports number of I/O operations to perform read and write operations.  These functions help the user to work with different types of devices such as keyboard, disk, tape drivers, etc.  Stream is an inter-mediator between I/O devices and the user.  The stream is a flow of data, measured in bytes, in sequence.  If data is received from input devices in sequence, then it is called as source stream.  When the data is passed to output devices, then it is called as destination stream.  This process of flow of data is also known as encapsulation through streams.  The data in source stream can be used as input data by the program.  So, the source stream is also called as input stream.  The destination stream that collects output data from the program is known as the output stream.  The input stream receives data from keyboard or storage devices such as hard disk, floppy disk.

 The data present in output stream is passed on to the output devices such as monitor or printer.

Standard streams in C++ or pre-defined stream

 A standard stream is a pre-connected stream provided to a computer program by its environment.  C++ comes with four predefined standard stream objects that have already been set up for your use.

  1. Cin: is a predefined input stream (defined in ).
  1. Cout: is a predefined output stream (defined in ).
  2. Cerr: is a predefined output error stream (defined in ), to which you should send all error messages. It defaults to the terminal (just like cout. )
  3. Clog: it is fully buffered version of cerr.

Buffering

 A buffer is a block of RAM that is used to hold input or output temporarily.  This can speed up I/O considerably because of the various overheads incurred when transferring data.  Writing data to the disk is very costly.  The read/write operation with disk takes a long time.  When these operations are carried out, the execution of the program will be slow for few seconds.  If the program involves many read and write operations, the program execution speed will be slower.  To avoid this problem, the stream provides buffer. It holds the data temporarily.  The input data is passed to the stream buffer.  The data is not written to the disk immediately till the buffer fills.  When the buffer is completely filled, the data is written to the disk.

Stream Class

 C++ streams are based on class and object theory.  C++ has number of classes that work with console and file operations.  These classes are known as stream classes.  It consists of 3 subclass

  1. istream
  2. ostream
  3. stream buf  istream class support to both formatted and unformatted data.  ostream class handle the formatting of output of data.  iostream class can be derived from istream & ostream class. Here istream ostream and iostream can be provide multiple inheritance.  Stream buffer is used to store input stream. It store temporarily. It is derived from iostream. File buffer class are derived from this stream. All three provide multilevel inheritance.

class Functions / contents

Ios 1. It is an input and output stream class

  1. It is used to implement a buffer, i.e. it is pointer to a buffer streambuf.
  2. ios maintains the information on the state of streambuf, i.e. good, bad, eof, etc. istream 1. istream provides formatted input.
  3. It is used to handle formatted as well as unformatted conversion of character from a streambuf.
  4. The properties of ios are inherited in istream class.
  5. The instance of class does not carry out the class
  6. The instance of class does not carry out the actual input.
  7. istream declares functions such as peek(), tellg(), seekg(), etc.
  8. istream class overloads the ‘>>’ operator. Ostream 1. It is used for general-purpose output.
  9. It is used to declare the output functions such as tellp(), put(), etc.
  10. It is the parent of all output stream.
  11. ostream overloads the ‘<<’ operator iostream 1. it is used to handle both input and output streams. istream_withassign 1. It is derived from istream

abc abc

Formatted I/O operations

 C++ provides various formatted I/O functions for formatting the output.  They are of 3 types:

  1. ios class function and flags
  2. manipulators
  3. user defined output functions ios class function and flags  The ios grants operations common to both input and output.  Three classes:
  4. istream performs formatted input.
  5. ostream performs formatted output
  6. iostream performs formatted input and output. ios class functions
  7. width()  To set the required field width.  The output will be displayed in given width.  Width can be declared in 2 ways:
  8. int width();  It returns the present width value
  9. int width(int);  It sets the width as per the given integer and returns the previous width setting.  The setting should be reset for each input or output value if a width other than the default is desired.
  10. precision()  To set number of decimal point to a float value.  This function can be declared in two ways:
  11. int precision(int);  It sets the floating-point precision and returns the previous setting.
  12. int precision();  It returns the current setting of floating-point precision.
  13. fill()  To set a character in the blank space of a field.  This function can be declared in 2 ways:
  14. char fill()  It returns the current setting of fill character.
  15. char fill(char)  It resets the fill character and returns the previous setting setf()  To set various flags for formatting output.  It can be declared in 2 ways:
  16. long setf(long v1, long v2);
  17. long setf(long v1);
  18. unsetf()  To remove the flag setting long unsetf(long v1); void main() { cout.fill(‘*’); cout.width(10); cout.precision(2); cout<<32.224; } OUTPUT *****32.

Bit fields

 The ios class contains the setf() member function.  The flag indicated the format design.

 unsetf is used to clear the flags. Syntax: cout.setf(v1, v2); cout.unsetf(v1);  v1, v2 are flags  There are 3 types of bit fields.

  1. Adjust field
  2. Float field
  3. Base field ios::adjustfield  It is a data member and used with setf() function to arrange padding to the left or right, or for internal fill.  It can be declared as follows: static const long adjustfield;  It contains 3 flags
  4. ios::left
  5. ios::right
  6. ios::internal ios::floatfield  It is a data member and used with setf() function to set the float point notation to scientific or fixed.  It is declared as follows: static const long floatfield;  It contains 2 types of flags
  7. ios::scientific
  8. ios::fixed ios::basefield  It is a data member and used with setf() function and used with setf() function to set the notation to a decimal, octal, or hexadecimal base. It is declared as follows: static const long basefield;  It contains 3 types of flags:
  9. ios::decimal
  10. ios::octal
  11. ios::hex void main() { cout.fill(‘*’); cout.width(10); cout.setf(ios::left, ios::adjustfield); cout<<”India”; } **OUTPUT India*******

Flags without bitfield

Syntax: long setf(long v1)  where v1 is a variable name of the flag.

  1. ios::showbase: U se base indicator on output
  2. ios::showpos: Display + preceding positive number
  3. ios: : showpoint: Display trailing decimal point and zeros
  4. ios: : skipws: Skip white space in output
  5. ios: : unibuf: Flush all streams after insertion
  6. ios: : uppercase: To convert into capital letter
  7. ios: : stdio: Adjust the stream with C standard input and output
  8. ios: : boolalpha: Converts bool values to text 1 or 0. void main() { cout.setf(ios::showpos); cout<<24; cout.setf(ios::showpoint); cout<<23.2;

Parts of C++ program

  1. Include files
  2. Class declaration or definition
  3. Function definition
  4. Main function Include files  It is used to include a header file in our program.  The header file has the extension .h  It is included by the macro statement #include  It can support all function in C++. Class declaration or definition  It is used to declare a class.  The class can be declared before or after main. But after main is better.  It contains data and function.  It can also contain the function prototype and also defined function. Function definition  The function can be defined inside or outside the class. main() function  It is the main part of C++ program.  Actually the execution automatically starts from here.

C++ tokens

 The smallest individual unit in a program is known as tokens  The program contains various components.  The compiler identifies them as tokens.  Tokens are classified into:

  1. Keywords
  2. Identifiers
  3. Constants
  4. Operators
  5. Special characters Keywords  It is a reserved set of words with special meaning.  The C++ keyword is same as C.  In C++ contains 63 keywords.  Turbo C++ contain extra 14 keywords. Eg: int, char, if, etc. Identifiers  Each variable is represented by a symbol using identifiers.  Identifiers are names of variables, functions, arrays, etc.  Rules for defining identifiers
  6. The identifier name must begin with a character or underscore and should not start with digit.
  7. No spaces are allowed.
  8. The identifier name should not be a keyword.
  9. The uppercase and lower case letters are not same. Variable  It is used to store values  Each variable is stored in memory location.  It can be of any data type.  It holds a single value at a time of its type, that is, valus of variable vary, and the programmer can change the value of the variable. Variable declaration  The variable must be declared before they are used in the program.  Once declared
  10. The compiler obtains the variable name and
  11. The compiler is notified about the data type of the variable being declared and helps in allocation of the memory.  The variable declared before main and it is called external variables.  In C++ variables can be declared anywhere in the program. Syntax:

data_type variable_name; Example: int a; Variable initialization  Before using a variable it is essential to initialize it.  Assigning a value to the variable is called as initialization.  When a value is assigned to the variable, the garbage value is removed and replaced with the given value.  Initialization can be done at the place where it is declared or anywhere in the program before their use.  Variables declared can be assigned using assignment operator ‘=’. Syntax: data_type variable_name = constant; Example: int a=10; Dynamic initialization  The declaration and initialization of variable in a single statement at any place in the program is called as dynamic initialization.  It is the process carried out at run-time. Constants  The values that do not change during execution of a program.  The constant have 2 types

  1. Literal constant
  2. Symbolic constant Literal constant  The value can be assigned directly to the variable.  After assignment the value cannot be changed Symbolic constant  The value cannot be changed.  The constant can be defined in 3 ways:
  3. Macro statement
  4. Constant
  5. enum Macro statement (#define)  It is a preprocessor.  It is used to define a constant by using #. Syntax: #define variable_name value #define n 5 void main() { cout<<n; getch(); } OUTPUT: 5 Constant  The constant can be declared by using the keyword const. Syntax: const data_type variable_name = value; void main() { const int n = 5; cout<<n; getch(); } OUTPUT: 5 enum  The enum keyword is used to create a new data type and also create variable for that data type. Syntax: enum variable_name{value1, value2}; Eg: enum logical(true, false};  Here logical is a new data type and true, false is a variable for logical data type.

void main() { int x=2, p; cout<<”Address of x=”<<&x; p=&x; cout<<”value of x=”<<p; } OUTPUT Address of x= Value of x=

Function

 It is a self-contained block or a sub-program of one or more statements that perform a special task when called.  The C++ functions are more civilized than C. void main() { void show(void); show(); } void show() { cout<<”Infunction show()”; } OUTPUT In function show()

Arrays

 It is a collection of elements of similar data type in which each element is located in separate memory location. Eg: int b[4]; void main() { int b[4]={2,4,3,7}; cout<<”b[0]=”<<b[0]<<endl; cout<<”b[1]=”<<b[1]<<endl; cout<<”b[2]=”<<b[2]<<endl; cout<<”b[3]=”<<b[3]<<endl; } OUTPUT b[0]=2 b[1]=4 b[2]=3 b[3]=

Reference

 The referencing operator (&) is used to define referencing variable.  A reference variable prepares an alternate name for previously defined variable. Syntax: data_type & reference variable name = variable name; Example: int qty=10; int &qt = qty;  Here, qty is already declared and initialized.  The second statement defines an alternative variable name, that is, qt to variable qty.  If both variables printed displays the same value.  Any change made in one of the variable causes the change in both the variables. qt=qt*2;

 Now, contents of qt and qty will be 20.

User defined Data Type

 User defined data types are structure and classes, union, and enumerator

Structure

 Struct is a keyword and used to combine variables of different data types into a single record. Syntax: struct { <data-type><variable-name1, variable-name2>; <data-type><variable-name3, variable-name4>; }; Example

struct my_friend { char fname[80], phone[80]; int age, height; }friend A;

Class

 The class is a new keyword introduced in C++.  Its use is the same as struct keyword. Syntax: <class-name>[<:baseclasslist>]{} Example: class circle { int radius; int area(void); };

Union

 A union is same as compared to a struct, but the only difference is that it allows the user to declare variables that share the same memory space.  The union requires bytes that are equal to the number of bytes required for the largest members. Syntax: union[] { <data-type>; }[]; Example: union charorint { char c; int i; }number;

enum

 The enum keyword is used to create a new data type and also create variable for that data type. Syntax: enum variable_name{value1, value2}; Eg: enum logical(true, false};  Here logical is a new data type and true, false is a variable for logical data type.  Here the true take the value 0 and false take the value 1.  When the value cannot be specified suppose we can change the value of enumerator by using assignment operator. Eg: enum logical{true=2, false=4};

 Here the value of true is 2 the value of false is 4.

CONTROL STRUCTURES / STATEMENTS

 A program is nothing but the execution of sequence of one or more instructions.  Quite often, it is desirable to alter the sequence of the statements in the program  Depending upon certain circumstances. (i.e., we have a number of situations where we may have to change the order of execution of statements based on certain conditions) (or)  Repeat a group of statements until certain specified conditions are met.  This involves a kind of decision making to see whether a particular condition has  Occurred or not and direct the computer to execute certain statements accordingly. Based on application, it is necessary / essential (i) To alter the flow of a program (ii) Test the logical conditions (iii) Control the flow of execution as per the selection these conditions can be placed in the program using decision-making statements.

Decision statements

  1. Simple if Statement 2) if – else Statement 3) Nested if-else statement 4) else – if Ladder
  2. switch statement

Simple “if” statement:

 The if statement is a powerful decision making statement and is used to control the flow of execution of statements.

Syntax:

int n; clrscr(); cout<<“Enter a number:”; cin>>n; if( (n%2)==0 ) cout<<”\n The given number is EVEN ”; else cout<<“\n The given number is ODD ”; getch( ); }

Output:

Enter a number: 24 The given number is EVEN

Nested “if–else” Statement:

 Using of one if-else statement in another if-else statement is called as nested if-else control statement.  When a series of decisions are involved, we may have to use more than one ifelse statement in nested form.

Syntax:

if ( Test Condition 1) { if ( Test Condition 2) { Statement -1; } else { Statement -2; } } else { if ( Test Condition 3) { Statement -3; } else { Statement -4; } } /* end of outer if-else */  If Test Condition-1 is true then enter into outer if block, and it checks Test Condition- 2 if it is true then Statement-1 executed if it is false then else block executed i.e Statement-2.  If Test Condition -1 is false then it skips the outer if block and it goes to else block and Test Condition-3 checks if it is true then Statement-3 executed, else Statement-4 executed

Example:

void main() { float a,b,c; cout<<“Enter Three Values:”; cin>>a>>b>>c; cout<<“\n Largest Value is:” ; if(a>b) { if(a>c) cout<< a; else cout<< c; } else { if (b>c) cout<<b; else cout<<c; } }

Output:

Enter three values: 9.12 5.34 3. Largest Value is: 9.

The “else – if” Ladder:

 This is another way of putting if „s together when multiple decisions are involved.  A multipath decision is a chain of if ‟s in which the statement associated with each else is an if.  Hence it forms a ladder called else–if ladder.

Syntax:

if (Test Condition -1) Statement -1; else if ( Test Condition -2) Statement -2; else if ( Test Condition -3) Statement -3; : else if ( Test Condition –n) Statement –n; else default statement; Rest of the Program Statements-X;  The above construction is known as else if ladders.  The conditions are evaluated from top to bottom.  As soon as a true condition is found, the statement associated with it is executed and the control is transferred to the Rest of the Program Statement–X (skipping rest of the ladder).  When all the “n‟ conditions become false, then the final else containing the default statement will be executed.

Example:

void main() { int a,b,c; clrscr(); cout<<“Enter the numbers:”; cin>>a>>b>>c); if ((a>b) && (a>c)) cout<<“Highest Number is:”<< a; else if ((b>a) && (b>c)) cout<<“Highest Number is:”<< b; else cout“Highest Numbers is:”<< c; getch(); }

Output:

Enter the numbers: 12 34 10 Highest number is : 34

The “switch-case” Statement:

 The switch statement causes a particular group of statements to be chosen from several available groups.  The selection is based upon the current value of an expression which is included within the switch statement.  The switch statement is a multi-way branch statement.  In a program if there is a possibility to make a choice from a number of options, this structured selected is useful.  The switch statement requires only one argument of int or char data type, which is checked with number of case options.  The switch statement evaluates expression and then looks for its value among the case constants.  If the value matches with case constant, then that particular case statement is executed.  If no one case constant not matched then default is executed.  Here switch, case and default are reserved words or keywords.  Every case statement terminates with colon “:”.  In switch each case block should end with break statement, i.e.

Syntax:

switch(variable or expression)

Syntax:

for(initialize expression; test condition; updation ) { Statement 1; Statement 2; }

  1. The initialization sets a loop to an initial value. This statement is executed only once.
  2. The test condition is a relational expression that determines the number of iterations desired or it determines when to exit from the loop. i. The for loop continues to execute as long as conditional test is satisfied. ii. When the condition becomes false the control of the program exits from the body of for loop and iii. executes next statements after the body of the loop.
  3. The updation(increment or decrement operations) decides how to make changes in the loop. I. The body of the loop may contain either a single statement or multiple statements.

Flow chart

Example:

void main() { int i; clrscr(); cout<<“The numbers of 1 to 25 are:”; for(i=1; i < =15; i=i+1) cout<< i; }

Output :

The Numbers of 1 to 15 are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Nested “for” loop:

 We can also use loop within loops.  i.e. one for statement within another for statement is allowed in C. (or „C‟ allows multiple for loops in the nested forms).  In nested for loops one or more for statements are included in the body of the loop.

Syntax:

for( initialize ; test condition ; updation) / outer loop / { for(initialize ; test condition ; updation) / inner loop / { Body of loop; } }  The outer loop controls the rows while the inner loop controls the columns.

Example:

void main() {

int a,b,sum; clrscr(); for (a=3; a > =1; a - - ) { for(b=1;b<=2;b++) { sub = a – b; cout<<”a=”<<a<<”b=”<<b”a-b=”<<sub); } } getch(); }

Output:

a=3 b =1 a-b = a=3 b =2 a-b = a=2 b =1 a-b = a=2 b =2 a-b = a=1 b =1 a-b = a=1 b =2 a-b =-

The “ while ” loop

 The simplest of all the looping structures in C is.

Syntax:

Initialization Expression; while( Test Condition) { Body of the loop }  The while is an entry – controlled loop statement.  The test condition is evaluated and if the condition is true, then the body of the loop is executed.  The execution process is repeated until the test condition becomes false and the control is transferred out of the loop  On exit, the program continues with the statement immediately after the body of the loop.  The body of the loop may have one or more statements.  The braces are needed only if the body contains two or more statements.  It‟s a good practice to use braces even if the body has only one statement.

Example:

void main() { int a=1,sum=0; clrscr(); while(a<=10) { sum = sum + a; a++; } Cout<<“Sum of 1 to 10 numbers is:”<<sum); getch(); }

Ouput:

Sum of 10 numbers is: 55

The “ do-while “ loop:

 In do-while, the condition is checked at the end of the loop.  The do-while loop will execute at least one time even if the condition is false initially.  The do-while loop executes until the condition becomes false.

Syntax:

Initialization Expression; do { Body of the loop; } while ( Test Condition);