For Statement (Contd.)
Summary
TLDRThis script discusses the use of the for loop in programming, exploring its structure including initialization, condition checking, and modulator expressions. It highlights the ability to use arithmetic expressions within the loop and the potential for infinite loops. Examples are provided to illustrate how to compute factorials and sum of squares using for loops. The script also touches on the use of the break and continue statements to control loop execution, emphasizing best practices for readability and logic in programming.
Takeaways
- 🔁 The for loop is a control structure used for creating loops in a program, consisting of initialization, condition checking, and a modulator (alteration) expression.
- 📐 Arithmetic expressions are used within the for loop for initialization and condition checking, allowing for complex conditions and variable manipulation.
- 🔄 The modulator expression can be used to increment or decrement the loop control variable, or to modify it in other ways, hence it's sometimes better referred to as an alteration expression.
- ⏪ The for loop can be used to create loops that count down, not just up, by using a decrementing modulator expression.
- 🚫 If the loop continuation condition is false from the start, the body of the for loop will not be executed even once.
- 🎲 Examples provided in the script demonstrate how to compute factorials and sum of squares using for loops, showcasing their versatility.
- 🔀 The comma operator allows for multiple initialization or alteration expressions within the for loop, although it's advised against for beginners due to potential readability issues.
- 🔁 Infinite loops can be created using for loops by omitting the initialization, condition, and modulator expressions, resulting in a loop that runs indefinitely.
- 🛑 The break statement can be used to exit a for loop prematurely when a specific condition is met, allowing for early termination of the loop.
- 🔁 The continue statement is used to skip the remaining part of the loop body and proceed to the next iteration of the loop.
Q & A
What is the purpose of the 'for' statement in programming?
-The 'for' statement is used to create loops in a program, allowing for repeated execution of a block of code as long as a specified condition is true.
What are the three main components of a 'for' loop?
-The three main components of a 'for' loop are the initialization expression, the loop continuation condition, and the alteration expression.
Can the increment in a 'for' loop be negative?
-Yes, the increment in a 'for' loop can be negative, allowing the loop to count down or decrement the loop control variable.
What is an infinite loop and how can it be created using a 'for' loop?
-An infinite loop is a loop that continues to execute indefinitely because the loop continuation condition never becomes false. It can be created using a 'for' loop by omitting the initialization, condition, and alteration parts, or by setting the condition to always be true.
What is the role of the 'break' statement in loops?
-The 'break' statement is used to exit a loop prematurely when a certain condition is met, preventing further iterations of the loop.
How does the 'continue' statement function within a loop?
-The 'continue' statement is used to skip the remaining part of the loop body and proceed to the next iteration of the loop.
What is the significance of the comma operator in the context of 'for' loops?
-The comma operator allows multiple expressions to be included in the initialization or alteration part of a 'for' loop, separating them with commas.
Why might a programmer choose to use a 'do while' loop instead of a 'for' loop?
-A programmer might choose to use a 'do while' loop instead of a 'for' loop when they want to ensure that the loop body executes at least once before the condition is checked.
Can you provide an example of how a 'for' loop can be used to compute the factorial of a number?
-A 'for' loop can be used to compute the factorial of a number by initializing a variable to 1, using a loop to multiply this variable by each integer up to the number, and breaking the loop when the factorial exceeds a certain value.
What is the difference between a 'for' loop and a 'while' loop in terms of their syntax and usage?
-A 'for' loop is more compact and is typically used when the number of iterations is known beforehand, while a 'while' loop is used when the number of iterations is not known and depends on a condition that is checked before each iteration.
Outlines
🔁 Understanding For Loops
This paragraph delves into the intricacies of for loops in programming, emphasizing their structure and functionality. It begins by contrasting for loops with while and do-while loops previously discussed. The for loop is dissected into three components: initialization, condition checking, and a modulator (previously termed 'increment'). The paragraph clarifies that the modulator can be any arithmetic expression, not just an increment, and illustrates this with examples. It also introduces the concept of a negative increment, or decrement, to reverse the order of operations within the loop. The paragraph concludes with a cautionary note on the complexity of expressions within for loops, advising beginners to prioritize clarity over brevity.
📉 Looping in Reverse with For Loops
The second paragraph demonstrates the use of for loops to iterate in reverse order. It provides a practical example where the loop prints numbers from 10 down to 5. This is achieved by initializing a variable 'j' to 10 and decrementing it within the loop until it reaches 5. The discussion highlights the flexibility of the for loop's structure, where the modulator part can be adjusted to not only increment but also decrement the loop variable. The paragraph also touches on the importance of the loop continuation condition, explaining that if this condition is false from the start, the loop body will not execute. It concludes with an example of computing factorials using a for loop, emphasizing the loop's utility in repetitive tasks.
🔢 For Loops for Summation and Factorials
This paragraph explores the application of for loops in summing series and calculating factorials. It presents a for loop that calculates the sum of squares of the first N natural numbers, explaining how the loop accumulates the sum with each iteration. Additionally, it revisits the factorial calculation, introducing the comma operator to condense the initialization and incrementation steps into a single line. The paragraph also addresses common pitfalls for beginners, such as omitting variable declarations and the potential for overly compact code to reduce readability. It concludes with a reminder to prioritize logical and syntactical correctness over code brevity.
🔄 Infinite Loops and Control Statements
The fourth paragraph introduces the concept of infinite loops, explaining how they occur when a loop's continuation condition never becomes false. It provides examples of how infinite loops can be intentionally created using for and while constructs, such as using 'for (;;)' or 'while (1)'. The paragraph also discusses the utility of infinite loops for tasks that require continuous operation. It then transitions into the discussion of control statements like 'break' and 'continue', explaining their role in exiting loops prematurely or skipping parts of the loop body. The 'break' statement is illustrated with an example where it is used to terminate a loop once a factorial exceeds a certain value, showcasing its use in conditional loop termination.
🚫 Breaking and Continuing Loops
This paragraph delves deeper into the use of 'break' and 'continue' statements within loops. It explains that 'break' is used to exit a loop immediately when a specific condition is met, using a factorial calculation example to demonstrate its application. The 'continue' statement, on the other hand, is shown to skip the remaining part of the loop body and proceed to the next iteration. The paragraph provides a detailed walkthrough of how these statements affect loop execution, emphasizing their utility in controlling loop flow. It concludes with a reminder of the importance of understanding loop mechanics for effective programming.
Mindmap
Keywords
💡for statement
💡arithmetic expression
💡increment
💡decrement
💡modulator
💡initialization
💡loop continuation condition
💡factorial
💡infinite loop
💡break statement
💡continue statement
Highlights
Introduction to the creation of loops using the for statement in programming.
Explanation of the for statement structure with initialization, condition checking, and alteration expressions.
Use of arithmetic expressions within the for loop structure.
Example of a for loop with a positive incrementing modulator.
Demonstration of a for loop with a negative decrementing modulator for reverse order printing.
Clarification that the alteration expression in a for loop can be any arithmetic operation, not just increment or decrement.
Discussion on the importance of the loop continuation condition and its impact on loop execution.
Example of a factorial calculation using a for loop.
Illustration of computing the sum of squares of natural numbers up to N using a for loop.
Introduction to the comma operator for including multiple initialization or alteration statements in a for loop.
Caution against using the comma operator for初学者 to avoid confusion and maintain code readability.
Definition and example of an infinite loop and its practical applications.
Explanation of how to create an infinite loop using a for statement with empty initialization, condition, and alteration parts.
Introduction to the break statement for exiting a loop prematurely based on a specific condition.
Example of using break in a while loop to exit when a factorial exceeds a certain value.
Introduction to the continue statement for skipping the remaining part of a loop's body and proceeding to the next iteration.
Example illustrating the combined use of continue and break statements in a loop.
Emphasis on understanding the for loop for repetition as a fundamental concept in programming.
Transcripts
Now, we are discussing about formation of loops,
creation of loops in a program using for statement. Before that we have seen the
while statement and do while statement and then we have seen the for statement as well.
Now, the for statement as we had shown we had discussed in the last class it is
basically starting to take an expression, arithmetic expression and then it starts
with in sorry initialization expression and then we check a particular condition. So,
something like this for some variable integer variable j assigned some value 5 maybe and then
some expression here this one is j less than equal to 25 and then here there will be some statements
which will be executed and after that there is a third expression which is altering it and that can
be j assigned j plus 5 all right and the body of the x loop. These are structure that we had seen.
Now, there are some critical issues that are to be noted for the for structure.
So, if you look at this you can see that we are using arithmetic expressions. For example,
x assigned 2 and y assigned 10 that is an arithmetic expression. So, similarly this
is a valid arithmetic expression for j assigned x, j less than equal to 4 times x times y that is the
condition. That means, after some computation will have to find out whether j is satisfying
this condition and here j here probably this is something this construct we have not shown you,
this is I do not like it very much and initially you need not bother about this j plus equal to y
by x this is a C structure, say C syntax expressing j equals j plus y by x. So,
the whole thing can be written in this way. So, this, but that is not important for the
purpose of understanding for expressions. So, here is just an expression.
And this is equivalent to like this for say x was 2 and y was 10, then this is equivalent to
j assigned 2 because j assigned x and j assigned 2 are essentially same; j as less than equal to 4
times x times y that means, 4 times 2 times 10 that means, 80 and j equals assigned j plus y
by x is 5. So, this is equivalent all right. So, this is initialization, this is loop continuation
condition and this is the increment or I as I was saying that this is a modulator or the alteration.
Now, increment can be negative. So, this increment all the way we are calling it increment that is
why we should not call it increment let us call it a modulator because say the same thing I can
write as for j assigned 2 maybe something j less than equal to 80 and might be j minus minus. It
can be the case when can it be. Say for example, if I add if I want that I will be printing the
numbers in the reverse order starting from 10. So, what should I do? So, can I do this what I
want to do is, that I want to print something like 10 9 8 7 5 all right in this order.
So, simply I can do this repeatedly in a loop for example, for j assigned 10 and j sorry, j
greater than equal to 5 j minus minus and here I just do printf percentage d backslash n j. So,
what will happen? Initially j is 10 less greater than equal to 5, so 10 will be printed. Then I
go back I decrement j. So, j will become 9 still greater than equal to 5 I come in here print j 9,
I again decrement j decrement j becomes 8 I compare with this still it is greater than
equal to 5 I get in and printed. In that way I can do it I can repeatedly do the same thing,
but here as you can see I am being able to achieve this reverse order by instead of
incrementing and decrementing this index. That is why I can increment to decrement,
I can multiply it, I change it, I modulate it, that is why this to an alteration
expression or modulation expression is a better term than increment or decrement.
So, if the loop continuation, if the loop continuation condition is
initially false is initially false then the body struck the for structure will
not be executed. It will proceed with the statement for the next statement.
So, for example, if I write something like this as you have seen earlier j
equal to 20 and for i equals i assigned 1, i greater than j i plus plus say and then I
want to do some things here all right. Now, j is 20 I will first initialize i
to 1 and immediately I find the first thing that I do is its false I check this and its
false i is not greater than j therefore, this stay these statements will not be
executed even once and the statements following the for loop will be executed.
Now, here are some examples of for loops. This is again computing the factorial
fact. Factorial is a the variable, fact is touring the factorial factorial all of you
know as factorial n is n multiplied by n minus 1 multiplied by n minus 2 so on so forth up to 1.
So, it is 1 and I have got a variable i. Now, you can see simply I can do it like this i assigned 1,
i less than 10 i plus plus fact assign fact times i. Now, what is happening here? So,
I have got fact to be 1. So, i equals 1 then with that what I do is 1 times 1 is
fine and I then make i to be 2 and then i, i becomes then 2. So, 1 times 2 then i becomes
3 then 1 times 2 times 3 then i becomes 4 then 1 times 2 times 4 times 3 times 4 and
so on and so forth it will go on in this loop. So, that is a nice way of writing factorial.
And here is another example you can see what it does quickly. You can explain it yourself what
it does. Sum is 0 and N is a variable and count is another integer variable all right. Sum is 0,
N is a 1 variable and count is another integer variable. Now,
we are reading N and for i equals 1, i less than equal to N I am adding some. So, what is
being done here what will happen if I press this program what is going to happen? Let us do that.
Suppose I have read N to be here, I have read N to be 5. Now, what am I doing here? I here there is
one problem here i should have been declared there is a mistake here int N and here i also add i
should have been declared here. Now, i assigned 1. So, i is 1, N was 5, i less than 5 less than equal
to 5. So, sum is sum was 0. So, sum is 0 plus i times i, i was 1. So, 0 plus 1 square and then I
check i increment i. So, i becomes 2, i becomes 2 and I check that i is less than it not less
than a is still less than equal to 5 so I got this sum and with that I add now, i square i times i,
so 2 square. Similarly, it will go on it will do 3 square. So, i will become then 4 and then still
it is less than equal to, so 4 square then i will become 5 and still it is true. So, it
will be 5 squared then i become 6 this condition will be violated and i will come to this printf.
So, what will sum be sum is 1 square plus 2 square plus 3 square and if I make it N then
up to N square. So, this is the very well known series the sum of the square of natural numbers
we can compute by this small program using for loop right. So, it is a nice example.
Now, we introduce the comma operator. As we say that here for when we write for then i assigned
1 instead of that I can put in more than one statements here using a comma operator. For
example, for fact 1 i equals 1, i less than equal to 10. Now, this part is what? This part
is the initialization. Now, remember that this will not be continuously initialized,
this is just an just a statement that I put here an assignment statement,
but my index variable for the control variable for the loop is i. So, I could have written
this earlier example of factorial maybe, earlier example of factorial this could be
initialized here also all right. So, that is just saving space saving the number of lines of code.
But personally I would suggest as I did earlier also that is for of those of you who are beginners
in programming you should not try this tricks or should not try this thriftiness reducing
the number of lines, that is not so important to how much you can reduce. The most important
thing is to be logically can syntactically correct while you write a program ok.
So, we can give several things in comma like some here again. So, the program becomes even smaller
look smarter, but sometimes at the beginning if you try to do that you try to be smart and
in the process you may result in some long program long long logic better avoid that.
Now, infinite loop in general what is an infinite loop. When a program continues,
program continues in a loop repeatedly it goes on and it is never completing its going on because
the condition that is supposed to turn out to be false at a particular point of time. So,
that it comes up the out of the loop never happens all right. That can always happen
that say if I write something like for i equals 1, i less than n and whatever i plus plus. Now,
every time inside the loop when you get in you read you do something and then increment i and
when you come inside the loop you do i minus minus, then whatever has been done here will be
canceled out here. So, this loop will never reach this condition I less than i therefore, that this
loop will continue forever such situations are known as the condition of infinite loop.
Now, sometimes usually we do not like that, but sometimes it may be necessary to specify
that something will happen forever all right. Say some particular work has to be done continuously.
Now, in order to specify that for loop provides us some facility like say for
and while everything say this one we had discussed earlier while 1, that means,
always it is true it is a nonzero this while loop this expression part condition
expression part should return nonzero and so it will go on. Now, here for and I put null;
that means, the for has had 3 parts, for the initialization part, some condition part and some
incrementation decrementation part whatever. Now, I just keep everything blank. So,
I turn it to be for nothing and nothing all these things are blank. In that case what
will happen? In that case what will happen? If I keep some statements here that will go on forever.
Similarly if I in the case of do while if I just put while 1 that is again in finite loop. So,
by this I can express my desire that some things will have should continue forever all right. So,
this is another trick that you can utilize in some cases for the for and the while constraints.
Now, we come to another statement which we have encountered a little few lectures earlier in
the context of switch statements. While we are considering the switch statements if you recall
you have seen that after every case statement switch on a particular variable then their case
red case, green case, blue if you recall then we did something and then give a break, did something
give a break like that we proceeded right. So, the break statement of course, we know
can help us we can use it with several things one is while, do while, for and switch. Now,
this switch, switch part we have seen, but we can also use it for while do while and for,
for breaking out of the loop, we want to break out of the loop. Sometimes that is required it
works with while, do while, for, but does not work with if and else statement. It causes
immediately exit from a while for a do while or case we have seen that switch statements earlier.
So, the program continues after with the next statement let us see. Why do we want
to use it? It helps us to escape early from a loop. Sometimes we want to escape early I
do not want to go till the end of the loop, when a particular condition is met I want
to come out. I am doing it in a loop, but waiting for some condition to take
place as soon as that condition takes place I come out of the loop. Maybe,
as we have seen in the case statement switch some expression all right color, then case R
we do something and then give break right, case G we do something and then give break right we do
like that. So, we skip the remaining part of the switch block right. We come out of that.
So, similarly we will see a couple of examples of this. Say here there is a complete example let us
look at that. Here is a complete example complete program, once again include stdio dot h you are
running some programs main, then fact and i are integers fact we are computing factorial. So,
fact is 1, i is 1, while i is less than 10; that means, I want to break out while
i is less than 10 fact times i, if fact is greater than 100, then factorial is above
100 factorial of a number is above 100. So, for example, I am going on up to 10 numbers. So,
what will happen with the factorials? Let us see. So, factorial 1 will be 1, factorial 2 will be 2,
factorial 3 will be 3 times 2 that is 6, factorial 4 will be 4 times 3 for 4 times 6, it will be 4
times 3 times 2, so 4 times 6; that means 24, then 24 times 5, so that will be how much it will be,
more than how much will it be if I have got this 4 3 2 and multiply that with 5, so 26.
So, here just with 5 numbers I am exceeding the value 120, but I do not know when I am
going to reach the value 100. So, I have written the program in this way,
fact while i is less than 10 I will test it up to 10 numbers every time, I compute fact if fact is
greater than 100 print. So, here as soon as fact becomes 100 will say factorial of 5 is above 100,
factorial of 5 is above 100 and then I break out. Otherwise if I had not put this break then this
would have continued till this loop all for all the 10 numbers up to factorial 10, but I just want
to stop whenever my result becomes more than 100. So, this is one way we can utilize a break right.
Similarly there is another statement although we do not use it often it is better to know
that sometimes it can come handy, that is a continued statement; that means,
the remaining part of the body of a loop we will skip if I put a continue all right.
So, let us see and it proceeds to the next iteration of the loop. So,
what happens is let us look at one example here.
So, while one that means what; that means, it is always true. It will continually go
on doing it. So, fact is fact times i, i plus plus. So, I start with i 1, then 2,
then 3. If i is less than 10 I will go into the loop otherwise I will break. So,
this continue is basically remain forcing me to go back to this point,
by forsaking this part. I am not coming to the remaining of the loop, but if this condition is
not holding then I will not execute continue I straight away come here and do break. I
think it will need a couple of moment for you to just realize what is happening here all right.
So, just look at this. So, in this way it will I think you can understand it. So, I have got i to
be 1. So, fact will be 1 times 1, then i becomes 2 and then I go back. So, it will be fact will be
1 times 1 times 2, i will be 3 and in that will go on, but as it will go on as long as i is 10,
less than 10. Then i will not come to break I will go back here. But if i is less than 10 i will come
to break and i will come out of the loop. So, it is a combination of continue and break this is.
But what I want is that you should understand how the for loop is used for repetition that is
very important to understand and will carry out with some examples in the next lecture.
Weitere ähnliche Videos ansehen
PL/SQL Tutorial #12: Loops, Type of Loops and Simple Loop in PLSQL
a BASH script PUSH-UP counter (for #gains )
While Loops | Godot GDScript Tutorial | Ep 07
Karel Python - For Loops
Looping Arrays, Breaking and Continuing | JavaScript 🔥 | Lecture 044
Chapter 4 - Introduction to Loop - Question Bank Solved Answers
5.0 / 5 (0 votes)