Control
structure:
Control
structure defines the flow of execution of a program.
There are
following control structures:
1. Sequential
2. Iteration
3. Conditional
4. Functions
Sequential
The sequential control structure is a type which
defines that the flow of execution will in a sequence.
Here is an example to understand it
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout << “Hello
world” ;
getch();
}
The above program is the example of sequential control structure. It means
that firstly clrscr(); function will be executed and then cout<< “Hello
world” ; statement will be executed and then getch(); function will be
executed. It is the normal flow of the execution of a program.
Iteration
Iteration means repetition. Iteration means
repeating a block of statement instead of writing the same statement many
times.
Here is an example to understand:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int c=0;
while(c<=5)
cout << “I love
Pakistan” << endl ;
getch();
}
Output:
I love Pakistan
I love Pakistan
I love Pakistan
I love Pakistan
I love Pakistan
The above example is the example of iteration control structure. It will
execute until value of c doesn’t reached to 5. Means it repeats cout <<
“I Love Pakistan” << endl ; five times.
The above output
can be generated by the following program.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout << “I love Pakistan” << endl
;
cout << “I love Pakistan” << endl
;
cout << “I love Pakistan” << endl
;
cout << “I love Pakistan” << endl
;
cout << “I love Pakistan” << endl
;
getch();
}
There are the main types of loops:
1. while loop
2. do-while loop
3. for loop
Later we will discuss about the types of loop in details.
Conditional
Conditional control structure defines the flow of
execution of a program in a condition.
Here is an example to understand the conditional control structure.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int marks;
cout<< “Enter marks: ” ;
cin>> marks;
if (marks > 40)
cout<< “ Congratulation! You have passed
” ;
getch();
}
In the above example
if you input marks to 40 the output will be “Congratulation!
You have passed” otherwise there will be nothing in the output of the program.
Function:
A Function is a set of instructions which is used
to perform a specific task. Every C++ program has at least one function which
is main(). You can divide your
program info different function depending on you.
Example:
A simple example of the function is the “clrscr();” function which is used to
clear the output window.
No comments:
Post a Comment