C Basics Loop
C Basics Loop
Language
Example 1:
#include <iostream>
int main() {
for (int i = 1; i <= 10; i++) {
cout << i << " ";
}
cout << endl;
return 0;
}
2.Main function:
•The for loop:
•for (int i = 1; i <= 10; i++):
•Initializes i to 1.
•Continues the loop as long as i is less than or equal to 10.
•Increments i by 1 after each iteration.
•cout << i << " ";: Prints the current value of i followed by a
space.
•cout << endl;: Prints a newline character to move to the next line.
Example 2:
1.Include header:
•#include <iostream>: Includes the standard input/output stream library for
input and output operations. #include <iostream>
}
4.Return statement: cout << endl;
•return 0;: Indicates successful program execution and returns 0 to the
operating system.
This program effectively demonstrates the use of a for loop to iterate through a return 0;
range of values and perform calculations or actions based on conditions. It provides
a clear and concise example of how loops can be used in C++ programming. }
C++ While Loop
Entry Controlled loops: In this type of loop, the test condition is tested before
entering the loop body. For Loop and While Loop is entry-controlled loops.
Exit Controlled Loops: In this type of loop the test condition is tested or
evaluated at the end of the loop body. Therefore, the loop body will execute at
least once, irrespective of whether the test condition is true or false. the do-
while loop is exit controlled loop.
DIY
DIY
C++ Do/While Loop
C++ Do/While Loop
C++ For Loop
Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been
executed.
Exercises:
Exercises:
Exercises:
1. Do-while Loop - do while loop prompts the user to enter a positive integer and adds it to the variable sum if it is positive. This process continues until the user enters a
negative integer.
The "inner loop" will be
Nested Loops executed one time for each
iteration of the "outer loop":
The foreach Loop
C++ Break
C++ Continue
Break and Continue in While Loop