Experiment 3
Experiment 3
Theory:
Loops in C++
Loops in C++ allow code to execute repeatedly based on a condition. Loops are fundamental in
programming for tasks where operations need to be repeated a certain number of times or until a
specific condition is met. There are three main types of loops in C++:
1. For Loop
2. While Loop
3. Do-While Loop
Entry-Controlled Loops
These loops check the loop condition at the start of each iteration. If the
condition is true, the loop body executes; if false, it skips. Examples in C++
include for and while loops.
Exit-Controlled Loops
These loops check the loop condition at the end of each iteration. This
guarantees that the loop executes at least once, regardless of the condition.
In C++, the do-while loop is exit-controlled.
Increment Operator
Increment Operator (++): This operator increases the value of a variable by 1. It can be used in
two forms:
Decrement Operator (--): This operator decreases the value of a variable by 1. It also has two
forms:
For Loop
While Loop
A do-while loop executes the loop body first, then checks the condition.
This ensures it runs at least once.
Syntax:
Do {
// Code to execute
} while (condition);
Explanation:
1. The loop body executes once before checking condition.
2. After the first run, condition is evaluated. If true, the loop
continues; if false, it exits.
Algorithm:
1. Start
2. Declare and Initialise variable num1=0,num2=1,num,number
3. Get numbers to be printed (num)
4. num = num - 2
5. Print num1 and num2
6. For i = 1, i++, while i < num
number = num1 + num2
num1 = num2
num2 = number
Print number
7. Stop
Flowchart:
Output
Conclusion
Thus from above experiment we understood the difference between entry
controlled and exit controlled loops, difference between types of increment
and decrement operators and how for loop, while loop & do-while loop works.