file · web viewinternal examination-i. department of . electronics and communication. and...

22

Click here to load reader

Upload: lydang

Post on 27-Apr-2019

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

Internal Examination-IDepartment of Electronics and Communication and Engineering

Branch & Section: ECE Date: 05.08.14Semester: III Max.Marks:50Subject code& Title: EC6301& Faculty In-Charge: S.DeepajothiOOPs& Data Structures

Part-A (5x2=10 marks)Answer all the questions

1. Why do we need the preprocessor directive #include <iostream.h>?2. What is scope resolution operator and how it can be used for global

variable?3. Why it is necessary to overload an operator?4. What is meant by call by reference?5. Write any four special properties of constructor?

Part-B (40 marks)Answer all the questions

6. a) What are access specifiers? How are they used to protect data inc++? (16)

(or)6. b) What is a friend function? What are the merits and demerits of using

friend function? (16)

7. a) Write an operator overloading program for manipulating matrices. (16) (or)

7.b) Explain the operators used for dynamic memory allocation with examples? (16)

8. Explain control structures of C++ with suitable examples. (8)

********All the Best********

Faculty In-charge HoD/ECE

Internal Examination –IDepartment of Electronics and Communication and Engineering

Branch & Section: ECE Date: 05.08.14Semester: III Max.Marks:50Subject code& Title: EC6301& Faculty In-Charge: S.DeepajothiOOPs& Data Structures

Part-A (5x2=10 marks)Answer all the questions

1. Why do we need the preprocessor directive #include <iostream.h>?2. What is scope resolution operator and how it can be used for global

variable?3. Why it is necessary to overload an operator?4. What is meant by call by reference?5. Write any four special properties of constructor?

Part-B (40 marks)Answer all the questions

6. a) What are access specifiers? How are they used to protect data inc++? (16)

(or)6. b) What is a friend function? What are the merits and demerits of using

friend function? (16)

7. a) Write an operator overloading program for manipulating matrices. (16) (or)

7.b) Explain the operators used for dynamic memory allocation with examples? (16)

8. Explain control structures of C++ with suitable examples. (8)

********All the Best********

Faculty In-charge HoD/ECE

Page 2: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

INTERNAL EXAMINATION-I

ANSWER KEY

PART-A

1. Why do we need the preprocessor directive #include <iostream.h>

iostream is essentially all the stuff that allows C++ the ability to

communicate with the kernel so it can interface with the

hardware.

Besides kernel information, many function and classes are

defined there, so without it, you'll not be able to used most of its

functions.

2. What is scope resolution operator and how it can be used for global variable?There are two uses of the scope resolution operator in C++.

The first use being that a scope resolution operator is used to unhide the

global variable that might have got hidden by the local variables. Hence

in order to access the hidden global variable one needs to prefix the

variable name with the scope resolution operator (::).

e.g. int i = 10; int main () { int i = 20; cout << i; // this prints the value 20 cout << ::i; // in order to use the global i one needs to prefix it with the

scope resolution operator. } The second use of the operator is used to access the members declared

in class scope. Whenever a scope resolution operator is used the name

of the member that follows the operator is looked up in the scope of the

class with the name that appears before the operator.

3. Why it is necessary to overload an operator?

Operator overloading make more sense to C++ classes that are maths-oriented. The reason because all we tend to associate + - += -= etc etc literals as doing some maths operation. For business-centric C++ classes, the use is less clear.

The only one operator overloading I like to use in almost all business-centric C++ classes is the ostream << operator. Very useful.e.gcout << my_C++_object << "\n"; //viola all the object data members are printed out for easier debugging purposes .

4. What is meant by call by reference?

The call by reference method of passing arguments to a function copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.

To pass the value by reference, argument reference is passed to the functions just like any other value. So accordingly you need to declare the function parameters as reference types as in the

Page 3: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

following function swap(), which exchanges the values of the two integer variables pointed to by its arguments.

5. Write any four special properties of constructor?

o A constructor creates an Object of the class that it is in by

initializing all the instance variables and creating a place in

memory to hold the Object.

o It is always used with the keyword new and then the Class

name.

o For instance, new String(); constructs a new String object.

o Sometimes in a few classes you may have to initialize a few of

the variables to values apart from their predefined data type

specific values.

Part-B (40 marks)Answer all the questions

6. a) What are access specifiers? How are they used to protect data inc++?

There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:

Public - The members declared as Public are accessible from outside the Class through an object of the class.

Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.

Private - These members are only accessible from within the class. No outside Access is allowed.

An Source Code Example:

class MyClass{ public: int a; protected: int b; private: int c;};

int main(){ MyClass obj; obj.a = 10; //Allowed obj.b = 20; //Not Allowed, gives compiler error obj.c = 30; //Not Allowed, gives compiler error}

Inheritance and Access Specifiers

Inheritance is C++ can be one of the following types:

Private Inheritance Public Inheritance Protected inheritance

Here are the member access rules with respect to each of these:

Page 4: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

First and most important rule Private members of a class are never accessible from anywhere except the members of the same class.

Public Inheritance:

All Public members of the Base Class become Public Members of the derived class &All Protected members of the Base Class become Protected Members of the Derived Class.

i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.

Code Example:

Class Base{ public: int a; protected: int b; private: int c;};

class Derived:public Base{ void doSomething() { a = 10; //Allowed b = 20; //Allowed c = 30; //Not Allowed, Compiler Error }};

int main(){ Derived obj; obj.a = 10; //Allowed obj.b = 20; //Not Allowed, Compiler Error

obj.c = 30; //Not Allowed, Compiler Error

}

Private Inheritance:

All Public members of the Base Class become Private Members of the Derived class &All Protected members of the Base Class become Private Members of the Derived Class.

An code Example:

Class Base{ public: int a; protected: int b; private: int c;};

class Derived:private Base //Not mentioning private is OK because for classes it defaults to private { void doSomething() { a = 10; //Allowed b = 20; //Allowed c = 30; //Not Allowed, Compiler Error }};

class Derived2:public Derived{ void doSomethingMore() { a = 10; //Not Allowed, Compiler Error, a is private member of Derived now

Page 5: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

b = 20; //Not Allowed, Compiler Error, b is private member of Derived now c = 30; //Not Allowed, Compiler Error }};

int main(){ Derived obj; obj.a = 10; //Not Allowed, Compiler Error obj.b = 20; //Not Allowed, Compiler Error obj.c = 30; //Not Allowed, Compiler Error

}

Protected Inheritance:

All Public members of the Base Class become Protected Members of the derived class &All Protected members of the Base Class become Protected Members of the Derived Class.

A Code Example:

Class Base{ public: int a; protected: int b; private: int c;};

class Derived:protected Base { void doSomething() { a = 10; //Allowed b = 20; //Allowed c = 30; //Not Allowed, Compiler Error

}};

class Derived2:public Derived{ void doSomethingMore() { a = 10; //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2 b = 20; //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2 c = 30; //Not Allowed, Compiler Error }};

int main(){ Derived obj; obj.a = 10; //Not Allowed, Compiler Error obj.b = 20; //Not Allowed, Compiler Error obj.c = 30; //Not Allowed, Compiler Error}

(or)

6. b) What is a friend function? What are the merits and demerits of using friend function? (16)

A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends.

Page 6: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend as follows:

class Box{ double width;public: double length; friend void printWidth( Box box ); void setWidth( double wid );};

To declare all member functions of class ClassTwo as friends of class ClassOne, place a following declaration in the definition of class ClassOne:

friend class ClassTwo;

Consider the following program:

#include <iostream> using namespace std; class Box{ double width;public: friend void printWidth( Box box ); void setWidth( double wid );};

// Member function definitionvoid Box::setWidth( double wid ){ width = wid;}

// Note: printWidth() is not a member function of any class.

void printWidth( Box box ){ /* Because printWidth() is a friend of Box, it can directly access any member of this class */ cout << "Width of box : " << box.width <<endl;} // Main function for the programint main( ){ Box box; // set box width without member function box.setWidth(10.0); // Use friend function to print the wdith. printWidth( box ); return 0;}

When the above code is compiled and executed, it produces the following result:

Width of box : 10

7. a) Write an operator overloading program for manipulating matrices. (16)

The meaning of operators are already defined and fixed for basic types like: int, float, double etc in C++ language. For example: If you want to add two integers then, + operator is used. But, for user-defined types(like: objects), you can define the meaning of operator, i.e, you can redefine the way that operator works. For example: If there are two objects of a class that contain string as its data member, you can use + operator to concatenate two strings. Suppose, instead of strings if that class contains integer data member, then you can use + operator to add integers. This feature in C++ programming that allows programmer to redefine the meaning of operator when they operate on class objects is known as operator overloading.

Page 7: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

Why Operator overloading is used in C++ programming?

You can write any C++ program without the knowledge of operator overloading. But, operator operating are profoundly used by programmer to make a program clearer. For example: you can replace the code like: calculation = add(mult(a,b),div(a,b)); with calculation = a*b+a/b; which is more readable and easy to understand.

How to overload operators in C++ programming?

To overload a operator, a operator function is defined inside a class as:

The return type comes first which is followed by keyword operator, followed by operator sign,i.e., the operator you want to overload like: +, <, ++ etc. and finally the arguments is passed. Then, inside the body of you want perform the task you want when this operator function is called.

This operator function is called when, the operator(sign) operates on the object of that class class_name.

Example of operator overloading in C++ Programming

/* Simple example to demonstrate the working of operator overloading*/#include <iostream>using namespace std;class temp{ private: int count; public: temp():count(5){ } void operator ++() { count=count+1; } void Display() { cout<<"Count: "<<count; }};int main(){ temp t; ++t; /* operator function void operator ++() is called */ t.Display(); return 0;}

Output

Count: 6

Explanation

In this program, a operator function void operator ++ () is defined(inside class temp), which is invoked when ++ operator operates on the object of type temp. This function will increase the value of count by 1.

Page 8: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

Things to remember while using Operator overloading in C++ language

1. Operator overloading cannot be used to change the way operator works on built-in types. Operator overloading only allows to redefine the meaning of operator for user-defined types.

2. There are two operators assignment operator(=) and address operator(&) which does not need to be overloaded. Because these two operators are already overloaded in C++ library. For example: If obj1 and obj2 are two objects of same class then, you can use code obj1=obj2; without overloading = operator. This code will copy the contents object of obj2 to obj1. Similarly, you can use address operator directly without overloading which will return the address of object in memory.

3. Operator overloading cannot change the precedence of operators and associativity of operators. But, if you want to change the order of evaluation, parenthesis should be used.

4. Not all operators in C++ language can be overloaded. The operators that cannot be overloaded in C++ are ::(scope resolution), .(member selection), .*(member selection through pointer to function) and ?:(ternary operator).

7.b) Explain the operators used for dynamic memory allocation with examples?

A good understanding of how dynamic memory really works in C++ is essential to becoming a good C++ programmer. Memory in your C++ program is divided into two parts:

The stack: All variables declared inside the function will take up memory from the stack.

The heap: This is unused memory of the program and can be used to allocate the memory dynamically when program runs.

Many times, you are not aware in advance how much memory you will need to store particular information in a defined variable and the size of required memory can be determined at run time.

You can allocate memory at run time within the heap for the variable of a given type using a special operator in C++ which returns the address of the space allocated. This operator is called new operator.

If you are not in need of dynamically allocated memory anymore, you can use delete operator, which de-allocates memory previously allocated by new operator.

The new and delete operators:

There is following generic syntax to use new operator to allocate memory dynamically for any data-type.

new data-type;

Here, data-type could be any built-in data type including an array or any user defined data types include class or structure. Let us start with built-in data types. For example we can define a pointer to type double and then request that the memory be allocated at execution time. We can do this using the new operator with the following statements:

double* pvalue = NULL; // Pointer initialized with nullpvalue = new double; // Request memory for the variable

The memory may not have been allocated successfully, if the free store had been used up. So it is good practice to check if new operator is returning NULL pointer and take appropriate action as below:

double* pvalue = NULL;if( !(pvalue = new double )){ cout << "Error: out of memory." <<endl;

Page 9: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

exit(1);

}

The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc() function. The main advantage of new over malloc() is that new doesn't just allocate memory, it constructs objects which is prime purpose of C++.

At any point, when you feel a variable that has been dynamically allocated is not anymore required, you can free up the memory that it occupies in the free store with the delete operator as follows:

delete pvalue; // Release memory pointed to by pvalue

Let us put above concepts and form the following example to show how new and delete work:

#include <iostream>using namespace std;

int main (){ double* pvalue = NULL; // Pointer initialized with null pvalue = new double; // Request memory for the variable *pvalue = 29494.99; // Store value at allocated address cout << "Value of pvalue : " << *pvalue << endl;

delete pvalue; // free up the memory.

return 0;}

If we compile and run above code, this would produce the following result:

Value of pvalue : 29495Dynamic Memory Allocation for Objects:

Objects are no different from simple data types. For example, consider the following code where we are going to use an array of objects to clarify the concept:

#include <iostream>using namespace std;

class Box{ public: Box() { cout << "Constructor called!" <<endl; } ~Box() { cout << "Destructor called!" <<endl; }};

int main( ){ Box* myBoxArray = new Box[4];

delete [] myBoxArray; // Delete array

return 0;}

If you were to allocate an array of four Box objects, the Simple constructor would be called four times and similarly while deleting these objects, destructor will also be called same number of times.

If we compile and run above code, this would produce the following result:

Page 10: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

Constructor called!Constructor called!Constructor called!Constructor called!Destructor called!Destructor called!Destructor called!Destructor called!

8. Explain control structures of C++ with suitable examples. (8)

Control structures form the basic entities of a “structured programming language“. We all know languages like C/C++ or Java are all structured programming languages. Control structures are used to alter the flow of execution of the program.  Why do we need to alter the program flow ? The reason is “decision making“! In life, we may be given with a set of option like doing “Electronics” or “Computer science”. We do make a decision by analyzing certain conditions (like our personal interest, scope of job opportunities etc). With the decision we make, we alter the flow of our life’s direction. This is exactly what happens in a C/C++ program. We use control structures to make decisions and alter the direction of program flow in one or the other path(s) available.

There are three types of control structures available in C and C++

1) Sequence structure (straight line paths)

2) Selection structure (one or many branches)

3)Loop structure (repetition of a set of activities)

All the 3 control structures and its flow of execution is represented in the flow charts given below.

Control statements in C/C++ to implement control structures

We have to keep in mind one important fact:- all program processes can be implemented with these 3 control structures only. That’s why I wrote “control structures are the basic entities of a structured programming language“. To  implements these “control structures” in a C/C++ program, the language provides ‘control statements’.  So to implement a particular control structure in a programming language, we need to learn how to use the relevant control statements in that particular language.

Page 11: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

The control statements are:-

Switch If If Else While Do While For

As shown in the flow charts:-

Selection structures are implemented using If , If Else and Switch statements.

Looping structures are implemented using While, Do While and For statements.

Selection structures 

Selection structure

Selection structures are used to perform ’decision making‘ and then branch the program flow based on the outcome of decision making. Selection structures are implemented in C/C++ with If, If Else and Switch statements. If and If Else statements are 2 way branching statements where as Switch is a multi branching statement.

The simple If statementThe syntax format of a simple if statement is as shown below.

if (expression) // This expression is evaluated. If expression is TRUE statements inside the braces will be executed{statement 1;statement 2;}statement 1;// Program control is transfered directly to this line, if the expression is FALSEstatement 2;

The expression given inside the brackets after if is evaluated first. If the expression is true, then statements inside the curly braces that follow if(expression) will be executed. If the expression is false, the statements inside curly braces will not be executed and program control goes directly to statements after curly braces.

Example program to demo “If” statement

Problem:- 

A simple example program to demo the use of If, If Else and Switch is shown here. An integer value is collected from user.If the integer entered by user is 1 – output on screen “UNITED STATES”. If the integer is 2 – output “SPAIN”, If the integer is 3

Page 12: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

output “INDIA”. If the user enters some other value – output “WRONG ENTRY”.

Note:- The same problem is used to develop example programs for “if else” and “switch” statements

#includevoid main(){int num;printf("Hello user, Enter a number");scanf("%d",&num); // Collects the number from userif(num==1){printf("UNITED STATES");}if(num==2){printf("SPAIN");}if(num==3){printf("INDIA");}}

The If Else statement.Syntax format for If Else statement is shown below.

if(expression 1)// Expression 1 is evaluated. If TRUE, statements inside the curly braces are executed.{ //If FALSE program control is transferred to immedate else if statement.

statement 1;statement 2;}else if(expression 2)// If expression 1 is FALSE, expression 2 is evaluated.{statement 1;

statement 2;}else if(expression 3) // If expression 2 is FALSE, expression 3 is evaluated{statement 1;statement 2;}else // If all expressions (1, 2 and 3) are FALSE, the statements that follow this else (inside curly braces) is executed.{statement 1;statement 2;}other statements;

The execution begins by evaluation expression 1. If it is TRUE, then statements inside the immediate curly braces is evaluated. If it is FALSE, program control is transferred directly to immediate else if statement. Here expression 2 is evaluated for TRUE or FALSE. The process continues. If all expressions inside the different if and else if statements are FALSE, then the last else statement (without any expression) is executed along with the statements 1 and 2 inside the curly braces of last else statement.

Example program to demo “If Else”

#includevoid main(){int num;printf("Hello user, Enter a number");scanf("%d",&num); // Collects the number from userif(num==1){printf("UNITED STATES");}else if(num==2){

Page 13: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

printf("SPAIN");}else if(num==3){printf("INDIA");}else{printf("WRONG ENTRY"); // See how else is used to output "WRONG ENTRY"}}

Note:- Notice how the use of If Else statements made program writing easier. Compare this with above program using simple If statement only.

Switch statementSwitch is a multi branching control statement. Syntax for switch statement is shown below.

switch(expression)// Expression is evaluated. The outcome of the expression should be an integer or a character constant{case value1: // case is the keyword used to match the integer/character constant from expression.//value1, value2 ... are different possible values that can come in expressionstatement 1;statement 2;break; // break is a keyword used to break the program control from switch block.case value2:statement 1;statement 2;break;default: // default is a keyword used to execute a set of statements inside switch, if no case values match the expression value.statement 1;

statement 2;break;}

Execution of switch statement begins by evaluating the expression inside the switch keyword brackets. The expression should be an integer (1, 2, 100, 57 etc ) or a character constant like ‘a’, ‘b’ etc. This expression’s value is then matched with each case values. There can be any number of case values inside a switch statements block. If first case value is not matched with the expression value, program control moves to next case value and so on. When a case value matches with expression value, the statements that belong to a particular case value are executed.

Notice that last set of lines that begins with default. The word default is a keyword in C/C++. When used inside switch block, it is intended to execute a set of statements, if no case values matches with expression value. So if no case values are matched with expression value, the set of statements that follow default: will get executed.

Note: Notice the break statement used at the end of each case values set of statements. The word break is a keyword in C/C++ used to break from a block of curly braces. The switch block has two curly braces { }. The keyword break causes program control to exit from switch block.

Example program to demo working of “switch” 

#includevoid main(){int num;printf("Hello user, Enter a number");scanf("%d",&num); // Collects the number from userswitch(num){case 1:printf("UNITED STATES");break;

Page 14: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

case 2:printf("SPAIN");break;case 3:printf("INDIA");default:printf("WRONG ENTRY");}}

Note:- Switch statement is used for multiple branching. The same can be implemented using nested “If Else” statements. But use of nested if else statements make program writing tedious and complex. Switch makes it much easier. Compare this program with above one.

Loop structures

Loop Structure

A loop structure is used to execute a certain set of actions for a predefined number of times or until a particular condition is satisfied. There are 3 control statements available in C/C++ to implement loop structures. While, Do while and For statements.

The while statement

Syntax for while loop is shown below:

while(condition)// This condition is tested for TRUE or FALSE. Statements inside curly braces are executed as long as condition is TRUE{statement 1;statement 2;statement 3;}

The condition is checked for TRUE first. If it is TRUE then all statements inside curly braces are executed.Then program control comes back to check the condition has changed or to check if it is still TRUE. The statements inside braces are executed repeatedly, as long as the condition is TRUE. When the condition turns FALSE, program control exits from while loop.

Note:- while is an entry controlled loop. Statement inside braces are allowed to execute only if condition inside while is TRUE.

Example program to demo working of “while loop”

An example program to collect a number from user and then print all numbers from zero to that particular collected number is shown below. That is, if user enters 10 as input, then numbers from 0 to 10 will be printed on screen.

Page 15: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

Note:- The same problem is used to develop programs for do while and for loops

#includevoid main(){int num;int count=0; // count is initialized as zero to start printing from zero.printf("Hello user, Enter a number");scanf("%d",&num); // Collects the number from userwhile(count<=num) // Checks the condition - if value of count has reached value of num or not.{printf("%d",count);count=count+1; // value of count is incremented by 1 to print next number.}}

The do while statement

Syntax for do while loop is shown below:

do{statement 1;statement 2;statement 3;}while(condition);

Unlike while, do while is an exit controlled loop. Here the set of statements inside braces are executed first. The condition inside while is checked only after finishing the first time execution of statements inside braces. If the condition is TRUE, then statements are executed again. This process continues as long as condition is TRUE. Program control exits the loop once the condition turns FALSE.

Example program to demo working of "do while"

#includevoid main(){int num;int count=0; // count is initialized as zero to start printing from zero.printf("Hello user, Enter a number");scanf("%d",&num); // Collects the number from userdo{printf("%d",count); // Here value of count is printed for one time intially and then only condition is checked.count=count+1; // value of count is incremented by 1 to print next number.}while(count<=num);}

The for statement

Syntax of for statement is shown below:

for(initialization statements;test condition;iteration statements){statement 1;statement 2;statement 3;}

The for statement is an entry controlled loop. The difference between while and for is in the number of repetitions. The for loop is used when an action is to be executed for a predefined number of times. The while loop is used when the number of repetitions is not predefined.

Page 16: file · Web viewInternal Examination-I. Department of . Electronics and Communication. and Engineering. Branch & Section: ECE. Date: 05.08.14. Semester: III. Max.Marks:50. Subject

Working of for loop:

The program control enters the for loop. At first it execute the statements given as initialization statements. Then the condition statement is evaluated. If conditions are TRUE, then the block of statements inside curly braces is executed. After executing curly brace statements fully, the control moves to the "iteration" statements. After executing iteration statements, control comes back to condition statements. Condition statements are evaluated again for TRUE or FALSE. If TRUE the curly brace statements are executed. This process continues until the condition turns FALSE.

Note 1:- The statements given as "initialization statements" are executed only once, at the beginning of a for loop.Note 2: There are 3 statements given to a for loop as shown. One for initialization purpose, other for condition testing and last one for iterating the loop. Each of these 3 statements are separated by semicolons.

Example program to demo working of  "for loop"

#includevoid main(){int num,count;printf("Hello user, Enter a number");scanf("%d",&num); // Collects the number from userfor(count=0;count<=num;count++)// count is initialized to zero inside for statement. The condition is checked and statements are

executed.{printf("%d",count); // Values from 0 are printed.}}

So that is all about "control statements" in C/C++ language. If you have any doubts ask in comments section.

****************** END ********************

Subject-Incharge HoD/ECE