IT, Programming, & Web Development › Forums › CS50’s Introduction to Computer Science by Harvard University on Edx › Week 1: [C] – Data Types, Operators, Conditional Statements, Loops, and Command Line › Choice of loops in C: Are the three loops exclusive or replaceable for a task
Tagged: C programming language, choice of loops in C, do-while loop, exit-controlled loop, for loop, incrementer, initialize the variable, iteration, loops, loops in C, Scratch repeat block, while loop
- This topic is empty.
-
AuthorPosts
-
August 20, 2021 at 8:33 am #94
#include<stdio.h> #include<cs50.h> int main(void) { int h; do { h = get_int("h"); } while (h < 0 || h > 8); }
In the above example, there is a reason to opt for do-while loop after going through this description: In a do…while loop, the condition is always executed after the body of a loop. It is also called an exit-controlled loop.(www.guru99.com/c-loop-statement.html). However, I find more compelling to opt for while loop after reading the description: In while loop, a condition is evaluated before processing a body of the loop. If a condition is true then and only then the body of a loop is executed. Is while loop not used because if someone enters say 9, the loop will terminate?
Now, coming to the next part to print a square of height and width n (before opting for right aligning with dots problem), the CS50 tutorial suggests using for loop:
“Just as Scratch has a Repeat block, so does C have a for loop, via which you can iterate some number times. Perhaps on each iteration, i, you could print that many hashes?…”
I find the above statement confusing as is it not that the purpose of all the three loops (do-while, while, for) is iterating number of times.
My query is can the above task of printing square be done using do-while loop? Is it that any operation in C can be done by choosing any of the three loops or there are certain operations that can be done by a specific loop. I mean are there operations that can be done by for loop exclusively (not possible by other two loops, do-while, while loop).
Reply
https://cs50.stackexchange.com/questions/41831/choice-of-loops-in-c-are-the-three-loops-exclusive-or-replaceable-for-a-task[learn_press_profile]
-
AuthorPosts
- You must be logged in to reply to this topic.