for loop Arduino/C - for-loop

My aim is to create a for loop that iterates through numbers and once it reaches the maximum, it stops printing. So far I managed to create a piece of code that stops printing the x but it keeps printing zeroes. How can I stop Serial.print() function to be executed once the iteration reached the maximum value?
int x;
boolean f = false;
void setup(){
Serial.begin(9600);
}
void loop(){
for(x=0;x<8;x++){
Serial.println(x);
delay(300);
if(x==7){
f = true;
}
if(f){
break;
}
}
}

Something like below should serve. Btw, I like to name my vars something meaningful to avoid potential confusion and make the code more intelligible.
(In general you are better off posting questions to the Arduino forum. More traffic and more knowledgeable/helpful people == more likelihood of getting an answer.)
int current;
int limit;
boolean complete;
void setup(){
Serial.begin(9600);
current = 0;
limit = 8;
complete = false;
}
void loop(){
if (!complete){
while (true){
Serial.println(current);
current++;
if (current >= limit){
complete = true;
break;
}
delay(300);
}
}
}

The key is the word loop - that function is called repetitively!
If you want something to happen once, do it in setup(), or (as another answer suggests), have a flag to keep track of the fact that you've done it already.
Another way (since x is global) would be:
void loop() {
if (x < 8) {
Serial.println(x);
x++;
}
}
or, getting rid of the global variable:
void loop() {
static int x = 0;
if (x < 8) {
Serial.println(x);
x++;
}
}

int x;
boolean f = false;
void setup(){
Serial.begin(9600);
}
Very similar to your code, just put the print statement in the if statement and you're set.
void loop(){
for(x=0;x<8;x++){
if(!f) {
Serial.println(x);
}
delay(300);
if(x==7){
f = true;
}
}
}

Related

Processing String splitting and loops to form a facade

I have tried many methods, and can't seem to grasp the idea of extracting an index from my array of strings to help me generate my desired number of building with a desired height, please help, here is my example
edit: Hi, i saw your feedback and posted my code below, hopefully it helps with the idea overall, as much as it is just creating rects, its more complicated as i need to involve arrays and string splitting along with loops. i more or less got that covered but i as i said above, i cannot extract the values from my array of string and create my facades at my own desired number and height
String buffer = " ";
String bh = "9,4,6,8,12,2";
int[] b = int(split(bh, ","));
int buildingheight = b.length;
void setup () {
size(1200, 800);
background(0);
}
void draw () {
}
void Textbox() {
textSize(30);
text(buffer, 5, height-10);
}
void keyTyped() {
if (key == BACKSPACE) {
if (buffer.length() > 0) {
buffer = buffer.substring(0, buffer.length() - 1);
}
} else if (key == ENTER) {
background(0);
stroke(0);
GenerateFacade();
println(buffer);
}
else {
buffer = buffer + key;
Textbox();
}
}
void GenerateFacade() {
fill(128);
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b.length; j++) {
if (int(b[j]) > buildingheight) {
buildingheight = int(b[j]);
}
}
rect(i*width/b.length, height - (int(b[i])*height/buildingheight), width/b.length, int(b[i])*height/buildingheight);
}
}
For the next time it would be great if you provide us with some code so we know what you tried and maybe can point you to the problem you have.
You need just the keyPressed function and some variables
int x = 0;
int buildingWidth = 50;
int buildingHeight = height / 6;
void setup(){
size(1000, 500);
background(255);
}
void draw(){
}
void keyPressed(){
if(key >= '0' && key <= '9'){
int numberPressed = key - '0' ;
fill(0);
rect(x, height - buildingHeight * numberPressed,
buildingWidth, buildingHeight * numberPressed);
x += buildingWidth;
}
}
This is my result

Why Numbers are getting printed in the form like "12-256" , "13-256" rather than 12,13 etc.?

I'm solving one of the algorithms problem from university to implemet queue using stacks.
I've got my logic right i guess but the numbers are getting printed in the form of 12-256, 13-256, 14-256 instead of 12,13,14.
Here's my C++ Code,
#include <iostream>
using namespace std;
class Stack{
private:
int arr[200];
int tos = -1;
public:
bool empty(){
return (tos == -1)?true:false;
}
void push(int element){
arr[++tos] = element;
}
int pop(){
return arr[tos--];
}
void show(){
if(tos == -1){
cout<<"stack empty";
}else{
for(int i=tos;i>0;i--)
cout<<arr[i]<<"\t";
}
}
};
class Queue{
private:
Stack s1,s2;
public:
void enQueue(int x){
//just using s1 to add new elements
s1.push(x);
}
int deQueue(){
if(s1.empty())
throw 'e';
else{
int e;
while(!s1.empty()){
e = s1.pop();
s2.push(e);
}
cout<<"\nelement to be removed:"<<s2.pop();
if(s2.empty())
throw 'f';
else{
int e;
while(!s2.empty()){
e = s2.pop();
s1.push(e);
}
}
}
}
};
int main()
{
try{
Queue q1;
q1.enQueue(12);
q1.enQueue(13);
q1.enQueue(14);
q1.enQueue(15);
cout<<q1.deQueue();
cout<<q1.deQueue();
cout<<q1.deQueue();
cout<<q1.deQueue();
}catch(char c){
cout<<"\nstack empty!";
}
return 0;
}
I'm basically a Python Guy so i'm not able to figure out what's wrong with this code.
I'm new to C++, so please guide me through this.
Thanks in advance!
deQueue suffers from the following problems.
It doesn't return anything.
It's OK for s2 to be empty after its top has been popped.
Here's an updated version that should work.
int deQueue(){
if(s1.empty())
throw 'e';
int e;
while(!s1.empty()){
e = s1.pop();
s2.push(e);
}
int ret = s2.pop();
cout<<"\nelement dequeued:"<< ret;
// This is not correct.
// It's OK for s2 to be empty after its top has been popped.
// if(s2.empty())
// throw 'f';
while(!s2.empty()){
e = s2.pop();
s1.push(e);
}
return ret;
}
Suggestion for further improvement
Queue does not need two Stack objects as member variables. s2 can be a function local variable in deQueue.
class Queue
{
private:
Stack s;
...
};
If you decide to make that change, you'll have to update enQueue and deQueue accordingly.

Translate recursive function calls into cost-efficient representation

I am trying to use some static analysis tools to check a program with extensive usage of recursive calls. Conceptually, it is something like this:
int counter = 0;
int access = 0;
extern int nd (); // a nondeterministic value
void compute1();
void compute2();
int get()
{
static int fpa[2] = {2, 2}; // each function can be called for twice
int k = nd() % 2;
if (fpa[k] > 0) {
fpa[k]--;
return k+1;
}
else
return 0;
}
void check_r(int* x) {
if (x == &counter) {
__VERIFIER_assert(!(access == 2));
access = 1;
}
}
void check_w(int* x) {
if (x == &counter) {
__VERIFIER_assert((access == 0));
access = 2;
}
}
void schedule() {
for (int i = 0; i < 5; i++) {
int fp = get();
if (fp == 0)
return;
elif (fp == 1)
compute1();
elif (fp == 2)
compute2();
}
}
void compute1()
{
// some computations
...
schedule(); // recursive call
check_w(&counter); // check write access
...
}
void compute2()
{
// some computations
...
schedule(); //recursive call
check_r(&counter);
...
}
int main()
{
schedule();
return 0;
}
My tentative tests show that due to the recursive call, the static analysis becomes too slow to terminate.
While in principle, I can somehow rewrite the recursive call into a switch statement or so, but the problem is that before the recursive call schedule, compute1 and compute2 functions have performed nontrivial amount of computations already, and it is difficult to save the program context for further usage.
I have been trapped to optimize this cases for a few days, but just cannot come up with a even ad-hoc solution. Could anyone please provide some comments and suggestions to get rid of the recursive call here? Thank you so much.
To me it looks like all the schedule function is doing is deciding whether to call compute1 or compute2 and all the get is doing is ensuring a single function is never called more than twice. I don't think the recursive call from compute to schedule is necessary then since there is never more than two calls. The recursion here seem to imply that every time we can successfully call one of the compute functions we wan't another chance to call compute again
void schedule() {
int chances = 1;
for (int i = 0; i < 5 || chances > 0; i++) {
int fp = get();
if (fp == 0){
chances--;
if(chances < 0)
chances = 0;
continue;
}
elif (fp == 1){
compute1(); chances++;
}
elif (fp == 2){
compute2(); chances++;
}
}
}
void compute1()
{
// some computations
...
//schedule(); remove
check_w(&counter); // check write access
...
}
void compute2()
{
// some computations
...
//schedule(); remove
check_r(&counter);
...
}
This code is a bit confusing so please clarify if I made any incorrect assumptions

IndexOutOfBoundsException when I attempt to use list.contain(...), not sure how to fix

public static void main(String[] args) {
List<String> stuff = new ArrayList<String>();
List<String> fc = new ArrayList<String>();
List<String> on = new ArrayList<String>();
List<String> done = new ArrayList<String>();
int d=0;
int x=0;
int r=0;
//"inputs" is an array with all the inputs from the user.
//You will have to go through and extract the data from "inputs" and store it in
//a data type that works
Scanner in = new Scanner(System.in);
int inputs_size = 0;
inputs_size = 100;
String[] inputs = new String[inputs_size];
for(int i = 0; i < inputs_size; i++) {
String inputs_item;
try {
inputs_item = in.nextLine();
} catch (Exception e) {
inputs_item = null;
}
inputs[i] = inputs_item;
}
for(int n=0; n<inputs.length-1; n++){
if(inputs[n]==null){
break;
}
stuff.add(inputs[n]);
}
while(d<stuff.size()){
if(stuff.get(d).equals("0")){
x++;
}
d++;
}
for(int t=0; t<stuff.size(); t++){
if(stuff.get(t).equals("0")){
break;
}
fc.add(stuff.get(t));
}
r=fc.size();
while(r<stuff.size()-1){
if(stuff.get(r).equals("0")){
r++;
x=x-1;
}
if(x==4 && stuff.get(r)!="0"){
on.add(stuff.get(r));
}
if(x==3 && stuff.get(r)!="0"){
tw.add(stuff.get(r));
}
if(x==2 && stuff.get(r)!="0"){
th.add(stuff.get(r));
}
if(x==1 && stuff.get(r)!="0"){
fo.add(stuff.get(r));
}
if(x==0 && stuff.get(r)!="0"){
fi.add(stuff.get(r));
}
if(x==-1 && stuff.get(r)!="0"){
si.add(stuff.get(r));
}
r++;
}
int z=0;
int counter = 1;
for(; counter < fc.size(); counter++) {
if(counter>fc.size()){
break;
}
**if(fc.contains(on.get(counter)))** {
z=0;
}
else{
z=1;
break;
}
}
if(z==0){
done.add(on.get(0));
}
counter=1;
z=0;
System.out.println(done);
}
}
I am getting an IndexOutOfBounds error for the line of code with the asterisks around it (fc.contains(...)). I am attempting to create a program that acts as a fridge, receives input and determines what recipes I am capable of making.
Example input:
(milk
cheese
eggs
honey) -ingredients in fridge
(0) -separates lists
(eggs and honey) -recipe in question
(eggs
honey) -ingredients required for recipe, are they in fridge?? yes
So my output would be: Eggs and Honey, or the names of the recipes I can make.
Where did I go wrong here? Thank you!
Following your code, I think your on array is null.
Look:
if(x==4 && stuff.get(r)!="0"){
on.add(stuff.get(r));
}
It is the only time you try to add something to your on. And your fc and stuff size will be the same, since you doesn't have something to make it different (instead of this .equals("0"), but if you enter anything else, it will be the same). After that, we have:
r=fc.size();
while(r<stuff.size()-1){
We know that fc and stuff have the same size, then r won't be lower than stuff.size()-1.
By not entering the loop, it will remains null. So any .get() will result in IndexOutOfBounds.

Time and space complexity of if(!areAllArrayElementsZero())

How can I calculate the time and space complexity of a program(pseudo code) as follows:
function(){
if(!areAllArrayElementsZero()){
if(hasAnyOdd()){
decreaseOneFromFirstOddElementInArray()
} else {
divideAllArrayElementByTwo()
}
}
}
Here areAllArrayElementsZero(),hasAnyOdd(),divideAllArrayElementByTwo() has the complexity O(n). Any leads would help. Actually I was designing the solution to this problem.
Here is the Java equivalent of the above pseudo code, I've designed:
package competitive;
/*
* Problem: http://www.geeksforgeeks.org/count-minimum-steps-get-given-desired-array/
*/
class formarray{
private static int[] elem;
private static boolean areAllZeros(){
for(int i=0; i<elem.length;i++){
if(elem[i]>0){
return false;
}
}
return true;
}
private static boolean hasAnyOdd(){
for(int i=0; i<elem.length;i++){
if(elem[i]%2 != 0){
// odd element discovered
return true;
}
}
return false;
}
private static boolean decreaseFirstOddByOne(){
for(int i=0; i<elem.length;i++){
if(elem[i]%2 != 0) {
// odd element discovered
elem[i]-=1;
// return true if one is decreased from first odd element
return true;
}
}
return false;
}
private static void DivideArrayElementsByTwo(){
for(int i=0; i<elem.length;i++){
// we are not checking element to be even as it has already been checked
elem[i] = elem[i]/2;
}
}
public static void main(String args[]){
elem = new int[args.length];
// assign values
for(int i=0;i<args.length;i++){
elem[i] = Integer.parseInt(args[i]);
}
int steps=0;
while(!areAllZeros()){
if(hasAnyOdd()){
// the array has odd members
if(decreaseFirstOddByOne()){
steps++;
}
} else {
DivideArrayElementsByTwo();
steps++;
}
}
System.out.println("Total steps required: "+steps);
}
}
There are exactly 4 paths of execution; sum up the cost of each, take the largest.
Or realize there are no loops and each path has a finite number of O(n) elements, making the whole thing O(n).

Resources