- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
For and While loops in Arduino
The for and while loops in Arduino follow the C language syntax.
The syntax for the for loop is −
Syntax
for(iterator initialization; stop condition; increment instruction){ //Do something }
Example
for(int i = 0; i< 50; i++){ //Do something }
Similarly, the syntax for the while loop is −
Syntax
while(condition){ //Do something }
Example
int i = 0 while(i < 50){ //Do something i = i+1; }
The following example will illustrate the working of for and while loops in an Arduino program.
Example
void setup() { Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: int i = 0; for(i = 0; i< 10; i++){ Serial.println(i); } while(i < 20){ i = i+1; Serial.println(i); } }
Note that we defined the integer i outside the for loop. Had I written for(int i = 0; i< 10; i++), then the scope of the variable i would have been restricted to the for loop only, and the while loop would not have been able to access it.
The Serial Monitor output of the above program is shown below −
Output
As you can see, the two loops are sharing the variable, i.
In order to write infinite loops, you can use the following syntax for for loops −
Syntax
for(;;){ //Do something continuously }
And the following for the while loops −
Syntax
while(1){ //Do something continuously }
- Related Articles
- How to use multiple for and while loops together in Python?
- Do-while loop in Arduino
- For Loops in Javascript
- Reduce decimals while printing in Arduino
- What is the difference between for...in and for...of loops in JavaScript?
- Reverse array with for loops JavaScript
- Loops in C and C++
- Check if two strings are equal while ignoring case in Arduino
- What is basic syntax of Python for Loops?
- While and For Range in Rust Programming
- What are the best practices for using loops in Python?
- Loops in Java
- Difference Between for and while loop
- Array flattening using loops and recursion in JavaScript
- Loops in Dart Programming

Advertisements