This a simpler proof-of-concept for comparing pins on a microcontroller and I am trying to work out the basics of this code before moving to the microcontroller IDE. In this code each element of the array is a pin and the values of the array elements are compared. My code achieves what I want it to do, but I am trying to simplify it so It is not multiple print lines and instead counts how many of the pins are the same value and can print what pins are the same and what those same pin values are.
#include<stdio.h>
int main(){
int count1=0;
//array represents pins, values range from 1 to 8. NOT COUNTING ARRAY ELEMENT 0.
int arrNew[]={0,1,1,2,6,7,3,4,3,4,5,8};
//FOR LOOPS TO COMPARE EACH PIN TO EACH OTHER.
for(int i = 1; i < 12; i )
for(int k = i; k < 12; k )
//PRINT IF PINS ARE NOT THE SAME
if(arrNew[i] != arrNew[k]){
printf("\nPin %d is not the same as %d.", arrNew[i], arrNew[k]);
}
}
Currently I am trying to create a counter for each time an array element value is a certain number, but I am getting an error of 'k' not declared in my for statement.
#include<stdio.h>
int main(){
int count1=0;
//array represents pins, values range from 1 to 8. NOT COUNTING ARRAY ELEMENT 0.
int arrNew[]={0,1,1,2,6,7,3,4,3,4,5,8};
//FOR LOOPS TO COMPARE EACH PIN TO EACH OTHER.
for(int i = 1; i < 12; i )
for(int k = i; k < 12; k )
//PRINT IF PINS ARE NOT THE SAME
if(arrNew[i] != arrNew[k]){
printf("\nPin %d is not the same as %d.", arrNew[i], arrNew[k]);
}
//keep count of WHAT pins are of the same value, and what VALUE those same pins are.
if (arrNew[k]=1){
count1 ;
}
}
21 13 C:\Users\xxxx\Desktop\dev c\Untitled1.cpp [Error] 'k' was not declared in this scope
Would combining the two FOR statements allow me to access the value of int k as it is updated through the FOR loop in order to keep count of how many array element values are 1, 2, etc..?
CodePudding user response:
The syntax for for
is:
for (...) STMT
Only the statement immediately following the parens is part of the loop. This statement could be a simple statement (an expression with a semi-colon), a block (statements in curlies), some flow control statement (like another for
loop), etc.
The important part is that only the first statement after the for
is part of the loop.
for (int i = 1; i < 12; i )
for (int k = i; k < 12; k )
if (arrNew[i] != arrNew[k]) {
printf("\nPin %d is not the same as %d.", arrNew[i], arrNew[k]);
}
if (arrNew[k]=1) { // <---- Not either loop
count1 ;
}
If you want more than one statement to form the body a loop, you'll need to wrap them in curlies (like you did for the if
statements).
Not sure what you were going for, so I'm not sure how to fix it.
Note that you appear to have confused =
for ==
in the bottom if
.